id
int64
0
843k
repository_name
stringlengths
7
55
file_path
stringlengths
9
332
class_name
stringlengths
3
290
human_written_code
stringlengths
12
4.36M
class_skeleton
stringlengths
19
2.2M
total_program_units
int64
1
9.57k
total_doc_str
int64
0
4.2k
AvgCountLine
float64
0
7.89k
AvgCountLineBlank
float64
0
300
AvgCountLineCode
float64
0
7.89k
AvgCountLineComment
float64
0
7.89k
AvgCyclomatic
float64
0
130
CommentToCodeRatio
float64
0
176
CountClassBase
float64
0
48
CountClassCoupled
float64
0
589
CountClassCoupledModified
float64
0
581
CountClassDerived
float64
0
5.37k
CountDeclInstanceMethod
float64
0
4.2k
CountDeclInstanceVariable
float64
0
299
CountDeclMethod
float64
0
4.2k
CountDeclMethodAll
float64
0
4.2k
CountLine
float64
1
115k
CountLineBlank
float64
0
9.01k
CountLineCode
float64
0
94.4k
CountLineCodeDecl
float64
0
46.1k
CountLineCodeExe
float64
0
91.3k
CountLineComment
float64
0
27k
CountStmt
float64
1
93.2k
CountStmtDecl
float64
0
46.1k
CountStmtExe
float64
0
90.2k
MaxCyclomatic
float64
0
759
MaxInheritanceTree
float64
0
16
MaxNesting
float64
0
34
SumCyclomatic
float64
0
6k
2,800
AaronWatters/jp_proxy_widget
AaronWatters_jp_proxy_widget/setup.py
setup.NPM
class NPM(Command): description = 'install package.json dependencies using npm' user_options = [] node_modules = os.path.join(node_root, 'node_modules') targets = [ os.path.join(here, 'jp_proxy_widget', 'static', 'extension.js'), os.path.join(here, 'jp_proxy_widget', 'static', 'index.js') ] def initialize_options(self): pass def finalize_options(self): pass def get_npm_name(self): npmName = 'npm'; if platform.system() == 'Windows': npmName = 'npm.cmd'; return npmName; def has_npm(self): npmName = self.get_npm_name(); try: check_call([npmName, '--version']) return True except: return False def should_run_npm_install(self): package_json = os.path.join(node_root, 'package.json') node_modules_exists = os.path.exists(self.node_modules) return self.has_npm() def run(self): has_npm = self.has_npm() if not has_npm: log.error("`npm` unavailable. If you're running this command using sudo, make sure `npm` is available to sudo") env = os.environ.copy() env['PATH'] = npm_path if self.should_run_npm_install(): log.info("Installing build dependencies with npm. This may take a while...") npmName = self.get_npm_name(); check_call([npmName, 'install'], cwd=node_root, stdout=sys.stdout, stderr=sys.stderr) os.utime(self.node_modules, None) for t in self.targets: if not os.path.exists(t): msg = 'Missing file: %s' % t if not has_npm: msg += '\nnpm is required to build a development version of a widget extension' raise ValueError(msg) # update package data in case this created new files update_package_data(self.distribution)
class NPM(Command): def initialize_options(self): pass def finalize_options(self): pass def get_npm_name(self): pass def has_npm(self): pass def should_run_npm_install(self): pass def run(self): pass
7
0
7
1
6
0
2
0.02
1
1
0
0
6
0
6
45
61
14
46
20
39
1
43
20
36
6
2
3
13
2,801
AaronWatters/jp_proxy_widget
AaronWatters_jp_proxy_widget/jp_proxy_widget/proxy_widget.py
jp_proxy_widget.proxy_widget.CommandMaker
class CommandMaker(CommandMakerSuperClass): """ Superclass for command proxy objects. Directly implements top level objects like "window" and "element". """ top_level_names = "window element".split() def __init__(self, name="window"): assert name in self.top_level_names self.name = name def __repr__(self): #return self.javascript() return repr(type(self)) + "::" + repr(id(self)) # disable informative reprs for now def javascript(self, level=0): "Return javascript text intended for this command" return indent_string(self.name, level) def _cmd(self): "Translate self to JSON representation for transmission to view." return [self.name] def __getattr__(self, name): "Proxy to get a property of a jS object." return MethodMaker(self, name) # for parallelism to _set _get = __getattr__ # in javascript these are essentially the same thing. __getitem__ = __getattr__ def _set(self, name, value): "Proxy to set a property of a JS object." return SetMaker(self, name, value) def __call__(self, *args): "Proxy to call a JS object." raise ValueError("top level object cannot be called.") def _null(self): "Proxy to discard results of JS evaluation." return ["null", self]
class CommandMaker(CommandMakerSuperClass): ''' Superclass for command proxy objects. Directly implements top level objects like "window" and "element". ''' def __init__(self, name="window"): pass def __repr__(self): pass def javascript(self, level=0): '''Return javascript text intended for this command''' pass def _cmd(self): '''Translate self to JSON representation for transmission to view.''' pass def __getattr__(self, name): '''Proxy to get a property of a jS object.''' pass def _set(self, name, value): '''Proxy to set a property of a JS object.''' pass def __call__(self, *args): '''Proxy to call a JS object.''' pass def _null(self): '''Proxy to discard results of JS evaluation.''' pass
9
7
3
0
2
1
1
0.67
1
4
2
5
8
1
8
9
46
12
21
13
12
14
21
13
12
1
2
0
8
2,802
AaronWatters/jp_proxy_widget
AaronWatters_jp_proxy_widget/tests/test_proxy_widget.py
test_proxy_widget.RequireMockElement
class RequireMockElement: "Used for mocking the element when testing loading requirejs" require_is_loaded = False when_loaded_succeeds = True when_loaded_delayed = False alias_called = False load_called = False def alias_require(self, require_ok, load_require): self.alias_called = True if self.require_is_loaded: return require_ok() else: return load_require() def when_loaded(self, paths, success, failure): self.load_called = True if self.when_loaded_succeeds: if self.when_loaded_delayed: self.delayed_success = success else: self.require_is_loaded = True success() else: failure() def load_completed(self): self.require_is_loaded = True self.delayed_success()
class RequireMockElement: '''Used for mocking the element when testing loading requirejs''' def alias_require(self, require_ok, load_require): pass def when_loaded(self, paths, success, failure): pass def load_completed(self): pass
4
1
6
0
6
0
2
0.04
0
0
0
0
3
1
3
3
29
3
25
10
21
1
22
10
18
3
0
2
6
2,803
AaronWatters/jp_proxy_widget
AaronWatters_jp_proxy_widget/tests/test_hex_codec.py
test_hex_codec.TestHexCodec
class TestHexCodec(unittest.TestCase): def test_to_bytes(self): b = hex_codec.hex_to_bytearray(hexstr) self.assertEqual(b, bytestr) def test_to_unicode(self): s = hex_codec.bytearray_to_hex(bytestr) self.assertEqual(s, hexstr) def test_json_roundtrip(self): encoded = hexstr import json dumped = json.dumps([encoded]) undumped = json.loads(dumped) assert undumped[0] == encoded
class TestHexCodec(unittest.TestCase): def test_to_bytes(self): pass def test_to_unicode(self): pass def test_json_roundtrip(self): pass
4
0
4
0
4
0
1
0
1
0
0
0
3
0
3
75
16
3
13
10
8
0
13
10
8
1
2
0
3
2,804
AaronWatters/jp_proxy_widget
AaronWatters_jp_proxy_widget/jp_proxy_widget/uploader.py
jp_proxy_widget.uploader.JavaScriptError
class JavaScriptError(Exception): "Exception sent from javascript."
class JavaScriptError(Exception): '''Exception sent from javascript.''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
10
2
0
1
1
0
1
1
1
0
0
3
0
0
2,805
AartGoossens/goldencheetahlib
AartGoossens_goldencheetahlib/goldencheetahlib/exceptions.py
goldencheetahlib.exceptions.GoldenCheetahNotAvailable
class GoldenCheetahNotAvailable(Exception): def __init__(self, host): Exception.__init__(self, 'GC not running at \'{}\''.format(host))
class GoldenCheetahNotAvailable(Exception): def __init__(self, host): pass
2
0
2
0
2
0
1
0
1
0
0
0
1
0
1
11
3
0
3
2
1
0
3
2
1
1
3
0
1
2,806
AartGoossens/goldencheetahlib
AartGoossens_goldencheetahlib/tests/test_client.py
tests.test_client.TestGoldenCheetahClient
class TestGoldenCheetahClient(TestCase): def setUp(self): self.client = GoldenCheetahClient(athlete='Aart') def test_client_init(self): client = GoldenCheetahClient(athlete='Aart') self.assertTrue(client) self.assertTrue(client.athlete) self.assertTrue(client.host) def test_client_init_without_athlete(self): client = GoldenCheetahClient() self.assertFalse(hasattr(client, 'athlete')) self.assertTrue(client.host) def test_client_init_non_existing_athlete(self): client = GoldenCheetahClient(athlete='NonExistingAthlete') self.assertTrue(client) self.assertTrue(client.athlete) self.assertTrue(client.host) def test_get_athletes(self): with vcr.use_cassette('test_get_athletes.yaml') as cass: athletes = self.client.get_athletes() self.assertEqual( 'http://localhost:12021/', cass.requests[0].uri) self.assertTrue(isinstance(athletes, pd.DataFrame)) self.assertEqual(2, len(athletes)) self.assertTrue('name' in athletes.columns) self.assertTrue('dob' in athletes.columns) self.assertTrue('weight' in athletes.columns) self.assertTrue('height' in athletes.columns) self.assertTrue('sex' in athletes.columns) def test_get_athletes_invalid_host(self): self.client.host = 'http://localhost:123456/' with self.assertRaises(exceptions.GoldenCheetahNotAvailable): self.client.get_athletes() def test_get_athletes_invalid_host_non_http(self): self.client.host = 'blalocalhost:123456/' with self.assertRaises(exceptions.GoldenCheetahNotAvailable): self.client.get_athletes() def test_get_activity_list(self): with vcr.use_cassette('test_get_activity_list.yaml') as cass: activity_list = self.client.get_activity_list() self.assertEqual( 'http://localhost:12021/Aart', cass.requests[0].uri) self.assertTrue(isinstance(activity_list, pd.DataFrame)) self.assertEqual(235, len(activity_list)) self.assertTrue('data' in activity_list.columns) self.assertTrue(isinstance(activity_list.data[0], np.float)) self.assertTrue('datetime' in activity_list.columns) self.assertTrue('axpower' in activity_list.columns) self.assertFalse(' filename' in activity_list.columns) def test_get_activity_list_incorrect_host(self): self.client.host = 'http://localhost:123456/' with self.assertRaises(exceptions.GoldenCheetahNotAvailable): self.client.get_activity_list() def test_get_activity_list_non_existing_athlete(self): with vcr.use_cassette('test_get_activity_list_non_existing_athlete.yaml') as cass: self.client.athlete = 'John Non Existent' with self.assertRaises(exceptions.AthleteDoesNotExist): self.client.get_activity_list() def test_get_activity(self): with vcr.use_cassette('test_get_activity_by_filename.yaml') as cass: filename = '2014_01_06_16_45_24.json' activity = self.client.get_activity(filename) self.assertEqual( 'http://localhost:12021/Aart/activity/{}'.format(filename), cass.requests[0].uri) self.assertTrue(isinstance(activity, pd.DataFrame)) self.assertEqual(6722, len(activity)) self.assertEqual(6, len(activity.columns)) self.assertTrue('speed' in activity.columns) self.assertTrue('distance' in activity.columns) self.assertTrue('altitude' in activity.columns) self.assertTrue('slope' in activity.columns) self.assertTrue('latitude' in activity.columns) self.assertTrue('longitude' in activity.columns) def test_get_activity_incorrect_host(self): self.client.host = 'http://localhost:123456/' with self.assertRaises(exceptions.GoldenCheetahNotAvailable): filename = '2014_01_06_16_45_24.json' self.client.get_activity(filename) def test_get_activity_non_existing_athlete(self): with vcr.use_cassette('test_get_activity_by_filename_non_existing_athlete.yaml') as cass: self.client.athlete = 'John Non Existent' filename = '2014_01_06_16_45_24.json' with self.assertRaises(exceptions.AthleteDoesNotExist): self.client.get_activity(filename) def test_get_activity_by_non_existing_filename(self): with vcr.use_cassette('test_get_activity_by_non_existing_filename.yaml') as cass: filename = 'non_existing_filename.json' with self.assertRaises(exceptions.ActivityDoesNotExist): self.client.get_activity(filename) def test_get_activities(self): with vcr.use_cassette('test_get_activity_by_filename.yaml') as cass: filename = '2014_01_06_16_45_24.json' activities = self.client.get_activities([filename]) self.assertEqual( 'http://localhost:12021/Aart/activity/{}'.format(filename), cass.requests[0].uri) self.assertEqual(len(activities), 1) activity = activities[0] self.assertTrue(isinstance(activity, pd.DataFrame)) self.assertEqual(6722, len(activity)) self.assertEqual(6, len(activity.columns)) self.assertTrue('speed' in activity.columns) self.assertTrue('distance' in activity.columns) self.assertTrue('altitude' in activity.columns) self.assertTrue('slope' in activity.columns) self.assertTrue('latitude' in activity.columns) self.assertTrue('longitude' in activity.columns) def test_get_last_activity(self): with vcr.use_cassette('test_get_last_activity.yaml') as cass: last_activity = self.client.get_last_activity() self.assertEqual( 'http://localhost:12021/Aart', cass.requests[0].uri) self.assertEqual( 'http://localhost:12021/Aart/activity/2016_05_10_11_14_58.json', cass.requests[1].uri) self.assertTrue(isinstance(last_activity, pd.DataFrame)) self.assertTrue('power' in last_activity.columns.tolist()) def test_get_last_activities(self): with vcr.use_cassette('test_get_last_activity.yaml') as cass: last_activities = self.client.get_last_activities(n=1) self.assertEqual( 'http://localhost:12021/Aart', cass.requests[0].uri) self.assertEqual( 'http://localhost:12021/Aart/activity/2016_05_10_11_14_58.json', cass.requests[1].uri) self.assertEqual(len(last_activities), 1) last_activity = last_activities[0] self.assertTrue(isinstance(last_activity, pd.DataFrame)) self.assertTrue('power' in last_activity.columns.tolist()) self.assertEqual(5404, len(last_activity)) self.assertEqual(5404, len(last_activity)) def test__request_activity_list(self): with vcr.use_cassette('test__request_activity_list.yaml') as cass: activity_list = self.client._request_activity_list(self.client.athlete) self.assertEqual( 'http://localhost:12021/Aart', cass.requests[0].uri) self.assertTrue(isinstance(activity_list, pd.DataFrame)) self.assertEqual(235, len(activity_list)) self.assertTrue('data' in activity_list.columns) self.assertTrue(isinstance(activity_list.data[0], np.float)) self.assertTrue('datetime' in activity_list.columns) self.assertTrue('axpower' in activity_list.columns) def test__request_activity_data(self): with vcr.use_cassette('test__request_activity_data.yaml') as cass: filename = '2014_01_06_16_45_24.json' activity = self.client._request_activity_data(self.client.athlete, filename) self.assertEqual( 'http://localhost:12021/Aart/activity/{}'.format(filename), cass.requests[0].uri) self.assertTrue(isinstance(activity, pd.DataFrame)) self.assertEqual(6722, len(activity)) self.assertEqual(6, len(activity.columns)) self.assertTrue('speed' in activity.columns) self.assertTrue('distance' in activity.columns) self.assertTrue('altitude' in activity.columns) self.assertTrue('slope' in activity.columns) self.assertTrue('latitude' in activity.columns) self.assertTrue('longitude' in activity.columns) def test__request_activity_list_caching(self): with vcr.use_cassette('test__request_activity_list_caching.yaml') as cass: self.client._request_activity_list(self.client.athlete) self.client._request_activity_list(self.client.athlete) self.assertEqual(1, len(cass.requests)) def test__request_activity_data_caching(self): with vcr.use_cassette('test__request_activity_data_caching.yaml') as cass: filename = '2014_01_06_16_45_24.json' self.client._request_activity_data(self.client.athlete, filename) self.client._request_activity_data(self.client.athlete, filename) self.assertEqual(1, len(cass.requests)) def test__athlete_endpoint(self): endpoint = self.client._athlete_endpoint(self.client.athlete) self.assertEqual(endpoint, 'http://localhost:12021/Aart') def test__activity_endpoint(self): filename = '2014_01_06_16_45_24.json' endpoint = self.client._activity_endpoint(self.client.athlete, filename) self.assertEqual(endpoint, 'http://localhost:12021/Aart/activity/2014_01_06_16_45_24.json') def test_get_athlete_zones(self): zones = self.client.get_athlete_zones() self.assertTrue(zones is None)
class TestGoldenCheetahClient(TestCase): def setUp(self): pass def test_client_init(self): pass def test_client_init_without_athlete(self): pass def test_client_init_non_existing_athlete(self): pass def test_get_athletes(self): pass def test_get_athletes_invalid_host(self): pass def test_get_athletes_invalid_host_non_http(self): pass def test_get_activity_list(self): pass def test_get_activity_list_incorrect_host(self): pass def test_get_activity_list_non_existing_athlete(self): pass def test_get_activity_list(self): pass def test_get_activity_incorrect_host(self): pass def test_get_activity_non_existing_athlete(self): pass def test_get_activity_by_non_existing_filename(self): pass def test_get_activities(self): pass def test_get_last_activity(self): pass def test_get_last_activities(self): pass def test__request_activity_list(self): pass def test__request_activity_data(self): pass def test__request_activity_list_caching(self): pass def test__request_activity_data_caching(self): pass def test__athlete_endpoint(self): pass def test__activity_endpoint(self): pass def test_get_athlete_zones(self): pass
25
0
8
1
8
0
1
0
1
2
1
0
24
1
24
96
222
36
186
63
161
0
165
50
140
1
2
2
24
2,807
AartGoossens/goldencheetahlib
AartGoossens_goldencheetahlib/goldencheetahlib/exceptions.py
goldencheetahlib.exceptions.AthleteDoesNotExist
class AthleteDoesNotExist(Exception): def __init__(self, athlete): Exception.__init__(self, 'Athlete \'{}\' does not exist.'.format(athlete))
class AthleteDoesNotExist(Exception): def __init__(self, athlete): pass
2
0
2
0
2
0
1
0
1
0
0
0
1
0
1
11
3
0
3
2
1
0
3
2
1
1
3
0
1
2,808
AartGoossens/goldencheetahlib
AartGoossens_goldencheetahlib/goldencheetahlib/exceptions.py
goldencheetahlib.exceptions.ActivityDoesNotExist
class ActivityDoesNotExist(Exception): def __init__(self, filename): Exception.__init__(self, 'Activity \'{}\' does not exist.'.format(filename))
class ActivityDoesNotExist(Exception): def __init__(self, filename): pass
2
0
2
0
2
0
1
0
1
0
0
0
1
0
1
11
3
0
3
2
1
0
3
2
1
1
3
0
1
2,809
AartGoossens/goldencheetahlib
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AartGoossens_goldencheetahlib/goldencheetahlib/client.py
goldencheetahlib.client.GoldenCheetahClient
class GoldenCheetahClient: """Class that provides access to GoldenCheetah's REST API Can be used to retrieve lists of and single activities, including raw data. """ def __init__(self, athlete=None, host=DEFAULT_HOST): """Initialize GC client. Keyword arguments: athlete -- Full name of athlete host -- the full host (including \'http://\') """ if athlete is not None: self.athlete = athlete self.host = host def get_athletes(self): """Get all available athletes This method is cached to prevent unnecessary calls to GC. """ response = self._get_request(self.host) response_buffer = StringIO(response.text) return pd.read_csv(response_buffer) def get_activity_list(self): """Get activity list for client.athlete""" return self._request_activity_list(self.athlete) def get_athlete_zones(self): """Get athlete zones for client.athlete. Not implemented yet. """ pass def get_activity(self, filename): """Get raw activity data for filename for self.athlete This call is slow and therefore this method is memory cached. Keyword arguments: filename -- filename of activity (e.g. \'2015_04_29_09_03_16.json\') """ return self._request_activity_data(self.athlete, filename) def get_activities(self, filenames): """Get raw activity data for filenames for self.athlete This call is slow and therefore this method is memory cached. Keyword arguments: filenames -- filenames of activity (e.g. \'2015_04_29_09_03_16.json\') """ return [self.get_activity(f) for f in filenames] def get_last_activities(self, n): """Get all activity data for the last activity Keyword arguments: """ filenames = self.get_activity_list().iloc[-n:].filename.tolist() last_activities = [self.get_activity(f) for f in filenames] return last_activities def get_last_activity(self): """Get all activity data for the last activity Keyword arguments: """ last_activities = self.get_last_activities(n=1) return last_activities[0] def _request_activity_list(self, athlete): """Actually do the request for activity list This call is slow and therefore this method is memory cached. Keyword arguments: athlete -- Full name of athlete """ response = self._get_request(self._athlete_endpoint(athlete)) response_buffer = StringIO(response.text) activity_list = pd.read_csv( filepath_or_buffer=response_buffer, parse_dates={'datetime': ['date', 'time']}, sep=',\s*', engine='python' ) activity_list.rename(columns=lambda x: x.lower(), inplace=True) activity_list.rename( columns=lambda x: '_' + x if x[0].isdigit() else x, inplace=True) activity_list['has_hr'] = activity_list.average_heart_rate.map(bool) activity_list['has_spd'] = activity_list.average_speed.map(bool) activity_list['has_pwr'] = activity_list.average_power.map(bool) activity_list['has_cad'] = activity_list.average_heart_rate.map(bool) activity_list['data'] = pd.Series(dtype=np.dtype("object")) return activity_list def _request_activity_data(self, athlete, filename): """Actually do the request for activity filename This call is slow and therefore this method is memory cached. Keyword arguments: athlete -- Full name of athlete filename -- filename of request activity (e.g. \'2015_04_29_09_03_16.json\') """ response = self._get_request( self._activity_endpoint(athlete, filename)).json() activity = pd.DataFrame(response['RIDE']['SAMPLES']) activity = activity.rename(columns=ACTIVITY_COLUMN_TRANSLATION) activity.index = pd.to_timedelta(activity.time, unit='s') activity.drop('time', axis=1, inplace=True) return activity[[i for i in ACTIVITY_COLUMN_ORDER if i in activity.columns]] def _athlete_endpoint(self, athlete): """Construct athlete endpoint from host and athlete name Keyword arguments: athlete -- Full athlete name """ return '{host}{athlete}'.format( host=self.host, athlete=quote_plus(athlete) ) def _activity_endpoint(self, athlete, filename): """Construct activity endpoint from host, athlete name and filename Keyword arguments: athlete -- Full athlete name filename -- filename of request activity (e.g. \'2015_04_29_09_03_16.json\') """ return '{host}{athlete}/activity/{filename}'.format( host=self.host, athlete=quote_plus(athlete), filename=filename ) @lru_cache(maxsize=256) def _get_request(self, endpoint): """Do actual GET request to GC REST API Also validates responses. Keyword arguments: endpoint -- full endpoint for GET request """ try: response = requests.get(endpoint) except requests.exceptions.RequestException: raise GoldenCheetahNotAvailable(endpoint) if response.text.startswith('unknown athlete'): match = re.match( pattern='unknown athlete (?P<athlete>.+)', string=response.text) raise AthleteDoesNotExist( athlete=match.groupdict()['athlete']) elif response.text == 'file not found': match = re.match( pattern='.+/activity/(?P<filename>.+)', string=endpoint) raise ActivityDoesNotExist( filename=match.groupdict()['filename']) return response
class GoldenCheetahClient: '''Class that provides access to GoldenCheetah's REST API Can be used to retrieve lists of and single activities, including raw data. ''' def __init__(self, athlete=None, host=DEFAULT_HOST): '''Initialize GC client. Keyword arguments: athlete -- Full name of athlete host -- the full host (including 'http://') ''' pass def get_athletes(self): '''Get all available athletes This method is cached to prevent unnecessary calls to GC. ''' pass def get_activity_list(self): '''Get activity list for client.athlete''' pass def get_athlete_zones(self): '''Get athlete zones for client.athlete. Not implemented yet. ''' pass def get_activity_list(self): '''Get raw activity data for filename for self.athlete This call is slow and therefore this method is memory cached. Keyword arguments: filename -- filename of activity (e.g. '2015_04_29_09_03_16.json') ''' pass def get_activities(self, filenames): '''Get raw activity data for filenames for self.athlete This call is slow and therefore this method is memory cached. Keyword arguments: filenames -- filenames of activity (e.g. '2015_04_29_09_03_16.json') ''' pass def get_last_activities(self, n): '''Get all activity data for the last activity Keyword arguments: ''' pass def get_last_activity(self): '''Get all activity data for the last activity Keyword arguments: ''' pass def _request_activity_list(self, athlete): '''Actually do the request for activity list This call is slow and therefore this method is memory cached. Keyword arguments: athlete -- Full name of athlete ''' pass def _request_activity_data(self, athlete, filename): '''Actually do the request for activity filename This call is slow and therefore this method is memory cached. Keyword arguments: athlete -- Full name of athlete filename -- filename of request activity (e.g. '2015_04_29_09_03_16.json') ''' pass def _athlete_endpoint(self, athlete): '''Construct athlete endpoint from host and athlete name Keyword arguments: athlete -- Full athlete name ''' pass def _activity_endpoint(self, athlete, filename): '''Construct activity endpoint from host, athlete name and filename Keyword arguments: athlete -- Full athlete name filename -- filename of request activity (e.g. '2015_04_29_09_03_16.json') ''' pass @lru_cache(maxsize=256) def _get_request(self, endpoint): '''Do actual GET request to GC REST API Also validates responses. Keyword arguments: endpoint -- full endpoint for GET request ''' pass
15
14
11
1
6
4
1
0.71
0
5
3
0
13
2
13
13
166
31
79
29
64
56
58
28
44
4
0
1
17
2,810
AbdealiJK/pycolorname
AbdealiJK_pycolorname/tests/deprecation_test.py
deprecation_test.DeprecationTest
class DeprecationTest(unittest.TestCase): """ This class is used to test whether the library has a whole is backward compatible. Hence, this is actually a functional test rather than a unittest. """ def get_pkl_colors(self, filename): with open(os.path.join(os.path.dirname(__file__), "old_pkl_files", filename), 'rb') as fp: pkl_colors = pickle.load(fp) return pkl_colors def compare_dicts(self, dict1, dict2): """ Helper function to compare dicts. Useful to get good statistics of why two dicts are not equal - especially when the two dicts are huge. """ keys1, keys2 = set(dict1.keys()), set(dict2.keys()) if keys1 != keys2: msg = ("Length of keys were different: {0} and {1}.\n" "{2} keys found that were common.\n" "dict1 has the following extra items: {3}\n" "dict2 has the following extra items: {4}\n" .format(len(keys1), len(keys2), len(keys1 & keys2), pprint.pformat({k: dict1[k] for k in keys1 - keys2}), pprint.pformat({k: dict2[k] for k in keys2 - keys1}))) raise AssertionError(msg) self.assertEqual(dict1, dict2) def test_pantone_pantonepaint(self): pkl_colors = self.get_pkl_colors("PMS_pantonepaint_raw.pkl") new_comparable_colors = {} for name, color in PantonePaint().items(): # Two color names are not there in the earlier set if name in ("PMS 13-1520 TPX (Rose Quartz)", "PMS 15-3919 TPX (Serenity)"): continue # Earlier there was an extra Pantone which has been removed from # the site now. This is unnecessary as we already have a PMS at # the beginning name = name[:-1] + " Pantone" + name[-1:] # Earlier "&amp;" was not being converted to "&". Now it is. name = name.replace("&", "&amp;") # Earlier unicode characters like "é" were taken as "?". name = name.encode("ascii", errors="replace").decode("utf-8") # There were typos earlier in the website. # Use the typo version again for comparison. if name == "PMS 19-4118 TPX (Dark Denim Pantone)": name = name.replace("Denim", "Derim") elif name == "PMS 16-0439 TPX (Spinach Green Pantone)": name = name.replace("Spinach", "spinach") elif name == "PMS 16-1343 TPX (Autumn Sunset Pantone)": name = name.replace("Sunset", "Sunst") elif name == "PMS 17-0000 TPX (Frost Gray Pantone)": name = name.replace("Gray", "Gary") elif name == "PMS 18-0601 TPX (Charcoal Gray Pantone)": name = name.replace("Charcoal", "Chalcoal") new_comparable_colors[name] = color self.compare_dicts(pkl_colors, new_comparable_colors) def test_pantone_logodesignteam(self): pkl_colors = self.get_pkl_colors("PMS_logodesignteam_raw.pkl") new_comparable_colors = {} for name, color in LogoDesignTeam().items(): new_comparable_colors[name] = color self.compare_dicts(pkl_colors, new_comparable_colors) def test_pantone_cal_print(self): pkl_colors = self.get_pkl_colors("PMS_cal-print.pkl") new_colors = CalPrint() common_color_names = set(pkl_colors.keys()) & set(new_colors.keys()) self.assertEqual(len(common_color_names), 656) self.assertEqual(len(pkl_colors.keys()), 992) self.assertEqual(len(new_colors.keys()), 992) # Now get all the values which actually had variable names # This is done because the delta_e implementation has changed in # colormath pkl_named_colors = {} for name, color in pkl_colors.items(): if not name.startswith("Pantone"): continue pkl_named_colors[name] = color new_named_colors = {} for name, color in new_colors.items(): if not name.startswith("Pantone"): continue new_named_colors[name] = color self.assertEqual(len(pkl_named_colors.keys()), 57) self.assertEqual(len(new_named_colors.keys()), 57) self.compare_dicts(pkl_named_colors, new_named_colors) def test_ral_classic_wikipedia(self): # The earlier names were wrong. They had the section names in # wikipedia. i.e. a lot of colors have the name "Yellow/Beige" # while wikipedia does provide give better names like "Beige", # "Sand yellow", etc. for those colors. # So we're removing that part and not checking it. comparable_chars = len("RAL 1000") pkl_compatible_colors = {} for name, color in self.get_pkl_colors("RAL_wikipedia.pkl").items(): name = name[:comparable_chars] pkl_compatible_colors[name] = color new_comparable_colors = {} for name, color in Wikipedia().items(): name = name[:comparable_chars] # 90xx arent there in the older version except 9003, 9005 if (name.startswith("RAL 90") and name not in ("RAL 9003", "RAL 9005")): continue new_comparable_colors[name] = color self.compare_dicts(pkl_compatible_colors, new_comparable_colors)
class DeprecationTest(unittest.TestCase): ''' This class is used to test whether the library has a whole is backward compatible. Hence, this is actually a functional test rather than a unittest. ''' def get_pkl_colors(self, filename): pass def compare_dicts(self, dict1, dict2): ''' Helper function to compare dicts. Useful to get good statistics of why two dicts are not equal - especially when the two dicts are huge. ''' pass def test_pantone_pantonepaint(self): pass def test_pantone_logodesignteam(self): pass def test_pantone_cal_print(self): pass def test_ral_classic_wikipedia(self): pass
7
2
19
2
14
4
4
0.31
1
6
4
0
6
0
6
78
128
19
83
27
76
26
67
26
60
8
2
2
22
2,811
AbdealiJK/pycolorname
AbdealiJK_pycolorname/tests/pantone/logodesignteam_test.py
logodesignteam_test.LogoDesignTeamTest
class LogoDesignTeamTest(unittest.TestCase): def setUp(self): self.uut = LogoDesignTeam() self.uut.load(refresh=True) def test_data(self): self.assertEqual(len(self.uut), 991) # We check a few random colors to be sure that things are fine. self.assertEqual(self.uut['PMS 245'], (232, 127, 201)) self.assertEqual(self.uut['PMS 202'], (140, 38, 51)) self.assertEqual(self.uut['Pantone Cool Gray 5'], (186, 183, 175)) self.assertEqual(self.uut['PMS 1345'], (255, 214, 145)) self.assertEqual(self.uut['Pantone Purple'], (191, 48, 181))
class LogoDesignTeamTest(unittest.TestCase): def setUp(self): pass def test_data(self): pass
3
0
6
1
5
1
1
0.09
1
1
1
0
2
1
2
74
15
3
11
4
8
1
11
4
8
1
2
0
2
2,812
AbdealiJK/pycolorname
AbdealiJK_pycolorname/tests/pantone/cal_print_test.py
cal_print_test.CalPrintTest
class CalPrintTest(unittest.TestCase): def setUp(self): self.uut = CalPrint() self.uut.load(refresh=True) def test_data(self): self.assertEqual(len(self.uut), 992) self.assertIn("White (White)", self.uut) # We check a few random colors to be sure that things are fine. self.assertEqual(self.uut['PMS 245 (Pantone Rhodamine Red)'], (232, 127, 201)) self.assertEqual(self.uut['PMS 202 (Pantone Rubine Red 2X)'], (140, 38, 51)) self.assertEqual(self.uut['Pantone Cool Gray 5 (Pantone Cool Gray 5)'], (186, 183, 175)) self.assertEqual(self.uut['PMS 1345 (Pantone Warm Gray 2)'], (255, 214, 145)) self.assertEqual(self.uut['Pantone Purple (Pantone Purple)'], (191, 48, 181)) # Check that the nearest color to named colors are themselves. # As, delta_e for named colors with themselves should be minimum. for name, color in self.uut.items(): if not name.startswith("PMS"): original_name, nearest_name = name.split(" (") nearest_name = nearest_name.replace(")", "") self.assertEqual(original_name, nearest_name)
class CalPrintTest(unittest.TestCase): def setUp(self): pass def test_data(self): pass
3
0
13
1
11
2
2
0.14
1
1
1
0
2
1
2
74
29
4
22
6
19
3
17
6
14
3
2
2
4
2,813
AbdealiJK/pycolorname
AbdealiJK_pycolorname/pycolorname/ral/classic/ralcolor.py
pycolorname.ral.classic.ralcolor.RALColor
class RALColor(ColorSystem): def __init__(self, *args, **kwargs): ColorSystem.__init__(self, *args, **kwargs) self.load() def refresh(self): full_data = self.request('GET', "http://www.ralcolor.com/") trs = full_data.find_all('tr') data = {} for tr in trs: tds = tr.find_all('td') # The tds are in the order: # RAL code, hyphen rgb, rgb-hex, dutch name, english name, etc. if len(tds) < 5: continue if (not tds[0].text.strip().startswith("RAL") and tds[1].text.strip().startswith("RAL") and tds[1].text.strip() != "RAL"): # omit head of table # Note: In some places there is an extra empty td at the # beginning. We ignore that. tds = tds[1:] ral_code = re.sub(re.compile(r"\s+"), " ", tds[0].text.strip()) # Replace &nbsp with space also eng_name = re.sub(re.compile(u(r"[\s\u00A0]+")), " ", tds[4].text.strip()) if ral_code.startswith("RAL"): name = "{0} ({1})".format(ral_code, eng_name) # Note: We replace `#` as some hex values in the site are # named wrongly as ##FFFF00. # Also, we use the 3rd column - which holds the hex # value. The 2nd column has the r-g-b and they don't # match ! color = self.hex_to_rgb(tds[2].text.strip().replace("#", "")) data[name] = color return data
class RALColor(ColorSystem): def __init__(self, *args, **kwargs): pass def refresh(self): pass
3
0
19
3
12
6
3
0.5
1
0
0
0
2
0
2
38
41
7
24
12
21
12
21
12
18
5
3
2
6
2,814
AbdealiJK/pycolorname
AbdealiJK_pycolorname/tests/pantone/pantonepaint_test.py
pantonepaint_test.PantonePaintTest
class PantonePaintTest(unittest.TestCase): def setUp(self): self.uut = PantonePaint() self.uut.load(refresh=True) def test_data(self): self.assertEqual(len(self.uut), 2095) # We check a few random colors to be sure that things are fine. self.assertEqual(self.uut['PMS 19-5918 TPX (Mountain View)'], (48, 65, 54)) self.assertEqual(self.uut['PMS 14-2808 TPX (Sweet Lilac)'], (231, 184, 211)) self.assertEqual(self.uut['PMS 15-4717 TPX (Aqua)'], (99, 162, 176)) self.assertEqual(self.uut['PMS 16-1720 TPX (Strawberry Ice)'], (227, 134, 143)) self.assertEqual(self.uut['PMS 19-4056 TPX (Olympian Blue)'], (46, 84, 147)) # Check names with unicode are working correctly self.assertEqual(self.uut[u('PMS 16-5919 TPX (Cr\xe9me de Menthe)')], (114, 162, 139))
class PantonePaintTest(unittest.TestCase): def setUp(self): pass def test_data(self): pass
3
0
11
1
9
1
1
0.11
1
1
1
0
2
1
2
74
24
4
18
4
15
2
12
4
9
1
2
0
2
2,815
AbdealiJK/pycolorname
AbdealiJK_pycolorname/pycolorname/pantone/cal_print.py
pycolorname.pantone.cal_print.CalPrint
class CalPrint(ColorSystem): def __init__(self, *args, **kwargs): ColorSystem.__init__(self, *args, **kwargs) self.load() def refresh(self): full_data = self.request('GET', "http://www.cal-print.com/InkColorChart.htm") tds = full_data.find_all('td', attrs={"bgcolor": re.compile(r".*")}) raw_data = {} known_names = [] for td in tds: table = td.find_parent('table') name = table.find("font").text color = self.hex_to_rgb(td['bgcolor']) # remove excess whitespace name = re.sub(re.compile(r"\s+"), " ", name.strip()) if 'PMS' not in name and 'Pantone' not in name: name = 'Pantone ' + name raw_data[name] = color if not name.startswith('PMS'): known_names.append(name) # Add white raw_data['White'] = (255, 255, 255) known_names.append('White') # Find distance between colors and find better names for unnamed # colors in the table. data = {} for name, color in raw_data.items(): rgb = sRGBColor(*color) lab = convert_color(rgb, LabColor, target_illuminant='D65') min_diff = float("inf") min_name = "" for known_name in known_names: known_color = raw_data[known_name] known_rgb = sRGBColor(*known_color) known_lab = convert_color(known_rgb, LabColor, target_illuminant='D65') diff = delta_e_cie2000(lab, known_lab) if min_diff > diff: min_diff = diff min_name = known_name data['{0} ({1})'.format(name, min_name)] = color return data
class CalPrint(ColorSystem): def __init__(self, *args, **kwargs): pass def refresh(self): pass
3
0
23
2
19
2
4
0.1
1
1
0
0
2
0
2
38
49
6
39
21
36
4
37
21
34
7
3
3
8
2,816
AbdealiJK/pycolorname
AbdealiJK_pycolorname/tests/ral/classic/ralcolor_test.py
ralcolor_test.RALColorTest
class RALColorTest(unittest.TestCase): def setUp(self): self.uut = RALColor() self.uut.load(refresh=True) def test_data(self): self.assertEqual(len(self.uut), 213) # We check a few random colors to be sure that things are fine. self.assertEqual(self.uut['RAL 1000 (Green beige)'], (190, 189, 127)) self.assertEqual(self.uut['RAL 3016 (Coral red)'], (179, 40, 33)) self.assertEqual(self.uut['RAL 5021 (Water blue)'], (37, 109, 123)) self.assertEqual(self.uut['RAL 7009 (Green grey)'], (77, 86, 69)) self.assertEqual(self.uut['RAL 9023 (Pearl dark grey)'], (130, 130, 130))
class RALColorTest(unittest.TestCase): def setUp(self): pass def test_data(self): pass
3
0
9
1
8
1
1
0.06
1
1
1
0
2
1
2
74
20
3
16
4
13
1
11
4
8
1
2
0
2
2,817
AbdealiJK/pycolorname
AbdealiJK_pycolorname/pycolorname/pantone/pantonepaint.py
pycolorname.pantone.pantonepaint.PantonePaint
class PantonePaint(ColorSystem): def __init__(self, *args, **kwargs): ColorSystem.__init__(self, *args, **kwargs) self.load() def refresh(self): full_data = self.request( 'POST', 'http://www.pantonepaint.co.kr/color/color_chip_ajax.asp', data={"cmp": "TPX", "keyword": ""}) lis = full_data.find_all('li', attrs={"attr_name": re.compile(r".*"), "attr_number": re.compile(r".*"), "attr_company": re.compile(r".*"), "id": re.compile(r".*")}) data = {} style_regex = re.compile(r'.*background-color *: *' r'rgb\((?P<rgb>[\d,]+ *).*') for li in lis: name = u("PMS {0} {1} ({2})").format(li['attr_number'], li['attr_company'], li['attr_name']) rgb = re.findall(style_regex, li['style'])[0] rgb = map(lambda x: int(x.strip()), rgb.split(",")) color = tuple(rgb) data[name] = color return data
class PantonePaint(ColorSystem): def __init__(self, *args, **kwargs): pass def refresh(self): pass
3
0
13
1
13
0
2
0
1
3
0
0
2
0
2
38
29
3
26
11
23
0
16
11
13
2
3
1
3
2,818
AbdealiJK/pycolorname
AbdealiJK_pycolorname/tests/color_system_test.py
color_system_test.ColorSystemTest
class ColorSystemTest(unittest.TestCase): def setUp(self): self.uut = ColorSystem() def test_dict(self): self.uut['test_key'] = 'test_val' self.assertEqual(len(self.uut), 1) self.assertEqual(list(self.uut.keys()), ['test_key']) self.assertEqual(list(self.uut.values()), ['test_val']) self.assertEqual(list(self.uut.items())[0], ('test_key', 'test_val')) self.assertIn('test_key', self.uut) self.uut.clear() self.assertEqual(len(self.uut), 0) self.assertNotIn('test_key', self.uut) self.uut.update({"test_key": "test_val"}) self.assertEqual(list(self.uut.items())[0], ('test_key', 'test_val')) def test_load(self): old_refresh = self.uut.refresh test_data = {"name": "color"} try: self.uut.refresh = lambda: test_data with make_temp() as filename: self.uut.load(filename) # Test if data loaded into class self.assertEqual(dict(self.uut), test_data) # Test if data saved into file with open(filename) as fp: json_data = json.load(fp) self.assertEqual(json_data, test_data) # Test if data is being read from file self.uut.clear() self.uut.refresh = lambda: {} self.uut.load(filename) self.assertEqual(json_data, test_data) # Test if load() respects refresh param and clears old data test_data = {"name2": "color2"} self.uut.refresh = lambda: test_data self.uut.load(filename, refresh=True) self.assertEqual(dict(self.uut), test_data) finally: self.uut.refresh = old_refresh def test_request(self): test_url = "http://a_url_to_test_with.org" def mock_request(url): self.assertEqual(url, test_url) class MockResponse: text = "<title>Test title</title>" return MockResponse() old_request = requests.request try: requests.request = mock_request bs = self.uut.request(test_url) self.assertEqual(bs.title.text, 'Test title') finally: requests.request = old_request def test_hex_to_rgb(self): self.assertEqual(self.uut.hex_to_rgb("#000"), (0, 0, 0)) self.assertEqual(self.uut.hex_to_rgb("#010101"), (1, 1, 1)) self.assertEqual(self.uut.hex_to_rgb("#aaa"), (170, 170, 170)) self.assertEqual(self.uut.hex_to_rgb("fff"), (255, 255, 255)) with self.assertRaises(ValueError): self.uut.hex_to_rgb("a") def test_find_closest(self): self.uut.update({"a": (0, 0, 0), "b": (100, 100, 100), "c": (200, 200, 200)}) name, color = self.uut.find_closest((0, 0, 0)) self.assertEqual(name, "a") self.assertEqual(color, (0, 0, 0)) name, color = self.uut.find_closest((210, 210, 210)) self.assertEqual(name, "c") self.assertEqual(color, (200, 200, 200))
class ColorSystemTest(unittest.TestCase): def setUp(self): pass def test_dict(self): pass def test_load(self): pass def test_request(self): pass def mock_request(url): pass class MockResponse: def test_hex_to_rgb(self): pass def test_find_closest(self): pass
9
0
12
2
10
1
1
0.1
1
5
2
0
6
1
6
78
88
17
67
20
58
7
63
18
54
1
2
3
7
2,819
AbdealiJK/pycolorname
AbdealiJK_pycolorname/tests/ral/classic/wikipedia_test.py
wikipedia_test.WikipediaTest
class WikipediaTest(unittest.TestCase): def setUp(self): self.uut = Wikipedia() self.uut.load(refresh=True) def test_data(self): self.assertEqual(len(self.uut), 213) # We check a few random colors to be sure that things are fine. self.assertEqual(self.uut['RAL 1000 (Green beige)'], (204, 197, 143)) self.assertEqual(self.uut['RAL 3016 (Coral red)'], (172, 64, 52)) self.assertEqual(self.uut['RAL 5021 (Water blue)'], (7, 115, 122)) self.assertEqual(self.uut['RAL 7009 (Green grey)'], (91, 98, 89)) self.assertEqual(self.uut['RAL 9023 (Pearl dark grey)'], (126, 129, 130))
class WikipediaTest(unittest.TestCase): def setUp(self): pass def test_data(self): pass
3
0
9
1
8
1
1
0.06
1
1
1
0
2
1
2
74
20
3
16
4
13
1
11
4
8
1
2
0
2
2,820
AbdealiJK/pycolorname
AbdealiJK_pycolorname/pycolorname/ral/classic/wikipedia.py
pycolorname.ral.classic.wikipedia.Wikipedia
class Wikipedia(ColorSystem): def __init__(self, *args, **kwargs): ColorSystem.__init__(self, *args, **kwargs) self.load() def refresh(self): full_data = self.request( 'GET', "https://en.wikipedia.org/wiki/List_of_RAL_colors") trs = full_data.find_all('tr') data = {} style_regex = re.compile(r'.*background *: *' r'(?P<rgb_hex>[0-9a-fA-F#]+).*') for tr in trs: tds = tr.find_all('td') # The tds are in the order: # RAL code, colored box, L, a, b, german name, english name, desc if len(tds) != 8: continue name = "{0} ({1})".format(tds[0].text.strip(), tds[6].text.strip()) rgb_hex = re.findall(style_regex, tds[1]['style'])[0] color = self.hex_to_rgb(rgb_hex) data[name] = color return data
class Wikipedia(ColorSystem): def __init__(self, *args, **kwargs): pass def refresh(self): pass
3
0
12
1
10
2
2
0.14
1
0
0
0
2
0
2
38
27
4
21
12
18
3
18
12
15
3
3
2
4
2,821
AbdealiJK/pycolorname
AbdealiJK_pycolorname/pycolorname/pantone/logodesignteam.py
pycolorname.pantone.logodesignteam.LogoDesignTeam
class LogoDesignTeam(ColorSystem): def __init__(self, *args, **kwargs): ColorSystem.__init__(self, *args, **kwargs) cssutils.log.setLevel(logging.CRITICAL) self.load() def refresh(self): full_data = self.request( 'GET', 'http://www.logodesignteam.com/logo-design-pantone-color-chart' '.html') css_request = requests.request( 'GET', 'http://www.logodesignteam.com/css/style.css') # Parse css and save only required data css_data = cssutils.parseString(css_request.text, validate=False) css_rules = {} for css_rule in css_data.cssRules: if not isinstance(css_rule, cssutils.css.CSSStyleRule): continue css_bgcolor = css_rule.style.backgroundColor if not css_bgcolor: continue for css_selector in css_rule.selectorList: if css_selector.selectorText.startswith(".color"): css_classname = css_selector.selectorText.replace(".", "") css_rules[css_classname] = css_bgcolor name_uls = full_data.find_all('ul', {'class': "color_text"}) color_uls = full_data.find_all('ul', {'class': "colors"}) data = {} for name_ul, color_ul in zip(name_uls, color_uls): name_lis = name_ul.find_all('li') color_lis = color_ul.find_all('li') for name_li, color_li in zip(name_lis, color_lis): for color_class in color_li['class']: color = css_rules.get(color_class, None) # Color not found or invalid color class if color is None or not color_class.startswith("color"): continue color = self.hex_to_rgb(color) name = name_li.text.strip() if 'Pantone' not in name: name = 'Pantone ' + name name = re.sub(r'Pantone (?P<ID>\d+)', r'PMS \g<ID>', name) data[name] = color break return data
class LogoDesignTeam(ColorSystem): def __init__(self, *args, **kwargs): pass def refresh(self): pass
3
0
24
2
22
1
6
0.05
1
1
0
0
2
0
2
38
51
5
44
21
41
2
39
21
36
11
3
4
12
2,822
AbdealiJK/pycolorname
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AbdealiJK_pycolorname/tests/color_system_test.py
color_system_test.ColorSystemTest.test_request.mock_request.MockResponse
class MockResponse: text = "<title>Test title</title>"
class MockResponse: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
2
0
2
2
1
0
2
2
1
0
0
0
0
2,823
AbletonAG/abl.vpath
AbletonAG_abl.vpath/abl/vpath/base/localfs.py
abl.vpath.base.localfs.LocalFileSystem
class LocalFileSystem(FileSystem): scheme = 'file' uri = LocalFileSystemUri def _initialize(self): pass def info(self, unc, set_info=None, followlinks=True): p = self._path(unc) use_link_functions = self.islink(unc) and not followlinks stat_func = os.lstat if use_link_functions else os.stat chmod_func = lchmod if use_link_functions else os.chmod if set_info is not None: if "mode" in set_info: chmod_func(p, set_info["mode"]) return stats = stat_func(p) ctime = stats[stat.ST_CTIME] mtime = stats[stat.ST_MTIME] atime = stats[stat.ST_ATIME] size = stats[stat.ST_SIZE] mode = stats[stat.ST_MODE] return Bunch( ctime = datetime.datetime.fromtimestamp(ctime), mtime = datetime.datetime.fromtimestamp(mtime), atime = datetime.datetime.fromtimestamp(atime), size = size, mode = mode, ) def open(self, unc, options=None, mimetype='application/octet-stream'): if options is not None: return open(self._path(unc), options) else: return open(self._path(unc)) def listdir(self, unc): return sorted(os.listdir(self._path(unc))) def removefile(self, unc): pth = self._path(unc) if sys.platform == 'win32': os.chmod(pth, stat.S_IWUSR) return os.unlink(pth) def removedir(self, unc): assert not unc.islink() pth = self._path(unc) return os.rmdir(pth) def mkdir(self, unc): path = self._path(unc) if path: return os.mkdir(path) def exists(self, unc): return os.path.exists(self._path(unc)) def isfile(self, unc): return os.path.isfile(self._path(unc)) def isdir(self, unc): return os.path.isdir(self._path(unc)) def isexec(self, unc, mode_mask): return self.info(unc).mode & mode_mask != 0 def set_exec(self, unc, mode): mask = stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH new_mode = (self.info(unc).mode & ~mask) | mode self.info(unc, dict(mode=new_mode)) def move(self, source, dest): """ the semantic should be like unix 'mv' command. Unfortunatelly, shutil.move does work differently!!! Consider (all paths point to directories) mv /a/b /a/c expected outcome: case 1.: 'c' does not exist: b moved over to /a such that /a/c is what was /a/b/ before case 2.: 'c' does exist: b is moved into '/a/c/' such that we have now '/a/c/b' But shutil.move will use os.rename whenever possible which means that '/a/b' is renamed to '/a/c'. The outcome is that the content from b ends up in c. """ if dest.scheme == 'file': if source.isdir() and dest.isdir(): dest /= source.basename() return shutil.move(source.path, dest.path) else: return super(LocalFileSystem, self).move(source, dest) def lock(self, path, fail_on_lock, cleanup): return LockFile(self._path(path), fail_on_lock=fail_on_lock, cleanup=cleanup) def mtime(self, path): return self.info(path).mtime def copystat(self, source, dest): shutil.copystat(source.path, dest.path) def supports_symlinks(self): return sys.platform != 'win32' def islink(self, path): return self.supports_symlinks() and os.path.islink(self._path(path)) def readlink(self, path): if not self.supports_symlinks(): raise OperationIsNotSupportedOnPlatform return URI(os.readlink(self._path(path))) def symlink(self, target, link_name): if not self.supports_symlinks(): raise OperationIsNotSupportedOnPlatform return os.symlink(self._path(target), self._path(link_name)) def dump(self, outf, no_binary=False): pass
class LocalFileSystem(FileSystem): def _initialize(self): pass def info(self, unc, set_info=None, followlinks=True): pass def open(self, unc, options=None, mimetype='application/octet-stream'): pass def listdir(self, unc): pass def removefile(self, unc): pass def removedir(self, unc): pass def mkdir(self, unc): pass def exists(self, unc): pass def isfile(self, unc): pass def isdir(self, unc): pass def isexec(self, unc, mode_mask): pass def set_exec(self, unc, mode): pass def move(self, source, dest): ''' the semantic should be like unix 'mv' command. Unfortunatelly, shutil.move does work differently!!! Consider (all paths point to directories) mv /a/b /a/c expected outcome: case 1.: 'c' does not exist: b moved over to /a such that /a/c is what was /a/b/ before case 2.: 'c' does exist: b is moved into '/a/c/' such that we have now '/a/c/b' But shutil.move will use os.rename whenever possible which means that '/a/b' is renamed to '/a/c'. The outcome is that the content from b ends up in c. ''' pass def lock(self, path, fail_on_lock, cleanup): pass def mtime(self, path): pass def copystat(self, source, dest): pass def supports_symlinks(self): pass def islink(self, path): pass def readlink(self, path): pass def symlink(self, target, link_name): pass def dump(self, outf, no_binary=False): pass
22
1
5
0
4
1
2
0.16
1
4
1
0
21
0
21
50
142
42
86
39
64
14
78
39
56
5
2
2
32
2,824
AbletonAG/abl.vpath
AbletonAG_abl.vpath/abl/vpath/base/fs.py
abl.vpath.base.fs.RevisionedUri
class RevisionedUri(BaseUri): @with_connection def switch(self, branch): return self.connection.switch(self, branch) @with_connection def update(self, recursive=True, clean=False): return self.connection.update(self, recursive, clean) @with_connection def log(self, limit=0, **kwargs): return self.connection.log(self, limit, **kwargs) @with_connection def log_by_time(self, start_time=None, stop_time=None): return self.connection.log_by_time(self, start_time, stop_time)
class RevisionedUri(BaseUri): @with_connection def switch(self, branch): pass @with_connection def update(self, recursive=True, clean=False): pass @with_connection def log(self, limit=0, **kwargs): pass @with_connection def log_by_time(self, start_time=None, stop_time=None): pass
9
0
2
0
2
0
1
0
1
0
0
0
4
0
4
52
19
6
13
9
4
0
9
5
4
1
2
0
4
2,825
AbletonAG/abl.vpath
AbletonAG_abl.vpath/abl/vpath/base/fs.py
abl.vpath.base.fs.ConnectionRegistry
class ConnectionRegistry(object): """ ConnectionRegistry: Singleton for file system backend registry Not ready for multithreaded code yet!!! Any backend must register itself (or must be registered). The URI object will ask the registry for the backend to use. @type connections: dict @ivar connections: holds all open connections @type schemes: dict @ivar schemes: key is a scheme; value is a factory function for scheme's backend @type run_clean_tread: bool @ivar run_clean_thread: boolean indicating if the cleaner thread should run, or not (shut down) @type clean_interval: int @ivar clean_interval: run the cleaning session every <clean_interval> seconds @type clean_timeout: int @ivar clean_timeout: close an open backend session after <clean_timeout> seconds and remove it. @type cleaner_thread: threading.Thread @ivar cleaner_thread: thread do run the cleaner method. @type creation_queue: Queue.Queue @ivar creation_queue: queue for creating connections @type creation_thread: threading.Thread @ivar creation_thread: paramiko is not setting its connection threads into daemonic mode. Due to this, it might be difficult to shut down a program, using paramiko if there is still an open connection. Since the i daemonic flag is inherited from the parent, the construction here makes sure that such connections are only created within a daemonic thread. """ def __init__(self, clean_interval=300, clean_timeout=1800): self.connections = {} self.schemes = {} self.run_clean_thread = True self.clean_interval = clean_interval self.clean_timeout = clean_timeout self.cleaner_thread = threading.Thread(target=self.cleaner) self.cleaner_thread.setDaemon(True) self.cleaner_thread.start() self.creation_locks = defaultdict(threading.Lock) def create(self, scheme, key, extras): with self.creation_locks[scheme]: conn = self.schemes[scheme](*key[1:-1], **extras) self.connections[key] = conn def get_connection(self, scheme='', hostname=None, port=None, username=None, password=None, vpath_connector=None, **extras ): """ get_connection: get connection for 'scheme' or create a new one. @type scheme: str @param scheme: the scheme to use (i.e. 'file', 'ssh', etc.) @type hostname: str|None @param hostname: the hostname (extracted from parsed uri) @type port: str|None @param port: the port (extracted from parsed uri) @type username: str|None @param username: the username (extracted from parsed uri) @type password: str|None @param password: the password (extracted from parsed uri) @type extras: dict @param extras: parameters that are given to the backend factory A key is calculated from given parameters. This key is used to check for existing connection. """ if scheme not in self.schemes: raise NoSchemeError( 'There is no handler registered for "{}" (available: {})'.format(scheme, list(self.schemes.keys())) ) key = ( scheme, hostname, port, username, password, vpath_connector, frozenset(extras.items()) ) if not key in self.connections: self.create(scheme, key, extras) return self.connections[key] def cleanup(self, force=False): now = time.time() for key, conn in list(self.connections.items()): if ((now - conn.last_used) > self.clean_timeout) or force: try: conn.close() except: print("### Exception while closing connection %s" % conn) traceback.print_exc() del self.connections[key] def cleaner(self): """ cleaner: method to be run in a thread to check for stale connections. """ while True: self.cleanup() now = time.time() try: while (time.time() - now) < self.clean_interval: if not self.run_clean_thread: return time.sleep(1) except: return def register(self, scheme, factory): "register: register factory callable 'factory' with scheme" self.schemes[scheme] = factory def shutdown(self): """ shutdown: to be run by atexit handler. All open connection are closed. """ self.run_clean_thread = False self.cleanup(True) if self.cleaner_thread.is_alive(): self.cleaner_thread.join()
class ConnectionRegistry(object): ''' ConnectionRegistry: Singleton for file system backend registry Not ready for multithreaded code yet!!! Any backend must register itself (or must be registered). The URI object will ask the registry for the backend to use. @type connections: dict @ivar connections: holds all open connections @type schemes: dict @ivar schemes: key is a scheme; value is a factory function for scheme's backend @type run_clean_tread: bool @ivar run_clean_thread: boolean indicating if the cleaner thread should run, or not (shut down) @type clean_interval: int @ivar clean_interval: run the cleaning session every <clean_interval> seconds @type clean_timeout: int @ivar clean_timeout: close an open backend session after <clean_timeout> seconds and remove it. @type cleaner_thread: threading.Thread @ivar cleaner_thread: thread do run the cleaner method. @type creation_queue: Queue.Queue @ivar creation_queue: queue for creating connections @type creation_thread: threading.Thread @ivar creation_thread: paramiko is not setting its connection threads into daemonic mode. Due to this, it might be difficult to shut down a program, using paramiko if there is still an open connection. Since the i daemonic flag is inherited from the parent, the construction here makes sure that such connections are only created within a daemonic thread. ''' def __init__(self, clean_interval=300, clean_timeout=1800): pass def create(self, scheme, key, extras): pass def get_connection(self, scheme='', hostname=None, port=None, username=None, password=None, vpath_connector=None, **extras ): ''' get_connection: get connection for 'scheme' or create a new one. @type scheme: str @param scheme: the scheme to use (i.e. 'file', 'ssh', etc.) @type hostname: str|None @param hostname: the hostname (extracted from parsed uri) @type port: str|None @param port: the port (extracted from parsed uri) @type username: str|None @param username: the username (extracted from parsed uri) @type password: str|None @param password: the password (extracted from parsed uri) @type extras: dict @param extras: parameters that are given to the backend factory A key is calculated from given parameters. This key is used to check for existing connection. ''' pass def cleanup(self, force=False): pass def cleaner(self): ''' cleaner: method to be run in a thread to check for stale connections. ''' pass def register(self, scheme, factory): '''register: register factory callable 'factory' with scheme''' pass def shutdown(self): ''' shutdown: to be run by atexit handler. All open connection are closed. ''' pass
8
5
14
1
10
4
2
0.85
1
4
1
0
7
7
7
7
155
30
68
28
52
58
50
20
42
5
1
4
17
2,826
AbletonAG/abl.vpath
AbletonAG_abl.vpath/abl/vpath/base/fs.py
abl.vpath.base.fs.BaseUri
class BaseUri(object): """An URI object represents a path, either on the local filesystem or on a remote server. On creation, the path is represented by an (more or less conform) uri like 'file:///some/local/file' or 'ssh://server:/remote/file'. The well kwown 'os'/'os.path' interface is used. Internally, the path separator is always '/'. The path property will return the url with the path separator that is given with 'sep' which defaults to 'os.sep'. The 'join' (as in os.path.join) can be used with the operator '/' which leads to more readable code. """ def __init__(self, uri, sep=os.sep, **extras): self._scheme = '' self.connection = None if isinstance(uri, BaseUri): self.uri = uri.uri self.sep = uri.sep self.parse_result = UriParse(uri.uri) self.extras = uri.extras.copy() else: if uri.startswith('file://'): uri = uri[7:] uri = normalize_uri(uri, '\\') if not '://' in uri and not (uri.startswith('/') or uri.startswith('.')): uri = './'+uri if not '://' in uri: uri = 'file://'+uri self.uri = uri self.sep = sep self.parse_result = UriParse(uri) self.extras = extras if self.username is None: if 'username' in self.extras: self.username = self.extras.pop('username') elif 'username' in self.parse_result.query: self.username = self.parse_result.query['username'] if self.password is None: if 'password' in self.extras: self.password = self.extras.pop('password') elif 'password' in self.parse_result.query: self.password = self.parse_result.query['password'] def get_connection(self): return CONNECTION_REGISTRY.get_connection(*self._key(), **self._extras()) def _extras(self): extras = self.extras.copy() if self.scheme not in ('http','https'): extras.update(self.query) return extras def _get_scheme(self): if not self._scheme: scheme = self.parse_result.scheme self._scheme = scheme return self._scheme def _set_scheme(self, scheme): self._scheme = scheme self.parse_result.scheme = scheme scheme = property(_get_scheme, _set_scheme) @property def port(self): try: return self.parse_result.port except ValueError: return None @property def path(self): path = self.parse_result.path parsed_path = path[1:] if path.startswith("/.") else path if os.name == "nt" and self.scheme == "file": parsed_path = os.path.normpath(re.sub(r"^/([a-zA-Z])/", r"\1:/", parsed_path)) return parsed_path @property def unipath(self): pathstr = self.parse_result.path if not (pathstr.startswith('.') or pathstr.startswith('/')): return './'+pathstr else: return pathstr def _key(self): return ( self.scheme, self.hostname, self.port, self.username, self.password, self.vpath_connector, ) def __str__(self): return str(self.parse_result) def __repr__(self): return str(self) def __getattr__(self, attr): return getattr(self.parse_result, attr) def __eq__(self, other): if isinstance(other, BaseUri): return self.parse_result == other.parse_result else: return False def __ne__(self, other): return not self == other def __div__(self, other): return self.join(other) def __truediv__(self, other): return self.join(other) def __add__(self, suffix): path = self.uri + suffix result = self.__class__( path, sep=self.sep, **self._extras() ) result.parse_result.query = self.query.copy() return result @property def is_absolute(self): path = self.parse_result.path if path.startswith('/.'): path = path[1:] return path.startswith('/') def split(self): """ split: like os.path.split @rtype: tuple(URI, str) @return: a 2 tuple. The first element is a URI instance and the second a string, representing the basename. """ try: first, second = self.uri.rsplit('/', 1) except ValueError: first = '' second = self.uri # we might be already on the root if first.endswith('//'): first = first + '/' if not first: first = '.' return (self.__class__( first, sep=self.sep, **self._extras() ), second.partition('?')[0] ) def directory(self, level=1): """ @return: the first part of the split method """ assert level > 0 newpath = self while level>0: newpath = newpath.split()[0] level -= 1 return newpath # os.path-compliance dirname = directory def basename(self): """ @return: the second part of the split method """ return self.split()[1] def splitext(self): return os.path.splitext(self.basename()) def last(self): """ last: similar to 'basename', but makes sure that the last part is really returned. example: URI('/some/dir/').basename() will return '' while URI('/some/dir/').last() will return 'dir'. @return: last part of uri @rvalue: str """ parts = self.uri.split('/') if not parts: return '' if len(parts) > 1: if not parts[-1]: return parts[-2] else: return parts[-1] else: return parts[-1] def join(self, *args): """ join: join paths parts together to represent a path. @return: URI instance of joined path @rtype: URI """ sep = self.sep if sep != '/': args = [x.replace(sep, '/') for x in args] args = ( [self.parse_result.path.rstrip('/')] + [x.strip('/') for x in args[:-1]] + [args[-1]] ) parts = self.parse_result.as_list() parts[2] = '/'.join(args) result = self.__class__( uri_from_parts(parts), sep=sep, **self._extras() ) result.parse_result.query = self.query.copy() return result @with_connection def copy(self, other, recursive=False, ignore=None, followlinks=True): """ copy: copy self to other @type other: URI @param other: the path to copy itself over. What will really happen depends on the backend. Note that file properties are only copied when self and other are located in the same backend, i.e. it is not possible to copy permissions etc. from a memory:// to a file:// based path. """ return self.connection.copy(self, other, recursive=recursive, ignore=ignore, followlinks=followlinks) @with_connection def copystat(self, other): """ copystat: copy file/folder metadata from self to other @type other: URI @param other: the path to copy the metadata to. Will copy file permissions, mtime, atime, etc. to path. Note: this ALWAYS follows symlinks. Consider using info with followslinks set to False to read and write the stat info of a symlink. """ return self.connection.copystat(self, other) @with_connection def move(self, other): """ move: move self to other @type other: URI @param other: the path to copy itself over. What will really happen depends on the backend. """ return self.connection.move(self, other) @with_connection def remove(self, recursive=False): """ remove: shortcut method to remove self. if 'self' represents a file, the backends 'removefile' method id used. if 'self' represents a directory, it will recursivly removed, if the options string contains 'r'. Otherwise, the backends 'removedir' method is used. """ if self.connection.islink(self): return self.connection.removefile(self) if not self.connection.exists(self): raise FileDoesNotExistError(str(self)) if self.connection.isdir(self): if recursive: return remove_dir_recursively(self.connection, self) else: return self.connection.removedir(self) elif self.connection.isfile(self): return self.connection.removefile(self) @with_connection def open(self, options=None, mimetype='application/octet-stream'): """ open: return a file like object for self. The method can be used with the 'with' statment. """ return self.connection.open(self, options, mimetype) @with_connection def makedirs(self): """ makedirs: recursivly create directory if it doesn't exist yet. """ return self.connection.makedirs(self) @with_connection def mkdir(self): """ mkdir: create directory self. The semantic will be the same than os.mkdir. """ return self.connection.mkdir(self) @with_connection def exists(self): """ exists: @rtype: bool @return: True is path exists on target system, else False """ return self.connection.exists(self) @with_connection def isfile(self): """ isfile: @rtype: bool @return: True is path is a file on target system, else False """ return self.connection.isfile(self) @with_connection def isdir(self): """ isdir: @rtype: bool @return: True is path is a directory on target system, else False """ return self.connection.isdir(self) @with_connection def isexec(self, mode=stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH): """ isexec: @rtype: bool @return: Indicates whether the path points to a file or folder which has the executable flag set. Note that on systems which do not support executables flags the result may be unpredicatable. On Windows the value is determined by the file extension, a *.exe file is executable, a *.sh not. """ return self.connection.isexec(self, mode) @with_connection def set_exec(self, mode): """ set_exec: @rtype: void @return: Set the executable flag of the receiver to mode (which can be any combination of stat.IXUSR, stat.IXGRP, or stat.IXOTH). Note that on systems which do not support executables flags the function may have no effect. """ return self.connection.set_exec(self, mode) @with_connection def islink(self): """ islink: @rtype: bool @return: Indicates whether the file this path is pointing to is a symlink. On systems which don't support symlinks this return alsways False. """ return self.connection.islink(self) @with_connection def readlink(self): """ readlink: @rtype: URI @return: the content of the symlink this path is pointing to. Throws an exception if this path is not a symlink (check with islink before) On systems which don't support symlinks this will always throw. """ return self.connection.readlink(self) @with_connection def symlink(self, link_name): """ symlink: @rtype: void Creates a symbolic link named link_name to the file this path is pointing to. On systems which don't support symlinks this will throw. """ return self.connection.symlink(self, link_name) @with_connection def mtime(self): """ mtime: @rtype: float @return: the last time of modification is seconds since the epoch. """ return self.connection.mtime(self) @with_connection def walk(self, topdown=True, followlinks=True): """ walk: walk the filesystem (just like os.walk). Use like: path = URI('/some/dir') for root, dirs, files in path.walk(): do_something() root will be an URI object. """ return self.connection.walk(self, topdown=topdown, followlinks=followlinks) @with_connection def listdir(self): """ listdir: list contents of directory self. The pathpart of 'self' will not be returned. """ return self.connection.listdir(self) @with_connection def info(self, set_info=None, followlinks=True): """ info: backend info about self (probably not implemented for all backends. The result will be backend specific). @param set_info: If not None, this data will be set on self. @param followlinks: If True, symlinks will be followed. If False, the info of the symlink itself will be returned. (Default: True) @rtype: Bunch @return: backend specific information about self. """ return self.connection.info(self, set_info=set_info, followlinks=followlinks) @with_connection def sync(self, other, options=''): return self.connection.sync(self, other, options) @with_connection def glob(self, pattern): return self.connection.glob(self, pattern) @with_connection def md5(self): """ Returns the md5-sum of this file. This is of course potentially expensive! """ hash_ = hashlib.md5() with self.open("rb") as inf: block = inf.read(4096) while block: hash_.update(block) block = inf.read(4096) return hash_.hexdigest() @with_connection def lock(self, fail_on_lock=False, cleanup=False): """ Allows to lock a file via abl.util.LockFile, with the same parameters there. Returns an opened, writable file. """ return self.connection.lock(self, fail_on_lock, cleanup) @with_connection def _manipulate(self, *args, **kwargs): """ This is a semi-private method. It's current use is to manipulate memory file system objects so that you can create certain conditions, to provoke errors that otherwise won't occur. """ self.connection._manipulate(self, *args, **kwargs)
class BaseUri(object): '''An URI object represents a path, either on the local filesystem or on a remote server. On creation, the path is represented by an (more or less conform) uri like 'file:///some/local/file' or 'ssh://server:/remote/file'. The well kwown 'os'/'os.path' interface is used. Internally, the path separator is always '/'. The path property will return the url with the path separator that is given with 'sep' which defaults to 'os.sep'. The 'join' (as in os.path.join) can be used with the operator '/' which leads to more readable code. ''' def __init__(self, uri, sep=os.sep, **extras): pass def get_connection(self): pass def _extras(self): pass def _get_scheme(self): pass def _set_scheme(self, scheme): pass @property def port(self): pass @property def path(self): pass @property def unipath(self): pass def _key(self): pass def __str__(self): pass def __repr__(self): pass def __getattr__(self, attr): pass def __eq__(self, other): pass def __ne__(self, other): pass def __div__(self, other): pass def __truediv__(self, other): pass def __add__(self, suffix): pass @property def is_absolute(self): pass def split(self): ''' split: like os.path.split @rtype: tuple(URI, str) @return: a 2 tuple. The first element is a URI instance and the second a string, representing the basename. ''' pass def directory(self, level=1): ''' @return: the first part of the split method ''' pass def basename(self): ''' @return: the second part of the split method ''' pass def splitext(self): pass def last(self): ''' last: similar to 'basename', but makes sure that the last part is really returned. example: URI('/some/dir/').basename() will return '' while URI('/some/dir/').last() will return 'dir'. @return: last part of uri @rvalue: str ''' pass def join(self, *args): ''' join: join paths parts together to represent a path. @return: URI instance of joined path @rtype: URI ''' pass @with_connection def copy(self, other, recursive=False, ignore=None, followlinks=True): ''' copy: copy self to other @type other: URI @param other: the path to copy itself over. What will really happen depends on the backend. Note that file properties are only copied when self and other are located in the same backend, i.e. it is not possible to copy permissions etc. from a memory:// to a file:// based path. ''' pass @with_connection def copystat(self, other): ''' copystat: copy file/folder metadata from self to other @type other: URI @param other: the path to copy the metadata to. Will copy file permissions, mtime, atime, etc. to path. Note: this ALWAYS follows symlinks. Consider using info with followslinks set to False to read and write the stat info of a symlink. ''' pass @with_connection def move(self, other): ''' move: move self to other @type other: URI @param other: the path to copy itself over. What will really happen depends on the backend. ''' pass @with_connection def remove(self, recursive=False): ''' remove: shortcut method to remove self. if 'self' represents a file, the backends 'removefile' method id used. if 'self' represents a directory, it will recursivly removed, if the options string contains 'r'. Otherwise, the backends 'removedir' method is used. ''' pass @with_connection def open(self, options=None, mimetype='application/octet-stream'): ''' open: return a file like object for self. The method can be used with the 'with' statment. ''' pass @with_connection def makedirs(self): ''' makedirs: recursivly create directory if it doesn't exist yet. ''' pass @with_connection def mkdir(self): ''' mkdir: create directory self. The semantic will be the same than os.mkdir. ''' pass @with_connection def exists(self): ''' exists: @rtype: bool @return: True is path exists on target system, else False ''' pass @with_connection def isfile(self): ''' isfile: @rtype: bool @return: True is path is a file on target system, else False ''' pass @with_connection def isdir(self): ''' isdir: @rtype: bool @return: True is path is a directory on target system, else False ''' pass @with_connection def isexec(self, mode=stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH): ''' isexec: @rtype: bool @return: Indicates whether the path points to a file or folder which has the executable flag set. Note that on systems which do not support executables flags the result may be unpredicatable. On Windows the value is determined by the file extension, a *.exe file is executable, a *.sh not. ''' pass @with_connection def set_exec(self, mode): ''' set_exec: @rtype: void @return: Set the executable flag of the receiver to mode (which can be any combination of stat.IXUSR, stat.IXGRP, or stat.IXOTH). Note that on systems which do not support executables flags the function may have no effect. ''' pass @with_connection def islink(self): ''' islink: @rtype: bool @return: Indicates whether the file this path is pointing to is a symlink. On systems which don't support symlinks this return alsways False. ''' pass @with_connection def readlink(self): ''' readlink: @rtype: URI @return: the content of the symlink this path is pointing to. Throws an exception if this path is not a symlink (check with islink before) On systems which don't support symlinks this will always throw. ''' pass @with_connection def symlink(self, link_name): ''' symlink: @rtype: void Creates a symbolic link named link_name to the file this path is pointing to. On systems which don't support symlinks this will throw. ''' pass @with_connection def mtime(self): ''' mtime: @rtype: float @return: the last time of modification is seconds since the epoch. ''' pass @with_connection def walk(self, topdown=True, followlinks=True): ''' walk: walk the filesystem (just like os.walk). Use like: path = URI('/some/dir') for root, dirs, files in path.walk(): do_something() root will be an URI object. ''' pass @with_connection def listdir(self): ''' listdir: list contents of directory self. The pathpart of 'self' will not be returned. ''' pass @with_connection def info(self, set_info=None, followlinks=True): ''' info: backend info about self (probably not implemented for all backends. The result will be backend specific). @param set_info: If not None, this data will be set on self. @param followlinks: If True, symlinks will be followed. If False, the info of the symlink itself will be returned. (Default: True) @rtype: Bunch @return: backend specific information about self. ''' pass @with_connection def sync(self, other, options=''): pass @with_connection def glob(self, pattern): pass @with_connection def md5(self): ''' Returns the md5-sum of this file. This is of course potentially expensive! ''' pass @with_connection def lock(self, fail_on_lock=False, cleanup=False): ''' Allows to lock a file via abl.util.LockFile, with the same parameters there. Returns an opened, writable file. ''' pass @with_connection def _manipulate(self, *args, **kwargs): ''' This is a semi-private method. It's current use is to manipulate memory file system objects so that you can create certain conditions, to provoke errors that otherwise won't occur. ''' pass
77
28
9
1
5
3
2
0.68
1
4
2
4
48
8
48
48
571
138
258
105
180
175
192
75
143
11
1
2
80
2,827
AbletonAG/abl.vpath
AbletonAG_abl.vpath/abl/vpath/base/exceptions.py
abl.vpath.base.exceptions.WrongSchemeError
class WrongSchemeError(PathError): "WrongSchemeError is raised if functionality requires specific schemes"
class WrongSchemeError(PathError): '''WrongSchemeError is raised if functionality requires specific schemes''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
10
2
0
1
1
0
1
1
1
0
0
4
0
0
2,828
AbletonAG/abl.vpath
AbletonAG_abl.vpath/abl/vpath/base/exceptions.py
abl.vpath.base.exceptions.RemoteConnectionTimeout
class RemoteConnectionTimeout(PathError): "Remote connection could not be established"
class RemoteConnectionTimeout(PathError): '''Remote connection could not be established''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
10
2
0
1
1
0
1
1
1
0
0
4
0
0
2,829
AbletonAG/abl.vpath
AbletonAG_abl.vpath/abl/vpath/base/exceptions.py
abl.vpath.base.exceptions.PathError
class PathError(Exception): "PathError: base exception for path module."
class PathError(Exception): '''PathError: base exception for path module.''' pass
1
1
0
0
0
0
0
1
1
0
0
7
0
0
0
10
2
0
1
1
0
1
1
1
0
0
3
0
0
2,830
AbletonAG/abl.vpath
AbletonAG_abl.vpath/abl/vpath/base/exceptions.py
abl.vpath.base.exceptions.OptionsError
class OptionsError(PathError): "OptionsError is raised if specific options need to be used"
class OptionsError(PathError): '''OptionsError is raised if specific options need to be used''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
10
2
0
1
1
0
1
1
1
0
0
4
0
0
2,831
AbletonAG/abl.vpath
AbletonAG_abl.vpath/abl/vpath/base/exceptions.py
abl.vpath.base.exceptions.OperationIsNotSupportedOnPlatform
class OperationIsNotSupportedOnPlatform(PathError): "This operation is not supported on this platform"
class OperationIsNotSupportedOnPlatform(PathError): '''This operation is not supported on this platform''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
10
2
0
1
1
0
1
1
1
0
0
4
0
0
2,832
AbletonAG/abl.vpath
AbletonAG_abl.vpath/tests/test_path.py
tests.test_path.TestHttpUri
class TestHttpUri(TestCase): def test_query(self): p = URI('http://storm/this') p.query['a'] = 'b' self.assertEqual(URI(str(p)), URI('http://storm/this?a=b')) def test_query_after_join(self): p = URI('http://storm/this') p /= 'other' self.assertEqual(URI(str(p)), URI('http://storm/this/other')) p.query['a'] = 'b' self.assertEqual(URI(str(p)), URI('http://storm/this/other?a=b'))
class TestHttpUri(TestCase): def test_query(self): pass def test_query_after_join(self): pass
3
0
5
0
5
0
1
0
1
1
0
0
2
0
2
74
13
2
11
5
8
0
11
5
8
1
2
0
2
2,833
AbletonAG/abl.vpath
AbletonAG_abl.vpath/abl/vpath/base/exceptions.py
abl.vpath.base.exceptions.NoSchemeError
class NoSchemeError(PathError): "NoSchemeError is raised if scheme is used that has no backend"
class NoSchemeError(PathError): '''NoSchemeError is raised if scheme is used that has no backend''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
10
2
0
1
1
0
1
1
1
0
0
4
0
0
2,834
AbletonAG/abl.vpath
AbletonAG_abl.vpath/abl/vpath/base/exceptions.py
abl.vpath.base.exceptions.NoDefinedOperationError
class NoDefinedOperationError(PathError): "NoDefinedOperationError is raised if method is not supported by backend"
class NoDefinedOperationError(PathError): '''NoDefinedOperationError is raised if method is not supported by backend''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
10
2
0
1
1
0
1
1
1
0
0
4
0
0
2,835
AbletonAG/abl.vpath
AbletonAG_abl.vpath/abl/vpath/base/exceptions.py
abl.vpath.base.exceptions.FileDoesNotExistError
class FileDoesNotExistError(PathError): "FileDoesNotExistError is raised, if resource does not exist"
class FileDoesNotExistError(PathError): '''FileDoesNotExistError is raised, if resource does not exist''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
10
2
0
1
1
0
1
1
1
0
0
4
0
0
2,836
AbletonAG/abl.vpath
AbletonAG_abl.vpath/abl/vpath/base/localfs.py
abl.vpath.base.localfs.LocalFileSystemUri
class LocalFileSystemUri(BaseUri): def __str__(self): return self.path @property def path(self): path = self.parse_result.path if self.sep != '/': return denormalize_path(path, self.sep) else: return super(LocalFileSystemUri, self).path
class LocalFileSystemUri(BaseUri): def __str__(self): pass @property def path(self): pass
4
0
4
0
4
0
2
0
1
1
0
0
2
0
2
50
11
1
10
5
6
0
8
4
5
2
2
1
3
2,837
AbletonAG/abl.vpath
AbletonAG_abl.vpath/abl/vpath/base/misc.py
abl.vpath.base.misc.TempFileHandle
class TempFileHandle(object): """ TempFileHandle -------------- remove the (temp) file after closing the handle. This is used in the following situation: 1. place some content into temp file 2. read the content once """ def __init__(self, tmpfilename): self.tmpfilename = tmpfilename self.handle = open(self.tmpfilename) def __enter__(self): return self def __exit__(self, exc_type, exc_value, tb): self.close() def read(self, limit=-1): return self.handle.read(limit) def close(self): retval = self.handle.close() os.unlink(self.tmpfilename) return retval
class TempFileHandle(object): ''' TempFileHandle -------------- remove the (temp) file after closing the handle. This is used in the following situation: 1. place some content into temp file 2. read the content once ''' def __init__(self, tmpfilename): pass def __enter__(self): pass def __exit__(self, exc_type, exc_value, tb): pass def read(self, limit=-1): pass def close(self): pass
6
1
3
0
3
0
1
0.57
1
0
0
0
5
2
5
5
27
5
14
9
8
8
14
9
8
1
1
0
5
2,838
AbletonAG/abl.vpath
AbletonAG_abl.vpath/abl/vpath/base/memory.py
abl.vpath.base.memory.NodeKind
class NodeKind(object): FILE = 0 DIR = 1 LINK = 2
class NodeKind(object): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
4
0
4
4
3
0
4
4
3
0
1
0
0
2,839
AbletonAG/abl.vpath
AbletonAG_abl.vpath/abl/vpath/base/uriparse.py
abl.vpath.base.uriparse.ImapsURLParser
class ImapsURLParser(URLParser): """Internal class to hold the defaults of IMAPS URLs""" _defaults=(None, None, 'localhost', 993, '/', None, None)
class ImapsURLParser(URLParser): '''Internal class to hold the defaults of IMAPS URLs'''
1
1
0
0
0
0
0
0.5
1
0
0
0
0
0
0
3
3
0
2
2
1
1
2
2
1
0
1
0
0
2,840
AbletonAG/abl.vpath
AbletonAG_abl.vpath/abl/vpath/base/memory.py
abl.vpath.base.memory.MemorySymlink
class MemorySymlink(object): kind = NodeKind.LINK def __init__(self, target): self.target = target self.mtime = self.ctime = time.time() self.mode = 0 def size(self): return 8
class MemorySymlink(object): def __init__(self, target): pass def size(self): pass
3
0
3
0
3
0
1
0
1
0
0
0
2
4
2
2
10
2
8
7
5
0
8
7
5
1
1
0
2
2,841
AbletonAG/abl.vpath
AbletonAG_abl.vpath/abl/vpath/base/memory.py
abl.vpath.base.memory.MemoryLock
class MemoryLock(object): def __init__(self, fs, path, fail_on_lock, cleanup): self.fs = fs self.path = path self.fail_on_lock = fail_on_lock self.cleanup = cleanup self.lock = None def __enter__(self): mfile = self.fs.open(self.path, "w", mimetype='application/octet-stream') self.lock = mfile.lock if self.fail_on_lock: if not self.lock.acquire(False): raise LockFileObtainException else: self.lock.acquire() return mfile def __exit__(self, unused_exc_type, unused_exc_val, unused_exc_tb): self.lock.release() if self.cleanup: self.path.remove()
class MemoryLock(object): def __init__(self, fs, path, fail_on_lock, cleanup): pass def __enter__(self): pass def __exit__(self, unused_exc_type, unused_exc_val, unused_exc_tb): pass
4
0
6
0
6
0
2
0
1
0
0
0
3
5
3
3
25
5
20
10
16
0
19
10
15
3
1
2
6
2,842
AbletonAG/abl.vpath
AbletonAG_abl.vpath/abl/vpath/base/memory.py
abl.vpath.base.memory.MemoryFileSystemUri
class MemoryFileSystemUri(BaseUri): def __init__(self, *args, **kwargs): super(MemoryFileSystemUri, self).__init__(*args, **kwargs) self._next_op_callback = None
class MemoryFileSystemUri(BaseUri): def __init__(self, *args, **kwargs): pass
2
0
3
0
3
0
1
0
1
1
0
0
1
1
1
49
5
1
4
3
2
0
4
3
2
1
2
0
1
2,843
AbletonAG/abl.vpath
AbletonAG_abl.vpath/abl/vpath/base/memory.py
abl.vpath.base.memory.MemoryFileSystem
class MemoryFileSystem(FileSystem): scheme = 'memory' uri = MemoryFileSystemUri def _initialize(self): assert not self.hostname, "The memory schema only allows 'memory:///' as root path" self.lookup_exc_class = OSError self._fs = MemoryDir() self.next_op_callbacks = {} MemoryFile.FILE_LOCKS.clear() def _child(self, parent, name, resolve_link=True, throw=True, linklevel=0): if parent.has(name): nd = parent.get(name) if nd.kind == NodeKind.LINK: if resolve_link: # TODO: supports absolute links only for now if linklevel >= 32: raise self.lookup_exc_class(errno.ELOOP, "Too many symbolic links encountered") nd = self._get_node_for_path(self._fs, nd.target, throw=throw, linklevel=linklevel + 1) if nd is None: return None assert nd.kind != NodeKind.LINK return nd return None def _create_child(self, parent, name, obj): parent.create(name, obj) def _del_child(self, parent, name): parent.remove(name) def _get_node_prev(self, base, steps, follow_link=True, throw=True, linklevel=0): prev = None current = base for part in steps: prev = current if current.has(part): is_last = part == steps[-1] current = self._child(current, part, resolve_link=follow_link if is_last else True, throw=throw, linklevel=linklevel) else: if throw: p = '/'.join(steps) raise self.lookup_exc_class(errno.ENOENT, "No such file or directory: %s" % p) else: return [None, None] return [prev, current] def _get_node(self, base, steps, follow_link=True, throw=True, linklevel=0): _, current = self._get_node_prev(base, steps, follow_link=follow_link, throw=throw, linklevel=linklevel) return current def _get_node_for_path(self, base, unc, follow_link=True, throw=True, linklevel=0): p = self._path(unc) if p: return self._get_node(base, p.split("/"), follow_link=follow_link, throw=throw, linklevel=linklevel) else: return base def _path(self, path): p = super(MemoryFileSystem, self)._path(path) # cut off leading slash, that's our root assert p.startswith("/") p = p[1:] return p def isdir(self, path): if self._path(path): try: nd = self._get_node_for_path(self._fs, path, throw=False) if nd is None: return False return nd.kind == NodeKind.DIR except OSError as e: if e.errno == errno.ELOOP: return False # the root always exists and is always a dir return True def isfile(self, path): if self._path(path): try: nd = self._get_node_for_path(self._fs, path, throw=False) if nd is None: return False return nd.kind == NodeKind.FILE except OSError as e: if e.errno == errno.ELOOP: return False return False def isexec(self, path, mode_mask): return self.info(path).mode & mode_mask != 0 def set_exec(self, path, mode): mask = stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH new_mode = (self.info(path).mode & ~mask) | mode self.info(path, dict(mode=new_mode)) def mkdir(self, path): p = self._path(path) if p: nd = self._get_node(self._fs, p.split("/")[:-1]) dir_to_create = p.split("/")[-1] if nd.has(dir_to_create): raise OSError(errno.EEXIST, "File exists: %r" % str(path)) self._create_child(nd, dir_to_create, MemoryDir()) def exists(self, path): if self._path(path): try: nd = self._get_node_for_path(self._fs, path, throw=False) if nd is None: return False except OSError as e: if e.errno == errno.ELOOP: return False # the root always exists return True def pre_call_hook(self, path, func): p = self._path(path) if p in self.next_op_callbacks and self.next_op_callbacks[p] is not None: self.next_op_callbacks[p](path, func) def _open_for_read(self, path, binary=False): nd = self._get_node_for_path(self._fs, path) nd.seek(0) return MemoryFileProxy(nd, True, binary=binary) def _open_for_write(self, path, binary=False): p = self._path(path) nd = self._get_node(self._fs, p.split("/")[:-1]) file_to_create = p.split("/")[-1] if nd.has(file_to_create): cnd = self._child(nd, file_to_create) if cnd is not None and cnd.kind == NodeKind.DIR: raise IOError(errno.EISDIR, "File is directory" ) cnd.reset() return MemoryFileProxy(cnd, False, binary=binary) else: f = MemoryFile(p) self._create_child(nd, file_to_create, f) return MemoryFileProxy(f, False, binary=binary) def _open_for_append(self, path, binary=False): nd = self._get_node_for_path(self._fs, path) nd.seek(len(nd)) return MemoryFileProxy(nd, False, binary=binary) def open(self, path, options, mimetype): with LookupExceptionClass(self, IOError): binary = (options and "b" in options) if options is None or "r" in options: return self._open_for_read(path, binary=binary) elif "w" in options: return self._open_for_write(path, binary=binary) elif "a" in options: return self._open_for_append(path, binary=binary) else: raise OSError(errno.EINVAL, "The mode flag is not valid") BINARY_MIME_TYPES = ["image/png", "image/gif", ] def dump(self, outf, no_binary=False): def traverse(current, path="memory:///"): for name, value in sorted(current.items()): if value.kind == NodeKind.FILE: if no_binary: mt, _ = mimetypes.guess_type(name) if mt in self.BINARY_MIME_TYPES: hash_ = hashlib.md5() hash_.update(value) value = "Binary: %s" % hash_.hexdigest() proxy = MemoryFileProxy(value, readable=True, binary=False) outf.write("--- START %s%s ---\n" % (path, name)) outf.write(proxy.read()) outf.write("\n--- END ---\n\n") elif value.kind == NodeKind.LINK: outf.write("LINK: %s%s -> %s\n" % (path, name, value.target)) else: outf.write("DIR: %s%s\n" % (path, name)) traverse(value, (path[:-1] if path.endswith("/") else path) + "/" + name + "/") outf.write("MEMORY DUMP: START\n") traverse(self._fs) outf.write("MEMORY DUMP: END\n") def info(self, unc, set_info=None, followlinks=True): current = self._get_node_for_path(self._fs, unc, follow_link=followlinks) if set_info is not None: if "mode" in set_info: current.mode = set_info["mode"] if "mtime" in set_info: current.mtime = set_info["mtime"] return return Bunch(mtime=current.mtime, mode=current.mode, size=current.size()) def copystat(self, src, dest): src_current = self._get_node_for_path(self._fs, src) dest_current = self._get_node_for_path(self._fs, dest) dest_current.mtime = src_current.mtime dest_current.mode = src_current.mode def listdir(self, path): nd = self._get_node(self._fs, [x for x in self._path(path).split("/") if x]) return sorted(nd.keys()) def mtime(self, path): return self._get_node_for_path(self._fs, path).mtime def removefile(self, path): parent, _ = self._get_node_prev(self._fs, [x for x in self._path(path).split("/") if x], follow_link=False) if parent is not None: self._del_child(parent, path.last()) def removedir(self, path): prev, _ = self._get_node_prev(self._fs, [x for x in self._path(path).split("/") if x]) if prev is not None: part = path.last() if self._child(prev, part).isempty(): self._del_child(prev, part) else: raise OSError(errno.ENOTEMPTY, "Directory not empty: %r" % path) def lock(self, path, fail_on_lock, cleanup): return MemoryLock(self, path, fail_on_lock, cleanup) SENTINEL = object() def _manipulate(self, path, lock=SENTINEL, unlock=SENTINEL, mtime=SENTINEL, next_op_callback=SENTINEL): if lock is not self.SENTINEL and lock: p = self._path(path) lock = MemoryFile(p).lock res = lock.acquire() assert res, "you tried to double-lock a file, that's currently not supported" if unlock is not self.SENTINEL and unlock: p = self._path(path) lock = MemoryFile(p).lock lock.release() if mtime is not self.SENTINEL: nd = self._get_node_for_path(self._fs, path) nd.mtime = mtime if next_op_callback is not self.SENTINEL: p = self._path(path) self.next_op_callbacks[p] = next_op_callback def supports_symlinks(self): return True def islink(self, path): if self._path(path): nd = self._get_node_for_path(self._fs, path, follow_link=False, throw=False) if nd is None: return False return nd.kind == NodeKind.LINK return False def symlink(self, target, link_name): p = self._path(link_name) if p: nd = self._get_node(self._fs, p.split("/")[:-1]) file_to_create = p.split("/")[-1] if nd.has(file_to_create): raise OSError(errno.EEXIST, "File exists: %r" % str(link_name)) self._create_child(nd, file_to_create, MemorySymlink(target)) def readlink(self, path): if self._path(path): nd = self._get_node_for_path(self._fs, path, follow_link=False) if nd.kind == NodeKind.LINK: return nd.target raise OSError(errno.EINVAL, "Not a link")
class MemoryFileSystem(FileSystem): def _initialize(self): pass def _child(self, parent, name, resolve_link=True, throw=True, linklevel=0): pass def _create_child(self, parent, name, obj): pass def _del_child(self, parent, name): pass def _get_node_prev(self, base, steps, follow_link=True, throw=True, linklevel=0): pass def _get_node_prev(self, base, steps, follow_link=True, throw=True, linklevel=0): pass def _get_node_for_path(self, base, unc, follow_link=True, throw=True, linklevel=0): pass def _path(self, path): pass def isdir(self, path): pass def isfile(self, path): pass def isexec(self, path, mode_mask): pass def set_exec(self, path, mode): pass def mkdir(self, path): pass def exists(self, path): pass def pre_call_hook(self, path, func): pass def _open_for_read(self, path, binary=False): pass def _open_for_write(self, path, binary=False): pass def _open_for_append(self, path, binary=False): pass def open(self, path, options, mimetype): pass def dump(self, outf, no_binary=False): pass def traverse(current, path="memory:///"): pass def info(self, unc, set_info=None, followlinks=True): pass def copystat(self, src, dest): pass def listdir(self, path): pass def mtime(self, path): pass def removefile(self, path): pass def removedir(self, path): pass def lock(self, path, fail_on_lock, cleanup): pass def _manipulate(self, path, lock=SENTINEL, unlock=SENTINEL, mtime=SENTINEL, next_op_callback=SENTINEL): pass def supports_symlinks(self): pass def islink(self, path): pass def symlink(self, target, link_name): pass def readlink(self, path): pass
34
0
8
0
8
0
3
0.02
1
11
7
0
32
3
32
61
330
71
255
92
218
4
224
86
190
7
2
4
85
2,844
AbletonAG/abl.vpath
AbletonAG_abl.vpath/abl/vpath/base/memory.py
abl.vpath.base.memory.MemoryFileProxy
class MemoryFileProxy(object): def __init__(self, mem_file, readable, binary=False): self.mem_file = mem_file self.readable = readable self.binary = binary def encode(self, data): return data if self.binary or isinstance(data, bytes) else data.encode("utf-8") def decode(self, data): return data if self.binary else data.decode('utf-8') def read(self, *args, **kwargs): if not self.readable: raise IOError(errno.EBADF, "bad file descriptor") return self.decode(self.mem_file.read(*args, **kwargs)) def write(self, data, *args, **kwargs): return self.mem_file.write(self.encode(data), *args, **kwargs) def __getattr__(self, name): return getattr(self.mem_file, name) def __enter__(self): return self def __exit__(self, *args): pass def __iter__(self): return self def __next__(self): return self.decode(next(self.mem_file)) next = __next__ # Python 2 iterator interface def readline(self): return self.decode(self.mem_file.readline()) def readlines(self): for line in self.mem_file.readlines(): yield self.decode(line)
class MemoryFileProxy(object): def __init__(self, mem_file, readable, binary=False): pass def encode(self, data): pass def decode(self, data): pass def read(self, *args, **kwargs): pass def write(self, data, *args, **kwargs): pass def __getattr__(self, name): pass def __enter__(self): pass def __exit__(self, *args): pass def __iter__(self): pass def __next__(self): pass def readline(self): pass def readlines(self): pass
13
0
3
0
2
0
1
0.03
1
1
0
0
12
3
12
12
56
25
31
17
18
1
31
17
18
2
1
1
16
2,845
AbletonAG/abl.vpath
AbletonAG_abl.vpath/abl/vpath/base/memory.py
abl.vpath.base.memory.MemoryFile
class MemoryFile(object): kind = NodeKind.FILE FILE_LOCKS = defaultdict(threading.Lock) def __init__(self, path): self.path = path self._data = BytesIO() self._line_reader = None self.mtime = self.ctime = time.time() self.mode = 0 self.lock = self.FILE_LOCKS[self.path] def reset(self): self._data = BytesIO() self._line_reader = None self.mtime = self.ctime = time.time() self.mode = 0 self.lock = self.FILE_LOCKS[self.path] def __len__(self): pos = self._data.tell() self._data.seek(-1,2) length = self._data.tell() + 1 self._data.seek(pos) return length def size(self): return len(self._data.getvalue()) def write(self, d): self._data.write(d) self.mtime = time.time() def read(self, size=-1): return self._data.read(size) def seek(self, to, whence=0): self._data.seek(to, whence) def seekable(self): return self._data.seekable() def tell(self): return self._data.tell() def flush(self): return self._data.flush() def truncate(self, pos=None): return self._data.truncate(pos) def seekable(self): return self._data.seekable() def __unicode__(self): return self._data.getvalue().decode('utf-8') def __bytes__(self): return self._data.getvalue() def __str__(self): return str(self._data.getvalue()) def close(self): self._line_reader = None self._data.seek(0) def readline(self): return self._data.readline() def readlines(self): for line in self: yield line def __next__(self): line = self.readline() if line: return line else: raise StopIteration next = __next__ # Python 2 iterator interface def __iter__(self): return self def items(self): return []
class MemoryFile(object): def __init__(self, path): pass def reset(self): pass def __len__(self): pass def size(self): pass def write(self, d): pass def read(self, size=-1): pass def seek(self, to, whence=0): pass def seekable(self): pass def tell(self): pass def flush(self): pass def truncate(self, pos=None): pass def seekable(self): pass def __unicode__(self): pass def __bytes__(self): pass def __str__(self): pass def close(self): pass def readline(self): pass def readlines(self): pass def __next__(self): pass def __iter__(self): pass def items(self): pass
22
0
3
0
3
0
1
0.02
1
2
0
0
21
7
21
21
111
45
66
34
44
1
65
34
43
2
1
1
23
2,846
AbletonAG/abl.vpath
AbletonAG_abl.vpath/abl/vpath/base/memory.py
abl.vpath.base.memory.MemoryDir
class MemoryDir(object): kind = NodeKind.DIR def __init__(self): self._files = {} self.mtime = self.ctime = time.time() self.mode = 0 def size(self): return 0 def items(self): return list(self._files.items()) def keys(self): return list(self._files.keys()) def has(self, name): return name in self._files def get(self, name): return self._files[name] def create(self, name, obj): self._files[name] = obj def remove(self, name): del self._files[name] def isempty(self): return len(self._files) == 0
class MemoryDir(object): def __init__(self): pass def size(self): pass def items(self): pass def keys(self): pass def has(self, name): pass def get(self, name): pass def create(self, name, obj): pass def remove(self, name): pass def isempty(self): pass
10
0
2
0
2
0
1
0
1
1
0
0
9
4
9
9
40
18
22
14
12
0
22
14
12
1
1
0
9
2,847
AbletonAG/abl.vpath
AbletonAG_abl.vpath/abl/vpath/base/misc.py
abl.vpath.base.misc.WorkingDirectory
class WorkingDirectory(object): def __init__(self, working_path): self.cwd = os.getcwd() self.working_path = working_path def __enter__(self): os.chdir(self.working_path.path) def __exit__(self, exc_type, exc_value, traceback): os.chdir(self.cwd)
class WorkingDirectory(object): def __init__(self, working_path): pass def __enter__(self): pass def __exit__(self, exc_type, exc_value, traceback): pass
4
0
2
0
2
0
1
0
1
0
0
0
3
2
3
3
11
3
8
6
4
0
8
6
4
1
1
0
3
2,848
AbletonAG/abl.vpath
AbletonAG_abl.vpath/abl/vpath/base/uriparse.py
abl.vpath.base.uriparse.DefaultURIParser
class DefaultURIParser(URLParser): """Internal class to hold the defaults of generic URIs""" _defaults=(None, None, None, None, '/', None, None)
class DefaultURIParser(URLParser): '''Internal class to hold the defaults of generic URIs'''
1
1
0
0
0
0
0
0.5
1
0
0
0
0
0
0
3
3
0
2
2
1
1
2
2
1
0
1
0
0
2,849
AbletonAG/abl.vpath
AbletonAG_abl.vpath/abl/vpath/base/uriparse.py
abl.vpath.base.uriparse.FileURLParser
class FileURLParser(URLParser): """Internal class to hold the defaults of file URLs""" _defaults=(None, None, None, None, '/', None, None)
class FileURLParser(URLParser): '''Internal class to hold the defaults of file URLs'''
1
1
0
0
0
0
0
0.5
1
0
0
0
0
0
0
3
3
0
2
2
1
1
2
2
1
0
1
0
0
2,850
AbletonAG/abl.vpath
AbletonAG_abl.vpath/abl/vpath/base/uriparse.py
abl.vpath.base.uriparse.FtpURLParser
class FtpURLParser(URLParser): """Internal class to hold the defaults of FTP URLs""" _defaults=('anonymous', 'anonymous', None, 21, '/', None, None)
class FtpURLParser(URLParser): '''Internal class to hold the defaults of FTP URLs'''
1
1
0
0
0
0
0
0.5
1
0
0
0
0
0
0
3
3
0
2
2
1
1
2
2
1
0
1
0
0
2,851
AbletonAG/abl.vpath
AbletonAG_abl.vpath/abl/vpath/base/uriparse.py
abl.vpath.base.uriparse.HttpURLParser
class HttpURLParser(URLParser): """Internal class to hold the defaults of HTTP URLs""" _defaults=(None, None, None, 80, '/', None, None)
class HttpURLParser(URLParser): '''Internal class to hold the defaults of HTTP URLs'''
1
1
0
0
0
0
0
0.5
1
0
0
2
0
0
0
3
3
0
2
2
1
1
2
2
1
0
1
0
0
2,852
AbletonAG/abl.vpath
AbletonAG_abl.vpath/abl/vpath/base/uriparse.py
abl.vpath.base.uriparse.HttpsURLParser
class HttpsURLParser(HttpURLParser): """Internal class to hold the defaults of HTTPS URLs""" _defaults=(None, None, None, 443, '/', None, None)
class HttpsURLParser(HttpURLParser): '''Internal class to hold the defaults of HTTPS URLs'''
1
1
0
0
0
0
0
0.5
1
0
0
0
0
0
0
3
3
0
2
2
1
1
2
2
1
0
2
0
0
2,853
AbletonAG/abl.vpath
AbletonAG_abl.vpath/abl/vpath/base/uriparse.py
abl.vpath.base.uriparse.ImapURLParser
class ImapURLParser(URLParser): """Internal class to hold the defaults of IMAP URLs""" _defaults=(None, None, 'localhost', 143, '/', None, None)
class ImapURLParser(URLParser): '''Internal class to hold the defaults of IMAP URLs'''
1
1
0
0
0
0
0
0.5
1
0
0
0
0
0
0
3
3
0
2
2
1
1
2
2
1
0
1
0
0
2,854
AbletonAG/abl.vpath
AbletonAG_abl.vpath/abl/vpath/base/simpleuri.py
abl.vpath.base.simpleuri.UriParse
class UriParse(object): """ UriParse is a simplistic replacement for urlparse, in case the uri in question is not a http url. """ def __init__(self, uri=''): """ starts to get complicated: ouchh... we want to have support for http urls in the following way: 1. after url creation, the query key, value pairs need to be set and need to show up when using the 'str' function on the url: >>> url = UriParse('http://host/some/path') >>> url.query['key1] = 'value1' >>> str(url) == 'http://host/some/path?key1=value1' True 2. absolute urls like 'http:///some/absolute/path' should work: >>> url = UriParse('http:///absolute/path') >>> str(url) == '/absolute/path' True 3. relative urls like 'http://./some/relative/path should work: >>> url = UriParse('http://./relative/path') >>> str(url) == 'relative/path' True """ self.uri = uri self.hostname = self.username = self.password = '' self.netloc = '' self.port = 0 self.query = {} self.scheme = '' self.path = '' self.authority = '' self.vpath_connector = '' self.fragment = '' if not '://' in uri: self.uri = 'file://'+uri ( self.scheme, self.authority, self.path, self.query, self.fragment ) = urisplit(uri) if self.authority and '((' in self.authority: self.vpath_connector = self.authority[2:-2] self.authority = '' if self.authority: ( self.username, self.password, self.hostname, self.port, ) = split_authority(self.authority) self.port = int(self.port or 0) if self.query: self.query = parse_query_string(self.query) else: self.query = {} if self.hostname: if self.port: self.netloc = ':'.join([self.hostname,str(self.port)]) else: self.netloc = self.hostname def __repr__(self): return '<SimpleUri (%s,%s,%s,%s,%s,%s) %s>' % ( self.scheme, self.hostname, self.port, self.username, self.password, self.query, self.path ) def __str__(self): if self.query: qup = ['%s=%s' % (key, value) for key, value in list(self.query.items())] rest = '?'+('&'.join(qup)) else: rest = '' if self.fragment: rest += '#%s' % self.fragment if ( (self.scheme.startswith('http') and self.hostname) or not self.scheme.startswith('http') ): parts = [self.scheme, '://'] else: parts = [] if self.username: parts.append(self.username) if self.password: parts += [':', self.password] if self.username or self.password: parts.append('@') if self.hostname: parts.append(self.hostname) elif self.vpath_connector: parts.append("((%s))" % self.vpath_connector) if self.port: parts += [':', str(self.port)] parts += [self.path, rest] return ''.join(parts) def __eq__(self, other): if not isinstance(other, self.__class__): return False return ( self.scheme == other.scheme and self.netloc == other.netloc and self.path == other.path and self.query == other.query ) def as_list(self): "return some attributes as a list" netloc = '' if self.vpath_connector: netloc = '(('+self.vpath_connector+'))' elif self.authority: netloc = self.authority else: netloc = self.netloc return [ self.scheme, netloc, self.path, self.query, '', ]
class UriParse(object): ''' UriParse is a simplistic replacement for urlparse, in case the uri in question is not a http url. ''' def __init__(self, uri=''): ''' starts to get complicated: ouchh... we want to have support for http urls in the following way: 1. after url creation, the query key, value pairs need to be set and need to show up when using the 'str' function on the url: >>> url = UriParse('http://host/some/path') >>> url.query['key1] = 'value1' >>> str(url) == 'http://host/some/path?key1=value1' True 2. absolute urls like 'http:///some/absolute/path' should work: >>> url = UriParse('http:///absolute/path') >>> str(url) == '/absolute/path' True 3. relative urls like 'http://./some/relative/path should work: >>> url = UriParse('http://./relative/path') >>> str(url) == 'relative/path' True ''' pass def __repr__(self): pass def __str__(self): pass def __eq__(self, other): pass def as_list(self): '''return some attributes as a list''' pass
6
3
26
2
21
4
5
0.23
1
3
0
0
5
12
5
5
141
14
104
20
98
24
64
20
58
10
1
2
23
2,855
AbletonAG/abl.vpath
AbletonAG_abl.vpath/abl/vpath/base/memory.py
abl.vpath.base.memory.LookupExceptionClass
class LookupExceptionClass(object): def __init__(self, fs, exc_class): self.fs = fs self.exc_class = exc_class self.prev_exc_class = None def __enter__(self): self.prev_exc_class = self.fs.lookup_exc_class self.fs.lookup_exc_class = self.exc_class return self def __exit__(self, *args): self.fs.lookup_exc_class = self.prev_exc_class
class LookupExceptionClass(object): def __init__(self, fs, exc_class): pass def __enter__(self): pass def __exit__(self, *args): pass
4
0
3
0
3
0
1
0
1
0
0
0
3
3
3
3
13
2
11
7
7
0
11
7
7
1
1
0
3
2,856
AbletonAG/abl.vpath
AbletonAG_abl.vpath/tests/test_path.py
tests.test_path.TestSchemeRe
class TestSchemeRe(TestCase): def test_file(self): m = scheme_re.match("file://something") self.assertTrue(m is not None) self.assertEqual(m.group(1), 'file') def test_with_plus(self): m = scheme_re.match("svn+ssh://something") self.assertTrue(m is not None) self.assertEqual(m.group(1), 'svn+ssh') def test_no_scheme(self): m = scheme_re.match("some/path") self.assertEqual(m, None)
class TestSchemeRe(TestCase): def test_file(self): pass def test_with_plus(self): pass def test_no_scheme(self): pass
4
0
4
0
4
0
1
0
1
0
0
0
3
0
3
75
16
4
12
7
8
0
12
7
8
1
2
0
3
2,857
AbletonAG/abl.vpath
AbletonAG_abl.vpath/abl/vpath/base/uriparse.py
abl.vpath.base.uriparse.URIParser
class URIParser(object): """Scheme-independent parsing frontend URIParser is a scheme-conscious parser that picks the right parser based on the scheme of the URI handed to it. """ Schemes = {'http': HttpURLParser, 'https': HttpsURLParser, 'imap': ImapURLParser, 'imaps': ImapsURLParser, 'ftp': FtpURLParser, 'tftp': TftpURLParser, 'file': FileURLParser, 'telnet': TelnetURLParser, 'mailto': MailtoURIParser, } def __init__(self, schemes=Schemes, extra={}): """Create a new URIParser schemes is the full set of schemes to consider. It defaults to URIParser.Schemes, which is the full set of parsers on hand. extra is a dictionary of schemename:parserclass that is added to the list of known parsers. """ self._parsers = {} self._parsers.update(schemes) self._parsers.update(extra) def parse(self, uri, defaults=None): """Parse the URI. uri is the uri to parse. defaults is a scheme-dependent list of values to use if there is no value for that part in the supplied URI. The return value is a tuple of scheme-dependent length. """ return tuple([self.scheme_of(uri)] + list(self.parser_for(uri)(defaults).parse(uri))) def unparse(self, pieces, defaults=None): """Join the parts of a URI back together to form a valid URI. pieces is a tuble of URI pieces. The scheme must be in pieces[0] so that the rest of the pieces can be interpreted. """ return self.parser_for(pieces[0])(defaults).unparse(pieces) # these work on any URI def scheme_of(self, uri): """Return the scheme of any URI.""" return uri.split(':')[0] def info_of(self, uri): """Return the non-scheme part of any URI.""" return uri.split(':')[1] def parser_for(self, uri): """Return the Parser object used to parse a particular URI. Parser objects are required to have only 'parse' and 'unparse' methods. """ return self._parsers.get(self.scheme_of(uri), DefaultURIParser)
class URIParser(object): '''Scheme-independent parsing frontend URIParser is a scheme-conscious parser that picks the right parser based on the scheme of the URI handed to it. ''' def __init__(self, schemes=Schemes, extra={}): '''Create a new URIParser schemes is the full set of schemes to consider. It defaults to URIParser.Schemes, which is the full set of parsers on hand. extra is a dictionary of schemename:parserclass that is added to the list of known parsers. ''' pass def parse(self, uri, defaults=None): '''Parse the URI. uri is the uri to parse. defaults is a scheme-dependent list of values to use if there is no value for that part in the supplied URI. The return value is a tuple of scheme-dependent length. ''' pass def unparse(self, pieces, defaults=None): '''Join the parts of a URI back together to form a valid URI. pieces is a tuble of URI pieces. The scheme must be in pieces[0] so that the rest of the pieces can be interpreted. ''' pass def scheme_of(self, uri): '''Return the scheme of any URI.''' pass def info_of(self, uri): '''Return the non-scheme part of any URI.''' pass def parser_for(self, uri): '''Return the Parser object used to parse a particular URI. Parser objects are required to have only 'parse' and 'unparse' methods. ''' pass
7
7
7
2
2
4
1
1.04
1
3
1
0
6
1
6
6
70
19
25
9
18
26
16
9
9
1
1
0
6
2,858
AbletonAG/abl.vpath
AbletonAG_abl.vpath/tests/test_fs.py
tests.test_fs.TestMemoryFSExec
class TestMemoryFSExec(CleanupMemoryBeforeTestMixin, CommonFSExecTest): __test__ = True def setUp(self): super(TestMemoryFSExec, self).setUp() self.baseurl = "memory:///" def tearDown(self): pass
class TestMemoryFSExec(CleanupMemoryBeforeTestMixin, CommonFSExecTest): def setUp(self): pass def tearDown(self): pass
3
0
3
0
3
0
1
0
2
1
0
0
2
1
2
76
9
2
7
5
4
0
7
5
4
1
3
0
2
2,859
AbletonAG/abl.vpath
AbletonAG_abl.vpath/tests/test_fs.py
tests.test_fs.TestMemoryFSSymlink
class TestMemoryFSSymlink(CleanupMemoryBeforeTestMixin, CommonLocalFSSymlinkTest): __test__ = True def setUp(self): super(TestMemoryFSSymlink, self).setUp() self.baseurl = "memory:///" def tearDown(self): pass
class TestMemoryFSSymlink(CleanupMemoryBeforeTestMixin, CommonLocalFSSymlinkTest): def setUp(self): pass def tearDown(self): pass
3
0
3
0
3
0
1
0
2
1
0
0
2
1
2
85
9
2
7
5
4
0
7
5
4
1
3
0
2
2,860
AbletonAG/abl.vpath
AbletonAG_abl.vpath/tests/test_fs.py
tests.test_fs.TestMemoryFileSystem
class TestMemoryFileSystem(CommonFileSystemTest): __test__ = True def local_setup(self): self.baseurl = "memory:///" foo_path = URI(self.baseurl) / 'foo' bar_path = foo_path / 'bar' bar_path.makedirs() some_path = foo_path / 'foo.txt' create_file(some_path) def local_teardown(self): pass
class TestMemoryFileSystem(CommonFileSystemTest): def local_setup(self): pass def local_teardown(self): pass
3
0
6
1
5
0
1
0
1
0
0
0
2
1
2
87
16
5
11
8
8
0
11
8
8
1
3
0
2
2,861
AbletonAG/abl.vpath
AbletonAG_abl.vpath/tests/test_fs.py
tests.test_fs.TestLocalFSExec
class TestLocalFSExec(CommonFSExecTest): __test__ = True def setUp(self): thisdir = os.path.split(os.path.abspath(__file__))[0] self.tmpdir = tempfile.mkdtemp('.temp', 'test-local-fs', thisdir) self.baseurl = 'file://' + self.tmpdir def tearDown(self): shutil.rmtree(self.tmpdir)
class TestLocalFSExec(CommonFSExecTest): def setUp(self): pass def tearDown(self): pass
3
0
3
0
3
0
1
0
1
0
0
0
2
2
2
75
10
2
8
7
5
0
8
7
5
1
3
0
2
2,862
AbletonAG/abl.vpath
AbletonAG_abl.vpath/tests/test_fs_symlink_copy.py
tests.test_fs_symlink_copy.TestLocalFSSymlinkCopy
class TestLocalFSSymlinkCopy(CommonLocalFSSymlinkCopyTest): __test__ = is_on_mac() def setUp(self): self.thisdir = os.path.split(os.path.abspath(__file__))[0] self.tmpdir = tempfile.mkdtemp('.temp', 'test-local-fs', self.thisdir) self.baseurl = 'file://' + self.tmpdir def tearDown(self): shutil.rmtree(self.tmpdir)
class TestLocalFSSymlinkCopy(CommonLocalFSSymlinkCopyTest): def setUp(self): pass def tearDown(self): pass
3
0
3
0
3
0
1
0
1
0
0
0
2
3
2
94
11
3
8
7
5
0
8
7
5
1
3
0
2
2,863
AbletonAG/abl.vpath
AbletonAG_abl.vpath/tests/test_fs_symlink_copy.py
tests.test_fs_symlink_copy.TestMemoryFSSymlinkCopy
class TestMemoryFSSymlinkCopy(CleanupMemoryBeforeTestMixin, CommonLocalFSSymlinkCopyTest): __test__ = True def setUp(self): super(TestMemoryFSSymlinkCopy, self).setUp() self.baseurl = "memory:///" def tearDown(self): pass
class TestMemoryFSSymlinkCopy(CleanupMemoryBeforeTestMixin, CommonLocalFSSymlinkCopyTest): def setUp(self): pass def tearDown(self): pass
3
0
3
0
3
0
1
0
2
1
0
0
2
1
2
95
9
2
7
5
4
0
7
5
4
1
3
0
2
2,864
AbletonAG/abl.vpath
AbletonAG_abl.vpath/tests/test_fs_symlink_loops.py
tests.test_fs_symlink_loops.CommonLocalFSSymlinkLoopTest
class CommonLocalFSSymlinkLoopTest(TestCase): __test__ = False def test_selfpointing_symlink(self): root = URI(self.baseurl) tee_path = root / 'helloworld' tee_path.symlink(tee_path) self.assertTrue(tee_path.islink()) self.assertEqual(tee_path.readlink(), tee_path) def test_listdir_fails_on_selfpointing_symlink(self): root = URI(self.baseurl) tee_path = root / 'helloworld' tee_path.symlink(tee_path) self.assertRaises(OSError, tee_path.listdir) def test_open_fails_on_selfpointing_symlink(self): root = URI(self.baseurl) tee_path = root / 'helloworld' tee_path.symlink(tee_path) self.assertRaises(IOError, load_file, tee_path) self.assertRaises(IOError, create_file, tee_path) def test_isexec_fails_on_selfpointing_symlink(self): root = URI(self.baseurl) tee_path = root / 'helloworld' tee_path.symlink(tee_path) self.assertRaises(OSError, tee_path.isexec) def test_set_exec_fails_on_selfpointing_symlink(self): root = URI(self.baseurl) tee_path = root / 'helloworld' tee_path.symlink(tee_path) self.assertRaises(OSError, tee_path.set_exec, stat.S_IXUSR | stat.S_IXGRP) def test_remove_fails_on_selfpointing_symlink(self): root = URI(self.baseurl) tee_path = root / 'helloworld' tee_path.symlink(tee_path) self.assertTrue(tee_path.islink()) tee_path.remove() self.assertTrue(not tee_path.islink()) self.assertTrue(not tee_path.exists()) def test_copystat_fails_on_selfpointing_symlink(self): root = URI(self.baseurl) bar_path = root / 'gaz.txt' create_file(bar_path) tee_path = root / 'helloworld' tee_path.symlink(tee_path) self.assertRaises(OSError, bar_path.copystat, tee_path) self.assertRaises(OSError, tee_path.copystat, bar_path) def test_isdir_doesnt_fail_on_selfpointing_symlink(self): root = URI(self.baseurl) tee_path = root / 'helloworld' tee_path.symlink(tee_path) self.assertTrue(not tee_path.isdir()) def test_isfile_doesnt_fail_on_selfpointing_symlink(self): root = URI(self.baseurl) tee_path = root / 'helloworld' tee_path.symlink(tee_path) self.assertTrue(not tee_path.isfile()) def test_exists_doesnt_fail_on_selfpointing_symlink(self): root = URI(self.baseurl) tee_path = root / 'helloworld' tee_path.symlink(tee_path) self.assertTrue(not tee_path.exists()) #------------------------------ def test_symlink_loop(self): root = URI(self.baseurl) foo_path = root / 'foo' bar_path = foo_path / 'foo' bar_path.makedirs() tee_path = bar_path / 'tee' foo_path.symlink(tee_path) self.assertTrue(tee_path.islink()) self.assertEqual(tee_path.readlink(), foo_path) def test_listdir_doesnt_fail_on_symlink_loop(self): root = URI(self.baseurl) foo_path = root / 'foo' bar_path = foo_path / 'foo' / 'bar' bar_path.makedirs() tee_path = bar_path / 'tee' foo_path.symlink(tee_path) moo_path = foo_path / 'moo.txt' create_file(moo_path) self.assertTrue('moo.txt' in tee_path.listdir()) def test_open_fails_on_symlink_loop(self): root = URI(self.baseurl) tee_path = root / 'helloworld' tee_path.symlink(tee_path) self.assertRaises(IOError, load_file, tee_path) self.assertRaises(IOError, create_file, tee_path) def test_isexec_fails_on_symlink_loop(self): root = URI(self.baseurl) tee_path = root / 'helloworld' tee_path.symlink(tee_path) self.assertRaises(OSError, tee_path.isexec) def test_set_exec_fails_on_symlink_loop(self): root = URI(self.baseurl) tee_path = root / 'helloworld' tee_path.symlink(tee_path) self.assertRaises(OSError, tee_path.set_exec, stat.S_IXUSR | stat.S_IXGRP) def test_remove_doesnt_fail_on_symlink_loop(self): root = URI(self.baseurl) tee_path = root / 'helloworld' tee_path.makedirs() foo_path = tee_path / 'foo' tee_path.symlink(foo_path) tee_path.remove(recursive=True) self.assertTrue(not tee_path.exists()) def test_copystat_fails_on_symlink_loop(self): root = URI(self.baseurl) bar_path = root / 'gaz.txt' create_file(bar_path) tee_path = root / 'helloworld' tee_path.symlink(tee_path) self.assertRaises(OSError, bar_path.copystat, tee_path) self.assertRaises(OSError, tee_path.copystat, bar_path) def test_filechecks_dont_fail_on_mutual_symlinks(self): root = URI(self.baseurl) tee_path = root / 'helloworld' foo_path = root / 'foo' tee_path.symlink(foo_path) foo_path.symlink(tee_path) self.assertTrue(not foo_path.isdir()) self.assertTrue(not foo_path.isfile()) self.assertTrue(not foo_path.exists()) self.assertTrue(foo_path.islink()) def test_remove_doesnt_fail_on_mutual_symlinks(self): root = URI(self.baseurl) tee_path = root / 'helloworld' foo_path = root / 'foo' foo_path.symlink(tee_path) tee_path.symlink(foo_path) tee_path.remove(recursive=True) self.assertTrue(not tee_path.exists()) self.assertTrue(foo_path.islink())
class CommonLocalFSSymlinkLoopTest(TestCase): def test_selfpointing_symlink(self): pass def test_listdir_fails_on_selfpointing_symlink(self): pass def test_open_fails_on_selfpointing_symlink(self): pass def test_isexec_fails_on_selfpointing_symlink(self): pass def test_set_exec_fails_on_selfpointing_symlink(self): pass def test_remove_fails_on_selfpointing_symlink(self): pass def test_copystat_fails_on_selfpointing_symlink(self): pass def test_isdir_doesnt_fail_on_selfpointing_symlink(self): pass def test_isfile_doesnt_fail_on_selfpointing_symlink(self): pass def test_exists_doesnt_fail_on_selfpointing_symlink(self): pass def test_symlink_loop(self): pass def test_listdir_doesnt_fail_on_symlink_loop(self): pass def test_open_fails_on_symlink_loop(self): pass def test_isexec_fails_on_symlink_loop(self): pass def test_set_exec_fails_on_symlink_loop(self): pass def test_remove_doesnt_fail_on_symlink_loop(self): pass def test_copystat_fails_on_symlink_loop(self): pass def test_filechecks_dont_fail_on_mutual_symlinks(self): pass def test_remove_doesnt_fail_on_mutual_symlinks(self): pass
20
0
8
1
7
0
1
0.01
1
1
0
2
19
0
19
91
189
58
130
69
110
1
130
69
110
1
2
0
19
2,865
AbletonAG/abl.vpath
AbletonAG_abl.vpath/tests/test_fs_symlink_loops.py
tests.test_fs_symlink_loops.TestLocalFSSymlinkLoop
class TestLocalFSSymlinkLoop(CommonLocalFSSymlinkLoopTest): __test__ = is_on_mac() def setUp(self): self.thisdir = os.path.split(os.path.abspath(__file__))[0] self.tmpdir = tempfile.mkdtemp('.temp', 'test-local-fs', self.thisdir) self.baseurl = 'file://' + self.tmpdir def tearDown(self): shutil.rmtree(self.tmpdir)
class TestLocalFSSymlinkLoop(CommonLocalFSSymlinkLoopTest): def setUp(self): pass def tearDown(self): pass
3
0
3
0
3
0
1
0
1
0
0
0
2
3
2
93
11
3
8
7
5
0
8
7
5
1
3
0
2
2,866
AbletonAG/abl.vpath
AbletonAG_abl.vpath/tests/test_fs_symlink_loops.py
tests.test_fs_symlink_loops.TestMemoryFSSymlinkLoop
class TestMemoryFSSymlinkLoop(CleanupMemoryBeforeTestMixin, CommonLocalFSSymlinkLoopTest): __test__ = True def setUp(self): super(TestMemoryFSSymlinkLoop, self).setUp() self.baseurl = "memory:///" def tearDown(self): pass
class TestMemoryFSSymlinkLoop(CleanupMemoryBeforeTestMixin, CommonLocalFSSymlinkLoopTest): def setUp(self): pass def tearDown(self): pass
3
0
3
0
3
0
1
0
2
1
0
0
2
1
2
94
9
2
7
5
4
0
7
5
4
1
3
0
2
2,867
AbletonAG/abl.vpath
AbletonAG_abl.vpath/tests/test_fs_symlink_remove.py
tests.test_fs_symlink_remove.CommonLocalFSSymlinkRemoveTest
class CommonLocalFSSymlinkRemoveTest(TestCase): __test__ = False def test_remove_recursive_with_symlinks(self): root = URI(self.baseurl) hw_path = root / 'doo' / 'helloworld' hw_path.makedirs() humpty_path = hw_path / 'humpty.txt' create_file(humpty_path) raz_path = root / 'raz' mam_path = raz_path / 'mam' mam_path.makedirs() create_file(mam_path / 'x') foo_path = root / 'foo' bar_path = foo_path / 'bar' bar_path.makedirs() gaz_path = bar_path / 'gaz.txt' create_file(gaz_path, content='foobar') # a symlink to a dir outside of foo tee_path = bar_path / 'tee' mam_path.symlink(tee_path) # a symlink to a file outside of foo moo_path = bar_path / 'moo.txt' humpty_path.symlink(moo_path) foo_path.remove(recursive=True) self.assertTrue(not foo_path.isdir()) # followlinks: the pointed to files should not been deleted self.assertTrue(humpty_path.isfile()) self.assertTrue(mam_path.isdir()) self.assertTrue(raz_path.isdir()) def test_remove_symlink_to_file(self): root = URI(self.baseurl) humpty_path = root / 'humpty.txt' create_file(humpty_path) foo_path = root / 'foo.txt' humpty_path.symlink(foo_path) foo_path.remove() self.assertTrue(humpty_path.isfile()) def test_remove_symlink_to_looped_symlink(self): root = URI(self.baseurl) humpty_path = root / 'humpty.txt' humpty_path.symlink(humpty_path) foo_path = root / 'foo.txt' humpty_path.symlink(foo_path) foo_path.remove() self.assertTrue(humpty_path.islink())
class CommonLocalFSSymlinkRemoveTest(TestCase): def test_remove_recursive_with_symlinks(self): pass def test_remove_symlink_to_file(self): pass def test_remove_symlink_to_looped_symlink(self): pass
4
0
19
5
13
1
1
0.07
1
0
0
2
3
0
3
75
64
19
42
21
38
3
42
21
38
1
2
0
3
2,868
AbletonAG/abl.vpath
AbletonAG_abl.vpath/tests/test_fs_symlink_remove.py
tests.test_fs_symlink_remove.TestLocalFSSymlinkRemove
class TestLocalFSSymlinkRemove(CommonLocalFSSymlinkRemoveTest): __test__ = is_on_mac() def setUp(self): self.thisdir = os.path.split(os.path.abspath(__file__))[0] self.tmpdir = tempfile.mkdtemp('.temp', 'test-local-fs', self.thisdir) self.baseurl = 'file://' + self.tmpdir def tearDown(self): shutil.rmtree(self.tmpdir)
class TestLocalFSSymlinkRemove(CommonLocalFSSymlinkRemoveTest): def setUp(self): pass def tearDown(self): pass
3
0
3
0
3
0
1
0
1
0
0
0
2
3
2
77
11
3
8
7
5
0
8
7
5
1
3
0
2
2,869
AbletonAG/abl.vpath
AbletonAG_abl.vpath/tests/test_fs_symlink_remove.py
tests.test_fs_symlink_remove.TestMemoryFSSymlinkRemove
class TestMemoryFSSymlinkRemove(CleanupMemoryBeforeTestMixin, CommonLocalFSSymlinkRemoveTest): __test__ = True def setUp(self): super(TestMemoryFSSymlinkRemove, self).setUp() self.baseurl = "memory:///" def tearDown(self): pass
class TestMemoryFSSymlinkRemove(CleanupMemoryBeforeTestMixin, CommonLocalFSSymlinkRemoveTest): def setUp(self): pass def tearDown(self): pass
3
0
3
0
3
0
1
0
2
1
0
0
2
1
2
78
9
2
7
5
4
0
7
5
4
1
3
0
2
2,870
AbletonAG/abl.vpath
AbletonAG_abl.vpath/tests/test_fs_walk.py
tests.test_fs_walk.CommonFileSystemWalkTest
class CommonFileSystemWalkTest(TestCase): __test__ = False def _walk(self, base_path, *args, **kwargs): actual = [] base_path_len = len(base_path.path) for dirname, dirs, files in base_path.walk(*args, **kwargs): relpath = '.%s' % dirname.path[base_path_len:].replace('\\', '/') actual.append("ROOT: %s" % relpath) for name in files: actual.append('FILE: %s' % name) for name in dirs: actual.append('DIR: %s' % name) return actual def _setup_hierarchy(self): """Walk the following tree: foo/ test.py bar/ file1a.txt file1b.png gaz/ file2a.jpg file2b.html """ path = URI(self.baseurl) foo_path = path / 'foo' bar_path = foo_path / 'bar' bar_path.makedirs() gaz_path = foo_path / 'gaz' gaz_path.makedirs() create_file(bar_path / 'file1a.txt') create_file(bar_path / 'file1b.png') create_file(foo_path / 'file2a.jpg') create_file(foo_path / 'file2b.html') create_file(foo_path / 'test.py') return foo_path def test_walk_topdown(self): foo_path = self._setup_hierarchy() actual = self._walk(foo_path, topdown=True, followlinks=True) expected = [ 'ROOT: .', 'FILE: file2a.jpg', 'FILE: file2b.html', 'FILE: test.py', 'DIR: bar', 'DIR: gaz', 'ROOT: ./bar', 'FILE: file1a.txt', 'FILE: file1b.png', 'ROOT: ./gaz', ] self.assertEqual(expected, actual) def test_walk_bottomup(self): foo_path = self._setup_hierarchy() actual = self._walk(foo_path, topdown=False, followlinks=True) expected = [ 'ROOT: ./bar', 'FILE: file1a.txt', 'FILE: file1b.png', 'ROOT: ./gaz', 'ROOT: .', 'FILE: file2a.jpg', 'FILE: file2b.html', 'FILE: test.py', 'DIR: bar', 'DIR: gaz', ] self.assertEqual(expected, actual) #-------------------------------------------------------------------------- def _setup_hierarchy_with_symlink(self, withloop=None, withbrokenlink=False): """Walk the following tree: foo/ test.py bar/ file1a.txt file1b.png humpty -> raz gaz/ file2a.jpg file2b.html raz/ moo/ test1.sh test2.sh """ path = URI(self.baseurl) foo_path = path / 'foo' bar_path = foo_path / 'bar' bar_path.makedirs() gaz_path = foo_path / 'gaz' gaz_path.makedirs() create_file(bar_path / 'file1a.txt') create_file(bar_path / 'file1b.png') create_file(foo_path / 'file2a.jpg') create_file(foo_path / 'file2b.html') create_file(foo_path / 'test.py') raz_path = path / 'raz' moo_path = raz_path / 'moo' moo_path.makedirs() create_file(moo_path / 'test1.sh') create_file(raz_path / 'test2.sh') raz_path.symlink(bar_path / 'humpty') if withloop == 'Dir': foo_path.symlink(moo_path / 'back_to_foo') elif withloop == 'file': dumpty_path = bar_path / 'dumpty' dumpty_path.symlink(dumpty_path) if withbrokenlink: ixw_path = bar_path / 'dumpty' (foo_path / 'nowhere_in_particular').symlink(ixw_path) return foo_path @mac_only def test_walk_topdown_follow_symlinks(self): foo_path = self._setup_hierarchy_with_symlink() actual = self._walk(foo_path, topdown=True, followlinks=True) expected = [ 'ROOT: .', 'FILE: file2a.jpg', 'FILE: file2b.html', 'FILE: test.py', 'DIR: bar', 'DIR: gaz', 'ROOT: ./bar', 'FILE: file1a.txt', 'FILE: file1b.png', 'DIR: humpty', 'ROOT: ./bar/humpty', 'FILE: test2.sh', 'DIR: moo', 'ROOT: ./bar/humpty/moo', 'FILE: test1.sh', 'ROOT: ./gaz', ] self.assertEqual(expected, actual) @mac_only def test_walk_topdown_dont_follow_symlinks(self): foo_path = self._setup_hierarchy_with_symlink() actual = self._walk(foo_path, topdown=True, followlinks=False) expected = [ 'ROOT: .', 'FILE: file2a.jpg', 'FILE: file2b.html', 'FILE: test.py', 'DIR: bar', 'DIR: gaz', 'ROOT: ./bar', 'FILE: file1a.txt', 'FILE: file1b.png', 'DIR: humpty', 'ROOT: ./gaz', ] self.assertEqual(expected, actual) @mac_only def test_walk_bottomup_follow_symlinks(self): foo_path = self._setup_hierarchy_with_symlink() actual = self._walk(foo_path, topdown=False, followlinks=True) expected = [ 'ROOT: ./bar/humpty/moo', 'FILE: test1.sh', 'ROOT: ./bar/humpty', 'FILE: test2.sh', 'DIR: moo', 'ROOT: ./bar', 'FILE: file1a.txt', 'FILE: file1b.png', 'DIR: humpty', 'ROOT: ./gaz', 'ROOT: .', 'FILE: file2a.jpg', 'FILE: file2b.html', 'FILE: test.py', 'DIR: bar', 'DIR: gaz', ] self.assertEqual(expected, actual) @mac_only def test_walk_bottomup_dont_follow_symlinks(self): foo_path = self._setup_hierarchy_with_symlink() actual = self._walk(foo_path, topdown=False, followlinks=False) expected = [ 'ROOT: ./bar', 'FILE: file1a.txt', 'FILE: file1b.png', 'DIR: humpty', 'ROOT: ./gaz', 'ROOT: .', 'FILE: file2a.jpg', 'FILE: file2b.html', 'FILE: test.py', 'DIR: bar', 'DIR: gaz', ] self.assertEqual(expected, actual) #--------------------------------------------------------------------------- # can't test behaviour of walk on followlinks with symlink loop across # multiple folders. os.walk has undefined behaviour here, and so has # abl.vpath.walk. os.walk will eventual stop after some time, and so # does localfs of abl.vpath. memoryfs stops, but with an unrelated # exception. # # Since we can't rely on os.walk's behaviour we should fix abl.vpath to # do proper cycle detection, which is a different story though. # def test_walk_topdown_follow_symlinks_breaks_on_loop(self): # foo_path = self._setup_hierarchy_with_symlink(withloop='Dir') # # actual = self._walk(foo_path, topdown=True, followlinks=True) # # self.failUnlessRaises(OSError, self._walk, foo_path, topdown=True, followlinks=True) @mac_only def test_walk_topdown_follow_symlinks_wont_break_on_fileloop(self): foo_path = self._setup_hierarchy_with_symlink(withloop='file') actual = self._walk(foo_path, topdown=True, followlinks=True) expected = [ 'ROOT: .', 'FILE: file2a.jpg', 'FILE: file2b.html', 'FILE: test.py', 'DIR: bar', 'DIR: gaz', 'ROOT: ./bar', 'FILE: dumpty', # a loop link is reported as a file 'FILE: file1a.txt', 'FILE: file1b.png', 'DIR: humpty', 'ROOT: ./bar/humpty', 'FILE: test2.sh', 'DIR: moo', 'ROOT: ./bar/humpty/moo', 'FILE: test1.sh', 'ROOT: ./gaz', ] self.assertEqual(expected, actual) @mac_only def test_walk_topdown_dont_follow_symlinks_wont_break_on_loop(self): foo_path = self._setup_hierarchy_with_symlink(withloop='Dir') actual = self._walk(foo_path, topdown=True, followlinks=False) expected = [ 'ROOT: .', 'FILE: file2a.jpg', 'FILE: file2b.html', 'FILE: test.py', 'DIR: bar', 'DIR: gaz', 'ROOT: ./bar', 'FILE: file1a.txt', 'FILE: file1b.png', 'DIR: humpty', 'ROOT: ./gaz', ] self.assertEqual(expected, actual) @mac_only def test_walk_topdown_dont_follow_symlinks_wont_break_on_loop_file(self): foo_path = self._setup_hierarchy_with_symlink(withloop='file') actual = self._walk(foo_path, topdown=True, followlinks=False) expected = [ 'ROOT: .', 'FILE: file2a.jpg', 'FILE: file2b.html', 'FILE: test.py', 'DIR: bar', 'DIR: gaz', 'ROOT: ./bar', 'FILE: dumpty', # a self loop link is reported as a file 'FILE: file1a.txt', 'FILE: file1b.png', 'DIR: humpty', 'ROOT: ./gaz', ] self.assertEqual(expected, actual) @mac_only def test_walk_topdown_follow_symlinks_wont_break_on_brokenlink(self): foo_path = self._setup_hierarchy_with_symlink(withbrokenlink=True) actual = self._walk(foo_path, topdown=True, followlinks=True) expected = [ 'ROOT: .', 'FILE: file2a.jpg', 'FILE: file2b.html', 'FILE: test.py', 'DIR: bar', 'DIR: gaz', 'ROOT: ./bar', 'FILE: dumpty', # a broken link is reported as a file 'FILE: file1a.txt', 'FILE: file1b.png', 'DIR: humpty', 'ROOT: ./bar/humpty', 'FILE: test2.sh', 'DIR: moo', 'ROOT: ./bar/humpty/moo', 'FILE: test1.sh', 'ROOT: ./gaz', ] self.assertEqual(expected, actual) @mac_only def test_walk_topdown_dont_follow_symlinks_wont_break_on_brokenlink(self): foo_path = self._setup_hierarchy_with_symlink(withbrokenlink=True) actual = self._walk(foo_path, topdown=True, followlinks=False) expected = [ 'ROOT: .', 'FILE: file2a.jpg', 'FILE: file2b.html', 'FILE: test.py', 'DIR: bar', 'DIR: gaz', 'ROOT: ./bar', 'FILE: dumpty', # a broken link is reported as a file 'FILE: file1a.txt', 'FILE: file1b.png', 'DIR: humpty', 'ROOT: ./gaz', ] self.assertEqual(expected, actual) @mac_only def test_walk_bottomup_follow_symlinks_wont_break_on_brokenlink(self): foo_path = self._setup_hierarchy_with_symlink(withbrokenlink=True) actual = self._walk(foo_path, topdown=False, followlinks=True) expected = [ 'ROOT: ./bar/humpty/moo', 'FILE: test1.sh', 'ROOT: ./bar/humpty', 'FILE: test2.sh', 'DIR: moo', 'ROOT: ./bar', 'FILE: dumpty', # a broken link is reported as a file 'FILE: file1a.txt', 'FILE: file1b.png', 'DIR: humpty', 'ROOT: ./gaz', 'ROOT: .', 'FILE: file2a.jpg', 'FILE: file2b.html', 'FILE: test.py', 'DIR: bar', 'DIR: gaz', ] self.assertEqual(expected, actual) @mac_only def test_walk_bottomup_dont_follow_symlinks_wont_break_on_brokenlink(self): foo_path = self._setup_hierarchy_with_symlink(withbrokenlink=True) actual = self._walk(foo_path, topdown=False, followlinks=False) expected = [ 'ROOT: ./bar', 'FILE: dumpty', # a broken link is reported as a file 'FILE: file1a.txt', 'FILE: file1b.png', 'DIR: humpty', 'ROOT: ./gaz', 'ROOT: .', 'FILE: file2a.jpg', 'FILE: file2b.html', 'FILE: test.py', 'DIR: bar', 'DIR: gaz', ] self.assertEqual(expected, actual) #-------------------------------------------------------------------------- def test_walk_very_deep_hierarchies(self): root = URI(self.baseurl) foo_path = root / 'foo' expected = [] def expected_root_str(path): return 'ROOT: .%s' % path.path[len(foo_path.path):].replace('\\', '/') d_path = foo_path for i in range(0, 49): nm = 'f%d' % i expected.append('DIR: %s' % nm) expected.append(expected_root_str(d_path)) d_path = d_path / nm d_path.makedirs() expected.append(expected_root_str(d_path)) expected.reverse() actual = self._walk(foo_path, topdown=False, followlinks=False) self.assertEqual(expected, actual) # expect the right amount of output. For 64 level with 2 lines per # level (1 x ROOT:, 1x DIR:) + 1 for the iinermost ('f63') self.assertEqual(len(actual), 99)
class CommonFileSystemWalkTest(TestCase): def _walk(self, base_path, *args, **kwargs): pass def _setup_hierarchy(self): '''Walk the following tree: foo/ test.py bar/ file1a.txt file1b.png gaz/ file2a.jpg file2b.html ''' pass def test_walk_topdown(self): pass def test_walk_bottomup(self): pass def _setup_hierarchy_with_symlink(self, withloop=None, withbrokenlink=False): '''Walk the following tree: foo/ test.py bar/ file1a.txt file1b.png humpty -> raz gaz/ file2a.jpg file2b.html raz/ moo/ test1.sh test2.sh ''' pass @mac_only def test_walk_topdown_follow_symlinks(self): pass @mac_only def test_walk_topdown_dont_follow_symlinks(self): pass @mac_only def test_walk_bottomup_follow_symlinks(self): pass @mac_only def test_walk_bottomup_dont_follow_symlinks(self): pass @mac_only def test_walk_topdown_follow_symlinks_wont_break_on_fileloop(self): pass @mac_only def test_walk_topdown_dont_follow_symlinks_wont_break_on_loop(self): pass @mac_only def test_walk_topdown_dont_follow_symlinks_wont_break_on_loop_file(self): pass @mac_only def test_walk_topdown_follow_symlinks_wont_break_on_brokenlink(self): pass @mac_only def test_walk_topdown_dont_follow_symlinks_wont_break_on_brokenlink(self): pass @mac_only def test_walk_bottomup_follow_symlinks_wont_break_on_brokenlink(self): pass @mac_only def test_walk_bottomup_dont_follow_symlinks_wont_break_on_brokenlink(self): pass def test_walk_very_deep_hierarchies(self): pass def expected_root_str(path): pass
30
2
23
3
18
2
1
0.15
1
1
0
2
17
0
17
89
474
98
332
94
302
50
135
83
116
4
2
2
25
2,871
AbletonAG/abl.vpath
AbletonAG_abl.vpath/tests/test_fs_walk.py
tests.test_fs_walk.TestLocalFSSymlinkWalk
class TestLocalFSSymlinkWalk(CommonFileSystemWalkTest): __test__ = True def setUp(self): self.thisdir = os.path.split(os.path.abspath(__file__))[0] self.tmpdir = tempfile.mkdtemp('.temp', 'test-local-fs', self.thisdir) self.baseurl = 'file://' + self.tmpdir def tearDown(self): shutil.rmtree(self.tmpdir)
class TestLocalFSSymlinkWalk(CommonFileSystemWalkTest): def setUp(self): pass def tearDown(self): pass
3
0
3
0
3
0
1
0
1
0
0
0
2
3
2
91
11
3
8
7
5
0
8
7
5
1
3
0
2
2,872
AbletonAG/abl.vpath
AbletonAG_abl.vpath/tests/test_fs_walk.py
tests.test_fs_walk.TestMemoryFSSymlinkWalk
class TestMemoryFSSymlinkWalk(CleanupMemoryBeforeTestMixin, CommonFileSystemWalkTest): __test__ = True def setUp(self): super(TestMemoryFSSymlinkWalk, self).setUp() self.baseurl = "memory:///" def tearDown(self): pass
class TestMemoryFSSymlinkWalk(CleanupMemoryBeforeTestMixin, CommonFileSystemWalkTest): def setUp(self): pass def tearDown(self): pass
3
0
3
0
3
0
1
0
2
1
0
0
2
1
2
92
9
2
7
5
4
0
7
5
4
1
3
0
2
2,873
AbletonAG/abl.vpath
AbletonAG_abl.vpath/tests/test_localfs.py
tests.test_localfs.TestLocalFSInfo
class TestLocalFSInfo(TestCase): def setUp(self): self.starttime = datetime.datetime.now() p = URI("test.txt") with p.open("w") as fs: fs.write('test') a_link = URI("test_link") if p.connection.supports_symlinks() and not a_link.islink(): p.symlink(a_link) def tearDown(self): p = URI("test.txt") if p.exists(): p.remove() l = URI("test_link") if l.islink(): l.remove() def test_info_ctime(self): p = URI("test.txt") self.assertTrue(p.info().ctime <= datetime.datetime.now()) self.assertEqual(p.info().ctime, p.info().mtime) def test_info_mtime(self): p = URI("test.txt") now = datetime.datetime.now() size = p.info().size with p.open('a') as fs: fs.write(' again') self.assertTrue(p.info().mtime >= p.info().ctime) self.assertTrue( p.info().size > size) # due to now's millisecond resolution, we must ignore milliseconds self.assertTrue(p.info().mtime.timetuple()[:6] >= now.timetuple()[:6]) def test_info_on_symlinks(self): a_file = URI("test.txt") a_link = URI("test_link") with a_file.open('w') as f: f.write("a" * 800) if not a_file.connection.supports_symlinks(): return self.assertEqual(a_file.info().size, 800) self.assertEqual(a_link.info().size, 800) self.assertNotEqual(a_link.info(followlinks=False).size, 800) @mac_only def test_set_info_on_symlinks(self): # lchmod is not supported on Linux, only on OSX a_file = URI("test.txt") a_link = URI("test_link") with a_file.open('w') as f: f.write("a" * 800) if not a_file.connection.supports_symlinks(): return self.assertEqual(a_file.info().size, 800) self.assertEqual(a_link.info().size, 800) self.assertNotEqual(a_link.info(followlinks=False).size, 800) orig_info = a_file.info() a_link.info({'mode': 0o120700}, followlinks=False) self.assertEqual(a_file.info().mode, orig_info.mode) self.assertEqual(a_link.info().mode, orig_info.mode) self.assertEqual(a_link.info(followlinks=False).mode, 0o120700) def test_locking(self): try: p = URI("lock.txt") content = "I'm something written into a locked file" with p.lock() as inf: inf.write(content) self.assertEqual(p.open().read(), content) finally: if p.exists(): p.remove() def test_setting_mode(self): # setting the permission flags are not supported on windows if sys.platform != "win32": p = URI("test.txt") mode = p.info().mode new_mode = mode | stat.S_IXUSR p.info(dict(mode=new_mode)) self.assertEqual( p.info().mode, new_mode, )
class TestLocalFSInfo(TestCase): def setUp(self): pass def tearDown(self): pass def test_info_ctime(self): pass def test_info_mtime(self): pass def test_info_on_symlinks(self): pass @mac_only def test_set_info_on_symlinks(self): pass def test_locking(self): pass def test_setting_mode(self): pass
10
0
10
1
9
0
2
0.04
1
2
0
0
8
1
8
80
98
20
75
34
65
3
70
28
61
3
2
2
15
2,874
AbletonAG/abl.vpath
AbletonAG_abl.vpath/tests/test_memory.py
tests.test_memory.MemoryFSTests
class MemoryFSTests(CleanupMemoryBeforeTestMixin, TestCase): def setUp(self): super(MemoryFSTests, self).setUp() self.temp_path = URI(tempfile.mktemp()) self.temp_path.mkdir() self.root = URI("memory:///") def tearDown(self): if self.temp_path.isdir(): self.temp_path.remove(recursive=True) super(MemoryFSTests, self).tearDown() def test_all(self): root = self.root assert root.isdir() subdir = root / "foo" subdir.mkdir() assert subdir.isdir() assert not subdir.isfile() out = subdir / "bar" with out.open("w") as outf: outf.write("foobar") assert not out.isdir() assert out.isfile() with out.open() as inf: content = inf.read() self.assertEqual(content, "foobar") assert subdir == root / "foo" time.sleep(.5) assert out.info().mtime < time.time() connection = subdir.connection out = StringIO() connection.dump(out) print((out.getvalue())) def test_write_text_read_binary(self): test_file = self.root / 'foo' with test_file.open('w') as text_proxy: text_proxy.write("spam & eggs") with test_file.open('rb') as binary_proxy: self.assertEqual(binary_proxy.read(), b"spam & eggs") def test_write_binary_read_text(self): test_file = self.root / 'foo' with test_file.open('wb') as binary_proxy: binary_proxy.write(b"spam & eggs") with test_file.open('r') as text_proxy: self.assertEqual(text_proxy.read(), "spam & eggs") def test_info_on_symlinks(self): root = self.root a_file = root / "a_file" a_link = root / "a_link" with a_file.open('w') as f: f.write("a" * 800) a_file.symlink(a_link) self.assertEqual(a_file.info().size, 800) self.assertEqual(a_link.info().size, 800) self.assertNotEqual(a_link.info(followlinks=False).size, 800) orig_info = a_file.info() new_info = a_file.info() new_info.mtime = new_info.mtime + 100 a_link.info(new_info, followlinks=False) self.assertEqual(a_file.info().mtime, orig_info.mtime) self.assertEqual(a_link.info().mtime, orig_info.mtime) self.assertEqual(a_link.info(followlinks=False).mtime, new_info.mtime) def test_listdir_empty_root(self): root = self.root files = root.listdir() assert not files def test_listdir_empty_dir(self): root = self.root foo = root / 'foo' foo.mkdir() rootfiles = root.listdir() assert 'foo' in rootfiles foofiles = foo.listdir() assert not foofiles def test_walk(self): root = self.root foo = root / 'foo' foo.mkdir() bar = root / 'bar' bar.mkdir() foofile = foo / 'foocontent.txt' with foofile.open('w') as fd: fd.write('foocontent') results = [] for root, dirs, files in root.walk(): results.append((root, dirs, files)) assert len(results) == 3 def test_next(self): root = self.root subdir = root / "foo" with subdir.open("w") as outf: outf.write("foo\nbar") with subdir.open() as inf: content = next(inf) self.assertEqual(content, "foo\n") content = next(inf) self.assertEqual(content, "bar") with subdir.open() as inf: for line in inf: self.assertIn(line, ["foo\n", "bar"]) def test_exists_on_root(self): root = self.root assert root.exists() def test_root_of_non_existing_dir_exists(self): dir_path = URI("memory:///foo") assert dir_path.dirname().exists() def test_directory_cant_be_overwritten_by_file(self): base = URI("memory:///") d = base / "foo" d.mkdir() assert d.exists() try: with d.open("w") as outf: outf.write("foo") except IOError as e: self.assertEqual(e.errno, errno.EISDIR) else: assert False, "You shouldn't be able to ovewrite a directory like this" def test_copy_into_fs(self): root = self.root for item in ["foo", "bar"]: with (root/item).open("wb") as fd: fd.write(item.encode('utf-8')) root.copy(self.temp_path, recursive=True) content = self.temp_path.listdir() self.assertEqual(set(content), set(["foo", "bar"])) def test_cleanup_removes_lingering_locks(self): lockfile = self.root / "lockfile" with lockfile.open("w") as outf: outf.write(" ") lockfile._manipulate(mtime=lockfile.mtime() + 3, lock=True) CONNECTION_REGISTRY.cleanup(force=True) with lockfile.lock(fail_on_lock=True): pass
class MemoryFSTests(CleanupMemoryBeforeTestMixin, TestCase): def setUp(self): pass def tearDown(self): pass def test_all(self): pass def test_write_text_read_binary(self): pass def test_write_binary_read_text(self): pass def test_info_on_symlinks(self): pass def test_listdir_empty_root(self): pass def test_listdir_empty_dir(self): pass def test_walk(self): pass def test_next(self): pass def test_exists_on_root(self): pass def test_root_of_non_existing_dir_exists(self): pass def test_directory_cant_be_overwritten_by_file(self): pass def test_copy_into_fs(self): pass def test_cleanup_removes_lingering_locks(self): pass
16
0
10
1
9
0
1
0
2
2
0
0
15
2
15
88
180
47
133
68
117
0
133
54
117
2
2
2
20
2,875
AbletonAG/abl.vpath
AbletonAG_abl.vpath/tests/test_memory.py
tests.test_memory.TestRemovalOfFilesAndDirs
class TestRemovalOfFilesAndDirs(CleanupMemoryBeforeTestMixin, TestCase): def setUp(self): super(TestRemovalOfFilesAndDirs, self).setUp() self.root_path = URI('memory:///') def test_first(self): self.assertEqual(self.root_path.listdir(),[]) def test_removedir(self): dir_path = self.root_path / 'foo' self.assertTrue(not dir_path.exists()) dir_path.mkdir() self.assertTrue(dir_path.exists()) self.assertTrue(dir_path.isdir()) dir_path.remove() self.assertTrue(not dir_path.exists()) def test_remove_not_existing_dir(self): dir_path = self.root_path / 'foo' self.assertRaises(FileDoesNotExistError, dir_path.remove, ()) def test_removefile(self): file_path = self.root_path / 'foo.txt' self.assertTrue(not file_path.exists()) with file_path.open('w') as fd: fd.write('bar') self.assertTrue(file_path.isfile()) file_path.remove() self.assertTrue(not file_path.exists()) def test_removefile_not_existing(self): file_path = self.root_path / 'foo.txt' self.assertRaises(FileDoesNotExistError, file_path.remove, ()) def test_remove_recursive(self): dir_path = self.root_path / 'foo' file_path = dir_path / 'bar.txt' dir_path.mkdir() with file_path.open('w') as fd: fd.write('info') self.assertTrue(dir_path.exists()) self.assertTrue(file_path.exists()) dir_path.remove(recursive=True) self.assertTrue(not dir_path.exists()) self.assertTrue(not file_path.exists()) def test_locking(self): p = self.root_path / "test.txt" try: content = "I'm something written into a locked file" with p.lock() as inf: inf.write(content) self.assertEqual(p.open().read(), content) finally: if p.exists(): p.remove() mfile = p.open("w") lock_a = mfile.lock mfile.close() mfile = p.open("w") assert lock_a is mfile.lock # artificially lock the file mfile.lock.acquire() try: with p.lock(fail_on_lock=True): assert False, "we shouldn't be allowed here!" except LockFileObtainException: pass finally: mfile.lock.release() def test_manipulation_api(self): p = self.root_path / "test.txt" p._manipulate(lock=True) mfile = p.open("w") assert not mfile.lock.acquire(False) p._manipulate(unlock=True) try: assert mfile.lock.acquire(False) finally: mfile.lock.release() with p.open("w") as outf: outf.write("foo") old_mtime = p.mtime() new_mtime = old_mtime + 100 p._manipulate(mtime=new_mtime) self.assertEqual(p.mtime(), new_mtime) error_file = self.root_path / "error" with error_file.open("wb") as outf: outf.write(b"foobarbaz") error_dir = self.root_path / "error.dir" error_dir.mkdir() def next_op_callback(_path, _func): raise OSError(13, "Permission denied") for error in (error_file, error_dir): error._manipulate(next_op_callback=next_op_callback) clone = URI(error) try: clone.remove() except OSError as e: self.assertEqual(e.errno, 13) else: assert False, "Shouldn't be here" def test_reading_from_write_only_files_not_working(self): p = self.root_path / "test.txt" with p.open("w") as outf: self.assertRaises(IOError, outf.read) def test_lockfile_cleanup(self): p = self.root_path / "test.txt" if p.exists(): p.remove() with p.lock(cleanup=True): assert p.exists() assert not p.exists() def test_file_name_comparison(self): a = self.root_path / "a" b = self.root_path / "b" assert a == a assert b == b assert a != b assert b != a assert not a != a assert not b != b def test_double_dir_creation_fails(self): a = self.root_path / "a" a.mkdir() self.assertRaises(OSError, a.mkdir) def test_setting_mode(self): p = self.root_path / "test.txt" if p.exists(): p.remove() create_file(p, content="foo") mode = p.info().mode new_mode = mode | stat.S_IXUSR p.info(set_info=dict(mode=new_mode)) self.assertEqual(p.info().mode, new_mode) def test_removing_non_empty_dirs(self): p = self.root_path / "test-dir" assert not p.exists() p.mkdir() create_file(p / "some-file.txt", content="foobar") self.assertRaises(OSError, p.remove) (p / "some-file.txt").remove() p.remove() assert not p.exists() p.mkdir() create_file(p / "some-file.txt", content="foobar") p.remove(recursive=True)
class TestRemovalOfFilesAndDirs(CleanupMemoryBeforeTestMixin, TestCase): def setUp(self): pass def test_first(self): pass def test_removedir(self): pass def test_remove_not_existing_dir(self): pass def test_removefile(self): pass def test_removefile_not_existing(self): pass def test_remove_recursive(self): pass def test_locking(self): pass def test_manipulation_api(self): pass def next_op_callback(_path, _func): pass def test_reading_from_write_only_files_not_working(self): pass def test_lockfile_cleanup(self): pass def test_file_name_comparison(self): pass def test_double_dir_creation_fails(self): pass def test_setting_mode(self): pass def test_removing_non_empty_dirs(self): pass
17
0
10
1
9
0
1
0.01
2
4
1
0
15
1
15
88
190
49
140
51
123
1
136
45
119
3
2
2
22
2,876
AbletonAG/abl.vpath
AbletonAG_abl.vpath/tests/test_misc.py
tests.test_misc.TestGlob
class TestGlob(CleanupMemoryBeforeTestMixin, TestCase): def test_globbing_by_prefix(self): base = URI("memory:///") a = base / "a.foo" b = base / "b.bar" for f in [a, b]: with f.open("w") as outf: outf.write("foo") self.assertEqual([a], base.glob("*.foo")) def test_globbing_by_prefix_in_subdir(self): base = URI("memory:///") / "dir" base.mkdir() a = base / "a.foo" b = base / "b.bar" for f in [a, b]: with f.open("w") as outf: outf.write("foo") self.assertEqual([a], base.glob("*.foo")) def test_globbing_by_suffix(self): base = URI("memory:///") a = base / "a.foo" b = base / "b.bar" for f in [a, b]: with f.open("w") as outf: outf.write("foo") self.assertEqual([a], base.glob("a.*")) def test_globbing_by_suffix_in_subdir(self): base = URI("memory:///") / "dir" base.mkdir() a = base / "a.foo" b = base / "b.bar" for f in [a, b]: with f.open("w") as outf: outf.write("foo") self.assertEqual([a], base.glob("a.*"))
class TestGlob(CleanupMemoryBeforeTestMixin, TestCase): def test_globbing_by_prefix(self): pass def test_globbing_by_prefix_in_subdir(self): pass def test_globbing_by_suffix(self): pass def test_globbing_by_suffix_in_subdir(self): pass
5
0
11
2
9
0
2
0
2
0
0
0
4
0
4
77
50
15
35
25
30
0
35
21
30
2
2
2
8
2,877
AbletonAG/abl.vpath
AbletonAG_abl.vpath/tests/test_misc.py
tests.test_misc.TestTempFileHandle
class TestTempFileHandle(object): def test_handle(self): fs = open('testfile', 'w') fs.write('hallo') fs.close() with TempFileHandle('testfile') as fs: content = fs.read() assert content == 'hallo' assert not os.path.exists('testfile')
class TestTempFileHandle(object): def test_handle(self): pass
2
0
8
0
8
0
1
0
1
1
1
0
1
0
1
1
9
0
9
4
7
0
9
4
7
1
1
1
1
2,878
AbletonAG/abl.vpath
AbletonAG_abl.vpath/tests/test_path.py
tests.test_path.KeepCurrentDir
class KeepCurrentDir: def __init__(self, directory): self._directory = directory self._currentdir = os.getcwd() def __enter__(self): os.chdir(self._directory) return self def __exit__(self, *exc_args): os.chdir(self._currentdir)
class KeepCurrentDir: def __init__(self, directory): pass def __enter__(self): pass def __exit__(self, *exc_args): pass
4
0
3
0
3
0
1
0
0
0
0
0
3
2
3
3
13
4
9
6
5
0
9
6
5
1
0
0
3
2,879
AbletonAG/abl.vpath
AbletonAG_abl.vpath/tests/test_fs.py
tests.test_fs.TestMemoryFSCopy2
class TestMemoryFSCopy2(CleanupMemoryBeforeTestMixin, CommonFSCopyTest): __test__ = True def setUp(self): super(TestMemoryFSCopy2, self).setUp() self.baseurl = "memory:///" def tearDown(self): pass
class TestMemoryFSCopy2(CleanupMemoryBeforeTestMixin, CommonFSCopyTest): def setUp(self): pass def tearDown(self): pass
3
0
3
0
3
0
1
0
2
1
0
0
2
1
2
80
9
2
7
5
4
0
7
5
4
1
3
0
2
2,880
AbletonAG/abl.vpath
AbletonAG_abl.vpath/tests/test_path.py
tests.test_path.TestCredentials
class TestCredentials(TestCase): """ credentials (username, password) are treated as a special case """ def test_regular(self): some_path = URI('scheme://username:password@host/some/path') self.assertEqual(some_path.username, 'username') self.assertEqual(some_path.password, 'password') def test_keyword_param(self): some_path = URI('scheme://host/some/path', username='username', password='password') self.assertEqual(some_path.username, 'username') self.assertEqual(some_path.password, 'password') def test_url_args(self): some_path = URI('scheme://host/some/path?username=username&password=password') self.assertEqual(some_path.username, 'username') self.assertEqual(some_path.password, 'password')
class TestCredentials(TestCase): ''' credentials (username, password) are treated as a special case ''' def test_regular(self): pass def test_keyword_param(self): pass def test_url_args(self): pass
4
1
4
0
4
0
1
0.23
1
0
0
0
3
0
3
75
21
5
13
7
9
3
13
7
9
1
2
0
3
2,881
AbletonAG/abl.vpath
AbletonAG_abl.vpath/tests/test_fs.py
tests.test_fs.TestLocalFileSystem
class TestLocalFileSystem(CommonFileSystemTest): __test__ = True def local_setup(self): thisdir = os.path.split(os.path.abspath(__file__))[0] self.tmpdir = tempfile.mkdtemp('.temp', 'test-local-fs', thisdir) self.baseurl = 'file://' + self.tmpdir foo_dir = os.path.join(self.tmpdir, 'foo') bar_dir = os.path.join(foo_dir, 'bar') os.makedirs(foo_dir) os.makedirs(bar_dir) some_file = os.path.join(foo_dir, 'foo.txt') os_create_file(some_file) def local_teardown(self): shutil.rmtree(self.tmpdir)
class TestLocalFileSystem(CommonFileSystemTest): def local_setup(self): pass def local_teardown(self): pass
3
0
7
1
6
0
1
0
1
0
0
0
2
2
2
87
19
5
14
10
11
0
14
10
11
1
3
0
2
2,882
AbletonAG/abl.vpath
AbletonAG_abl.vpath/abl/vpath/base/uriparse.py
abl.vpath.base.uriparse.ShttpURLParser
class ShttpURLParser(HttpURLParser): """Internal class to hold the defaults of SHTTP URLs""" _defaults=(None, None, None, 443, '/', None, None)
class ShttpURLParser(HttpURLParser): '''Internal class to hold the defaults of SHTTP URLs'''
1
1
0
0
0
0
0
0.5
1
0
0
0
0
0
0
3
3
0
2
2
1
1
2
2
1
0
2
0
0
2,883
AbletonAG/abl.vpath
AbletonAG_abl.vpath/tests/test_fs.py
tests.test_fs.CommonLocalFSSymlinkTest
class CommonLocalFSSymlinkTest(TestCase): __test__ = False def test_symlink_dir(self): root = URI(self.baseurl) bar_path = root / 'foo' / 'bar' bar_path.makedirs() create_file(bar_path / 'gaz.txt') moo_path = root / 'moo' self.assertTrue(not moo_path.exists()) self.assertTrue(not moo_path.islink()) bar_path.symlink(moo_path) self.assertTrue(moo_path.exists()) self.assertTrue(moo_path.islink()) # a symlink to a dir is a dir self.assertTrue(moo_path.isdir()) link = moo_path.readlink() self.assertEqual(link, bar_path) # check that gaz.txt is accessible through the symlink self.assertTrue(moo_path / 'gaz.txt') def test_symlink_file(self): root = URI(self.baseurl) bar_path = root / 'foo' / 'bar' bar_path.makedirs() gaz_path = bar_path / 'gaz.txt' create_file(gaz_path, content='foobar') tee_path = root / 'helloworld' self.assertTrue(not tee_path.exists()) self.assertTrue(not tee_path.islink()) gaz_path.symlink(tee_path) self.assertTrue(tee_path.exists()) self.assertTrue(tee_path.islink()) # a symlink to a file is a file self.assertTrue(tee_path.isfile()) link = tee_path.readlink() self.assertEqual(link, gaz_path) # check that gaz.txt is accessible through the symlink self.assertEqual(load_file(tee_path), 'foobar') #------------------------------ def test_symlink_on_unknown_file(self): """Check that backends fail with a proper exception when trying to create a symlink on a path where directory steps do not exist. """ root = URI(self.baseurl) notexisting_path = root / 'ma' / 'moo' tee_path = root / 'helloworld' notexisting_path.symlink(tee_path) self.assertTrue(tee_path.islink()) self.assertEqual(tee_path.readlink(), notexisting_path) self.assertTrue(not notexisting_path.exists()) def test_open_deadlink_fails(self): root = URI(self.baseurl) notexisting_path = root / 'foo' / 'bar' tee_path = root / 'helloworld' notexisting_path.symlink(tee_path) self.assertRaises(IOError, load_file, tee_path) self.assertRaises(IOError, create_file, tee_path) def test_listdir_deadlink_fails(self): root = URI(self.baseurl) notexisting_path = root / 'foo' / 'bar' tee_path = root / 'helloworld' notexisting_path.symlink(tee_path) self.assertRaises(OSError, tee_path.listdir) def test_isfile_doesnt_fail_on_deadlink(self): root = URI(self.baseurl) notexisting_path = root / 'foo' / 'bar' tee_path = root / 'helloworld' notexisting_path.symlink(tee_path) self.assertTrue(not tee_path.isfile()) self.assertTrue(not tee_path.isdir()) self.assertTrue(not tee_path.exists()) def test_isdir_doesnt_fail_on_deadlink(self): root = URI(self.baseurl) notexisting_path = root / 'foo' / 'bar' tee_path = root / 'helloworld' notexisting_path.symlink(tee_path) self.assertTrue(not tee_path.isdir()) def test_exists_doesnt_fail_on_deadlink(self): root = URI(self.baseurl) notexisting_path = root / 'foo' / 'bar' tee_path = root / 'helloworld' notexisting_path.symlink(tee_path) self.assertTrue(not tee_path.exists()) def test_isexec_fails_on_deadlink(self): root = URI(self.baseurl) notexisting_path = root / 'foo' / 'bar' tee_path = root / 'helloworld' notexisting_path.symlink(tee_path) self.assertRaises(OSError, tee_path.isexec) def test_set_exec_fails_on_deadlink(self): root = URI(self.baseurl) notexisting_path = root / 'foo' / 'bar' tee_path = root / 'helloworld' notexisting_path.symlink(tee_path) self.assertRaises(OSError, tee_path.set_exec, stat.S_IXUSR | stat.S_IXGRP)
class CommonLocalFSSymlinkTest(TestCase): def test_symlink_dir(self): pass def test_symlink_file(self): pass def test_symlink_on_unknown_file(self): '''Check that backends fail with a proper exception when trying to create a symlink on a path where directory steps do not exist. ''' pass def test_open_deadlink_fails(self): pass def test_listdir_deadlink_fails(self): pass def test_isfile_doesnt_fail_on_deadlink(self): pass def test_isdir_doesnt_fail_on_deadlink(self): pass def test_exists_doesnt_fail_on_deadlink(self): pass def test_isexec_fails_on_deadlink(self): pass def test_set_exec_fails_on_deadlink(self): pass
11
1
12
3
9
1
1
0.09
1
1
0
2
10
0
10
82
144
49
87
45
76
8
86
45
75
1
2
0
10
2,884
AbletonAG/abl.vpath
AbletonAG_abl.vpath/tests/test_fs.py
tests.test_fs.CommonFileSystemTest
class CommonFileSystemTest(CleanupMemoryBeforeTestMixin, TestCase): __test__ = False def setUp(self): super(CommonFileSystemTest, self).setUp() self.local_setup() self.foo_path = URI(self.baseurl) / 'foo' self.existing_dir = ujoin(self.baseurl, 'foo') self.existing_file = ujoin(self.baseurl, 'foo', 'foo.txt') self.non_existing_file = ujoin(self.baseurl, 'bar.txt') def tearDown(self): self.local_teardown() def test_file(self): path = URI(self.baseurl) / 'testfile.txt' create_file(path, content='hallo') content = load_file(path) self.assertEqual(content, 'hallo') self.assertTrue(path.exists()) self.assertTrue(path.isfile()) path.remove() self.assertTrue(not path.exists()) path = URI(self.existing_file) self.assertTrue(path.exists()) self.assertTrue(path.isfile()) content = load_file(path) self.assertTrue(content) def test_dir(self): testdir = URI('testdir') testdir.makedirs() self.assertTrue(testdir.exists()) self.assertTrue(testdir.isdir()) self.assertTrue(not testdir.isfile()) testfile = URI('testdir/somefile') create_file(testfile, content='test') testdir.remove(recursive=True) self.assertTrue(not testdir.exists()) self.assertTrue(not testfile.exists()) testdir = URI(self.existing_dir) self.assertTrue(testdir.exists()) self.assertTrue(testdir.isdir()) def test_listdir(self): path = URI(self.existing_dir) dirs = path.listdir() self.assertTrue('foo.txt' in dirs) def test_copy_and_move_file(self): single_file = URI(self.non_existing_file) target_file = URI(self.baseurl) / 'target_file.txt' create_file(single_file) single_file.copy(target_file) self.assertTrue(target_file.exists()) self.assertTrue(target_file.isfile()) self.assertEqual(load_file(target_file), 'content') target_file.remove() self.assertTrue(not target_file.exists()) single_file.move(target_file) self.assertTrue(not single_file.exists()) self.assertTrue(target_file.exists()) self.assertTrue(target_file.isfile()) self.assertEqual(load_file(target_file), 'content') target_file.remove() def test_copy_and_move_dir(self): folder = URI(self.baseurl) / 'folder' folder.makedirs() self.assertTrue(folder.isdir()) afile = folder / 'afile.txt' create_file(afile) target = URI(self.baseurl) / 'target' self.assertTrue(not target.exists()) folder.copy(target, recursive=True) self.assertTrue(target.exists()) target_file = target / 'afile.txt' self.assertTrue(target_file.exists()) self.assertEqual(load_file(target_file), 'content') target.remove(recursive=True) self.assertTrue(not target.exists()) target.makedirs() folder.copy(target, recursive=True) newtarget = target / 'folder' self.assertTrue(newtarget.exists()) self.assertTrue(newtarget.isdir()) newtarget_file = newtarget / 'afile.txt' self.assertTrue(newtarget_file.exists()) self.assertTrue(newtarget_file.isfile()) target.remove(recursive=True) folder.move(target) self.assertTrue(not folder.exists()) self.assertTrue(target.exists()) self.assertTrue(target.isdir()) self.assertTrue(target_file.exists()) self.assertTrue(target_file.isfile()) target.remove(recursive=True) def test_move_folder_to_subfolder(self): """Test moving a directory '/some/path/folder' to '/some/path/target'. '/some/path/target' does already exist. It is expected that after the move '/some/path/target/folder' exists. """ folder = self.foo_path / 'folder' content = folder / 'content_dir' and_more = content / 'and_more' and_more.makedirs() target = self.foo_path / 'target' target.makedirs() folder.move(target) self.assertTrue(not folder.exists()) self.assertTrue(target.exists()) self.assertTrue('folder' in target.listdir()) self.assertTrue((target / 'folder').isdir()) self.assertTrue((target / 'folder' / 'content_dir').isdir()) def test_rename_folder(self): """Test moving a directory '/some/path/folder' to '/some/path/target'. '/some/path/target' does NOT yet exist. It is expected that after the move '/some/path/target' exists and is actually the former '/some/path/folder'. """ folder = self.foo_path / 'folder' content = folder / 'content_dir' and_more = content / 'and_more' and_more.makedirs() target = self.foo_path / 'target' folder.move(target) self.assertTrue(not folder.exists()) self.assertTrue(target.isdir()) self.assertTrue('content_dir' in target.listdir()) def test_copy_recursive_with_preservelinks(self): src_path = URI(self.baseurl) / 'folder' base_path = src_path / 'gaz' foo_path = base_path / 'foo' bar_path = foo_path / 'tmp' bar_path.makedirs() mee_path = foo_path / 'mee.txt' create_file(mee_path) mee2_path = bar_path / 'mee2.txt' create_file(mee2_path) dest_path = URI(self.baseurl) / 'helloworld' src_path.copy(dest_path, recursive=True, followlinks=False) self.assertTrue((dest_path / 'gaz' / 'foo' / 'mee.txt').isfile()) self.assertTrue((dest_path / 'gaz' / 'foo' / 'tmp').isdir()) def test_remove_recursive_with_readonly_file(self): foo_path = URI(self.baseurl) / 'foo' bar_path = foo_path / 'bar' bar_path.makedirs() gaz_path = bar_path / 'ghaz.txt' create_file(gaz_path) mode = gaz_path.info().mode gaz_path.info(set_info=dict(mode=mode & ~stat.S_IWUSR)) foo_path.remove(recursive=True) self.assertTrue(not foo_path.exists()) #------------------------------ def test_open_unknown_file_fails(self): """Check that both backends fail with a proper exception when trying to open a path for loading, which does not exist. """ root = URI(self.baseurl) notexisting_path = root / 'ma' / 'moo' self.assertRaises(IOError, load_file, notexisting_path) self.assertRaises(IOError, create_file, notexisting_path)
class CommonFileSystemTest(CleanupMemoryBeforeTestMixin, TestCase): def setUp(self): pass def tearDown(self): pass def test_file(self): pass def test_dir(self): pass def test_listdir(self): pass def test_copy_and_move_file(self): pass def test_copy_and_move_dir(self): pass def test_move_folder_to_subfolder(self): '''Test moving a directory '/some/path/folder' to '/some/path/target'. '/some/path/target' does already exist. It is expected that after the move '/some/path/target/folder' exists. ''' pass def test_rename_folder(self): '''Test moving a directory '/some/path/folder' to '/some/path/target'. '/some/path/target' does NOT yet exist. It is expected that after the move '/some/path/target' exists and is actually the former '/some/path/folder'. ''' pass def test_copy_recursive_with_preservelinks(self): pass def test_remove_recursive_with_readonly_file(self): pass def test_open_unknown_file_fails(self): '''Check that both backends fail with a proper exception when trying to open a path for loading, which does not exist. ''' pass
13
3
15
2
12
1
1
0.09
2
2
0
2
12
4
12
85
208
53
142
53
129
13
142
53
129
1
2
0
12
2,885
AbletonAG/abl.vpath
AbletonAG_abl.vpath/tests/test_path.py
tests.test_path.TestURI
class TestURI(TestCase): def test_rescheming(self): some_path = URI('first:///scheme') some_path.scheme = 'second' joined_path = some_path / 'other' self.assertEqual(joined_path.scheme, 'second') def test_creation(self): local_path = URI('/tmp/this') self.assertEqual(local_path.path.split(os.sep), ['', 'tmp', 'this']) self.assertEqual(local_path.scheme, 'file') path = URI('localpath', sep='/') self.assertEqual(path.path, './localpath', path.path) path = URI('trailing/slash/', sep='/') self.assertEqual(path.path, './trailing/slash/') def test_split(self): local_path = URI('/some/long/dir/structure') pth, tail = local_path.split() self.assertEqual(pth, URI('/some/long/dir')) self.assertEqual(tail, 'structure') local_path = URI('somedir') pth, tail = local_path.split() self.assertEqual(pth, URI('.')) self.assertEqual(tail, 'somedir') def test_split_with_short_path(self): local_path = URI('/some') pth, tail = local_path.split() self.assertEqual(pth, URI('/')) self.assertEqual(tail, 'some') def test_split_with_args(self): local_path = URI('file:///some/long?extra=arg') pth, tail = local_path.split() self.assertEqual(tail, 'long') def test_root_split(self): pth = URI('/') directory, name = pth.split() self.assertEqual(directory, URI('/')) self.assertEqual(name, '') def test_win_somehow_broken_on_windows(self): path = URI("file://C:\\some\\windows\\path", sep='\\') self.assertEqual(path.path, r'C:\some\windows\path') self.assertEqual(path.uri, 'file:///C/some/windows/path') self.assertEqual(path.unipath, '/C/some/windows/path') def test_windows_repr(self): path = URI(r'C:\some\path\on\windows', sep='\\') self.assertEqual(path.path, r'C:\some\path\on\windows') self.assertEqual(path.uri, 'file:///C/some/path/on/windows') def test_split_windows(self): path = URI(r'C:\some\path\on\windows', sep='\\') pth, tail = path.split() self.assertEqual(pth.uri, 'file:///C/some/path/on') self.assertEqual(pth.path, r'C:\some\path\on') self.assertEqual(pth, URI(r'C:\some\path\on', sep='\\')) self.assertEqual(tail, 'windows') def test_join_windows(self): path = URI('C:\\some', sep='\\') self.assertEqual(path.uri, 'file:///C/some') new_path = path / 'other' self.assertEqual(new_path.uri, 'file:///C/some/other') def test_unipath_windows(self): path = URI('C:\\some?extra=arg', sep='\\') self.assertEqual(path.path, 'C:\\some') self.assertEqual(path.unipath, '/C/some') self.assertEqual(path.uri, 'file:///C/some?extra=arg') new_path = path / 'other' self.assertEqual(new_path.unipath, '/C/some/other') self.assertEqual(new_path.uri, 'file:///C/some/other?extra=arg') def test_relative_dir_and_unipath(self): path = URI('somedir', sep='\\') self.assertEqual(path.unipath, './somedir') def test_join(self): long_path = URI('this/is/a/long/path') self.assertEqual(long_path, URI('this') / 'is' / 'a' / 'long' / 'path') def test_augmented_join(self): testpath = URI('/a') testpath /= 'path' self.assertEqual(URI('/a/path'), testpath) def test_join_with_vpath_authority(self): testpath = URI('zip://((/path/to/file.zip))/') testpath /= 'content.txt' self.assertEqual(URI('zip://((/path/to/file.zip))/content.txt'), testpath) def test_adding_suffix(self): testpath = URI("/a") other = testpath + ".foo" self.assertEqual(URI("/a.foo"), other) testpath += ".bar" self.assertEqual(URI("/a.bar"), testpath) def test_path_equality(self): pth_one = URI("/a") pth_two = URI("file:///a") self.assertEqual(pth_one, pth_two) def test_path_equals_path_with_trailing_slash(self): pth_one = URI("/a") pth_two = URI("/a/") self.assertNotEqual(pth_one, pth_two) self.assertEqual((pth_one / 'something'), (pth_two / 'something')) def test_extra_args(self): pth = URI("scheme://some/path?extra=arg") self.assertEqual(pth._extras(), {'extra':'arg'}) def test_extra_args_and_kwargs(self): pth = URI("scheme://some/path?extra=arg", something='different') self.assertEqual(pth._extras(), {'extra':'arg', 'something':'different'}) def test_dirname(self): pth = URI("/this/is/a/path") self.assertEqual(pth.dirname(), URI("/this/is/a")) self.assertEqual(pth.dirname(level=2), URI("/this/is")) self.assertEqual(pth.dirname(level=3), URI("/this")) self.assertEqual(pth.dirname(level=4), URI("/")) self.assertEqual(pth.dirname(level=5), URI("/"))
class TestURI(TestCase): def test_rescheming(self): pass def test_creation(self): pass def test_split(self): pass def test_split_with_short_path(self): pass def test_split_with_args(self): pass def test_root_split(self): pass def test_win_somehow_broken_on_windows(self): pass def test_windows_repr(self): pass def test_split_windows(self): pass def test_join_windows(self): pass def test_unipath_windows(self): pass def test_relative_dir_and_unipath(self): pass def test_join_windows(self): pass def test_augmented_join(self): pass def test_join_with_vpath_authority(self): pass def test_adding_suffix(self): pass def test_path_equality(self): pass def test_path_equals_path_with_trailing_slash(self): pass def test_extra_args(self): pass def test_extra_args_and_kwargs(self): pass def test_dirname(self): pass
22
0
5
0
5
0
1
0
1
0
0
0
21
0
21
93
153
43
110
55
88
0
108
55
86
1
2
0
21
2,886
AbletonAG/abl.vpath
AbletonAG_abl.vpath/tests/test_path.py
tests.test_path.TestUnicodeURI
class TestUnicodeURI(TestCase): def setUp(self): self.thisdir = os.path.split(os.path.abspath(__file__))[0] self.foo_dir = os.path.join(self.thisdir, 'foo') self.bar_dir = os.path.join(self.thisdir, 'bar') def tearDown(self): p = URI(self.foo_dir) if p.isdir(): p.remove(recursive=True) b = URI(self.bar_dir) if b.isdir(): b.remove(recursive=True) def test_creation(self): local_path = URI('/tmp/thisü') self.assertEqual(local_path.path.split(os.sep), ['', 'tmp', 'thisü']) self.assertEqual(local_path.scheme, 'file') def test_mkdir(self): p = URI(str(self.foo_dir)) p.mkdir() def test_unicode_extra(self): URI(self.foo_dir, some_query="what's üp") def test_copy(self): p = URI(str(self.foo_dir)) p.mkdir() dest = URI(self.bar_dir) p.copy(dest, recursive=True) def test_dont_mix_unicode_and_bytes(self): p = URI("Vögel") p2 = p / "no_ünicode" self.assertTrue(type(p2.uri) is str) p3 = URI("Vögel") p4 = p3 / "ünicode" self.assertTrue(type(p4.uri) is str)
class TestUnicodeURI(TestCase): def setUp(self): pass def tearDown(self): pass def test_creation(self): pass def test_mkdir(self): pass def test_unicode_extra(self): pass def test_copy(self): pass def test_dont_mix_unicode_and_bytes(self): pass
8
0
5
0
5
0
1
0
1
2
0
0
7
3
7
79
46
13
33
21
25
0
33
21
25
3
2
1
9
2,887
AbletonAG/abl.vpath
AbletonAG_abl.vpath/tests/test_simpleuri.py
tests.test_simpleuri.TestSimpleUri
class TestSimpleUri(unittest.TestCase): def test_one(self): uri = UriParse('file:///tmp/this') self.assertEqual(uri.path, '/tmp/this') def test_two(self): uri = UriParse('scheme:///some/path') self.assertEqual(uri.scheme, 'scheme') self.assertEqual(uri.path, '/some/path') def test_three(self): uri = UriParse('svn://user@host:/some/path') self.assertEqual(uri.scheme, 'svn') self.assertEqual(uri.path, '/some/path') self.assertEqual(uri.hostname, 'host') self.assertEqual(uri.username, 'user') def test_non_http_scheme(self): uri = UriParse('scheme://user:password@host:/some/path') self.assertEqual(uri.scheme, 'scheme') self.assertEqual(uri.path, '/some/path') self.assertEqual(uri.hostname, 'host') self.assertEqual(uri.username, 'user') self.assertEqual(uri.password, 'password') def test_non_http_uri_with_query_part(self): uri = UriParse('scheme:///some/path?key_one=val_one&key_two=val_two') self.assertEqual(uri.query, {'key_one':'val_one', 'key_two':'val_two'} ) def test_funny_name(self): uri = UriParse('file:///.#something') self.assertEqual(uri.path, '/.#something') def test_url_with_fragment(self): uri = UriParse('http://somewhere/something#frack') self.assertEqual(uri.path, '/something') self.assertEqual(uri.fragment, 'frack') def test_query(self): uri = UriParse('http://heinz/?a=1') self.assertEqual(uri.query['a'], '1') uri = UriParse('http://heinz/?a=1&b=2') self.assertEqual(uri.query['a'], '1') self.assertEqual(uri.query['b'], '2') def test_query_unsplit(self): uri = UriParse('http://heinz/') uri.query = dict(a='1', b='2') self.assertEqual(uri, UriParse(str(uri))) def test_absolute_url(self): uri = UriParse('http:///local/path') self.assertEqual(str(uri), '/local/path') def test_relative_url(self): uri = UriParse('http://tmp/this') self.assertEqual(uri.scheme, 'http') self.assertEqual(uri.path, '/this') def test_relative_uri(self): uri = UriParse('file://./local/path') self.assertEqual(uri.path, './local/path') def test_relative_uri_with_scheme(self): uri = UriParse('scheme://./local/path') self.assertEqual(uri.path, './local/path') def test_suburi_as_serverpart(self): uri = UriParse('scheme://((/path/to/local/file.zip))/content.txt') self.assertEqual(uri.vpath_connector, '/path/to/local/file.zip') self.assertEqual(uri.path, '/content.txt')
class TestSimpleUri(unittest.TestCase): def test_one(self): pass def test_two(self): pass def test_three(self): pass def test_non_http_scheme(self): pass def test_non_http_uri_with_query_part(self): pass def test_funny_name(self): pass def test_url_with_fragment(self): pass def test_query(self): pass def test_query_unsplit(self): pass def test_absolute_url(self): pass def test_relative_url(self): pass def test_relative_uri(self): pass def test_relative_uri_with_scheme(self): pass def test_suburi_as_serverpart(self): pass
15
0
4
0
4
0
1
0.05
1
3
1
0
14
0
14
86
75
15
60
29
45
3
58
29
43
1
2
0
14
2,888
AbletonAG/abl.vpath
AbletonAG_abl.vpath/tests/test_uriparse.py
tests.test_uriparse.TestURIParser
class TestURIParser(unittest.TestCase): def test_simple(self): result = ('scheme', '', '/some/path', None, None) self.assertEqual(urisplit('scheme:///some/path'), result) def test_with_authority_replace(self): result = ('scheme', '((file:///inner/path))', '/some/path', None, None) self.assertEqual(urisplit('scheme://((file:///inner/path))/some/path'), result) def test_special_file_notation(self): result = ('file', None, './relative/path', None, None) self.assertEqual(urisplit('file://./relative/path'), result) def test_special_notation_for_scheme(self): result = ('scheme', None, './relative/path', None, None) self.assertEqual(urisplit('scheme://./relative/path'), result)
class TestURIParser(unittest.TestCase): def test_simple(self): pass def test_with_authority_replace(self): pass def test_special_file_notation(self): pass def test_special_notation_for_scheme(self): pass
5
0
3
0
3
0
1
0
1
0
0
0
4
0
4
76
18
4
14
9
9
0
13
9
8
1
2
0
4
2,889
AbletonAG/abl.vpath
AbletonAG_abl.vpath/tests/test_zip.py
tests.test_zip.TestAdvancedZip
class TestAdvancedZip(ZipTestCase): def setUp(self): super(TestAdvancedZip, self).setUp() self.zip_path = URI('memory:///file.zip') zip_handle = self.zip_path.open('wb') try: self.fp_zip = ZipFile(zip_handle, 'w') self.fp_zip.writestr('/dir1/foo.txt', 'bar') self.fp_zip.writestr('/dir1/bar.txt', 'bar') self.fp_zip.writestr('/bar.txt', 'bar') self.fp_zip.close() finally: zip_handle.close() def tearDown(self): self.zip_path.remove() def test_walk(self): root = URI('zip://((%s))/' % self.zip_path.uri) self.assertEqual(len(root.listdir()), 2) rlist = [] for base, dirs, files in root.walk(): rlist.append((base, dirs, files)) self.assertEqual(rlist, [(root, ['dir1'], ['bar.txt']), ((root / 'dir1'), [], ['bar.txt', 'foo.txt'])])
class TestAdvancedZip(ZipTestCase): def setUp(self): pass def tearDown(self): pass def test_walk(self): pass
4
0
8
0
8
0
1
0
1
2
0
0
3
2
3
76
28
4
24
10
20
0
21
10
17
2
3
1
4
2,890
AbletonAG/abl.vpath
AbletonAG_abl.vpath/tests/test_zip.py
tests.test_zip.TestHelper
class TestHelper(TestCase): def test_content_item_in_root(self): path1 = '/' path2 = '/foo' self.assertEqual(content_item(path1, path2), 'foo') def test_dir_item_in_root(self): path1 = '/' path2 = '/foo/other' self.assertEqual(content_item(path1, path2), 'foo') def test_content_item_exists(self): path1 = '/foo' path2 = '/foo/bar' self.assertEqual(content_item(path1, path2), 'bar') def test_content_item_exists_not(self): path1 = '/foo' path2 = '/foofoo/bar' self.assertEqual(content_item(path1, path2), '') def test_compare_unequal(self): self.assertTrue(not compare_parts([1,2],[3,4])) def test_compare_ISDIR(self): self.assertEqual(compare_parts([1,2],[1,2,3]), ISDIR) def test_compare_ISFILE(self): self.assertEqual(compare_parts([1,2,3],[1,2,3]), ISFILE)
class TestHelper(TestCase): def test_content_item_in_root(self): pass def test_dir_item_in_root(self): pass def test_content_item_exists(self): pass def test_content_item_exists_not(self): pass def test_compare_unequal(self): pass def test_compare_ISDIR(self): pass def test_compare_ISFILE(self): pass
8
0
3
0
3
0
1
0
1
0
0
0
7
0
7
79
29
6
23
16
15
0
23
16
15
1
2
0
7
2,891
AbletonAG/abl.vpath
AbletonAG_abl.vpath/tests/test_zip.py
tests.test_zip.TestListDir
class TestListDir(ZipTestCase): def setUp(self): super(TestListDir, self).setUp() self.zip_path = URI('memory:///file.zip') def tearDown(self): if self.zip_path.exists(): self.zip_path.remove() def test_listdir(self): base_path = URI('zip://((%s))/' % self.zip_path.uri) self.assertEqual(base_path.listdir(), []) p1 = URI('zip://((%s))/foo.txt' % self.zip_path.uri) with p1.open('wb') as fd: fd.write(b'foo') self.assertEqual(base_path.listdir(), ['foo.txt']) p2 = URI('zip://((%s))/dir/foo.txt' % self.zip_path.uri) with p2.open('w') as fd: fd.write(b'foo') self.assertEqual(set(base_path.listdir()), set(['foo.txt', 'dir']))
class TestListDir(ZipTestCase): def setUp(self): pass def tearDown(self): pass def test_listdir(self): pass
4
0
6
0
6
0
1
0
1
2
0
0
3
1
3
76
20
2
18
9
14
0
18
8
14
2
3
1
4
2,892
AbletonAG/abl.vpath
AbletonAG_abl.vpath/tests/test_zip.py
tests.test_zip.TestReadingZip
class TestReadingZip(ZipTestCase): def setUp(self): super(TestReadingZip, self).setUp() self.zip_path = URI('memory:///file.zip') zip_handle = self.zip_path.open('wb') try: self.fp_zip = ZipFile(zip_handle, 'w') self.fp_zip.writestr('/foo.txt', 'bar') self.fp_zip.close() finally: zip_handle.close() def tearDown(self): if self.zip_path.exists(): self.zip_path.remove() def test_read_a_file(self): p = URI('zip://((memory:///file.zip))/foo.txt') with p.open('rb') as fd: self.assertEqual(fd.read(), b'bar') def test_write_a_file(self): p = URI('zip://((memory:///file.zip))/bar.txt') with p.open('wb') as fd: fd.write(b'foo') with p.open() as fd: self.assertEqual(fd.read(), b'foo') def test_exists(self): p = URI('zip://((memory:///file.zip))/foo.txt') with p.open('wb') as fd: fd.write(b'foo') self.assertTrue(p.exists()) def test_isfile(self): p = URI('zip://((memory:///file.zip))/foo.txt') with p.open('wb') as fd: fd.write(b'foo') self.assertTrue(p.isfile()) def test_isdir(self): dir_path = URI('zip://((memory:///file.zip))/somedir') p = dir_path / 'foo.txt' with p.open('wb') as fd: fd.write(b'foo') self.assertTrue(dir_path.isdir()) def test_path(self): dir_path = URI('zip://((memory:///file.zip))/somedir') self.assertEqual(dir_path.path, '/somedir') new_path = dir_path / 'other' self.assertEqual(new_path.path, '/somedir/other')
class TestReadingZip(ZipTestCase): def setUp(self): pass def tearDown(self): pass def test_read_a_file(self): pass def test_write_a_file(self): pass def test_exists(self): pass def test_isfile(self): pass def test_isdir(self): pass def test_path(self): pass
9
0
6
0
6
0
1
0
1
2
0
0
8
2
8
81
54
9
45
25
36
0
44
20
35
2
3
1
9
2,893
AbletonAG/abl.vpath
AbletonAG_abl.vpath/tests/test_zip.py
tests.test_zip.TestWritingZip
class TestWritingZip(ZipTestCase): def setUp(self): super(TestWritingZip, self).setUp() self.zip_uri = 'file://./file.zip' self.zip_path = URI(self.zip_uri) def tearDown(self): # reset the connection registry, otherwise the zip file cannot # be deleted on windows since it is still opened by the # backend CONNECTION_REGISTRY.cleanup(force=True) if self.zip_path.exists(): self.zip_path.remove() def test_write_file_to_non_existing_zip(self): foo = URI('zip://((%s))/foo.txt' % self.zip_uri) with foo.open('wb') as fd: fd.write(b'bar') def test_write_file_to_non_existing_zip_2(self): foo = URI('zip://((%s))/deeper/foo.txt' % self.zip_uri) with foo.open('wb') as fd: fd.write(b'bar') def test_write_two_files(self): foo = URI('zip://((%s))/foo.txt' % self.zip_uri) with foo.open('wb') as fd: fd.write(b'bar') bar = URI('zip://((%s))/bar.txt' % self.zip_uri) with bar.open('wb') as fd: fd.write(b'foo')
class TestWritingZip(ZipTestCase): def setUp(self): pass def tearDown(self): pass def test_write_file_to_non_existing_zip(self): pass def test_write_file_to_non_existing_zip_2(self): pass def test_write_two_files(self): pass
6
0
5
0
5
1
1
0.13
1
1
0
0
5
2
5
78
35
8
24
15
18
3
24
12
18
2
3
1
6
2,894
AbletonAG/abl.vpath
AbletonAG_abl.vpath/tests/test_zip.py
tests.test_zip.ZipTestCase
class ZipTestCase(TestCase): def setUp(self): clean_registry()
class ZipTestCase(TestCase): def setUp(self): pass
2
0
2
0
2
0
1
0
1
0
0
4
1
0
1
73
3
0
3
2
1
0
3
2
1
1
2
0
1
2,895
AbletonAG/abl.vpath
AbletonAG_abl.vpath/tests/test_fs.py
tests.test_fs.CommonFSExecTest
class CommonFSExecTest(TestCase): __test__ = False def test_exec_flags(self): root = URI(self.baseurl) # create a file with execution flag xfile = create_file(root / 'xfile.exe') xfile.set_exec(stat.S_IXUSR) self.assertTrue(xfile.isexec()) self.assertEqual(xfile.info().mode & stat.S_IXUSR, stat.S_IXUSR) # create a file without exec flag ofile = create_file(root / 'otherfile.txt') self.assertEqual(ofile.info().mode & stat.S_IXUSR, 0) self.assertTrue(not ofile.isexec())
class CommonFSExecTest(TestCase): def test_exec_flags(self): pass
2
0
15
4
9
2
1
0.18
1
0
0
2
1
0
1
73
18
5
11
6
9
2
11
6
9
1
2
0
1
2,896
AbletonAG/abl.vpath
AbletonAG_abl.vpath/tests/test_fs.py
tests.test_fs.CommonFSCopyTest
class CommonFSCopyTest(TestCase): __test__ = False def test_copystat_exec_to_nonexec(self): root = URI(self.baseurl) # create a file with execution flag xfile = create_file(root / 'xfile.exe') xfile.set_exec(stat.S_IXUSR) # create a file without exec flag ofile = create_file(root / 'otherfile.exe') xfile.copystat(ofile) self.assertTrue(ofile.isexec()) def test_copystat_nonexec_to_exec(self): root = URI(self.baseurl) # create a file with execution flag xfile = create_file(root / 'xfile.sh') xfile.set_exec(stat.S_IXUSR) # create a file without exec flag ofile = create_file(root / 'otherfile.txt') ofile.copystat(xfile) self.assertTrue(not xfile.isexec()) def test_copy_recursive(self): root = URI(self.baseurl) foo_path = root / 'foo' foo_path.mkdir() bar_path = root / 'bar' # create a file with execution flag xfile = create_file(foo_path / 'xfile.exe') xfile.set_exec(stat.S_IXUSR) zfile = create_file(foo_path / 'zfile.exe') zfile.set_exec(stat.S_IXUSR) # create a file without exec flag create_file(foo_path / 'otherfile.txt') create_file(foo_path / 'nfile.txt') foo_path.copy(bar_path, recursive=True) self.assertTrue((bar_path / 'xfile.exe').isexec()) self.assertTrue((bar_path / 'zfile.exe').isexec()) self.assertTrue(not (bar_path / 'otherfile.txt').isexec()) self.assertTrue(not (bar_path / 'nfile.txt').isexec()) def test_copy_dir_to_file(self): root = URI(self.baseurl) bar_path = root / 'foo' / 'bar' bar_path.makedirs() gaz_path = bar_path / 'gaz.txt' create_file(gaz_path, content='foobar') moo_path = root / 'moo.txt' create_file(moo_path, content='moomoo') # can't copy dir on (existing) file self.assertRaises(OSError, bar_path.copy, moo_path, recursive=True) def test_copy_empty_dirs_recursive(self): root = URI(self.baseurl) root.makedirs() gaz_path = root / 'gaz' gaz_path.makedirs() moo_path = root / 'moo' gaz_path.copy(moo_path, recursive=True) self.assertTrue((moo_path).isdir())
class CommonFSCopyTest(TestCase): def test_copystat_exec_to_nonexec(self): pass def test_copystat_nonexec_to_exec(self): pass def test_copy_recursive(self): pass def test_copy_dir_to_file(self): pass def test_copy_empty_dirs_recursive(self): pass
6
0
15
4
10
1
1
0.14
1
1
0
2
5
0
5
77
86
29
50
25
44
7
49
25
43
1
2
0
5
2,897
AbletonAG/abl.vpath
AbletonAG_abl.vpath/tests/common.py
tests.common.CleanupMemoryBeforeTestMixin
class CleanupMemoryBeforeTestMixin(object): def setUp(self): CONNECTION_REGISTRY.cleanup(force=True)
class CleanupMemoryBeforeTestMixin(object): def setUp(self): pass
2
0
2
0
2
0
1
0
1
0
0
11
1
0
1
1
4
1
3
2
1
0
3
2
1
1
1
0
1
2,898
AbletonAG/abl.vpath
AbletonAG_abl.vpath/abl/vpath/base/zip.py
abl.vpath.base.zip.ZipFileSystemUri
class ZipFileSystemUri(BaseUri): pass
class ZipFileSystemUri(BaseUri): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
48
2
0
2
1
1
0
2
1
1
0
2
0
0
2,899
AbletonAG/abl.vpath
AbletonAG_abl.vpath/abl/vpath/base/zip.py
abl.vpath.base.zip.WriteStatement
class WriteStatement(object): def __init__(self, path_string, zip_backend): self.path_string = path_string self.zip_backend = zip_backend self.byte_buffer = BytesIO() def __enter__(self): return self def __exit__(self, etype, evalue, etraceback): self.zip_backend._ziphandle.writestr(self.path_string, self.byte_buffer.getvalue()) self.byte_buffer.close() self.zip_backend.close_zip() self.zip_backend.open_zip() def __getattr__(self, attr): return getattr(self.byte_buffer, attr)
class WriteStatement(object): def __init__(self, path_string, zip_backend): pass def __enter__(self): pass def __exit__(self, etype, evalue, etraceback): pass def __getattr__(self, attr): pass
5
0
4
0
4
0
1
0
1
0
0
0
4
3
4
4
21
6
15
8
10
0
14
8
9
1
1
0
4