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
144,348
KxSystems/pyq
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/KxSystems_pyq/src/pyq/tests/test_numpy.py
pyq.tests.test_numpy.test_no_dtype.NoDtype
class NoDtype(numpy.ndarray): """A helper class to test error branches""" @property def dtype(self): raise AttributeError('intentional error')
class NoDtype(numpy.ndarray): '''A helper class to test error branches''' @property def dtype(self): pass
3
1
2
0
2
0
1
0.25
1
1
0
0
1
0
1
1
6
1
4
3
1
1
3
2
1
1
1
0
1
144,349
KxSystems/pyq
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/KxSystems_pyq/src/pyq/tests/test_q.py
pyq.tests.test_q.TestGUID
class TestGUID(unittest.TestCase): def test_conversion(self): from uuid import UUID u = UUID('cc165d74-88df-4973-8dd1-a1f2e0765a80') self.assertEqual(int(K(u)), u.int)
class TestGUID(unittest.TestCase): def test_conversion(self): pass
2
0
5
1
4
0
1
0
1
2
0
0
1
0
1
73
6
1
5
4
2
0
5
4
2
1
2
0
1
144,350
KyleJamesWalker/yamlsettings
KyleJamesWalker_yamlsettings/tests/__init__.py
tests.SoftwareEngineer
class SoftwareEngineer(object): def __init__(self, name): self.name = name
class SoftwareEngineer(object): def __init__(self, name): pass
2
0
2
0
2
0
1
0
1
0
0
0
1
1
1
1
3
0
3
3
1
0
3
3
1
1
1
0
1
144,351
KyleJamesWalker/yamlsettings
KyleJamesWalker_yamlsettings/yamlsettings/extensions/local.py
yamlsettings.extensions.local.LocalExtension
class LocalExtension(YamlSettingsExtension): """Local filesystem, works with any valid system path. This is the default and will be used if you don't include the scheme. examples: * file://relative/foo/bar/baz.txt (opens a relative file) * file:///home/user (opens a directory from a absolute path) * foo/bar.baz (file:// is the default) """ protocols = ['file'] default_query = {} @classmethod def load_target(cls, scheme, path, fragment, username, password, hostname, port, query, load_method, **kwargs): full_path = (hostname or '') + path query.update(kwargs) return load_method(open(full_path, **query))
class LocalExtension(YamlSettingsExtension): '''Local filesystem, works with any valid system path. This is the default and will be used if you don't include the scheme. examples: * file://relative/foo/bar/baz.txt (opens a relative file) * file:///home/user (opens a directory from a absolute path) * foo/bar.baz (file:// is the default) ''' @classmethod def load_target(cls, scheme, path, fragment, username, password, hostname, port, query, load_method, **kwargs): pass
3
1
6
0
6
0
1
0.7
1
0
0
0
0
0
1
3
20
3
10
8
5
7
7
5
5
1
1
0
1
144,352
KyleJamesWalker/yamlsettings
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/KyleJamesWalker_yamlsettings/tests/test_yamldict.py
tests.test_yamldict.YamlDictTestCase
class YamlDictTestCase(unittest.TestCase): def setUp(self): # Patch open related functions. open_patcher = mock.patch('{}.open'.format(builtin_module)) open_patch = open_patcher.start() open_patch.side_effect = open_override self.addCleanup(open_patcher.stop) path_patcher = mock.patch('os.path.exists') path_patch = path_patcher.start() path_patch.side_effect = path_override self.addCleanup(path_patcher.stop) isfile_patcher = mock.patch('os.path.isfile') isfile_patch = isfile_patcher.start() isfile_patch.side_effect = isfile_override self.addCleanup(isfile_patcher.stop) def test_load_single_file(self): test_defaults = load('defaults.yml') self.assertEqual(test_defaults.config.greet, 'Hello') self.assertEqual(test_defaults.config.leave, 'Goodbye') self.assertEqual(test_defaults.config.secret, 'I have no secrets') self.assertEqual(test_defaults.config.meaning, 42) # Verify missing raises an AttributeError and not a KeyError self.assertRaises(AttributeError, getattr, test_defaults, 'missing') # Verify access to class attributes self.assertEqual(str(test_defaults.__class__), "<class 'yamlsettings.yamldict.YAMLDict'>") # Test dir access of keys for tab complete self.assertEqual(dir(test_defaults.config), ['greet', 'leave', 'meaning', 'secret']) # Test representation of value self.assertEqual( str(test_defaults.config), 'greet: Hello\nleave: Goodbye\nsecret: I have no secrets\n' 'meaning: 42\n', ) self.assertEqual( repr(test_defaults.config), "{'greet': 'Hello', 'leave': 'Goodbye', " "'secret': 'I have no secrets', 'meaning': 42}", ) # Test foo is saved in keys test_defaults.foo = 'bar' self.assertEqual(test_defaults.foo, 'bar') self.assertEqual(test_defaults['foo'], 'bar') def test_load_first_found(self): test_settings = load(['missing.yml', 'defaults.yml', 'settings.yml']) self.assertEqual(test_settings.config.greet, 'Hello') self.assertEqual(test_settings.config.leave, 'Goodbye') self.assertEqual(test_settings.config.secret, 'I have no secrets') self.assertEqual(test_settings.config.meaning, 42) @mock.patch.dict('os.environ', { 'CONFIG_MEANING': '42.42', 'CONFIG_SECRET': '!!python/object/apply:tests.get_secret []'}) def test_load_with_envs(self): test_defaults = load('defaults.yml') update_from_env(test_defaults) self.assertEqual(test_defaults.config.greet, 'Hello') self.assertEqual(test_defaults.config.leave, 'Goodbye') self.assertEqual(test_defaults.config.secret, 's3cr3tz') self.assertEqual(test_defaults.config.meaning, 42.42) def test_update(self): test_settings = load('defaults.yml') test_settings.update(load('settings.yml')) self.assertEqual(test_settings.config.greet, 'Hello') self.assertEqual(test_settings.config.leave, 'Goodbye') self.assertEqual(test_settings.config.secret, 'I have many secrets') self.assertEqual(test_settings.config.meaning, 42) self.assertEqual(test_settings.config_excited.greet, "Whazzzzup!") def test_rebase(self): test_settings = load('settings.yml') test_settings.rebase(load('defaults.yml')) self.assertEqual(test_settings.config.greet, 'Hello') self.assertEqual(test_settings.config.leave, 'Goodbye') self.assertEqual(test_settings.config.secret, 'I have many secrets') self.assertEqual(test_settings.config.meaning, 42) self.assertEqual(test_settings.config_excited.greet, "Whazzzzup!") def test_limit(self): test_settings = load('settings.yml') test_settings.limit(['config']) self.assertEqual(list(test_settings), ['config']) test_settings2 = load('settings.yml') test_settings2.limit('config') self.assertEqual(list(test_settings), list(test_settings2)) def test_clone_changes_isolated(self): test_settings = load('defaults.yml') test_clone = test_settings.clone() test_settings.config.greet = "Hodo" self.assertNotEqual(test_settings.config.greet, test_clone.config.greet) def test_load_all(self): for test_input in ['fancy.yml', ['fancy.yml']]: section_count = 0 for c_yml in load_all(test_input): if section_count == 0: self.assertEqual(c_yml.test.id1.name, 'hi') self.assertEqual(c_yml.test.test[2].sub_test.a, 10) self.assertEqual(c_yml.test.test[2].sub_test.b.name, 'hi') elif section_count == 1: self.assertEqual(c_yml.test_2.test2.message, 'same here') elif section_count == 2: self.assertEqual(c_yml.test_3.test.name, 'Hello') section_count += 1 self.assertEqual(section_count, 3) def test_save_all(self): cur_ymls = load_all('fancy.yml') m = mock_open() with mock.patch('{}.open'.format(builtin_module), m, create=True): save_all(cur_ymls, 'out.yml') m.assert_called_once_with('out.yml', 'w') def test_update_from_file(self): test_defaults = load('defaults.yml') update_from_file(test_defaults, 'settings.yml') self.assertEqual(test_defaults.config.secret, 'I have many secrets') self.assertEqual(list(test_defaults), ['config']) @mock.patch.dict('os.environ', { 'TEST_GREETING_INTRODUCE': 'The environment says hello!', 'TEST_DICT_VAR_MIX_B': 'Goodbye Variable', }) def test_variable_override(self): test_settings = load("single_fancy.yml") update_from_env(test_settings) self.assertEqual(test_settings.test.greeting.introduce, 'The environment says hello!') self.assertEqual(test_settings.test.dict_var_mix.b, 'Goodbye Variable') @mock.patch.dict('os.environ', { 'TEST_CONFIG_DB': 'OurSQL', }) def test_stupid_override(self): test_settings = load("stupid.yml") update_from_env(test_settings) self.assertEqual(test_settings.test.config.db, 'OurSQL') self.assertEqual(test_settings.test.config_db, 'OurSQL') @mock.patch.dict('os.environ', { 'TEST_GREETING_INTRODUCE': 'The environment says hello!', }) def test_file_writing(self): test_settings = load("single_fancy.yml") update_from_env(test_settings) m = mock_open() with mock.patch('{}.open'.format(builtin_module), m, create=True): with open('current_file.yml', 'w') as h: h.write(str(test_settings)) m.assert_called_once_with('current_file.yml', 'w') handle = m() handle.write.assert_called_with( 'test:\n' ' id1: &id001\n' ' name: hi\n' ' id2: &id002\n' ' name: hello\n' ' var_list:\n' ' - *id001\n' ' - *id002\n' ' dict_var_mix:\n' ' a: 10\n' ' b: *id001\n' ' dict_with_list:\n' ' name: jin\n' ' set:\n' ' - 1\n' ' - 2\n' ' - 3\n' ' greeting:\n' ' introduce: The environment says hello!\n' ' part: Till we meet again\n' ' crazy:\n' ' type: !!python/name:logging.handlers.SysLogHandler \'\'\n' ' module: !!python/module:sys \'\'\n' ' instance: !!python/object:tests.SoftwareEngineer\n' ' name: jin\n' ) def test_yaml_dict_merge(self): test_settings = load("merge.yml") # Verify the merge was successful self.assertEqual(test_settings.base.config.db, "MySQL") self.assertEqual(test_settings.merged.config.db, "MySQL") # Verify whoami was properly overridden self.assertEqual(test_settings.base.whoami, "base") self.assertEqual(test_settings.merged.whoami, "merged") def test_list_replace_on_update(self): test_defaults = load('defaults.yml') test_defaults.update({'a': [1, 2, 3]}) self.assertEqual(test_defaults.a, [1, 2, 3]) test_defaults.update({'a': (4,)}) self.assertEqual(test_defaults.a, (4,)) @mock.patch.dict('os.environ', {'FOO_BAR': 'new-baz'}) def test_dash_vars_with_env(self): """Test items with dashes can be overritten with env""" test_settings = yamldict.YAMLDict({'foo-bar': 'baz'}) assert test_settings['foo-bar'] == 'baz' update_from_env(test_settings) assert test_settings['foo-bar'] == 'new-baz'
class YamlDictTestCase(unittest.TestCase): def setUp(self): pass def test_load_single_file(self): pass def test_load_first_found(self): pass @mock.patch.dict('os.environ', { 'CONFIG_MEANING': '42.42', 'CONFIG_SECRET': '!!python/object/apply:tests.get_secret []'}) def test_load_with_envs(self): pass def test_update(self): pass def test_rebase(self): pass def test_limit(self): pass def test_clone_changes_isolated(self): pass def test_load_all(self): pass def test_save_all(self): pass def test_update_from_file(self): pass @mock.patch.dict('os.environ', { 'TEST_GREETING_INTRODUCE': 'The environment says hello!', 'TEST_DICT_VAR_MIX_B': 'Goodbye Variable', }) def test_variable_override(self): pass @mock.patch.dict('os.environ', { 'TEST_CONFIG_DB': 'OurSQL', }) def test_stupid_override(self): pass @mock.patch.dict('os.environ', { 'TEST_GREETING_INTRODUCE': 'The environment says hello!', }) def test_file_writing(self): pass def test_yaml_dict_merge(self): pass def test_list_replace_on_update(self): pass @mock.patch.dict('os.environ', {'FOO_BAR': 'new-baz'}) def test_dash_vars_with_env(self): '''Test items with dashes can be overritten with env''' pass
23
1
11
0
10
1
1
0.05
1
4
1
0
17
0
17
89
218
23
186
62
154
9
129
47
111
6
2
3
22
144,353
KyleJamesWalker/yamlsettings
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/KyleJamesWalker_yamlsettings/tests/test_settings.py
tests.test_settings.YamlSettingsWithSectionsTestCase
class YamlSettingsWithSectionsTestCase(unittest.TestCase): def setUp(self): path_patcher = mock.patch('os.path.exists') path_patch = path_patcher.start() path_patch.side_effect = path_override self.addCleanup(path_patcher.stop) isfile_patcher = mock.patch('os.path.isfile') isfile_patch = isfile_patcher.start() isfile_patch.side_effect = isfile_override self.addCleanup(isfile_patcher.stop) @mock.patch('{}.open'.format(builtin_module)) def test_settings_with_sections(self, open_patch): open_patch.side_effect = open_override test_settings = YamlSettings('defaults.yml', 'settings.yml', default_section='config') # Verify Base Settings base_settings = test_settings.get_settings() self.assertEqual(base_settings.greet, 'Hello') self.assertEqual(base_settings.leave, 'Goodbye') self.assertEqual(base_settings.secret, 'I have many secrets') # Verify Excited Settings (greet overridden, leave inherits) excited_settings = test_settings.get_settings('config_excited') self.assertEqual(excited_settings.greet, 'Whazzzzup!') self.assertEqual(excited_settings.leave, 'Goodbye') # Verify Cool Settings (greet overridden, leave inherits) cool_settings = test_settings.get_settings('config_cool') self.assertEqual(cool_settings.greet, 'Sup...') self.assertEqual(cool_settings.leave, 'Goodbye') @mock.patch('{}.open'.format(builtin_module)) def test_settings_without_sections(self, open_patch): open_patch.side_effect = open_override test_settings = YamlSettings('defaults_no_sec.yml', 'settings_no_sec.yml') base_settings = test_settings.get_settings() self.assertEqual(base_settings.config.greet, 'Why hello good sir or mam.') self.assertEqual(base_settings.config.leave, 'Goodbye') @mock.patch.dict('os.environ', {'CONFIG_GREET': 'Howdy'}) @mock.patch('{}.open'.format(builtin_module)) def test_settings_without_environment(self, open_patch): open_patch.side_effect = open_override test_settings = YamlSettings('defaults.yml', 'settings.yml', default_section='config', override_envs=False) base_settings = test_settings.get_settings('config_cool') self.assertEqual(base_settings.greet, 'Sup...') self.assertEqual(base_settings.leave, 'Goodbye') @mock.patch.dict('os.environ', {'CONFIG_GREET': 'Howdy'}) @mock.patch('{}.open'.format(builtin_module)) def test_settings_with_environment(self, open_patch): open_patch.side_effect = open_override test_settings = YamlSettings('defaults.yml', 'settings.yml', default_section='config') base_settings = test_settings.get_settings('config_cool') self.assertEqual(base_settings.greet, 'Howdy') self.assertEqual(base_settings.leave, 'Goodbye') @mock.patch.dict('os.environ', {'CONFIG_GREET': 'Howdy', 'CONFIG_LEAVE': 'Later'}) @mock.patch('{}.open'.format(builtin_module)) def test_settings_with_environment_pre(self, open_patch): open_patch.side_effect = open_override test_settings = YamlSettings('defaults.yml', 'settings.yml', default_section='config', envs_override_defaults_only=True) base_settings = test_settings.get_settings('config_cool') self.assertEqual(base_settings.greet, 'Sup...') self.assertEqual(base_settings.leave, 'Later') @mock.patch.dict('os.environ', {'CONFIG_GREET': 'Howdy'}) @mock.patch('{}.open'.format(builtin_module)) def test_settings_without_sections_or_environment(self, open_patch): open_patch.side_effect = open_override test_settings = YamlSettings('defaults_no_sec.yml', 'settings_no_sec.yml', override_envs=False) base_settings = test_settings.get_settings() self.assertEqual(base_settings.config.greet, 'Why hello good sir or mam.') self.assertEqual(base_settings.config.leave, 'Goodbye') @mock.patch.dict('os.environ', {'CONFIG_GREET': 'Howdy', 'CONFIG_LEAVE': 'Later'}) @mock.patch('{}.open'.format(builtin_module)) def test_settings_without_sections_with_environment(self, open_patch): open_patch.side_effect = open_override test_settings = YamlSettings('defaults_no_sec.yml', 'settings_no_sec.yml', override_envs=True) base_settings = test_settings.get_settings() self.assertEqual(base_settings.config.greet, 'Howdy') self.assertEqual(base_settings.config.leave, 'Later') @mock.patch.dict('os.environ', {'CONFIG_GREET': 'Howdy', 'CONFIG_LEAVE': 'Later'}) @mock.patch('{}.open'.format(builtin_module)) def test_settings_without_sections_with_environment_pre(self, open_patch): open_patch.side_effect = open_override test_settings = YamlSettings('defaults_no_sec.yml', 'settings_no_sec.yml', override_envs=True, envs_override_defaults_only=True) base_settings = test_settings.get_settings() self.assertEqual(base_settings.config.greet, 'Why hello good sir or mam.') self.assertEqual(base_settings.config.leave, 'Later') @mock.patch('{}.open'.format(builtin_module)) def test_settings_without_required_override_file(self, open_patch): open_patch.side_effect = open_override self.assertRaises(IOError, YamlSettings, 'defaults.yml', 'no_settings.yml', override_required=True) @mock.patch('{}.open'.format(builtin_module)) def test_settings_without_optional_override_file(self, open_patch): open_patch.side_effect = open_override test_settings = YamlSettings('defaults.yml', 'no_settings.yml', override_required=False) base_settings = test_settings.get_settings() self.assertEqual(base_settings.config.greet, 'Hello') self.assertEqual(base_settings.config.leave, 'Goodbye') @mock.patch('{}.open'.format(builtin_module)) def test_settings_bad_default_section(self, open_patch): open_patch.side_effect = open_override self.assertRaises(KeyError, YamlSettings, 'defaults.yml', 'settings.yml', default_section='configuration') @mock.patch('{}.open'.format(builtin_module)) def test_serialization(self, open_patch): open_patch.side_effect = open_override test_settings = YamlSettings('defaults.yml', 'settings.yml', default_section='config') base_settings = test_settings.get_settings() self.assertEqual( dict(base_settings), { 'greet': 'Hello', 'leave': 'Goodbye', 'secret': 'I have many secrets', 'meaning': 42 } ) self.assertEqual( json.dumps(base_settings), '{"greet": "Hello", "leave": "Goodbye", ' '"secret": "I have many secrets", "meaning": 42}' ) def test_all_without_override_file(self): pass def test_single_section_load(self): pass def test_callback_support(self): # Might add at least one configurable callback # Shell example def build_connections(path, format): search_path = path path_format = format def callback(settings): # Do stuff with search_path and path_format settings[search_path] = path_format return callback pass
class YamlSettingsWithSectionsTestCase(unittest.TestCase): def setUp(self): pass @mock.patch('{}.open'.format(builtin_module)) def test_settings_with_sections(self, open_patch): pass @mock.patch('{}.open'.format(builtin_module)) def test_settings_without_sections(self, open_patch): pass @mock.patch.dict('os.environ', {'CONFIG_GREET': 'Howdy'}) @mock.patch('{}.open'.format(builtin_module)) def test_settings_without_environment(self, open_patch): pass @mock.patch.dict('os.environ', {'CONFIG_GREET': 'Howdy'}) @mock.patch('{}.open'.format(builtin_module)) def test_settings_with_environment(self, open_patch): pass @mock.patch.dict('os.environ', {'CONFIG_GREET': 'Howdy', 'CONFIG_LEAVE': 'Later'}) @mock.patch('{}.open'.format(builtin_module)) def test_settings_with_environment_pre(self, open_patch): pass @mock.patch.dict('os.environ', {'CONFIG_GREET': 'Howdy'}) @mock.patch('{}.open'.format(builtin_module)) def test_settings_without_sections_or_environment(self, open_patch): pass @mock.patch.dict('os.environ', {'CONFIG_GREET': 'Howdy', 'CONFIG_LEAVE': 'Later'}) @mock.patch('{}.open'.format(builtin_module)) def test_settings_without_sections_with_environment(self, open_patch): pass @mock.patch.dict('os.environ', {'CONFIG_GREET': 'Howdy', 'CONFIG_LEAVE': 'Later'}) @mock.patch('{}.open'.format(builtin_module)) def test_settings_without_sections_with_environment_pre(self, open_patch): pass @mock.patch('{}.open'.format(builtin_module)) def test_settings_without_required_override_file(self, open_patch): pass @mock.patch('{}.open'.format(builtin_module)) def test_settings_without_optional_override_file(self, open_patch): pass @mock.patch('{}.open'.format(builtin_module)) def test_settings_bad_default_section(self, open_patch): pass @mock.patch('{}.open'.format(builtin_module)) def test_serialization(self, open_patch): pass def test_all_without_override_file(self): pass def test_single_section_load(self): pass def test_callback_support(self): pass def build_connections(path, format): pass def callback(settings): pass
37
0
9
1
8
0
1
0.04
1
3
1
0
16
0
16
88
195
37
152
62
112
6
95
47
76
1
2
0
18
144,354
KyleJamesWalker/yamlsettings
KyleJamesWalker_yamlsettings/yamlsettings/yamldict.py
yamlsettings.yamldict.YAMLDictRepresenter
class YAMLDictRepresenter(yaml.representer.Representer): def represent_YAMLDict(self, mapping): value = [] node = yaml.MappingNode(u'tag:yaml.org,2002:map', value, flow_style=None) if self.alias_key is not None: self.represented_objects[self.alias_key] = node best_style = True if hasattr(mapping, 'items'): mapping = mapping.items() for item_key, item_value in mapping: node_key = self.represent_data(item_key) node_value = self.represent_data(item_value) if not (isinstance(node_key, yaml.ScalarNode) and not node_key.style): best_style = False if not (isinstance(node_value, yaml.ScalarNode) and not node_value.style): best_style = False value.append((node_key, node_value)) if self.default_flow_style is not None: node.flow_style = self.default_flow_style else: node.flow_style = best_style return node
class YAMLDictRepresenter(yaml.representer.Representer): def represent_YAMLDict(self, mapping): pass
2
0
24
0
24
0
7
0
1
0
0
1
1
0
1
1
26
1
25
8
23
0
21
8
19
7
1
2
7
144,355
KyleJamesWalker/yamlsettings
KyleJamesWalker_yamlsettings/yamlsettings/yamldict.py
yamlsettings.yamldict.YAMLDictLoader
class YAMLDictLoader(yaml.FullLoader, yaml.constructor.UnsafeConstructor): ''' Loader for YAMLDict object Adopted from: https://gist.github.com/844388 ''' def __init__(self, *args, **kwargs): super(YAMLDictLoader, self).__init__(*args, **kwargs) # override constructors for maps (i.e. dictionaries) self.add_constructor(u'tag:yaml.org,2002:map', type(self).construct_yaml_map) self.add_constructor(u'tag:yaml.org,2002:omap', type(self).construct_yaml_map) # Method override to create YAMLDict rather than dict def construct_yaml_map(self, node): data = YAMLDict() yield data value = self.construct_mapping(node) # Call the original update() function here to maintain YAMLDict super(YAMLDict, data).update(value) # method override to create YAMLDict rather than dict def construct_mapping(self, node, deep=False): if isinstance(node, yaml.MappingNode): self.flatten_mapping(node) if not isinstance(node, yaml.MappingNode): raise yaml.constructor.ConstructorError( None, None, 'expected a mapping node, but found {0}'.format(node.id), node.start_mark ) mapping = YAMLDict() for key_node, value_node in node.value: key = self.construct_object(key_node, deep=deep) try: hash(key) except TypeError as exc: raise yaml.constructor.ConstructorError( 'while constructing a mapping', node.start_mark, 'found unacceptable key ({0})'.format(exc), key_node.start_mark ) value = self.construct_object(value_node, deep=deep) mapping[key] = value return mapping
class YAMLDictLoader(yaml.FullLoader, yaml.constructor.UnsafeConstructor): ''' Loader for YAMLDict object Adopted from: https://gist.github.com/844388 ''' def __init__(self, *args, **kwargs): pass def construct_yaml_map(self, node): pass def construct_mapping(self, node, deep=False): pass
4
1
13
0
12
1
2
0.24
2
5
1
0
3
0
3
54
49
3
37
11
33
9
25
10
21
5
4
2
7
144,356
KyleJamesWalker/yamlsettings
KyleJamesWalker_yamlsettings/yamlsettings/yamldict.py
yamlsettings.yamldict.YAMLDictDumper
class YAMLDictDumper(yaml.emitter.Emitter, yaml.serializer.Serializer, YAMLDictRepresenter, yaml.resolver.Resolver): def __init__(self, stream, default_style=None, default_flow_style=None, canonical=None, indent=None, width=None, allow_unicode=None, line_break=None, encoding=None, version=None, tags=None, explicit_start=None, explicit_end=None, sort_keys=None): yaml.emitter.Emitter.__init__(self, stream, canonical=canonical, indent=indent, width=width, allow_unicode=allow_unicode, line_break=line_break) yaml.serializer.Serializer.__init__(self, encoding=encoding, explicit_start=explicit_start, explicit_end=explicit_end, version=version, tags=tags) YAMLDictRepresenter.__init__(self, default_style=default_style, default_flow_style=default_flow_style) yaml.resolver.Resolver.__init__(self)
class YAMLDictDumper(yaml.emitter.Emitter, yaml.serializer.Serializer, YAMLDictRepresenter, yaml.resolver.Resolver): def __init__(self, stream, default_style=None, default_flow_style=None, canonical=None, indent=None, width=None, allow_unicode=None, line_break=None, encoding=None, version=None, tags=None, explicit_start=None, explicit_end=None, sort_keys=None): pass
2
0
19
0
19
0
1
0
4
0
0
0
1
0
1
2
24
1
23
10
13
0
6
2
4
1
2
0
1
144,357
KyleJamesWalker/yamlsettings
KyleJamesWalker_yamlsettings/yamlsettings/yamldict.py
yamlsettings.yamldict.YAMLDict
class YAMLDict(collections.OrderedDict): ''' Order-preserved, attribute-accessible dictionary object for YAML settings Improved from: https://github.com/mk-fg/layered-yaml-attrdict-config ''' def __init__(self, *args, **kwargs): super(YAMLDict, self).__init__(*args, **kwargs) # Reset types of all sub-nodes through the hierarchy self.update(self) def __getattribute__(self, k): try: return super(YAMLDict, self).__getattribute__(k) except AttributeError: try: return self[k] except KeyError: raise AttributeError def __setattr__(self, k, v): if k.startswith('_OrderedDict__'): return super(YAMLDict, self).__setattr__(k, v) self[k] = v def __str__(self): return dump(self, stream=None, default_flow_style=False) def __repr__(self): return '{' + ', '.join(['{0}: {1}'.format(repr(k), repr(v)) for k, v in self.items()]) + '}' def __dir__(self): return self.keys() def traverse(self, callback): ''' Traverse through all keys and values (in-order) and replace keys and values with the return values from the callback function. ''' def _traverse_node(path, node, callback): ret_val = callback(path, node) if ret_val is not None: # replace node with the return value node = ret_val else: # traverse deep into the hierarchy if isinstance(node, YAMLDict): for k, v in node.items(): node[k] = _traverse_node(path + [k], v, callback) elif isinstance(node, list): for i, v in enumerate(node): node[i] = _traverse_node(path + ['[{0}]'.format(i)], v, callback) else: pass return node _traverse_node([], self, callback) def update(self, yaml_dict): ''' Update the content (i.e. keys and values) with yaml_dict. ''' def _update_node(base_node, update_node): if isinstance(update_node, YAMLDict) or \ isinstance(update_node, dict): if not (isinstance(base_node, YAMLDict)): # NOTE: A regular dictionary is replaced by a new # YAMLDict object. new_node = YAMLDict() else: new_node = base_node for k, v in update_node.items(): new_node[k] = _update_node(new_node.get(k), v) elif isinstance(update_node, list) or isinstance( update_node, tuple ): # NOTE: A list/tuple is replaced by a new list/tuple. new_node = [] for v in update_node: new_node.append(_update_node(None, v)) if isinstance(update_node, tuple): new_node = tuple(new_node) else: new_node = update_node return new_node # Convert non-YAMLDict objects to a YAMLDict if not (isinstance(yaml_dict, YAMLDict) or isinstance(yaml_dict, dict)): yaml_dict = YAMLDict(yaml_dict) _update_node(self, yaml_dict) def clone(self): ''' Creates and returns a new copy of self. ''' clone = YAMLDict() clone.update(self) return clone def rebase(self, yaml_dict): ''' Use yaml_dict as self's new base and update with existing reverse of update. ''' base = yaml_dict.clone() base.update(self) self.clear() self.update(base) def limit(self, keys): ''' Remove all keys other than the keys specified. ''' if not isinstance(keys, list) and not isinstance(keys, tuple): keys = [keys] remove_keys = [k for k in self.keys() if k not in keys] for k in remove_keys: self.pop(k)
class YAMLDict(collections.OrderedDict): ''' Order-preserved, attribute-accessible dictionary object for YAML settings Improved from: https://github.com/mk-fg/layered-yaml-attrdict-config ''' def __init__(self, *args, **kwargs): pass def __getattribute__(self, k): pass def __setattr__(self, k, v): pass def __str__(self): pass def __repr__(self): pass def __dir__(self): pass def traverse(self, callback): ''' Traverse through all keys and values (in-order) and replace keys and values with the return values from the callback function. ''' pass def _traverse_node(path, node, callback): pass def update(self, yaml_dict): ''' Update the content (i.e. keys and values) with yaml_dict. ''' pass def _update_node(base_node, update_node): pass def clone(self): ''' Creates and returns a new copy of self. ''' pass def rebase(self, yaml_dict): ''' Use yaml_dict as self's new base and update with existing reverse of update. ''' pass def limit(self, keys): ''' Remove all keys other than the keys specified. ''' pass
14
6
11
0
9
2
2
0.31
1
6
0
0
11
0
11
61
117
11
81
22
67
25
68
22
54
7
3
3
30
144,358
KyleJamesWalker/yamlsettings
KyleJamesWalker_yamlsettings/yamlsettings/helpers.py
yamlsettings.helpers.YamlSettings
class YamlSettings(object): """Deprecated: Old helper class to load settings in a opinionated way. It's recommended to write or use an opinionated extension now. """ def __init__(self, default_settings, override_settings, override_envs=True, default_section=None, cur_section=None, param_callback=None, override_required=False, envs_override_defaults_only=False, single_section_load=False): defaults = registry.load(default_settings) if override_envs and envs_override_defaults_only: if default_section: prefix = default_section section = defaults[default_section] else: prefix = "" section = defaults update_from_env(section, prefix) self.cur_section = default_section if default_section is None: # No section support simply update with overrides self.settings = defaults try: # WAS: # self.settings.update_yaml(override_settings) self.settings.update(registry.load(override_settings)) except IOError: if override_required: raise if override_envs and not envs_override_defaults_only: update_from_env(self.settings, "") else: # Load Overrides first and merge with defaults try: self.settings = registry.load(override_settings) except IOError: if override_required: raise # Note this will copy to itself right now, but # will allows for simpler logic to get environment # variables to work self.settings = defaults for cur_section in self.settings: cur = self.settings[cur_section] cur.rebase(defaults[self.cur_section]) if override_envs and not envs_override_defaults_only: update_from_env(cur, default_section) # Make sure default section is created if default_section not in self.settings: self.settings[default_section] = defaults[default_section] if override_envs and not envs_override_defaults_only: update_from_env(self.settings[default_section], default_section) def get_settings(self, section_name=None): if section_name is None: section_name = self.cur_section if section_name is None: return self.settings else: return self.settings[section_name]
class YamlSettings(object): '''Deprecated: Old helper class to load settings in a opinionated way. It's recommended to write or use an opinionated extension now. ''' def __init__(self, default_settings, override_settings, override_envs=True, default_section=None, cur_section=None, param_callback=None, override_required=False, envs_override_defaults_only=False, single_section_load=False): pass def get_settings(self, section_name=None): pass
3
1
31
3
24
4
8
0.22
1
0
0
0
2
2
2
2
69
9
49
13
42
11
41
9
38
13
1
3
16
144,359
KyleJamesWalker/yamlsettings
KyleJamesWalker_yamlsettings/tests/extensions/test_registry.py
tests.extensions.test_registry.MockExtension2
class MockExtension2(YamlSettingsExtension): protocols = ['mock2'] @classmethod def load_target(cls, scheme, path, fragment, username, password, hostname, port, query, load_method, **kwargs): return load_method("mock: test")
class MockExtension2(YamlSettingsExtension): @classmethod def load_target(cls, scheme, path, fragment, username, password, hostname, port, query, load_method, **kwargs): pass
3
0
4
0
4
0
1
0
1
0
0
0
0
0
1
3
8
1
7
6
2
0
4
3
2
1
1
0
1
144,360
KyleJamesWalker/yamlsettings
KyleJamesWalker_yamlsettings/yamlsettings/extensions/registry.py
yamlsettings.extensions.registry.RegistryError
class RegistryError(Exception): """The base exception thrown by the registry"""
class RegistryError(Exception): '''The base exception thrown by the registry''' pass
1
1
0
0
0
0
0
1
1
0
0
2
0
0
0
10
2
0
1
1
0
1
1
1
0
0
3
0
0
144,361
KyleJamesWalker/yamlsettings
KyleJamesWalker_yamlsettings/yamlsettings/extensions/registry.py
yamlsettings.extensions.registry.NoProtocolError
class NoProtocolError(RegistryError): """Thrown when there is no extension for the given protocol"""
class NoProtocolError(RegistryError): '''Thrown when there is no extension for the given protocol''' 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
144,362
KyleJamesWalker/yamlsettings
KyleJamesWalker_yamlsettings/yamlsettings/extensions/registry.py
yamlsettings.extensions.registry.InvalidQuery
class InvalidQuery(RegistryError): """Thrown when an extension is passed unexpected arguments"""
class InvalidQuery(RegistryError): '''Thrown when an extension is passed unexpected arguments'''
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
144,363
KyleJamesWalker/yamlsettings
KyleJamesWalker_yamlsettings/yamlsettings/extensions/registry.py
yamlsettings.extensions.registry.ExtensionRegistry
class ExtensionRegistry(object): def __init__(self, extensions): """A registry that stores extensions to open and parse Target URIs :param extensions: A list of extensions. :type extensions: yamlsettings.extensions.base.YamlSettingsExtension """ self.registry = {} self.extensions = {} self.default_protocol = 'file' for extension in extensions: self.add(extension) self._discover() def _get_entry_points(self): """Get all entry points for yamlsettings10""" ep = entry_points() try: points = ep.select(group='yamlsettings10') except AttributeError: # Compatibility fallback points = ep.get('yamlsettings10', []) return points def _discover(self): """Find and install all extensions""" for ep in self._get_entry_points(): ext = ep.load() if callable(ext): ext = ext() self.add(ext) def get_extension(self, protocol): """Retrieve extension for the given protocol :param protocol: name of the protocol :type protocol: string :raises NoProtocolError: no extension registered for protocol """ if protocol not in self.registry: raise NoProtocolError("No protocol for %s" % protocol) index = self.registry[protocol] return self.extensions[index] def add(self, extension): """Adds an extension to the registry :param extension: Extension object :type extension: yamlsettings.extensions.base.YamlSettingsExtension """ index = len(self.extensions) self.extensions[index] = extension for protocol in extension.protocols: self.registry[protocol] = index def _load_first(self, target_uris, load_method, **kwargs): """Load first yamldict target found in uri list. :param target_uris: Uris to try and open :param load_method: load callback :type target_uri: list or string :type load_method: callback :returns: yamldict """ if isinstance(target_uris, string_types): target_uris = [target_uris] # TODO: Move the list logic into the extension, otherwise a # load will always try all missing files first. # TODO: How would multiple protocols work, should the registry hold # persist copies? for target_uri in target_uris: target = urlsplit(target_uri, scheme=self.default_protocol) extension = self.get_extension(target.scheme) query = extension.conform_query(target.query) try: yaml_dict = extension.load_target( target.scheme, target.path, target.fragment, target.username, target.password, target.hostname, target.port, query, load_method, **kwargs ) return yaml_dict except extension.not_found_exception: pass raise IOError("unable to load: {0}".format(target_uris)) def load(self, target_uris, fields=None, **kwargs): """Load first yamldict target found in uri. :param target_uris: Uris to try and open :param fields: Fields to filter. Default: None :type target_uri: list or string :type fields: list :returns: yamldict """ yaml_dict = self._load_first( target_uris, yamlsettings.yamldict.load, **kwargs ) # TODO: Move this into the extension, otherwise every load from # a persistant location will refilter fields. if fields: yaml_dict.limit(fields) return yaml_dict def load_all(self, target_uris, **kwargs): ''' Load *all* YAML settings from a list of file paths given. - File paths in the list gets the priority by their orders of the list. ''' yaml_series = self._load_first( target_uris, yamlsettings.yamldict.load_all, **kwargs ) yaml_dicts = [] for yaml_dict in yaml_series: yaml_dicts.append(yaml_dict) # return YAMLDict objects return yaml_dicts
class ExtensionRegistry(object): def __init__(self, extensions): '''A registry that stores extensions to open and parse Target URIs :param extensions: A list of extensions. :type extensions: yamlsettings.extensions.base.YamlSettingsExtension ''' pass def _get_entry_points(self): '''Get all entry points for yamlsettings10''' pass def _discover(self): '''Find and install all extensions''' pass def get_extension(self, protocol): '''Retrieve extension for the given protocol :param protocol: name of the protocol :type protocol: string :raises NoProtocolError: no extension registered for protocol ''' pass def add(self, extension): '''Adds an extension to the registry :param extension: Extension object :type extension: yamlsettings.extensions.base.YamlSettingsExtension ''' pass def _load_first(self, target_uris, load_method, **kwargs): '''Load first yamldict target found in uri list. :param target_uris: Uris to try and open :param load_method: load callback :type target_uri: list or string :type load_method: callback :returns: yamldict ''' pass def load(self, target_uris, fields=None, **kwargs): '''Load first yamldict target found in uri. :param target_uris: Uris to try and open :param fields: Fields to filter. Default: None :type target_uri: list or string :type fields: list :returns: yamldict ''' pass def load_all(self, target_uris, **kwargs): ''' Load *all* YAML settings from a list of file paths given. - File paths in the list gets the priority by their orders of the list. ''' pass
9
8
16
2
9
5
2
0.6
1
2
1
0
8
3
8
8
137
25
70
29
61
42
55
29
46
4
1
2
19
144,364
KyleJamesWalker/yamlsettings
KyleJamesWalker_yamlsettings/yamlsettings/extensions/package.py
yamlsettings.extensions.package.PackageExtension
class PackageExtension(YamlSettingsExtension): """Load a yaml resource from a python package. Args: resource: The resource to load from the package (default: settings.yaml) env: When set the yamldict will update with env variables (default: true) prefix: Prefix for environment loading (default: None) persist: When set the yamldict will only be loaded once. (default: true) examples: * pkg://example (opens the settings.yaml resource and loads env vars) """ protocols = ['pkg', 'package'] default_query = { 'resource': 'settings.yaml', 'env': True, 'prefix': None, 'persist': True, } _persistence = {} @classmethod def load_target(cls, scheme, path, fragment, username, password, hostname, port, query, load_method, **kwargs): package_path = (hostname or '') + path query.update(kwargs) resource = query['resource'] env = query['env'] prefix = query['prefix'] persist = query['persist'] persistence_key = "{}:{}".format(package_path, resource) if persist and persistence_key in cls._persistence: yaml_contents = cls._persistence[persistence_key] else: pkg_data = pkgutil.get_data(package_path, resource) if pkg_data is None: raise IOError("package - {}:{}".format(package_path, resource)) yaml_contents = load_method(pkg_data) # Load all returns a generator list of configurations many = isinstance(yaml_contents, types.GeneratorType) yaml_contents = list(yaml_contents) if many else yaml_contents if env and many: for contents in yaml_contents: yamlsettings.update_from_env(contents, prefix) elif env: yamlsettings.update_from_env(yaml_contents, prefix) if persist: cls._persistence[persistence_key] = yaml_contents return yaml_contents
class PackageExtension(YamlSettingsExtension): '''Load a yaml resource from a python package. Args: resource: The resource to load from the package (default: settings.yaml) env: When set the yamldict will update with env variables (default: true) prefix: Prefix for environment loading (default: None) persist: When set the yamldict will only be loaded once. (default: true) examples: * pkg://example (opens the settings.yaml resource and loads env vars) ''' @classmethod def load_target(cls, scheme, path, fragment, username, password, hostname, port, query, load_method, **kwargs): pass
3
1
35
7
27
1
8
0.27
1
1
0
0
0
0
1
3
58
11
37
18
32
10
27
15
25
8
1
3
8
144,365
KyleJamesWalker/yamlsettings
KyleJamesWalker_yamlsettings/tests/extensions/test_registry.py
tests.extensions.test_registry.MockExtension
class MockExtension(YamlSettingsExtension): protocols = ['mock'] @classmethod def load_target(cls, scheme, path, fragment, username, password, hostname, port, query, load_method, **kwargs): return load_method("mock: test")
class MockExtension(YamlSettingsExtension): @classmethod def load_target(cls, scheme, path, fragment, username, password, hostname, port, query, load_method, **kwargs): pass
3
0
4
0
4
0
1
0
1
0
0
0
0
0
1
3
8
1
7
6
2
0
4
3
2
1
1
0
1
144,366
Kyria/EsiPy
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Kyria_EsiPy/test/test_client.py
test.test_client.TestEsiPy
class TestEsiPy(unittest.TestCase): CALLBACK_URI = "https://foo.bar/baz/callback" LOGIN_EVE = "https://login.eveonline.com" OAUTH_VERIFY = "%s/oauth/verify" % LOGIN_EVE OAUTH_TOKEN = "%s/oauth/token" % LOGIN_EVE CLIENT_ID = 'foo' SECRET_KEY = 'bar' BASIC_TOKEN = six.u('Zm9vOmJhcg==') SECURITY_NAME = 'evesso' RSC_SSO_ENDPOINTS = "test/resources/oauth-authorization-server.json" RSC_JWKS = "test/resources/jwks.json" @mock.patch('six.moves.urllib.request.urlopen') def setUp(self, urlopen_mock): # I hate those mock... thx urlopen instead of requests... urlopen_mock.return_value = open('test/resources/swagger.json') warnings.simplefilter('ignore') self.app = App.create( 'https://esi.evetech.net/latest/swagger.json' ) with open(TestEsiPy.RSC_SSO_ENDPOINTS, 'r') as sso_endpoints: with open(TestEsiPy.RSC_JWKS, "r") as jwks: self.security = EsiSecurity( app=self.app, redirect_uri=TestEsiPy.CALLBACK_URI, client_id=TestEsiPy.CLIENT_ID, secret_key=TestEsiPy.SECRET_KEY, sso_endpoints=json.load(sso_endpoints), jwks_key=json.load(jwks) ) self.cache = DictCache() self.client = EsiClient(self.security, cache=self.cache) self.client_no_auth = EsiClient(cache=self.cache, retry_requests=True) def tearDown(self): """ clear the cache so we don't have residual data """ self.cache._dict = {} def test_esipy_client_no_args(self): client_no_args = EsiClient() self.assertIsNone(client_no_args.security) self.assertTrue(isinstance(client_no_args.cache, DictCache)) self.assertEqual( client_no_args._session.headers['User-Agent'], 'EsiPy/Client - https://github.com/Kyria/EsiPy' ) self.assertEqual(client_no_args.raw_body_only, False) def test_esipy_client_with_headers(self): client_with_headers = EsiClient(headers={'User-Agent': 'foobar'}) self.assertEqual( client_with_headers._session.headers['User-Agent'], 'foobar' ) def test_esipy_client_with_adapter(self): transport_adapter = HTTPAdapter() client_with_adapters = EsiClient( transport_adapter=transport_adapter ) self.assertEqual( client_with_adapters._session.get_adapter('http://'), transport_adapter ) self.assertEqual( client_with_adapters._session.get_adapter('https://'), transport_adapter ) def test_esipy_client_without_cache(self): client_without_cache = EsiClient(cache=None) self.assertTrue(isinstance(client_without_cache.cache, DummyCache)) def test_esipy_client_with_cache(self): cache = DictCache() client_with_cache = EsiClient(cache=cache) self.assertTrue(isinstance(client_with_cache.cache, BaseCache)) self.assertEqual(client_with_cache.cache, cache) def test_esipy_client_wrong_cache(self): with self.assertRaises(ValueError): EsiClient(cache=DictCache) def test_esipy_request_public(self): with httmock.HTTMock(public_incursion): incursions = self.client_no_auth.request( self.app.op['get_incursions']() ) self.assertEqual(incursions.data[0].type, 'Incursion') self.assertEqual(incursions.data[0].faction_id, 500019) def test_esipy_request_authed(self): with httmock.HTTMock(*_all_auth_mock_): self.security.auth('let it bee') char_location = self.client.request( self.app.op['get_characters_character_id_location']( character_id=123456789 ) ) self.assertEqual(char_location.data.station_id, 60004756) # force expire self.security.token_expiry = 0 char_location_with_refresh = self.client.request( self.app.op['get_characters_character_id_location']( character_id=123456789 ) ) self.assertEqual( char_location_with_refresh.data.station_id, 60004756 ) def test_client_cache_request(self): @httmock.all_requests def fail_if_request(url, request): self.fail('Cached data is not supposed to do requests') incursion_operation = self.app.op['get_incursions'] with httmock.HTTMock(public_incursion_no_expires): incursions = self.client_no_auth.request(incursion_operation()) self.assertEqual(incursions.data[0].state, 'mobilizing') with httmock.HTTMock(public_incursion_no_expires_second): incursions = self.client_no_auth.request(incursion_operation()) self.assertEqual(incursions.data[0].state, 'established') with httmock.HTTMock(public_incursion): incursions = self.client_no_auth.request(incursion_operation()) self.assertEqual(incursions.data[0].state, 'mobilizing') with httmock.HTTMock(fail_if_request): incursions = self.client_no_auth.request(incursion_operation()) self.assertEqual(incursions.data[0].state, 'mobilizing') def test_client_warning_header(self): # deprecated warning warnings.simplefilter('error') with httmock.HTTMock(public_incursion_warning): incursion_operation = self.app.op['get_incursions'] with self.assertRaises(UserWarning): self.client_no_auth.request(incursion_operation()) with self.assertRaises(UserWarning): self.client_no_auth.head(incursion_operation()) def test_client_raw_body_only(self): client = EsiClient(raw_body_only=True) self.assertEqual(client.raw_body_only, True) with httmock.HTTMock(public_incursion): incursions = client.request(self.app.op['get_incursions']()) self.assertIsNone(incursions.data) self.assertTrue(len(incursions.raw) > 0) incursions = client.request( self.app.op['get_incursions'](), raw_body_only=False ) self.assertIsNotNone(incursions.data) def test_esipy_reuse_operation(self): operation = self.app.op['get_incursions']() with httmock.HTTMock(public_incursion): incursions = self.client_no_auth.request(operation) self.assertEqual(incursions.data[0].faction_id, 500019) # this shouldn't create any errors incursions = self.client_no_auth.request(operation) self.assertEqual(incursions.data[0].faction_id, 500019) def test_esipy_multi_request(self): operation = self.app.op['get_incursions']() with httmock.HTTMock(public_incursion): count = 0 for req, incursions in self.client_no_auth.multi_request( [operation, operation, operation], threads=2): self.assertEqual(incursions.data[0].faction_id, 500019) count += 1 # Check we made 3 requests self.assertEqual(count, 3) def test_esipy_backoff(self): operation = self.app.op['get_incursions']() start_calls = time.time() with httmock.HTTMock(public_incursion_server_error): incursions = self.client_no_auth.request(operation) self.assertEqual(incursions.data.error, 'broke') end_calls = time.time() # Check we retried 5 times self.assertEqual(incursions.data.count, 5) # Check that backoff slept for a sum > 2 seconds self.assertTrue(end_calls - start_calls > 2) def test_esipy_timeout(self): def send_function(*args, **kwargs): """ manually create a ConnectionError to test the retry and be sure no exception is thrown """ send_function.count += 1 raise ConnectionError send_function.count = 0 self.client_no_auth._session.send = mock.MagicMock( side_effect=send_function ) operation = self.app.op['get_incursions']() with httmock.HTTMock(public_incursion): incursions = self.client_no_auth.request(operation) # there shouldn't be any exceptions self.assertEqual(incursions.status, 500) self.assertEqual(send_function.count, 5) def test_esipy_raise_on_error(self): operation = self.app.op['get_incursions']() with httmock.HTTMock(public_incursion_server_error): # try with retries with self.assertRaises(APIException): self.client_no_auth.request(operation, raise_on_error=True) # try without retries with self.assertRaises(APIException): self.client.request(operation, raise_on_error=True) # try with head with self.assertRaises(APIException): self.client_no_auth.head(operation, raise_on_error=True) def test_esipy_expired_response(self): operation = self.app.op['get_incursions'] with httmock.HTTMock(public_incursion_expired): warnings.filterwarnings('error', '.*returned expired result') with self.assertRaises(UserWarning): self.client_no_auth.request(operation()) warnings.resetwarnings() warnings.simplefilter('ignore') incursions = self.client_no_auth.request(operation()) self.assertEquals(incursions.status, 200) def test_esipy_uncached_method(self): operation = self.app.op['post_universe_ids'](names=['Foo']) self.assertEqual(self.cache._dict, {}) with httmock.HTTMock(post_universe_id): res = self.client.request(operation) self.assertEqual(res.data.characters[0].id, 123456789) self.assertEqual(self.cache._dict, {}) def test_esipy_head_request(self): operation = self.app.op['get_incursions']() with httmock.HTTMock(public_incursion): res = self.client.head(operation) self.assertIsNone(res.data) self.assertIn('Expires', res.header) def test_esipy_expired_header_etag(self): @httmock.all_requests def check_etag(url, request): self.assertEqual( request.headers.get('If-None-Match'), '"esipy_test_etag_status"' ) return httmock.response( headers={'Etag': '"esipy_test_etag_status"', 'expires': make_expire_time_str(), 'date': make_expire_time_str()}, status_code=304) operation = self.app.op['get_status']() with httmock.HTTMock(eve_status): self.assertEqual(self.cache._dict, {}) res = self.client.request(operation) self.assertNotEqual(self.cache._dict, {}) self.assertEqual(res.data.server_version, "1313143") time.sleep(2) with httmock.HTTMock(check_etag): res = self.client.request(operation) self.assertEqual(res.data.server_version, "1313143") def test_esipy_expired_header_etag_no_body(self): # check that the response is empty with no_etag_body=True @httmock.all_requests def check_etag(url, request): return httmock.response( headers={'Etag': '"esipy_test_etag_status"', 'expires': make_expire_time_str(), 'date': make_expire_time_str()}, status_code=304) operation = self.app.op['get_status']() self.client.no_etag_body = True with httmock.HTTMock(eve_status): self.assertEqual(self.cache._dict, {}) res = self.client.request(operation) self.assertNotEqual(self.cache._dict, {}) self.assertEqual(res.data.server_version, "1313143") time.sleep(2) with httmock.HTTMock(check_etag): res = self.client.request(operation) self.assertEqual(res.data, None) def test_esipy_expired_header_noetag(self): def check_etag(url, request): self.assertNotIn('If-None-Match', request.headers) return httmock.response( status_code=200, content={ "players": 29597, "server_version": "1313143", "start_time": "2018-05-20T11:04:30Z" } ) operation = self.app.op['get_status']() with httmock.HTTMock(eve_status_noetag): res = self.client.request(operation) self.assertEqual(res.data.server_version, "1313143") time.sleep(2) with httmock.HTTMock(check_etag): res = self.client.request(operation) self.assertEqual(res.data.server_version, "1313143") def test_esipy_non_json_response(self): operation = self.app.op['get_status']() with httmock.HTTMock(non_json_error): try: self.client.request(operation) except APIException as exc: self.assertEqual(exc.status_code, 502) self.assertEqual( exc.response, six.b('<html><body>Some HTML Errors</body></html>') ) try: self.client_no_auth.request(operation) except APIException as exc: self.assertEqual(exc.status_code, 502) self.assertEqual( exc.response, six.b('<html><body>Some HTML Errors</body></html>') )
class TestEsiPy(unittest.TestCase): @mock.patch('six.moves.urllib.request.urlopen') def setUp(self, urlopen_mock): pass def tearDown(self): ''' clear the cache so we don't have residual data ''' pass def test_esipy_client_no_args(self): pass def test_esipy_client_with_headers(self): pass def test_esipy_client_with_adapter(self): pass def test_esipy_client_without_cache(self): pass def test_esipy_client_with_cache(self): pass def test_esipy_client_wrong_cache(self): pass def test_esipy_request_public(self): pass def test_esipy_request_authed(self): pass def test_client_cache_request(self): pass @httmock.all_requests def fail_if_request(url, request): pass def test_client_warning_header(self): pass def test_client_raw_body_only(self): pass def test_esipy_reuse_operation(self): pass def test_esipy_multi_request(self): pass def test_esipy_backoff(self): pass def test_esipy_timeout(self): pass def send_function(*args, **kwargs): ''' manually create a ConnectionError to test the retry and be sure no exception is thrown ''' pass def test_esipy_raise_on_error(self): pass def test_esipy_expired_response(self): pass def test_esipy_uncached_method(self): pass def test_esipy_head_request(self): pass def test_esipy_expired_header_etag(self): pass @httmock.all_requests def check_etag(url, request): pass def test_esipy_expired_header_etag_no_body(self): pass @httmock.all_requests def check_etag(url, request): pass def test_esipy_expired_header_noetag(self): pass def check_etag(url, request): pass def test_esipy_non_json_response(self): pass
35
2
12
2
10
1
1
0.05
1
10
6
0
25
5
25
97
371
73
283
93
248
15
214
86
183
3
2
2
33
144,367
Kyria/EsiPy
Kyria_EsiPy/esipy/security.py
esipy.security.EsiSecurity
class EsiSecurity(object): """ Contains all the OAuth2 knowledge for ESI use. Based on pyswagger Security object, to be used with pyswagger BaseClient implementation. """ def __init__( self, redirect_uri, client_id, secret_key=None, code_verifier=None, **kwargs): """ Init the ESI Security Object :param redirect_uri: the uri to redirect the user after login into SSO :param client_id: the OAuth2 client ID :param secret_key: the OAuth2 secret key :param token_identifier: (optional) identifies the token for the user the value will then be passed as argument to any callback :param security_name: (optionnal) the name of the object holding the informations in the securityDefinitions, used to check authed endpoint :param headers: (optional) additional headers to add to the requests done here :param signal_token_updated: (optional) allow to define a specific signal to use, instead of using the global AFTER_TOKEN_REFRESH :param sso_endpoints: (optional) :param sso_endpoints_url: (optional) :param jwks_key: (optional) """ sso_endpoints_url = kwargs.pop( 'sso_endpoints_url', ('https://login.eveonline.com/' '.well-known/oauth-authorization-server') ) if sso_endpoints_url is None or sso_endpoints_url == "": raise AttributeError("sso_endpoints_url cannot be None or empty") if secret_key is None and code_verifier is None: raise AttributeError( "Either secret_key or code_verifier must be filled" ) self.security_name = kwargs.pop('security_name', 'evesso') self.redirect_uri = redirect_uri self.client_id = client_id self.secret_key = secret_key self.code_verifier = code_verifier # session requests stuff self._session = Session() headers = kwargs.pop('headers', {}) if 'User-Agent' not in headers: warning_message = ( "Defining a 'User-Agent' header is a" " good practice, and allows CCP to contact you if required." " To do this, simply add the following when creating" " the security object: headers={'User-Agent':'something'}." ) LOGGER.warning(warning_message) warnings.warn(warning_message) self._session.headers.update({ 'User-Agent': ( 'EsiPy/Security/ - ' 'https://github.com/Kyria/EsiPy - ' 'ClientID: %s' % self.client_id ) }) self._session.headers.update({"Accept": "application/json"}) self._session.headers.update(headers) # get sso endpoints from given dict, else get it from EVE SSO # raise error if not 200 / json fail sso_endpoints = kwargs.pop('sso_endpoints', None) if sso_endpoints is None or not isinstance(sso_endpoints, dict): res = self._session.get(sso_endpoints_url) res.raise_for_status() sso_endpoints = res.json() self.oauth_issuer = sso_endpoints['issuer'] self.oauth_authorize = sso_endpoints['authorization_endpoint'] self.oauth_token = sso_endpoints['token_endpoint'] self.oauth_revoke = sso_endpoints['revocation_endpoint'] self.__get_jwks_key(sso_endpoints['jwks_uri'], **kwargs) # token data self.token_identifier = kwargs.pop('token_identifier', None) self.refresh_token = None self.access_token = None self.token_expiry = None # other stuff self.signal_token_updated = kwargs.pop( 'signal_token_updated', AFTER_TOKEN_REFRESH ) def __get_jwks_key(self, jwks_uri, **kwargs): """Get from jwks_ui all the JWK keys required to decode JWT Token. Parameters ---------- jwks_uri : string The URL where to gather JWKS key kwargs : Dict The constructor parameters """ jwks_key = kwargs.pop('jwks_key', None) if not jwks_key: res = self._session.get(jwks_uri) res.raise_for_status() jwks_key = res.json() self.jwks_key_set = None self.jwks_key = None if 'keys' in jwks_key: self.jwks_key_set = {} for jwks in jwks_key['keys']: self.jwks_key_set[jwks['kid']] = jwks else: self.jwks_key = jwks_key def __get_basic_auth_header(self): """Return the Basic Authorization header for oauth if secret_key exists Returns ------- type A dictionary that contains the Basic Authorization key/value, or {} if secret_key is None """ if self.secret_key is None: return {} # encode/decode for py2/py3 compatibility auth_b64 = "%s:%s" % (self.client_id, self.secret_key) auth_b64 = base64.b64encode(auth_b64.encode('utf-8')) auth_b64 = auth_b64.decode('utf-8') return {'Authorization': 'Basic %s' % auth_b64} def __prepare_token_request(self, params, url=None): """Generate the request parameters to execute the POST call to get or refresh a token. Parameters ---------- params : dictionary Contains the parameters that will be given as data to the oauth endpoint Returns ------- type The filled request parameters with all required informations """ if self.secret_key is None: params['code_verifier'] = self.code_verifier params['client_id'] = self.client_id request_params = { 'headers': self.__get_basic_auth_header(), 'data': params, 'url': self.oauth_token if url is None else url, } return request_params def get_auth_uri(self, state, scopes=None, implicit=False): """Constructs the full auth uri and returns it.. Parameters ---------- state : string The state to pass through the auth process scopes : list (optional) The list of scope to have implicit : Boolean (optional) Activate or not the implicit flow Returns ------- String The generated URL for the user to log into EVE SSO """ if state is None or state == '': raise AttributeError('"state" must be non empty, non None string') scopes_list = [] if not scopes else scopes response_type = 'code' if not implicit else 'token' # generate the auth URI auth_uri = '%s?response_type=%s&redirect_uri=%s&client_id=%s%s%s' % ( self.oauth_authorize, response_type, quote(self.redirect_uri, safe=''), self.client_id, '&scope=%s' % '+'.join(scopes_list) if scopes else '', '&state=%s' % state ) # add code challenge if we have one if self.secret_key is None and not implicit: auth_uri += '&code_challenge_method=S256&code_challenge=%s' % ( generate_code_challenge(self.code_verifier) ) return auth_uri def get_access_token_params(self, code): """ Return the param object for the post() call to get the access_token from the auth process (using the code) :param code: the code get from the authentification process :return: a dict with the url, params and header """ params = { 'grant_type': 'authorization_code', 'code': code, } return self.__prepare_token_request(params) def get_refresh_token_params(self, scope_list=None): """ Return the param object for the post() call to get the access_token from the refresh_token :param code: the refresh token :return: a dict with the url, params and header """ if self.refresh_token is None: raise AttributeError('No refresh token is defined.') params = { 'grant_type': 'refresh_token', 'refresh_token': self.refresh_token, } if scope_list: if isinstance(scope_list, list): scopes = '+'.join(scope_list) else: raise AttributeError('scope_list must be a list of scope.') params['scope'] = scopes return self.__prepare_token_request(params) def update_token(self, response_json, **kwargs): """ Update access_token, refresh_token and token_expiry from the response body. The response must be converted to a json object before being passed as a parameter :param response_json: the response body to use. :param token_identifier: the user identifier for the token """ self.token_identifier = kwargs.pop( 'token_identifier', self.token_identifier ) self.access_token = response_json['access_token'] self.token_expiry = int(time.time()) + response_json['expires_in'] if 'refresh_token' in response_json: self.refresh_token = response_json['refresh_token'] def is_token_expired(self, offset=0): """ Return true if the token is expired. The offset can be used to change the expiry time: - positive value decrease the time (sooner) - negative value increase the time (later) If the expiry is not set, always return True. This case allow the users to define a security object, only knowing the refresh_token and get a new access_token / expiry_time without errors. :param offset: the expiry offset (in seconds) [default: 0] :return: boolean true if expired, else false. """ if self.token_expiry is None: return True return int(time.time()) >= (self.token_expiry - offset) def refresh(self, scope_list=None): """ Update the auth data (tokens) using the refresh token in auth. """ request_data = self.get_refresh_token_params(scope_list) res = self._session.post(**request_data) if res.status_code != 200: raise APIException( request_data['url'], res.status_code, response=res.content, request_param=request_data, response_header=res.headers ) json_res = res.json() self.update_token(json_res) return json_res def auth(self, code): """ Request the token to the /oauth/token endpoint. Update the security tokens. :param code: the code you get from the auth process """ request_data = self.get_access_token_params(code) res = self._session.post(**request_data) if res.status_code != 200: raise APIException( request_data['url'], res.status_code, response=res.content, request_param=request_data, response_header=res.headers ) json_res = res.json() self.update_token(json_res) return json_res def revoke(self): """Revoke the current tokens then empty all stored tokens This returns nothing since the endpoint return HTTP/200 whatever the result is... Currently not working with JWT, left here for compatibility. """ if not self.refresh_token and not self.access_token: raise AttributeError('No access/refresh token are defined.') if self.refresh_token: data = { 'token_type_hint': 'refresh_token', 'token': self.refresh_token, } else: data = { 'token_type_hint': 'access_token', 'token': self.access_token, } request_data = self.__prepare_token_request(data, self.oauth_revoke) self._session.post(**request_data) self.access_token = None self.refresh_token = None self.token_expiry = None def verify(self, kid='JWT-Signature-Key', options=None): """Decode and verify the token and return the decoded informations Parameters ---------- kid : string The JWKS key id to identify the key to decode the token. Default is 'JWT-Signature-Key'. Only change if CCP changes it. options : Dict The dictionary of options for skipping validation steps. See https://python-jose.readthedocs.io/en/latest/jwt/api.html#jose.jwt.decode Returns ------- Dict The JWT informations from the token, such as character name etc. Raises ------ jose.exceptions.JWTError: If the signature is invalid in any way. jose.exceptions.ExpiredSignatureError: If the signature has expired jose.exceptions.JWTClaimsError: If any claim is invalid in any way. """ if self.access_token is None or self.access_token == "": raise AttributeError('No access token are available at this time') if options is None: options = {} if self.jwks_key_set is None: key = self.jwks_key else: key = self.jwks_key_set[kid] return jwt.decode( self.access_token, key, issuer=self.oauth_issuer, options=options, audience="EVE Online" ) def __call__(self, request): """Check if the request need security header and apply them. Required for pyswagger.core.BaseClient.request(). Parameters ---------- request : pyswagger.io.Request the pyswagger request object to check, generated from app operation Returns ------- pyswagger.io.Request The pyswagger request with auth headers added if required. """ if not request._security: return request if self.is_token_expired(): json_response = self.refresh() self.signal_token_updated.send( token_identifier=self.token_identifier, **json_response ) for security in request._security: if self.security_name not in security: LOGGER.warning( "Missing Securities: [%s]", ", ".join(security.keys()) ) continue if self.access_token is not None: request._p['header'].update( {'Authorization': 'Bearer %s' % self.access_token} ) return request
class EsiSecurity(object): ''' Contains all the OAuth2 knowledge for ESI use. Based on pyswagger Security object, to be used with pyswagger BaseClient implementation. ''' def __init__( self, redirect_uri, client_id, secret_key=None, code_verifier=None, **kwargs): ''' Init the ESI Security Object :param redirect_uri: the uri to redirect the user after login into SSO :param client_id: the OAuth2 client ID :param secret_key: the OAuth2 secret key :param token_identifier: (optional) identifies the token for the user the value will then be passed as argument to any callback :param security_name: (optionnal) the name of the object holding the informations in the securityDefinitions, used to check authed endpoint :param headers: (optional) additional headers to add to the requests done here :param signal_token_updated: (optional) allow to define a specific signal to use, instead of using the global AFTER_TOKEN_REFRESH :param sso_endpoints: (optional) :param sso_endpoints_url: (optional) :param jwks_key: (optional) ''' pass def __get_jwks_key(self, jwks_uri, **kwargs): '''Get from jwks_ui all the JWK keys required to decode JWT Token. Parameters ---------- jwks_uri : string The URL where to gather JWKS key kwargs : Dict The constructor parameters ''' pass def __get_basic_auth_header(self): '''Return the Basic Authorization header for oauth if secret_key exists Returns ------- type A dictionary that contains the Basic Authorization key/value, or {} if secret_key is None ''' pass def __prepare_token_request(self, params, url=None): '''Generate the request parameters to execute the POST call to get or refresh a token. Parameters ---------- params : dictionary Contains the parameters that will be given as data to the oauth endpoint Returns ------- type The filled request parameters with all required informations ''' pass def get_auth_uri(self, state, scopes=None, implicit=False): '''Constructs the full auth uri and returns it.. Parameters ---------- state : string The state to pass through the auth process scopes : list (optional) The list of scope to have implicit : Boolean (optional) Activate or not the implicit flow Returns ------- String The generated URL for the user to log into EVE SSO ''' pass def get_access_token_params(self, code): ''' Return the param object for the post() call to get the access_token from the auth process (using the code) :param code: the code get from the authentification process :return: a dict with the url, params and header ''' pass def get_refresh_token_params(self, scope_list=None): ''' Return the param object for the post() call to get the access_token from the refresh_token :param code: the refresh token :return: a dict with the url, params and header ''' pass def update_token(self, response_json, **kwargs): ''' Update access_token, refresh_token and token_expiry from the response body. The response must be converted to a json object before being passed as a parameter :param response_json: the response body to use. :param token_identifier: the user identifier for the token ''' pass def is_token_expired(self, offset=0): ''' Return true if the token is expired. The offset can be used to change the expiry time: - positive value decrease the time (sooner) - negative value increase the time (later) If the expiry is not set, always return True. This case allow the users to define a security object, only knowing the refresh_token and get a new access_token / expiry_time without errors. :param offset: the expiry offset (in seconds) [default: 0] :return: boolean true if expired, else false. ''' pass def refresh(self, scope_list=None): ''' Update the auth data (tokens) using the refresh token in auth. ''' pass def auth(self, code): ''' Request the token to the /oauth/token endpoint. Update the security tokens. :param code: the code you get from the auth process ''' pass def revoke(self): '''Revoke the current tokens then empty all stored tokens This returns nothing since the endpoint return HTTP/200 whatever the result is... Currently not working with JWT, left here for compatibility. ''' pass def verify(self, kid='JWT-Signature-Key', options=None): '''Decode and verify the token and return the decoded informations Parameters ---------- kid : string The JWKS key id to identify the key to decode the token. Default is 'JWT-Signature-Key'. Only change if CCP changes it. options : Dict The dictionary of options for skipping validation steps. See https://python-jose.readthedocs.io/en/latest/jwt/api.html#jose.jwt.decode Returns ------- Dict The JWT informations from the token, such as character name etc. Raises ------ jose.exceptions.JWTError: If the signature is invalid in any way. jose.exceptions.ExpiredSignatureError: If the signature has expired jose.exceptions.JWTClaimsError: If any claim is invalid in any way. ''' pass def __call__(self, request): '''Check if the request need security header and apply them. Required for pyswagger.core.BaseClient.request(). Parameters ---------- request : pyswagger.io.Request the pyswagger request object to check, generated from app operation Returns ------- pyswagger.io.Request The pyswagger request with auth headers added if required. ''' pass
15
15
30
4
16
10
3
0.61
1
6
1
0
14
17
14
14
434
69
227
65
206
138
143
59
128
6
1
2
46
144,368
Kyria/EsiPy
Kyria_EsiPy/test/test_cache.py
test.test_cache.BaseTest
class BaseTest(unittest.TestCase): def __init__(self, *args, **kwargs): super(BaseTest, self).__init__(*args, **kwargs) # example of simple data self.ex_str = ('eve', 'online') self.ex_int = ('int', 12345) # tuple of frozenset in key, namedtuple in value self.ex_cpx = ( ( frozenset([('foo', 'bar'), ('int', 2)]), frozenset([('header', 'bla')]), ), CachedResponse( status_code=200, headers={'foo', 'bar'}, content='SomeContent'.encode('latin-1'), url='http://example.com' ) ) def check_complex(self, cplx): self.assertTrue(isinstance(cplx, CachedResponse)) self.assertEqual(cplx.status_code, self.ex_cpx[1].status_code) self.assertEqual(cplx.headers, self.ex_cpx[1].headers) self.assertEqual(cplx.content, self.ex_cpx[1].content) self.assertEqual(cplx.url, self.ex_cpx[1].url)
class BaseTest(unittest.TestCase): def __init__(self, *args, **kwargs): pass def check_complex(self, cplx): pass
3
0
13
1
11
1
1
0.09
1
2
0
6
2
3
2
74
28
3
23
6
20
2
12
6
9
1
2
0
2
144,369
Kyria/EsiPy
Kyria_EsiPy/test/test_cache.py
test.test_cache.TestBaseCache
class TestBaseCache(BaseTest): """ BaseCache test class """ def setUp(self): self.c = BaseCache() def test_base_cache_set(self): self.assertRaises(NotImplementedError, self.c.get, 'key') def test_base_cache_get(self): self.assertRaises(NotImplementedError, self.c.set, 'key', 'val') def test_base_cache_invalidate(self): self.assertRaises(NotImplementedError, self.c.invalidate, 'key')
class TestBaseCache(BaseTest): ''' BaseCache test class ''' def setUp(self): pass def test_base_cache_set(self): pass def test_base_cache_get(self): pass def test_base_cache_invalidate(self): pass
5
1
2
0
2
0
1
0.11
1
2
1
0
4
1
4
78
14
4
9
6
4
1
9
6
4
1
3
0
4
144,370
Kyria/EsiPy
Kyria_EsiPy/test/test_cache.py
test.test_cache.TestDictCache
class TestDictCache(BaseTest): """ DictCache test class """ def setUp(self): self.c = DictCache() self.c.set(*self.ex_str) self.c.set(*self.ex_int) self.c.set(*self.ex_cpx) def tearDown(self): self.c.invalidate(self.ex_str[0]) self.c.invalidate(self.ex_int[0]) self.c.invalidate(self.ex_cpx[0]) def test_dict_cache_set(self): self.assertEqual(self.c._dict[self.ex_str[0]], self.ex_str[1]) self.assertEqual(self.c._dict[self.ex_int[0]], self.ex_int[1]) self.assertEqual(self.c._dict[self.ex_cpx[0]], self.ex_cpx[1]) def test_dict_cache_get(self): self.check_complex(self.c.get(self.ex_cpx[0])) def test_dict_cache_invalidate(self): self.c.invalidate(self.ex_cpx[0]) self.assertIsNone(self.c.get(self.ex_cpx[0])) def test_dict_cache_clear(self): self.assertEqual(self.c._dict[self.ex_str[0]], self.ex_str[1]) self.assertEqual(len(self.c._dict), 3) self.c.clear() self.assertEqual(len(self.c._dict), 0)
class TestDictCache(BaseTest): ''' DictCache test class ''' def setUp(self): pass def tearDown(self): pass def test_dict_cache_set(self): pass def test_dict_cache_get(self): pass def test_dict_cache_invalidate(self): pass def test_dict_cache_clear(self): pass
7
1
4
0
4
0
1
0.04
1
1
1
0
6
1
6
80
31
6
24
8
17
1
24
8
17
1
3
0
6
144,371
Kyria/EsiPy
Kyria_EsiPy/test/test_cache.py
test.test_cache.TestFileCache
class TestFileCache(BaseTest): """ Class for testing the filecache """ def setUp(self): shutil.rmtree('tmp', ignore_errors=True) self.c = FileCache('tmp') def tearDown(self): del self.c shutil.rmtree('tmp', ignore_errors=True) def test_file_cache_get_set(self): self.c.set(*self.ex_str) self.c.set(*self.ex_int) self.c.set(*self.ex_cpx) self.assertEqual(self.c.get(self.ex_str[0]), self.ex_str[1]) self.assertEqual(self.c.get(self.ex_int[0]), self.ex_int[1]) self.check_complex(self.c.get(self.ex_cpx[0])) def test_file_cache_update(self): self.c.set( self.ex_cpx[0], CachedResponse( status_code=200, headers={'foo', 'test'}, content='Nothing'.encode('latin-1'), url='http://foobarbaz.com' ) ) self.c.set(*self.ex_cpx) self.check_complex(self.c.get(self.ex_cpx[0])) def test_file_cache_invalidate(self): self.c.set('key', 'bar') self.assertEqual(self.c.get('key'), 'bar') self.c.invalidate('key') self.assertEqual(self.c.get('key'), None) def test_file_cache_expire(self): self.c.set('key', 'bar', expire=1) self.assertEqual(self.c.get('key'), 'bar') time.sleep(1) self.assertEqual(self.c.get('key', None), None) self.c.set('key', 'bar', expire=0) self.assertEqual(self.c.get('key'), 'bar') time.sleep(1) self.assertEqual(self.c.get('key', None), 'bar') self.c.set('foo', 'baz', expire=None) self.assertEqual(self.c.get('foo'), 'baz') time.sleep(1) self.assertEqual(self.c.get('foo', None), 'baz')
class TestFileCache(BaseTest): ''' Class for testing the filecache ''' def setUp(self): pass def tearDown(self): pass def test_file_cache_get_set(self): pass def test_file_cache_update(self): pass def test_file_cache_invalidate(self): pass def test_file_cache_expire(self): pass
7
1
8
0
7
0
1
0.02
1
1
1
0
6
1
6
80
53
8
44
8
37
1
36
8
29
1
3
0
6
144,372
Kyria/EsiPy
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Kyria_EsiPy/test/test_app.py
test.test_app.TestEsiApp
class TestEsiApp(unittest.TestCase): ESI_CACHE_PREFIX = 'esipy_test' ESI_V1_CACHE_KEY = '%s:app://esi.evetech.net/v1/swagger.json' % ( ESI_CACHE_PREFIX ) ESI_META_SWAGGER = 'test/resources/meta_swagger.json' ESI_V1_SWAGGER = 'test/resources/swagger.json' @mock.patch('six.moves.urllib.request.urlopen') def setUp(self, urlopen_mock): # I hate those mock... thx urlopen instead of requests... urlopen_mock.return_value = open(TestEsiApp.ESI_META_SWAGGER) with httmock.HTTMock(*_swagger_spec_mock_): self.app = EsiApp(cache_prefix='esipy_test') @mock.patch('six.moves.urllib.request.urlopen') def test_app_op_attribute(self, urlopen_mock): self.assertTrue(self.app.op) self.assertEqual( self.app.op['verify'].url, '//esi.evetech.net/verify/' ) urlopen_mock.return_value = open(TestEsiApp.ESI_META_SWAGGER) with httmock.HTTMock(*_swagger_spec_mock_): app = EsiApp(cache_prefix='esipy_test', cache_time=-1) self.assertEqual(app.expire, 86400) def test_app_getattr_fail(self): with self.assertRaises(AttributeError): self.app.doesnotexist with self.assertRaises(AttributeError): self.app.verify @mock.patch('six.moves.urllib.request.urlopen') def test_app_invalid_cache_value(self, urlopen_mock): cache = DictCache() cache.set(self.app.esi_meta_cache_key, 'somerandomvalue') urlopen_mock.return_value = open(TestEsiApp.ESI_META_SWAGGER) with httmock.HTTMock(*_swagger_spec_mock_): EsiApp(cache_prefix='esipy_test', cache=cache) self.assertNotEqual( cache.get(self.app.esi_meta_cache_key), 'somerandomvalue' ) @mock.patch('six.moves.urllib.request.urlopen') def test_app_getattr_and_cache(self, urlopen_mock): with httmock.HTTMock(*_swagger_spec_mock_): urlopen_mock.return_value = open(TestEsiApp.ESI_V1_SWAGGER) self.assertIsNotNone( self.app.cache.get(self.app.esi_meta_cache_key, None) ) self.assertEqual(len(self.app.cache._dict), 1) appv1 = self.app.get_v1_swagger self.assertTrue(isinstance(appv1, App)) self.assertEqual( self.app.cache.get(self.ESI_V1_CACHE_KEY)[0], appv1 ) appv1_bis = self.app.get_v1_swagger self.assertEqual(appv1, appv1_bis) self.app.clear_cached_endpoints() self.assertIsNone( self.app.cache.get(self.app.esi_meta_cache_key, None) ) self.assertIsNone(self.app.cache.get(self.ESI_V1_CACHE_KEY, None)) urlopen_mock.return_value = open(TestEsiApp.ESI_META_SWAGGER) self.app.op self.assertIsNotNone( self.app.cache.get(self.app.esi_meta_cache_key, None) ) @mock.patch('six.moves.urllib.request.urlopen') def test_app_getattr_no_cache(self, urlopen_mock): with httmock.HTTMock(*_swagger_spec_mock_): urlopen_mock.return_value = open(TestEsiApp.ESI_META_SWAGGER) app_nocache = EsiApp( cache=None, cache_prefix=self.ESI_CACHE_PREFIX) urlopen_mock.return_value = open(TestEsiApp.ESI_V1_SWAGGER) self.assertIsNone( app_nocache.cache.get(self.app.esi_meta_cache_key, None) ) appv1 = app_nocache.get_v1_swagger self.assertTrue(isinstance(appv1, App)) self.assertIsNone( app_nocache.cache.get(self.ESI_V1_CACHE_KEY, None)) @mock.patch('six.moves.urllib.request.urlopen') def test_app_expired_header_etag(self, urlopen_mock): @httmock.all_requests def check_etag(url, request): self.assertEqual( request.headers.get('If-None-Match'), '"esipyetag"') return httmock.response( headers={ 'Expires': make_expire_time_str(), 'Etag': '"esipyetag"' }, status_code=304) cache = DictCache() with httmock.HTTMock(*_swagger_spec_mock_): urlopen_mock.return_value = open(TestEsiApp.ESI_META_SWAGGER) self.assertEqual(len(cache._dict), 0) app = EsiApp( cache_time=None, cache=cache, cache_prefix='esipy_test') self.assertEqual(len(cache._dict), 1) cache.get( app.esi_meta_cache_key )[1]['expires'] = make_expired_time_str() cached_app = cache.get(app.esi_meta_cache_key)[0] with httmock.HTTMock(check_etag): urlopen_mock.return_value = open(TestEsiApp.ESI_META_SWAGGER) esiapp = EsiApp( cache_time=None, cache=cache, cache_prefix='esipy_test') self.assertEqual(cached_app, esiapp.app) urlopen_mock.return_value.close() @mock.patch('six.moves.urllib.request.urlopen') def test_app_expired_header_no_etag(self, urlopen_mock): cache = DictCache() with httmock.HTTMock(*_swagger_spec_mock_): urlopen_mock.return_value = open(TestEsiApp.ESI_META_SWAGGER) app = EsiApp( cache_time=None, cache=cache, cache_prefix='esipy_test') urlopen_mock.return_value = open(TestEsiApp.ESI_V1_SWAGGER) appv1 = app.get_v1_swagger cache.get(self.ESI_V1_CACHE_KEY)[1]['Expires'] = None urlopen_mock.return_value = open(TestEsiApp.ESI_V1_SWAGGER) appv1_uncached = app.get_v1_swagger self.assertNotEqual(appv1, appv1_uncached) @mock.patch('six.moves.urllib.request.urlopen') def test_app_valid_header_etag(self, urlopen_mock): @httmock.all_requests def fail_if_request(url, request): self.fail('Cached data is not supposed to do requests') cache = DictCache() with httmock.HTTMock(*_swagger_spec_mock_): urlopen_mock.return_value = open(TestEsiApp.ESI_META_SWAGGER) EsiApp(cache_time=None, cache=cache, cache_prefix='esipy_test') with httmock.HTTMock(fail_if_request): urlopen_mock.return_value = open(TestEsiApp.ESI_META_SWAGGER) EsiApp(cache_time=None, cache=cache, cache_prefix='esipy_test') urlopen_mock.return_value.close() @mock.patch('six.moves.urllib.request.urlopen') def test_app_http_error_retry_fail(self, urlopen_mock): urlopen_mock.side_effect = HTTPError( "http://mock.test", 500, "HTTP 500 whatever", None, None ) with httmock.HTTMock(*_swagger_spec_mock_): with self.assertRaises(APIException): self.app = EsiApp(cache_prefix='esipy_test') self.assertEqual(urlopen_mock.call_count, 3) @mock.patch('six.moves.urllib.request.urlopen') def test_app_http_error_retry_ok(self, urlopen_mock): http_error = HTTPError( "http://mock.test", 500, "HTTP 500 whatever", None, None ) # this will make the function raise exception / return the value # in this given order side_effect_results = [ http_error, http_error, open(TestEsiApp.ESI_META_SWAGGER) ] urlopen_mock.side_effect = side_effect_results with httmock.HTTMock(*_swagger_spec_mock_): EsiApp(cache_prefix='esipy_test') self.assertEqual(urlopen_mock.call_count, 3)
class TestEsiApp(unittest.TestCase): @mock.patch('six.moves.urllib.request.urlopen') def setUp(self, urlopen_mock): pass @mock.patch('six.moves.urllib.request.urlopen') def test_app_op_attribute(self, urlopen_mock): pass def test_app_getattr_fail(self): pass @mock.patch('six.moves.urllib.request.urlopen') def test_app_invalid_cache_value(self, urlopen_mock): pass @mock.patch('six.moves.urllib.request.urlopen') def test_app_getattr_and_cache(self, urlopen_mock): pass @mock.patch('six.moves.urllib.request.urlopen') def test_app_getattr_no_cache(self, urlopen_mock): pass @mock.patch('six.moves.urllib.request.urlopen') def test_app_expired_header_etag(self, urlopen_mock): pass @httmock.all_requests def check_etag(url, request): pass @mock.patch('six.moves.urllib.request.urlopen') def test_app_expired_header_no_etag(self, urlopen_mock): pass @mock.patch('six.moves.urllib.request.urlopen') def test_app_valid_header_etag(self, urlopen_mock): pass @httmock.all_requests def fail_if_request(url, request): pass @mock.patch('six.moves.urllib.request.urlopen') def test_app_http_error_retry_fail(self, urlopen_mock): pass @mock.patch('six.moves.urllib.request.urlopen') def test_app_http_error_retry_ok(self, urlopen_mock): pass
26
0
14
1
12
0
1
0.02
1
4
3
0
11
1
11
83
199
30
166
48
140
3
105
36
91
1
2
2
13
144,373
Kyria/EsiPy
Kyria_EsiPy/test/test_cache.py
test.test_cache.TestMemcachedCache
class TestMemcachedCache(BaseTest): """ Memcached tests """ def setUp(self): memcached = memcache.Client(['localhost:11211'], debug=0) self.c = MemcachedCache(memcached) def tearDown(self): self.c.invalidate(self.ex_str[0]) self.c.invalidate(self.ex_int[0]) self.c.invalidate(self.ex_cpx[0]) self.c._mc.disconnect_all() def test_memcached_get_set(self): self.c.set(*self.ex_str) self.c.set(*self.ex_int) self.c.set(*self.ex_cpx) self.assertEqual(self.c.get(self.ex_str[0]), self.ex_str[1]) self.assertEqual(self.c.get(self.ex_int[0]), self.ex_int[1]) self.check_complex(self.c.get(self.ex_cpx[0])) def test_memcached_update(self): self.c.set( self.ex_cpx[0], CachedResponse( status_code=200, headers={'foo', 'test'}, content='Nothing'.encode('latin-1'), url='http://foobarbaz.com' ) ) self.c.set(*self.ex_cpx) self.check_complex(self.c.get(self.ex_cpx[0])) def test_memcached_invalidate(self): self.c.set(*self.ex_str) self.assertEqual(self.c.get(self.ex_str[0]), self.ex_str[1]) self.c.invalidate(self.ex_str[0]) self.assertEqual(self.c.get(self.ex_str[0]), None) def test_memcached_invalid_argument(self): with self.assertRaises(TypeError): MemcachedCache(None) def test_memcached_expire(self): self.c.set(self.ex_str[0], self.ex_str[1], expire=1) self.assertEqual(self.c.get(self.ex_str[0]), self.ex_str[1]) time.sleep(1) self.assertEqual(self.c.get(self.ex_str[0], None), None) self.c.set(self.ex_str[0], self.ex_str[1], expire=0) self.assertEqual(self.c.get(self.ex_str[0]), self.ex_str[1]) time.sleep(1) self.assertEqual(self.c.get(self.ex_str[0], None), self.ex_str[1]) self.c.set(self.ex_int[0], self.ex_int[1], expire=None) self.assertEqual(self.c.get(self.ex_int[0]), self.ex_int[1]) time.sleep(1) self.assertEqual(self.c.get(self.ex_int[0], None), self.ex_int[1])
class TestMemcachedCache(BaseTest): ''' Memcached tests ''' def setUp(self): pass def tearDown(self): pass def test_memcached_get_set(self): pass def test_memcached_update(self): pass def test_memcached_invalidate(self): pass def test_memcached_invalid_argument(self): pass def test_memcached_expire(self): pass
8
1
7
0
7
0
1
0.02
1
2
1
0
7
1
7
81
59
9
49
10
41
1
41
10
33
1
3
1
7
144,374
Kyria/EsiPy
Kyria_EsiPy/test/test_cache.py
test.test_cache.TestRedisCache
class TestRedisCache(BaseTest): """RedisCache tests""" def setUp(self): redis_client = redis.Redis(host='localhost', port=6379, db=0) self.c = RedisCache(redis_client) def tearDown(self): self.c.invalidate(self.ex_str[0]) self.c.invalidate(self.ex_int[0]) self.c.invalidate(self.ex_cpx[0]) def test_redis_get_set(self): self.c.set(*self.ex_str) self.c.set(*self.ex_int) self.c.set(*self.ex_cpx) self.assertEqual(self.c.get(self.ex_str[0]), self.ex_str[1]) self.assertEqual(self.c.get(self.ex_int[0]), self.ex_int[1]) self.check_complex(self.c.get(self.ex_cpx[0])) def test_redis_update(self): self.c.set( self.ex_cpx[0], CachedResponse( status_code=200, headers={'foo', 'test'}, content='Nothing'.encode('latin-1'), url='http://foobarbaz.com' ) ) self.c.set(*self.ex_cpx) self.check_complex(self.c.get(self.ex_cpx[0])) def test_redis_invalidate(self): self.c.set(*self.ex_str) self.assertEqual(self.c.get(self.ex_str[0]), self.ex_str[1]) self.c.invalidate(self.ex_str[0]) self.assertEqual(self.c.get(self.ex_str[0]), None) def test_redis_invalid_argument(self): with self.assertRaises(TypeError): RedisCache(None) def test_redis_expire(self): self.c.set(self.ex_str[0], self.ex_str[1], expire=1) self.assertEqual(self.c.get(self.ex_str[0]), self.ex_str[1]) time.sleep(1) self.assertEqual(self.c.get(self.ex_str[0], None), None) self.c.set(self.ex_str[0], self.ex_str[1], expire=0) self.assertEqual(self.c.get(self.ex_str[0]), self.ex_str[1]) time.sleep(1) self.assertEqual(self.c.get(self.ex_str[0], None), self.ex_str[1]) self.c.set(self.ex_int[0], self.ex_int[1], expire=None) self.assertEqual(self.c.get(self.ex_int[0]), self.ex_int[1]) time.sleep(1) self.assertEqual(self.c.get(self.ex_int[0], None), self.ex_int[1])
class TestRedisCache(BaseTest): '''RedisCache tests''' def setUp(self): pass def tearDown(self): pass def test_redis_get_set(self): pass def test_redis_update(self): pass def test_redis_invalidate(self): pass def test_redis_invalid_argument(self): pass def test_redis_expire(self): pass
8
1
7
0
7
0
1
0.02
1
2
1
0
7
1
7
81
58
9
48
10
40
1
40
10
32
1
3
1
7
144,375
Kyria/EsiPy
Kyria_EsiPy/test/test_events.py
test.test_events.TestSignal
class TestSignal(unittest.TestCase): EVENT_ARG = "testing" def event_receiver(self, example_arg): self.assertEqual(example_arg, TestSignal.EVENT_ARG) def event_receiver_exception(self): raise AssertionError("Triggered") def setUp(self): self.signal = Signal() def test_signal_send(self): self.signal.add_receiver(self.event_receiver) self.signal.send(example_arg=TestSignal.EVENT_ARG) def test_signal_send_exception(self): self.signal.add_receiver(self.event_receiver_exception) with self.assertRaises(AssertionError): self.signal.send() def test_signal_send_robust(self): self.signal.add_receiver(self.event_receiver) self.signal.send_robust(example_arg=TestSignal.EVENT_ARG) def test_signal_send_robust_exception(self): self.signal.add_receiver(self.event_receiver_exception) self.signal.send_robust() def test_signal_add_remove_receiver(self): self.signal.add_receiver(self.event_receiver_exception) self.assertIn( self.event_receiver_exception, self.signal.event_receivers ) self.signal.remove_receiver(self.event_receiver_exception) self.assertNotIn( self.event_receiver_exception, self.signal.event_receivers ) def test_signal_add_not_callable_receiver(self): with self.assertRaises(TypeError): self.signal.add_receiver("No callable receiver")
class TestSignal(unittest.TestCase): def event_receiver(self, example_arg): pass def event_receiver_exception(self): pass def setUp(self): pass def test_signal_send(self): pass def test_signal_send_exception(self): pass def test_signal_send_robust(self): pass def test_signal_send_robust_exception(self): pass def test_signal_add_remove_receiver(self): pass def test_signal_add_not_callable_receiver(self): pass
10
0
4
0
4
0
1
0
1
3
1
0
9
1
9
81
44
9
35
12
25
0
29
12
19
1
2
1
9
144,376
Kyria/EsiPy
Kyria_EsiPy/test/test_exceptions.py
test.test_exceptions.TestApiException
class TestApiException(unittest.TestCase): URL = "http://foo.bar" STATUS_CODE = 404 STATUS_CODE_STR = '404' ERROR_RESPONSE = {'error': 'This is an error'} MESSAGE_RESPONSE = {'message': 'This is a message'} PARAMS = {'some': 'params'} HEADERS = {'just': 'someheader'} def test_api_exception_error(self): e = APIException( TestApiException.URL, TestApiException.STATUS_CODE, response=TestApiException.ERROR_RESPONSE, request_param=TestApiException.PARAMS, response_header=TestApiException.HEADERS ) self.assertEqual(e.url, TestApiException.URL) self.assertIn(TestApiException.STATUS_CODE_STR, str(e)) self.assertIn(TestApiException.ERROR_RESPONSE['error'], str(e)) self.assertEqual(e.request_param, TestApiException.PARAMS) self.assertEqual(e.response_header, TestApiException.HEADERS)
class TestApiException(unittest.TestCase): def test_api_exception_error(self): pass
2
0
14
1
13
0
1
0
1
2
1
0
1
0
1
73
23
2
21
10
19
0
15
10
13
1
2
0
1
144,377
Kyria/EsiPy
Kyria_EsiPy/test/test_cache.py
test.test_cache.TestDummyCache
class TestDummyCache(BaseTest): """ DummyCache test class. """ def setUp(self): self.c = DummyCache() self.c.set('never_stored', True) def test_dummy_cache_set(self): self.assertNotIn('never_stored', self.c._dict) def test_dummy_cache_get(self): self.assertEqual(self.c.get('never_stored'), None) def test_dummy_cache_invalidate(self): self.c.invalidate('never_stored') self.assertIsNone(self.c.get('never_stored'))
class TestDummyCache(BaseTest): ''' DummyCache test class. ''' def setUp(self): pass def test_dummy_cache_set(self): pass def test_dummy_cache_get(self): pass def test_dummy_cache_invalidate(self): pass
5
1
3
0
3
0
1
0.09
1
1
1
0
4
1
4
78
16
4
11
6
6
1
11
6
6
1
3
0
4
144,378
Kyria/EsiPy
Kyria_EsiPy/esipy/cache.py
esipy.cache.DictCache
class DictCache(BaseCache): """ BaseCache implementation using Dict to store the cached data. Caution: due to its nature, DictCache do not expire keys !""" def __init__(self): self._dict = {} def get(self, key, default=None): return self._dict.get(key, default) def set(self, key, value, expire=300): self._dict[key] = value def invalidate(self, key): self._dict.pop(key, None) def clear(self): self._dict.clear()
class DictCache(BaseCache): ''' BaseCache implementation using Dict to store the cached data. Caution: due to its nature, DictCache do not expire keys !''' def __init__(self): pass def get(self, key, default=None): pass def set(self, key, value, expire=300): pass def invalidate(self, key): pass def clear(self): pass
6
1
2
0
2
0
1
0.18
1
0
0
0
5
1
5
8
19
6
11
7
5
2
11
7
5
1
2
0
5
144,379
Kyria/EsiPy
Kyria_EsiPy/esipy/exceptions.py
esipy.exceptions.APIException
class APIException(Exception): """ Exception for SSO related errors """ def __init__(self, url, code, **kwargs): self.url = url self.status_code = code self.response = kwargs.pop('response', '{}') self.request_param = kwargs.pop('request_param', {}) self.response_header = kwargs.pop('response_header', {}) super(APIException, self).__init__(str(self)) def __str__(self): return 'HTTP Error %s: %s' % (self.status_code, self.response)
class APIException(Exception): ''' Exception for SSO related errors ''' def __init__(self, url, code, **kwargs): pass def __str__(self): pass
3
1
5
0
5
0
1
0.1
1
2
0
0
2
5
2
12
13
2
10
8
7
1
10
8
7
1
3
0
2
144,380
Kyria/EsiPy
Kyria_EsiPy/test/test_utils.py
test.test_utils.TestUtils
class TestUtils(unittest.TestCase): def test_code_verifier(self): with self.assertRaises(ValueError): utils.generate_code_verifier(30) with self.assertRaises(ValueError): utils.generate_code_verifier(98) code_verifier = utils.generate_code_verifier() self.assertGreater(len(code_verifier), 0) def test_code_challenge(self): # example from RFC 7636 CODE_VERIFIER = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk" EXP_CODE_CHALLENGE = "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM" code_challenge = utils.generate_code_challenge(CODE_VERIFIER) self.assertEqual(code_challenge, EXP_CODE_CHALLENGE)
class TestUtils(unittest.TestCase): def test_code_verifier(self): pass def test_code_challenge(self): pass
3
0
8
2
6
1
1
0.08
1
1
0
0
2
0
2
74
19
5
13
7
10
1
13
7
10
1
2
1
2
144,381
Kyria/EsiPy
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Kyria_EsiPy/test/test_security.py
test.test_security.TestEsiSecurity.test_esisecurity_call.RequestTest
class RequestTest(object): def __init__(self): self._security = [] self._p = {'header': {}}
class RequestTest(object): def __init__(self): pass
2
0
3
0
3
0
1
0
1
0
0
0
1
2
1
1
5
1
4
4
2
0
4
4
2
1
1
0
1
144,382
Kyria/EsiPy
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Kyria_EsiPy/test/test_security.py
test.test_security.TestEsiSecurity.test_esisecurity_callback_refresh.RequestTest
class RequestTest(object): """ pyswagger Request object over simplified for test purpose""" def __init__(self): self._security = ['evesso'] self._p = {'header': {}}
class RequestTest(object): ''' pyswagger Request object over simplified for test purpose''' def __init__(self): pass
2
1
3
0
3
0
1
0.25
1
0
0
0
1
2
1
1
5
0
4
4
2
1
4
4
2
1
1
0
1
144,383
Kyria/EsiPy
Kyria_EsiPy/esipy/events.py
esipy.events.Signal
class Signal(object): """ Signal class. This class allows subscribers to hook to some specific event and be notified when something happen """ def __init__(self): """ Alarm constructor. """ self.event_receivers = [] def add_receiver(self, receiver): """ Add a receiver to the list of receivers. :param receiver: a callable variable """ if not callable(receiver): raise TypeError("receiver must be callable") self.event_receivers.append(receiver) def remove_receiver(self, receiver): """ Remove a receiver to the list of receivers. :param receiver: a callable variable """ if receiver in self.event_receivers: self.event_receivers.remove(receiver) def send(self, **kwargs): """ Trigger all receiver and pass them the parameters If an exception is raised, it will stop the process and all receivers may not be triggered at this moment. :param kwargs: all arguments from the event. """ for receiver in self.event_receivers: receiver(**kwargs) def send_robust(self, **kwargs): """ Trigger all receiver and pass them the parameters If an exception is raised it will be catched and displayed as error in the logger (if defined). :param kwargs: all arguments from the event. """ for receiver in self.event_receivers: try: receiver(**kwargs) except Exception: # pylint: disable=W0703 LOGGER.exception( 'Exception while sending to "%s".', getattr(receiver, '__name__', repr(receiver)) )
class Signal(object): ''' Signal class. This class allows subscribers to hook to some specific event and be notified when something happen ''' def __init__(self): ''' Alarm constructor. ''' pass def add_receiver(self, receiver): ''' Add a receiver to the list of receivers. :param receiver: a callable variable ''' pass def remove_receiver(self, receiver): ''' Remove a receiver to the list of receivers. :param receiver: a callable variable ''' pass def send(self, **kwargs): ''' Trigger all receiver and pass them the parameters If an exception is raised, it will stop the process and all receivers may not be triggered at this moment. :param kwargs: all arguments from the event. ''' pass def send_robust(self, **kwargs): ''' Trigger all receiver and pass them the parameters If an exception is raised it will be catched and displayed as error in the logger (if defined). :param kwargs: all arguments from the event. ''' pass
6
6
8
1
4
4
2
0.91
1
2
0
0
5
1
5
5
50
9
22
9
16
20
19
9
13
3
1
2
10
144,384
Kyria/EsiPy
Kyria_EsiPy/test/test_security.py
test.test_security.TestEsiSecurity
class TestEsiSecurity(unittest.TestCase): CALLBACK_URI = "https://foo.bar/baz/callback" CLIENT_ID = 'foo' SECRET_KEY = 'bar' BASIC_TOKEN = six.u('Zm9vOmJhcg==') SECURITY_NAME = 'evesso' TOKEN_IDENTIFIER = 'ESIPY_TEST_TOKEN' CODE_VERIFIER = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk" CODE_CHALLENGE = "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM" RSC_SSO_ENDPOINTS = "test/resources/oauth-authorization-server.json" RSC_JWKS = "test/resources/jwks.json" def setUp(self): warnings.simplefilter('ignore') self.custom_refresh_token_signal = Signal() with httmock.HTTMock(*_all_auth_mock_): self.security = EsiSecurity( redirect_uri=TestEsiSecurity.CALLBACK_URI, client_id=TestEsiSecurity.CLIENT_ID, secret_key=TestEsiSecurity.SECRET_KEY, signal_token_updated=self.custom_refresh_token_signal, token_identifier=TestEsiSecurity.TOKEN_IDENTIFIER ) self.security_pkce = EsiSecurity( redirect_uri=TestEsiSecurity.CALLBACK_URI, client_id=TestEsiSecurity.CLIENT_ID, code_verifier=TestEsiSecurity.CODE_VERIFIER, ) with open(TestEsiSecurity.RSC_SSO_ENDPOINTS, 'r') as sso_endpoints: self.sso_endpoints = json.load(sso_endpoints) def test_esisecurity_init(self): with httmock.HTTMock(*_all_auth_mock_): with self.assertRaises(AttributeError): EsiSecurity( redirect_uri=TestEsiSecurity.CALLBACK_URI, client_id=TestEsiSecurity.CLIENT_ID, secret_key=TestEsiSecurity.SECRET_KEY, sso_endpoints_url="" ) with self.assertRaises(AttributeError): EsiSecurity( redirect_uri=TestEsiSecurity.CALLBACK_URI, client_id=TestEsiSecurity.CLIENT_ID ) with open(TestEsiSecurity.RSC_JWKS, 'r') as jwks: jwks = json.load(jwks) EsiSecurity( redirect_uri=TestEsiSecurity.CALLBACK_URI, client_id=TestEsiSecurity.CLIENT_ID, secret_key=TestEsiSecurity.SECRET_KEY, jwks_key=jwks['keys'][0] ) self.assertEqual( self.security.security_name, TestEsiSecurity.SECURITY_NAME ) self.assertEqual( self.security.redirect_uri, TestEsiSecurity.CALLBACK_URI ) self.assertEqual( self.security.client_id, TestEsiSecurity.CLIENT_ID ) self.assertEqual( self.security.secret_key, TestEsiSecurity.SECRET_KEY ) self.assertEqual( self.security.token_identifier, TestEsiSecurity.TOKEN_IDENTIFIER ) self.assertEqual( self.security.oauth_issuer, self.sso_endpoints['issuer'] ) self.assertEqual( self.security.oauth_authorize, self.sso_endpoints['authorization_endpoint'] ) self.assertEqual( self.security.oauth_token, self.sso_endpoints['token_endpoint'] ) self.assertEqual( self.security.oauth_revoke, self.sso_endpoints['revocation_endpoint'] ) def test_esisecurity_update_token(self): self.security.update_token({ 'access_token': 'access_token', 'refresh_token': 'refresh_token', 'expires_in': 60 }) self.assertEqual(self.security.access_token, 'access_token') self.assertEqual(self.security.refresh_token, 'refresh_token') self.assertEqual(self.security.token_expiry, int(time.time() + 60)) def test_esisecurity_get_auth_uri(self): with self.assertRaises(AttributeError): self.security.get_auth_uri(state="") self.assertEqual( self.security.get_auth_uri(state='teststate'), ("%s?response_type=code" "&redirect_uri=%s&client_id=%s&state=teststate") % ( self.sso_endpoints['authorization_endpoint'], quote(TestEsiSecurity.CALLBACK_URI, safe=''), TestEsiSecurity.CLIENT_ID ) ) self.assertEqual( self.security.get_auth_uri(implicit=True, state='teststate'), ("%s?response_type=token" "&redirect_uri=%s&client_id=%s&state=teststate") % ( self.sso_endpoints['authorization_endpoint'], quote(TestEsiSecurity.CALLBACK_URI, safe=''), TestEsiSecurity.CLIENT_ID ) ) scopes = ["Scope1", "Scope2"] self.assertEqual( self.security.get_auth_uri(scopes=scopes, state='teststate'), ("%s?response_type=code&redirect_uri=%s" "&client_id=%s&scope=Scope1+Scope2&state=teststate") % ( self.sso_endpoints['authorization_endpoint'], quote(TestEsiSecurity.CALLBACK_URI, safe=''), TestEsiSecurity.CLIENT_ID ) ) def test_esisecurity_get_access_token_request_params(self): params = self.security.get_access_token_params('foo') self.assertEqual( params['headers'], {'Authorization': 'Basic %s' % TestEsiSecurity.BASIC_TOKEN} ) self.assertEqual( params['url'], self.sso_endpoints['token_endpoint'] ) self.assertEqual( params['data'], { 'grant_type': 'authorization_code', 'code': 'foo', } ) def test_esisecurity_get_refresh_token_request_params(self): with self.assertRaises(AttributeError): self.security.get_refresh_token_params() self.security.update_token({ 'access_token': 'access_token', 'refresh_token': 'refresh_token', 'expires_in': 60 }) # refresh all scopes params = self.security.get_refresh_token_params() self.assertEqual( params['headers'], {'Authorization': 'Basic %s' % TestEsiSecurity.BASIC_TOKEN} ) self.assertEqual( params['url'], self.sso_endpoints['token_endpoint'] ) self.assertEqual( params['data'], { 'grant_type': 'refresh_token', 'refresh_token': 'refresh_token', } ) # refresh specific scopes params = self.security.get_refresh_token_params(scope_list=['a', 'b']) self.assertEqual( params['data'], { 'grant_type': 'refresh_token', 'refresh_token': 'refresh_token', 'scope': 'a+b' } ) # refresh specific scopes exception with self.assertRaises(AttributeError): self.security.get_refresh_token_params(scope_list='notalist') def test_esisecurity_token_expiry(self): self.security.token_expiry = None self.assertTrue(self.security.is_token_expired()) self.security.token_expiry = time.time() - 10 self.assertTrue(self.security.is_token_expired()) self.security.token_expiry = time.time() + 60 self.assertFalse(self.security.is_token_expired()) self.assertTrue(self.security.is_token_expired(offset=70)) def test_esisecurity_auth(self): with httmock.HTTMock(oauth_token): ret = self.security.auth('let it bee') self.assertEqual(ret['access_token'], 'access_token') self.assertEqual(ret['refresh_token'], 'refresh_token') self.assertEqual(ret['expires_in'], 1200) ret = self.security.auth('no_refresh') self.assertEqual(ret['access_token'], 'access_token') self.assertNotIn('refresh_token', ret) self.assertEqual(ret['expires_in'], 1200) with self.assertRaises(APIException): self.security.auth('fail_test') def test_esisecurity_refresh(self): with httmock.HTTMock(oauth_token): self.security.refresh_token = 'refresh_token' ret = self.security.refresh() self.assertEqual(ret['access_token'], 'access_token') self.assertEqual(ret['refresh_token'], 'refresh_token') self.assertEqual(ret['expires_in'], 1200) with self.assertRaises(APIException): self.security.refresh_token = 'fail_test_token' self.security.refresh() def test_esisecurity_revoke(self): with httmock.HTTMock(oauth_revoke): self.security.refresh_token = 'refresh_token' self.security.revoke() self.security.access_token = 'access_token' self.security.revoke() with self.assertRaises(AttributeError): self.security.revoke() def test_esisecurity_verify(self): # this is just for coverage purpose. This doesn't work without valid # jwt token with self.assertRaises(AttributeError): self.security.verify() self.security.update_token({ 'access_token': 'access_token', 'refresh_token': 'refresh_token', 'expires_in': 60 }) with self.assertRaises(JWTError): self.security.verify() with httmock.HTTMock(*_all_auth_mock_): with open(TestEsiSecurity.RSC_JWKS, 'r') as jwks: jwks = json.load(jwks) security_nojwks = EsiSecurity( redirect_uri=TestEsiSecurity.CALLBACK_URI, client_id=TestEsiSecurity.CLIENT_ID, secret_key=TestEsiSecurity.SECRET_KEY, jwks_key=jwks['keys'][0] ) security_nojwks.update_token({ 'access_token': 'access_token', 'refresh_token': 'refresh_token', 'expires_in': 60 }) with self.assertRaises(JWTError): security_nojwks.verify() def test_esisecurity_call(self): class RequestTest(object): def __init__(self): self._security = [] self._p = {'header': {}} self.security.update_token({ 'access_token': 'access_token', 'refresh_token': 'refresh_token', 'expires_in': 60 }) req = RequestTest() self.security(req) self.assertNotIn('Authorization', req._p['header']) req._security.append({ 'unknown_security_name': {}, }) self.security(req) self.assertNotIn('Authorization', req._p['header']) req._security.append({ 'evesso': {}, }) self.security(req) self.assertIn('Authorization', req._p['header']) self.assertEqual( 'Bearer access_token', req._p['header']['Authorization'] ) def test_esisecurity_callback_refresh(self): class RequestTest(object): """ pyswagger Request object over simplified for test purpose""" def __init__(self): self._security = ['evesso'] self._p = {'header': {}} def callback_function(**kwargs): callback_function.count += 1 callback_function.count = 0 self.custom_refresh_token_signal.add_receiver(callback_function) self.security.update_token({ 'access_token': 'access_token', 'refresh_token': 'refresh_token', 'expires_in': -1 }) # test the auto refresh callback event customized with httmock.HTTMock(oauth_token): req = RequestTest() self.security(req) self.assertEqual(callback_function.count, 1) def test_esisecurity_non_json_response(self): self.security.update_token({ 'access_token': 'access_token', 'refresh_token': 'refresh_token', 'expires_in': -1 }) with httmock.HTTMock(non_json_error): try: self.security.auth('somecode') except APIException as exc: self.assertEqual(exc.status_code, 502) self.assertEqual( exc.response, six.b('<html><body>Some HTML Errors</body></html>') ) try: self.security.refresh() except APIException as exc: self.assertEqual(exc.status_code, 502) self.assertEqual( exc.response, six.b('<html><body>Some HTML Errors</body></html>') ) def test_esisecurity_pkce(self): uri = self.security_pkce.get_auth_uri('test') self.assertIn( 'code_challenge=%s' % TestEsiSecurity.CODE_CHALLENGE, uri ) params = self.security_pkce.get_access_token_params('test') self.assertEqual( params['data']['code_verifier'], TestEsiSecurity.CODE_VERIFIER ) self.assertEqual( params['data']['client_id'], TestEsiSecurity.CLIENT_ID ) self.assertNotIn('Authorization', params['headers'])
class TestEsiSecurity(unittest.TestCase): def setUp(self): pass def test_esisecurity_init(self): pass def test_esisecurity_update_token(self): pass def test_esisecurity_get_auth_uri(self): pass def test_esisecurity_get_access_token_request_params(self): pass def test_esisecurity_get_refresh_token_request_params(self): pass def test_esisecurity_token_expiry(self): pass def test_esisecurity_auth(self): pass def test_esisecurity_refresh(self): pass def test_esisecurity_revoke(self): pass def test_esisecurity_verify(self): pass def test_esisecurity_call(self): pass class RequestTest(object): def __init__(self): pass def test_esisecurity_callback_refresh(self): pass class RequestTest(object): ''' pyswagger Request object over simplified for test purpose''' def __init__(self): pass def callback_function(**kwargs): pass def test_esisecurity_non_json_response(self): pass def test_esisecurity_pkce(self): pass
21
1
20
2
18
0
1
0.02
1
7
5
0
15
4
15
87
382
48
327
53
306
7
167
49
146
3
2
2
20
144,385
Kyria/EsiPy
Kyria_EsiPy/esipy/client.py
esipy.client.EsiClient
class EsiClient(BaseClient): """ EsiClient is a pyswagger client that override some behavior and also add some features like auto retry, parallel calls... """ __schemes__ = set(['https']) __uncached_methods__ = ['POST', 'PUT', 'DELETE', 'HEAD'] def __init__(self, security=None, retry_requests=False, **kwargs): """ Init the ESI client object :param security: (optional) the security object [default: None] :param retry_requests: (optional) use a retry loop for all requests :param headers: (optional) additional headers we want to add :param transport_adapter: (optional) an HTTPAdapter object / implement :param cache: (optional) esipy.cache.BaseCache cache implementation. :param raw_body_only: (optional) default value [False] for all requests :param signal_api_call_stats: (optional) allow to define a specific signal to use, instead of using the global API_CALL_STATS :param timeout: (optional) default value [None=No timeout] timeout in seconds for requests :param no_etag_body: (optional) default False, set to return empty response when ETag requests return 304 (normal http behavior) """ super(EsiClient, self).__init__(security) self.security = security self._session = Session() # set the proper request implementation if retry_requests: self.request = self._retry_request else: self.request = self._request # store default raw_body_only in case user never want parsing self.raw_body_only = kwargs.pop('raw_body_only', False) # check for specified headers and update session.headers headers = kwargs.pop('headers', {}) if 'User-Agent' not in headers: warning_message = ( "Defining a 'User-Agent' header is a" " good practice, and allows CCP to contact you if required." " To do this, simply add the following when creating" " the client: headers={'User-Agent':'something'}." ) LOGGER.warning(warning_message) warnings.warn(warning_message) headers['User-Agent'] = ( 'EsiPy/Client - ' 'https://github.com/Kyria/EsiPy' ) self._session.headers.update({"Accept": "application/json"}) self._session.headers.update(headers) # transport adapter transport_adapter = kwargs.pop('transport_adapter', None) if isinstance(transport_adapter, HTTPAdapter): self._session.mount('http://', transport_adapter) self._session.mount('https://', transport_adapter) # initiate the cache object self.cache = check_cache(kwargs.pop('cache', False)) # other self.signal_api_call_stats = kwargs.pop( 'signal_api_call_stats', API_CALL_STATS ) self.timeout = kwargs.pop('timeout', None) self.no_etag_body = kwargs.pop('no_etag_body', False) def _retry_request(self, req_and_resp, _retry=0, **kwargs): """Uses self._request in a sane retry loop (for 5xx level errors). Do not use the _retry parameter, use the same params as _request Used when ESIClient is initialized with retry_requests=True if raise_on_error is True, this will only raise exception after all retry have been done """ raise_on_error = kwargs.pop('raise_on_error', False) if _retry: # backoff delay loop in seconds: 0.01, 0.16, 0.81, 2.56, 6.25 time.sleep(_retry ** 4 / 100) res = self._request(req_and_resp, **kwargs) if 500 <= res.status <= 599: _retry += 1 if _retry < 5: LOGGER.warning( "[failure #%d] %s %d: %r", _retry, req_and_resp[0].url, res.status, res.data, ) return self._retry_request( req_and_resp, _retry=_retry, raise_on_error=raise_on_error, **kwargs ) if res.status >= 400 and raise_on_error: raise APIException( req_and_resp[0].url, res.status, response=res.raw, request_param=req_and_resp[0].query, response_header=res.header ) return res def multi_request(self, reqs_and_resps, threads=20, **kwargs): """Use a threadpool to send multiple requests in parallel. :param reqs_and_resps: iterable of req_and_resp tuples :param raw_body_only: applied to every request call :param opt: applies to every request call :param threads: number of concurrent workers to use :return: a list of [(pyswagger.io.Request, pyswagger.io.Response), ...] """ opt = kwargs.pop('opt', {}) raw_body_only = kwargs.pop('raw_body_only', self.raw_body_only) # you shouldnt need more than 100, 20 is probably fine in most cases threads = max(min(threads, 100), 1) def _multi_shim(req_and_resp): """Shim self.request to also return the original request.""" return req_and_resp[0], self.request( req_and_resp, raw_body_only=raw_body_only, opt=opt, ) results = [] with ThreadPoolExecutor(max_workers=threads) as pool: for result in pool.map(_multi_shim, reqs_and_resps): results.append(result) return results def _request(self, req_and_resp, **kwargs): """ Take a request_and_response object from pyswagger.App and check auth, token, headers, prepare the actual request and fill the response Note on performance : if you need more performance (because you are using this in a batch) you'd rather set raw_body_only=True, as parsed body is really slow. You'll then have to get data from response.raw and convert it to json using "json.loads(response.raw)" :param req_and_resp: the request and response object from pyswagger.App :param raw_body_only: define if we want the body to be parsed as object instead of staying a raw dict. [Default: False] :param opt: options, see pyswagger/blob/master/pyswagger/io.py#L144 :param raise_on_error: boolean to raise an error if HTTP Code >= 400 :return: the final response. """ opt = kwargs.pop('opt', {}) # reset the request and response to reuse existing req_and_resp req_and_resp[0].reset() req_and_resp[1].reset() # required because of inheritance request, response = super(EsiClient, self).request(req_and_resp, opt) # check cache here so we have all headers, formed url and params cache_key = make_cache_key(request) res = self.__make_request(request, opt, cache_key) if res.status_code == 200: self.__cache_response(cache_key, res, request.method.upper()) # generate the Response object from requests response response.raw_body_only = kwargs.pop( 'raw_body_only', self.raw_body_only ) try: response.apply_with( status=res.status_code, header=res.headers, raw=six.BytesIO(res.content).getvalue() ) except (ValueError, Exception): # catch when response is not JSON raise APIException( request.url, res.status_code, response=res.content, request_param=request.query, response_header=res.headers ) if 'warning' in res.headers: # send in logger and warnings, so the user doesn't have to use # logging to see it (at least once) LOGGER.warning("[%s] %s", res.url, res.headers['warning']) warnings.warn("[%s] %s" % (res.url, res.headers['warning'])) if res.status_code >= 400 and kwargs.pop('raise_on_error', False): raise APIException( request.url, res.status_code, response=response.raw, request_param=request.query, response_header=response.header ) return response def head(self, req_and_resp, **kwargs): """ Take a request_and_response object from pyswagger.App, check and prepare everything to make a valid HEAD request :param req_and_resp: the request and response object from pyswagger.App :param opt: options, see pyswagger/blob/master/pyswagger/io.py#L144 :param raise_on_error: boolean to raise an error if HTTP Code >= 400 :return: the final response. """ opt = kwargs.pop('opt', {}) # reset the request and response to reuse existing req_and_resp req_and_resp[0].reset() req_and_resp[1].reset() # required because of inheritance request, response = super(EsiClient, self).request(req_and_resp, opt) res = self.__make_request(request, opt, method='HEAD') response.apply_with( status=res.status_code, header=res.headers, raw=None, ) if 'warning' in res.headers: # send in logger and warnings, so the user doesn't have to use # logging to see it (at least once) LOGGER.warning("[%s] %s", res.url, res.headers['warning']) warnings.warn("[%s] %s" % (res.url, res.headers['warning'])) if res.status_code >= 400 and kwargs.pop('raise_on_error', False): raise APIException( request.url, res.status_code, response='', request_param=request.query, response_header=response.header ) return response def __cache_response(self, cache_key, res, method): """ cache the response if method is one of self.__uncached_method__, don't cache anything """ if ('expires' in res.headers and method not in self.__uncached_methods__): cache_timeout = get_cache_time_left(res.headers.get('expires')) # Occasionally CCP swagger will return an outdated expire # warn and skip cache if timeout is <0 if cache_timeout >= 0: self.cache.set( cache_key, CachedResponse( status_code=res.status_code, headers=res.headers, content=res.content, url=res.url, ), cache_timeout ) else: LOGGER.warning( "[%s] returned expired result: %s", res.url, res.headers) warnings.warn("[%s] returned expired result" % res.url) def __make_request(self, request, opt, cache_key=None, method=None): """ Check cache, deal with expiration and etag, make the request and return the response or cached response. :param request: the pyswagger.io.Request object to prepare the request :param opt: options, see pyswagger/blob/master/pyswagger/io.py#L144 :param cache_key: the cache key used for the cache stuff. :param method: [default:None] allows to force the method, especially useful if you want to make a HEAD request. Default value will use endpoint method """ # check expiration and etags opt_headers = {} cached_response = self.cache.get(cache_key, None) if cached_response is not None: # if we have expires cached, and still validd expires = cached_response.headers.get('expires', None) if expires is not None: cache_timeout = get_cache_time_left( cached_response.headers['expires'] ) if cache_timeout >= 0: return cached_response # if we have etags, add the header to use them etag = cached_response.headers.get('etag', None) if etag is not None: opt_headers['If-None-Match'] = etag # if nothing makes us use the cache, invalidate everything if (expires is None or cache_timeout < 0) and etag is None: self.cache.invalidate(cache_key) # apply request-related options before preparation. request.prepare( scheme=self.prepare_schemes(request).pop(), handle_files=False ) request._patch(opt) # prepare the request and make it. method = method or request.method.upper() request.header.update(opt_headers) prepared_request = self._session.prepare_request( Request( method=method, url=request.url, params=request.query, data=request.data, headers=request.header ) ) start_api_call = time.time() try: res = self._session.send( prepared_request, timeout=self.timeout, ) except (RequestsConnectionError, Timeout) as exc: # timeout issue, generate a fake response to finish the process # as a normal error 500 res = CachedResponse( status_code=500, headers={}, content=('{"error": "%s"}' % str(exc)).encode('latin-1'), url=prepared_request.url ) # event for api call stats self.signal_api_call_stats.send( url=res.url, status_code=res.status_code, elapsed_time=time.time() - start_api_call, message=res.content if res.status_code != 200 else None ) # if we have HTTP 304 (content didn't change), return the cached # response updated with the new headers if (res.status_code == 304 and cached_response is not None and not self.no_etag_body): cached_response.headers['Expires'] = res.headers.get('Expires') cached_response.headers['Date'] = res.headers.get('Date') return cached_response return res
class EsiClient(BaseClient): ''' EsiClient is a pyswagger client that override some behavior and also add some features like auto retry, parallel calls... ''' def __init__(self, security=None, retry_requests=False, **kwargs): ''' Init the ESI client object :param security: (optional) the security object [default: None] :param retry_requests: (optional) use a retry loop for all requests :param headers: (optional) additional headers we want to add :param transport_adapter: (optional) an HTTPAdapter object / implement :param cache: (optional) esipy.cache.BaseCache cache implementation. :param raw_body_only: (optional) default value [False] for all requests :param signal_api_call_stats: (optional) allow to define a specific signal to use, instead of using the global API_CALL_STATS :param timeout: (optional) default value [None=No timeout] timeout in seconds for requests :param no_etag_body: (optional) default False, set to return empty response when ETag requests return 304 (normal http behavior) ''' pass def _retry_request(self, req_and_resp, _retry=0, **kwargs): '''Uses self._request in a sane retry loop (for 5xx level errors). Do not use the _retry parameter, use the same params as _request Used when ESIClient is initialized with retry_requests=True if raise_on_error is True, this will only raise exception after all retry have been done ''' pass def multi_request(self, reqs_and_resps, threads=20, **kwargs): '''Use a threadpool to send multiple requests in parallel. :param reqs_and_resps: iterable of req_and_resp tuples :param raw_body_only: applied to every request call :param opt: applies to every request call :param threads: number of concurrent workers to use :return: a list of [(pyswagger.io.Request, pyswagger.io.Response), ...] ''' pass def _multi_shim(req_and_resp): '''Shim self.request to also return the original request.''' pass def _request(self, req_and_resp, **kwargs): ''' Take a request_and_response object from pyswagger.App and check auth, token, headers, prepare the actual request and fill the response Note on performance : if you need more performance (because you are using this in a batch) you'd rather set raw_body_only=True, as parsed body is really slow. You'll then have to get data from response.raw and convert it to json using "json.loads(response.raw)" :param req_and_resp: the request and response object from pyswagger.App :param raw_body_only: define if we want the body to be parsed as object instead of staying a raw dict. [Default: False] :param opt: options, see pyswagger/blob/master/pyswagger/io.py#L144 :param raise_on_error: boolean to raise an error if HTTP Code >= 400 :return: the final response. ''' pass def head(self, req_and_resp, **kwargs): ''' Take a request_and_response object from pyswagger.App, check and prepare everything to make a valid HEAD request :param req_and_resp: the request and response object from pyswagger.App :param opt: options, see pyswagger/blob/master/pyswagger/io.py#L144 :param raise_on_error: boolean to raise an error if HTTP Code >= 400 :return: the final response. ''' pass def __cache_response(self, cache_key, res, method): ''' cache the response if method is one of self.__uncached_method__, don't cache anything ''' pass def __make_request(self, request, opt, cache_key=None, method=None): ''' Check cache, deal with expiration and etag, make the request and return the response or cached response. :param request: the pyswagger.io.Request object to prepare the request :param opt: options, see pyswagger/blob/master/pyswagger/io.py#L144 :param cache_key: the cache key used for the cache stuff. :param method: [default:None] allows to force the method, especially useful if you want to make a HEAD request. Default value will use endpoint method ''' pass
9
9
48
8
28
12
4
0.43
1
9
1
0
7
8
7
7
388
69
224
46
215
96
121
44
112
9
1
3
32
144,386
Kyria/EsiPy
Kyria_EsiPy/esipy/app.py
esipy.app.EsiApp
class EsiApp(object): """ EsiApp is an app object that'll allows us to play with ESI Meta API, not to have to deal with all ESI versions manually / meta """ def __init__(self, **kwargs): """ Constructor. :param cache: if specified, use that cache, else use DictCache :param cache_time: is the minimum cache time for versions endpoints. If set to 0, never expires". None uses header expires Default 86400 (1d) :param cache_prefix: the prefix used to all cache key for esiapp :param meta_url: the meta url you want to use. Default is meta esi URL https://esi.evetech.net/swagger.json :param datasource: the EVE datasource to be used. Default: tranquility """ self.meta_url = kwargs.pop( 'meta_url', 'https://esi.evetech.net/swagger.json' ) self.expire = kwargs.pop('cache_time', 86400) if self.expire is not None and self.expire < 0: self.expire = 86400 self.cache_prefix = kwargs.pop('cache_prefix', 'esipy') self.esi_meta_cache_key = '%s:app:meta_swagger_url' % self.cache_prefix cache = kwargs.pop('cache', False) self.caching = True if cache is not None else False self.cache = check_cache(cache) self.datasource = kwargs.pop('datasource', 'tranquility') self.app = self.__get_or_create_app( self.meta_url, self.esi_meta_cache_key ) def __get_or_create_app(self, url, cache_key): """ Get the app from cache or generate a new one if required Because app object doesn't have etag/expiry, we have to make a head() call before, to have these informations first... """ headers = {"Accept": "application/json"} app_url = '%s?datasource=%s' % (url, self.datasource) cached = self.cache.get(cache_key, (None, None, 0)) if cached is None or len(cached) != 3: self.cache.invalidate(cache_key) cached_app, cached_headers, cached_expiry = (cached, None, 0) else: cached_app, cached_headers, cached_expiry = cached if cached_app is not None and cached_headers is not None: # we didn't set custom expire, use header expiry expires = cached_headers.get('expires', None) cache_timeout = -1 if self.expire is None and expires is not None: cache_timeout = get_cache_time_left( cached_headers['expires'] ) if cache_timeout >= 0: return cached_app # we set custom expire, check this instead else: if self.expire == 0 or cached_expiry >= time.time(): return cached_app # if we have etags, add the header to use them etag = cached_headers.get('etag', None) if etag is not None: headers['If-None-Match'] = etag # if nothing makes us use the cache, invalidate it if ((expires is None or cache_timeout < 0 or cached_expiry < time.time()) and etag is None): self.cache.invalidate(cache_key) # set timeout value in case we have to cache it later timeout = 0 if self.expire is not None and self.expire > 0: timeout = time.time() + self.expire # we are here, we know we have to make a head call... res = requests.head(app_url, headers=headers) if self.expire is not None and self.expire > 0: expiration = self.expire else: expiration = get_cache_time_left( res.headers.get('expires') ) if res.status_code == 304 and cached_app is not None: self.cache.set( cache_key, (cached_app, res.headers, timeout), expiration ) return cached_app # ok, cache is not accurate, make the full stuff # also retry up to 3 times if we get any errors app = None for _retry in range(1, 4): try: app = App.create(app_url) except HTTPError as error: LOGGER.warning( "[failure #%d] %s %d: %r", _retry, app_url, error.code, error.msg ) continue break if app is None: raise APIException( app_url, 500, response="Cannot fetch '%s'." % app_url ) if self.caching and app: self.cache.set(cache_key, (app, res.headers, timeout), expiration) return app def __getattr__(self, name): """ Return the request object depending on its nature. if "op" is requested, simply return "app.op" which is a pyswagger app if anything else is requested, check if it exists, then if it's a swagger endpoint, try to create it and return it. """ if name == 'op': return self.app.op try: op_attr = self.app.op[name] except KeyError: raise AttributeError('%s is not a valid operation' % name) # if the endpoint is a swagger spec if 'swagger.json' in op_attr.url: spec_url = 'https:%s' % op_attr.url cache_key = '%s:app:%s' % (self.cache_prefix, op_attr.url) return self.__get_or_create_app(spec_url, cache_key) else: raise AttributeError('%s is not a swagger endpoint' % name) def __getattribute__(self, name): """ Get attribute. If attribute is app, and app is None, create it again from cache / by querying ESI """ attr = super(EsiApp, self).__getattribute__(name) if name == 'app' and attr is None: attr = self.__get_or_create_app( self.meta_url, self.esi_meta_cache_key ) self.app = attr return attr def clear_cached_endpoints(self, prefix=None): """ Invalidate all cached endpoints, meta included Loop over all meta endpoints to generate all cache key the invalidate each of them. Doing it this way will prevent the app not finding keys as the user may change its prefixes Meta endpoint will be updated upon next call. :param: prefix the prefix for the cache key (default is cache_prefix) """ prefix = prefix if prefix is not None else self.cache_prefix for endpoint in self.app.op.values(): cache_key = '%s:app:%s' % (prefix, endpoint.url) self.cache.invalidate(cache_key) self.cache.invalidate('%s:app:meta_swagger_url' % self.cache_prefix) self.app = None
class EsiApp(object): ''' EsiApp is an app object that'll allows us to play with ESI Meta API, not to have to deal with all ESI versions manually / meta ''' def __init__(self, **kwargs): ''' Constructor. :param cache: if specified, use that cache, else use DictCache :param cache_time: is the minimum cache time for versions endpoints. If set to 0, never expires". None uses header expires Default 86400 (1d) :param cache_prefix: the prefix used to all cache key for esiapp :param meta_url: the meta url you want to use. Default is meta esi URL https://esi.evetech.net/swagger.json :param datasource: the EVE datasource to be used. Default: tranquility ''' pass def __get_or_create_app(self, url, cache_key): ''' Get the app from cache or generate a new one if required Because app object doesn't have etag/expiry, we have to make a head() call before, to have these informations first... ''' pass def __getattr__(self, name): ''' Return the request object depending on its nature. if "op" is requested, simply return "app.op" which is a pyswagger app if anything else is requested, check if it exists, then if it's a swagger endpoint, try to create it and return it. ''' pass def __getattribute__(self, name): ''' Get attribute. If attribute is app, and app is None, create it again from cache / by querying ESI ''' pass def clear_cached_endpoints(self, prefix=None): ''' Invalidate all cached endpoints, meta included Loop over all meta endpoints to generate all cache key the invalidate each of them. Doing it this way will prevent the app not finding keys as the user may change its prefixes Meta endpoint will be updated upon next call. :param: prefix the prefix for the cache key (default is cache_prefix) ''' pass
6
6
34
4
23
7
5
0.34
1
5
1
0
5
8
5
5
178
25
115
34
109
39
83
33
77
15
1
3
27
144,387
Kyria/EsiPy
Kyria_EsiPy/esipy/cache.py
esipy.cache.MemcachedCache
class MemcachedCache(BaseCache): """ Base cache implementation for memcached. This cache requires you to install memcached using `pip install python-memcached` """ def __init__(self, memcache_client): """ memcache_client must be an instance of memcache.Client(). """ import memcache if not isinstance(memcache_client, memcache.Client): raise TypeError('cache must be an instance of memcache.Client') self._mc = memcache_client def get(self, key, default=None): value = self._mc.get(_hash(key)) return value if value is not None else default def set(self, key, value, expire=300): expire = 0 if expire is None else expire return self._mc.set(_hash(key), value, time=int(expire)) def invalidate(self, key): return self._mc.delete(_hash(key))
class MemcachedCache(BaseCache): ''' Base cache implementation for memcached. This cache requires you to install memcached using `pip install python-memcached` ''' def __init__(self, memcache_client): ''' memcache_client must be an instance of memcache.Client(). ''' pass def get(self, key, default=None): pass def set(self, key, value, expire=300): pass def invalidate(self, key): pass
5
2
4
0
3
1
2
0.43
1
2
0
0
4
1
4
7
25
5
14
8
8
6
14
8
8
2
2
1
7
144,388
Kyria/EsiPy
Kyria_EsiPy/esipy/cache.py
esipy.cache.DummyCache
class DummyCache(BaseCache): """ Base cache implementation that provide a fake cache that allows a "no cache" use without breaking everything """ def __init__(self): self._dict = {} def get(self, key, default=None): return default def set(self, key, value, expire=300): pass def invalidate(self, key): pass
class DummyCache(BaseCache): ''' Base cache implementation that provide a fake cache that allows a "no cache" use without breaking everything ''' def __init__(self): pass def get(self, key, default=None): pass def set(self, key, value, expire=300): pass def invalidate(self, key): pass
5
1
2
0
2
0
1
0.22
1
0
0
0
4
1
4
7
15
4
9
6
4
2
9
6
4
1
2
0
4
144,389
Kyria/EsiPy
Kyria_EsiPy/esipy/cache.py
esipy.cache.FileCache
class FileCache(BaseCache): """ BaseCache implementation using files to store the data. This implementation uses diskcache.Cache see http://www.grantjenks.com/docs/diskcache/api.html#cache for more informations This cache requires you to install diskcache using `pip install diskcache` """ def __init__(self, path, **settings): """ Constructor Arguments: path {String} -- The path on the disk to save the data settings {dict} -- The settings values for diskcache """ from diskcache import Cache self._cache = Cache(path, **settings) def __del__(self): """ Close the connection as the cache instance is deleted. Safe to use as there are no circular ref. """ self._cache.close() def set(self, key, value, expire=300): expire = None if expire == 0 or expire is None else int(expire) self._cache.set(_hash(key), value, expire=expire) def get(self, key, default=None): return self._cache.get(_hash(key), default) def invalidate(self, key): self._cache.delete(_hash(key))
class FileCache(BaseCache): ''' BaseCache implementation using files to store the data. This implementation uses diskcache.Cache see http://www.grantjenks.com/docs/diskcache/api.html#cache for more informations This cache requires you to install diskcache using `pip install diskcache` ''' def __init__(self, path, **settings): ''' Constructor Arguments: path {String} -- The path on the disk to save the data settings {dict} -- The settings values for diskcache ''' pass def __del__(self): ''' Close the connection as the cache instance is deleted. Safe to use as there are no circular ref. ''' pass def set(self, key, value, expire=300): pass def get(self, key, default=None): pass def invalidate(self, key): pass
6
3
4
0
2
2
1
1.08
1
1
0
0
5
1
5
8
34
7
13
8
6
14
13
8
6
2
2
0
6
144,390
Kyria/EsiPy
Kyria_EsiPy/esipy/cache.py
esipy.cache.RedisCache
class RedisCache(BaseCache): """ BaseCache implementation for Redis cache. This cache handler requires the redis package to be installed `pip install redis` """ def __init__(self, redis_client): """ redis_client must be an instance of redis.Redis""" from redis import Redis if not isinstance(redis_client, Redis): raise TypeError('cache must be an instance of redis.Redis') self._r = redis_client def get(self, key, default=None): value = self._r.get(_hash(key)) return pickle.loads(value) if value is not None else default def set(self, key, value, expire=300): if expire is None or expire == 0: return self._r.set(_hash(key), pickle.dumps(value)) return self._r.setex( name=_hash(key), value=pickle.dumps(value), time=datetime.timedelta(seconds=int(expire)), ) def invalidate(self, key): return self._r.delete(_hash(key))
class RedisCache(BaseCache): ''' BaseCache implementation for Redis cache. This cache handler requires the redis package to be installed `pip install redis` ''' def __init__(self, redis_client): ''' redis_client must be an instance of redis.Redis''' pass def get(self, key, default=None): pass def set(self, key, value, expire=300): pass def invalidate(self, key): pass
5
2
5
0
5
0
2
0.26
1
3
0
0
4
1
4
7
29
5
19
8
13
5
15
8
9
2
2
1
7
144,391
LABHR/octohatrack
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LABHR_octohatrack/versioneer.py
versioneer.get_cmdclass.cmd_sdist
class cmd_sdist(_sdist): def run(self): versions = get_versions() self._versioneer_generated_versions = versions # unless we update this, the command will keep using the old # version self.distribution.metadata.version = versions["version"] return _sdist.run(self) def make_release_tree(self, base_dir, files): root = get_root() cfg = get_config_from_root(root) _sdist.make_release_tree(self, base_dir, files) # now locate _version.py in the new base_dir directory # (remembering that it may be a hardlink) and replace it with an # updated value target_versionfile = os.path.join(base_dir, cfg.versionfile_source) print("UPDATING %s" % target_versionfile) write_to_version_file( target_versionfile, self._versioneer_generated_versions )
class cmd_sdist(_sdist): def run(self): pass def make_release_tree(self, base_dir, files): pass
3
0
10
0
7
3
1
0.33
1
0
0
0
2
1
2
2
21
1
15
8
12
5
13
8
10
1
1
0
2
144,392
LABHR/octohatrack
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LABHR_octohatrack/versioneer.py
versioneer.get_cmdclass.cmd_py2exe
class cmd_py2exe(_py2exe): def run(self): root = get_root() cfg = get_config_from_root(root) versions = get_versions() target_versionfile = cfg.versionfile_source print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, versions) _py2exe.run(self) os.unlink(target_versionfile) with open(cfg.versionfile_source, "w") as f: LONG = LONG_VERSION_PY[cfg.VCS] f.write( LONG % { "DOLLAR": "$", "STYLE": cfg.style, "TAG_PREFIX": cfg.tag_prefix, "PARENTDIR_PREFIX": cfg.parentdir_prefix, "VERSIONFILE_SOURCE": cfg.versionfile_source, } )
class cmd_py2exe(_py2exe): def run(self): pass
2
0
22
1
21
0
1
0
1
0
0
0
1
0
1
1
23
1
22
8
20
0
13
7
11
1
1
1
1
144,393
LABHR/octohatrack
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LABHR_octohatrack/versioneer.py
versioneer.get_cmdclass.cmd_version
class cmd_version(Command): description = "report generated version string" user_options = [] boolean_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): vers = get_versions(verbose=True) print("Version: %s" % vers["version"]) print(" full-revisionid: %s" % vers.get("full-revisionid")) print(" dirty: %s" % vers.get("dirty")) print(" date: %s" % vers.get("date")) if vers["error"]: print(" error: %s" % vers["error"])
class cmd_version(Command): def initialize_options(self): pass def finalize_options(self): pass def run(self): pass
4
0
4
0
4
0
1
0
1
0
0
0
3
0
3
3
19
3
16
8
12
0
16
8
12
2
1
1
4
144,394
LABHR/octohatrack
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LABHR_octohatrack/versioneer.py
versioneer.get_cmdclass.cmd_build_exe
class cmd_build_exe(_build_exe): def run(self): root = get_root() cfg = get_config_from_root(root) versions = get_versions() target_versionfile = cfg.versionfile_source print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, versions) _build_exe.run(self) os.unlink(target_versionfile) with open(cfg.versionfile_source, "w") as f: LONG = LONG_VERSION_PY[cfg.VCS] f.write( LONG % { "DOLLAR": "$", "STYLE": cfg.style, "TAG_PREFIX": cfg.tag_prefix, "PARENTDIR_PREFIX": cfg.parentdir_prefix, "VERSIONFILE_SOURCE": cfg.versionfile_source, } )
class cmd_build_exe(_build_exe): def run(self): pass
2
0
22
1
21
0
1
0
1
0
0
0
1
0
1
1
23
1
22
8
20
0
13
7
11
1
1
1
1
144,395
LABHR/octohatrack
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LABHR_octohatrack/versioneer.py
versioneer.get_cmdclass.cmd_build_py
class cmd_build_py(_build_py): def run(self): root = get_root() cfg = get_config_from_root(root) versions = get_versions() _build_py.run(self) # now locate _version.py in the new build/ directory and replace # it with an updated value if cfg.versionfile_build: target_versionfile = os.path.join( self.build_lib, cfg.versionfile_build) print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, versions)
class cmd_build_py(_build_py): def run(self): pass
2
0
11
0
9
2
2
0.2
1
0
0
0
1
0
1
1
12
0
10
6
8
2
10
6
8
2
1
1
2
144,396
LCAV/pylocus
LCAV_pylocus/test/test_srls_fail.py
test.test_srls_fail.TestSRLSFail
class TestSRLSFail(unittest.TestCase): """ trying to reproduce a fail of SRLS. """ def setUp(self): # from error logs: self.all_points = np.array([[0.89, 2.87, 1.22], [2.12000000001, 0.0, 1.5], [5.83999999999, 2.5499998, 1.37999999], [5.83999999999, 4.6399997, 1.57000001], [0.100000000001, 3.0, 1.48], [0.100000000001, 4.20000000002, 1.5], [2.879999999999, 3.33999999999, 0.75], [5.759999999998, 3.46, 1.0], [3.54, 6.8700001, 1.139999]]) self.anchors = self.all_points[1:, :] self.xhat = [0.8947106, 2.87644499, 1.22189597] distances = [1.1530589508606381, 1.6797066823110891, 1.1658051261713582, 0.42021624764667165, 1.1196561208517539, 0.44373006779135082, 1.3051970883541162, 2.6628083049963136] [M, d] = self.anchors.shape N = M + 1 self.edm = np.zeros((N, N)) self.edm[1:, 1:] = get_edm(self.anchors) self.edm[0, 1:] = np.array(distances) ** 2.0 self.edm[1:, 0] = np.array(distances) ** 2.0 weights = [10.0, 1.0, 10.0, 10.0, 10.0, 10.0, 10.0, 1.0] self.weights = np.zeros((N, N)) self.weights[1:, 1:] = 10.0 self.weights[0, 1:] = weights self.weights[1:, 0] = weights def test_strange_case(self): xhat = reconstruct_srls(self.edm, self.all_points, W=self.weights) print(xhat[0]) xhat = reconstruct_srls(self.edm, self.all_points, W=self.weights, rescale=False, z=self.all_points[0, 2]) print(xhat[0])
class TestSRLSFail(unittest.TestCase): ''' trying to reproduce a fail of SRLS. ''' def setUp(self): pass def test_strange_case(self): pass
3
1
18
1
16
1
1
0.06
1
0
0
0
2
5
2
74
38
3
33
12
30
2
22
12
19
1
2
0
2
144,397
LCAV/pylocus
LCAV_pylocus/test/test_emds.py
test.test_emds.TestEMDS
class TestEMDS(BaseCommon.TestAlgorithms): def setUp(self): print('TestEMDS:setUp') BaseCommon.TestAlgorithms.setUp(self) self.n_it = 5 self.N_zero = [5] self.N_relaxed = [5] self.eps = 1e-7 self.methods = ['relaxed','iterative'] def create_points(self, N=5, d=3): print('TestEMDS:create_points') self.pts = HeterogenousSet(N, d) self.pts.set_points('normal') self.C, self.b = self.pts.get_KE_constraints() def call_method(self, method=''): print('TestEMDS:call_method with', method) if method == '': return reconstruct_emds(self.pts.edm, Om=self.pts.Om, all_points=self.pts.points) else: return reconstruct_emds(self.pts.edm, Om=self.pts.Om, all_points=self.pts.points, C=self.C, b=self.b, method=method)
class TestEMDS(BaseCommon.TestAlgorithms): def setUp(self): pass def create_points(self, N=5, d=3): pass def call_method(self, method=''): pass
4
0
7
0
7
0
1
0
1
2
2
0
3
8
3
100
24
2
22
11
18
0
19
11
15
2
5
1
4
144,398
LCAV/pylocus
LCAV_pylocus/test/test_completion.py
test.test_completion.TestAlgorithms
class TestAlgorithms(unittest.TestCase): def setUp(self): self.pts = PointSet(N=5, d=3) self.pts.set_points(mode='convex') W = np.ones(self.pts.edm.shape) indices_missing = ([4,1],[0,3]) W[indices_missing] = 0.0 W = np.multiply(W, W.T) np.fill_diagonal(W, 0.0) self.W = W # TODO: find out why sdr and rank alternation don't work. #self.methods = ['acd', 'dwmds', 'sdr', 'rank'] self.methods = ['acd', 'dwmds'] def call_method(self, edm_input, method): print('running method', method) edm_missing = np.multiply(edm_input, self.W) if method == 'sdr': return semidefinite_relaxation(edm_input, lamda=1000, W=self.W) elif method == 'rank': return rank_alternation(edm_missing, rank=self.pts.d+2, niter=100)[0] else: X0 = self.pts.points X0 += np.random.normal(loc=0.0, scale=0.01) if method == 'acd': return completion_acd(edm_missing, X0, self.W) elif method == 'dwmds': return completion_dwmds(edm_missing, X0, self.W) def test_complete(self): for i in range(10): self.pts.set_points('random') for method in self.methods: edm_complete = self.pts.edm.copy() edm_output = self.call_method(edm_complete, method) np.testing.assert_allclose(edm_complete, edm_output)
class TestAlgorithms(unittest.TestCase): def setUp(self): pass def call_method(self, edm_input, method): pass def test_complete(self): pass
4
0
11
0
10
1
3
0.06
1
2
1
0
3
3
3
75
38
4
32
15
28
2
29
15
25
5
2
2
9
144,399
LCAV/pylocus
LCAV_pylocus/test/test_common.py
test.test_common.BaseCommon
class BaseCommon: ''' Empty class such that TestCommon is not run as a test class. TestAlgorithms is abstract and needs to be run through the inheriting classes. ''' class TestAlgorithms(ABC, unittest.TestCase): def setUp(self): self.eps = 1e-10 self.success_rate = 50 self.n_it = 100 self.N_zero = range(8, 12) self.N_relaxed = range(4, 10) self.methods = [''] @abstractmethod def create_points(self, N, d): raise NotImplementedError( 'Call to virtual method! create_points has to be defined by sublcasses!') @abstractmethod def call_method(self, method=''): raise NotImplementedError( 'Call to virtual method! call_method has to be defined by sublcasses!') def test_multiple(self): print('TestCommon:test_multiple') for i in range(self.n_it): # seed 381 used to fail. np.random.seed(i) self.test_zero_noise(it=i) def test_zero_noise(self, it=0): print('TestCommon:test_zero_noise') for N in self.N_zero: for d in (2, 3): self.create_points(N, d) for method in self.methods: points_estimate = self.call_method(method) if points_estimate is None: continue np.testing.assert_allclose(self.pts.points, points_estimate, self.eps)
class BaseCommon: ''' Empty class such that TestCommon is not run as a test class. TestAlgorithms is abstract and needs to be run through the inheriting classes. ''' class TestAlgorithms(ABC, unittest.TestCase): def setUp(self): pass @abstractmethod def create_points(self, N, d): pass @abstractmethod def call_method(self, method=''): pass def test_multiple(self): pass def test_zero_noise(self, it=0): pass
9
1
6
0
6
0
2
0.13
0
0
0
0
0
0
0
0
40
5
32
20
23
4
28
18
21
5
0
4
10
144,400
LCAV/pylocus
LCAV_pylocus/test/test_basics.py
test.test_basics.TestProjection
class TestProjection(unittest.TestCase): def setUp(self, N=4): self.N = N self.A = np.random.rand(self.N, self.N) self.b = np.random.rand(self.N) self.x = np.random.rand(self.N, self.N) def test_multiple(self): for i in range(10): self.test_square_matrix() self.test_square_vector() def test_square_vector(self): self.A = np.random.rand(self.N, self.N) self.b = np.random.rand(self.N) self.x = np.random.rand(self.N) self.test_projection() def test_square_matrix(self): self.A = np.random.rand(self.N, self.N) self.b = np.random.rand(self.N) self.x = np.random.rand(self.N, self.N) self.test_projection() def test_projection(self): xhat, cost, constraints = projection(self.x, self.A, self.b) self.assertTrue(constraints <= 1e-15, 'Constraints not satisfied:{}'.format(constraints)) xhat2, __, __ = projection(xhat, self.A, self.b) idempotent_error = mse(xhat, xhat2) self.assertTrue(idempotent_error < 1e-10, 'Projection not idempotent.')
class TestProjection(unittest.TestCase): def setUp(self, N=4): pass def test_multiple(self): pass def test_square_vector(self): pass def test_square_matrix(self): pass def test_projection(self): pass
6
0
5
0
5
0
1
0
1
1
0
0
5
4
5
77
32
6
26
14
20
0
26
14
20
2
2
1
6
144,401
LCAV/pylocus
LCAV_pylocus/test/test_alternating.py
test.test_alternating.TestAlternating
class TestAlternating(BaseCommon.TestAlgorithms): def setUp(self): print('TestAlternating:setUp') BaseCommon.TestAlgorithms.setUp(self) self.n_it = 1 self.eps = 1e-8 self.N_zero = [5] self.N_relaxed = [5] self.methods = ['dwMDS', 'ACD'] def create_points(self, N=10, d=3): print('TestAlternating:create_points') self.pts = PointSet(N, d) self.pts.set_points('normal') self.X0 = self.pts.points.copy() + \ np.random.normal(scale=self.eps * 0.01, size=self.pts.points.shape) def call_method(self, method=''): Xhat, __ = call_method(self.pts.edm, X0=self.X0, tol=self.eps, method=method) return Xhat def test_nonzero_noise(self): from pylocus.simulation import create_noisy_edm noises = np.logspace(-8, -3, 10) self.create_points() for method in self.methods: for noise in noises: noisy_edm = create_noisy_edm(self.pts.edm, noise) eps = noise * 100 Xhat, costs = call_method(noisy_edm, X0=self.X0, tol=self.eps, method=method) err = np.linalg.norm(Xhat - self.pts.points) self.assertTrue( err < eps, 'error {} not smaller than {}'.format(err, eps)) def test_decreasing_cost(self): self.create_points() for method in self.methods: Xhat, costs = call_method( self.pts.edm, X0=self.X0, tol=self.eps, method=method) cprev = np.inf for c in costs: self.assertTrue(c <= cprev + self.eps, 'c: {}, cprev:{}'.format(c, cprev)) cprev = c
class TestAlternating(BaseCommon.TestAlgorithms): def setUp(self): pass def create_points(self, N=10, d=3): pass def call_method(self, method=''): pass def test_nonzero_noise(self): pass def test_decreasing_cost(self): pass
6
0
8
0
8
0
2
0
1
2
2
0
5
7
5
102
46
4
42
26
35
0
36
26
29
3
5
2
9
144,402
LCAV/pylocus
LCAV_pylocus/test/test_acd.py
test.test_acd.TestACD
class TestACD(BaseCommon.TestAlgorithms): def setUp(self): BaseCommon.TestAlgorithms.setUp(self) self.create_points() self.n_it = 10 def create_points(self, N=5, d=2): print('TestACD:create_points') self.pts = PointSet(N, d) self.pts.set_points('random') self.pts.init() self.index = 0 def call_method(self, method=''): print('TestACD:call_method') Xhat, costs = reconstruct_acd(self.pts.edm, W=np.ones(self.pts.edm.shape), X0=self.pts.points, print_out=False, sweeps=3) return Xhat def add_noise(self, noise=1e-6): self.pts.edm = create_noisy_edm(self.pts.edm, noise)
class TestACD(BaseCommon.TestAlgorithms): def setUp(self): pass def create_points(self, N=5, d=2): pass def call_method(self, method=''): pass def add_noise(self, noise=1e-6): pass
5
0
5
0
5
0
1
0
1
2
2
0
4
3
4
101
23
3
20
9
15
0
17
9
12
1
5
0
4
144,403
LCAV/pylocus
LCAV_pylocus/pylocus/point_set.py
pylocus.point_set.HeterogenousSet
class HeterogenousSet(PointSet): """ Class containing heteregenous information in the form of direction vectors. :param self.m: Number of edges. :param self.V: Matrix of edges (self.m x self.d) :param self.KE: dissimilarity matrix (self.m x self.m) :param self.C: matrix for getting edges from points (self.V = self.C.dot(self.X)) :param self.dm: vector containing lengths of edges (self.m x 1) :param self.Om: Matrix containing cosines of inner angles (self.m x self.m) """ def __init__(self, N, d): PointSet.__init__(self, N, d) self.m = int((self.N - 1) * self.N / 2.0) self.V = np.zeros((self.m, d)) self.KE = np.zeros((self.m, self.m)) self.C = np.zeros((self.m, self.N)) self.dm = np.zeros((self.m, 1)) self.Om = np.zeros((self.m, self.m)) def init(self): PointSet.init(self) self.create_V() self.create_Om() def create_V(self): start = 0 for i in range(self.N): n = self.N - i - 1 self.C[start:start + n, i] = 1 self.C[start:start + n, i + 1:] = -np.eye(n) start = start + n self.V = np.dot(self.C, self.points) self.KE = np.dot(self.V, self.V.T) self.dm = np.linalg.norm(self.V, axis=1) def create_Om(self): for i in range(self.m): for j in range(self.m): if i != j: norm = np.linalg.norm( self.V[i, :]) * np.linalg.norm(self.V[j, :]) cos_inner_angle = np.dot(self.V[i, :], self.V[ j, :]) / norm else: cos_inner_angle = 1.0 self.Om[i, j] = cos_inner_angle def get_KE_constraints(self): """Get linear constraints on KE matrix. """ C2 = np.eye(self.m) C2 = C2[:self.m - 2, :] to_be_deleted = [] for idx_vij_1 in range(self.m - 2): idx_vij_2 = idx_vij_1 + 1 C2[idx_vij_1, idx_vij_2] = -1 i1 = np.where(self.C[idx_vij_1, :] == 1)[0][0] i2 = np.where(self.C[idx_vij_2, :] == 1)[0][0] j = np.where(self.C[idx_vij_1, :] == -1)[0][0] if i1 == i2: i = i1 k = np.where(self.C[idx_vij_2, :] == -1)[0][0] i_indices = self.C[:, j] == 1 j_indices = self.C[:, k] == -1 idx_vij_3 = np.where(np.bitwise_and( i_indices, j_indices))[0][0] C2[idx_vij_1, idx_vij_3] = 1 else: to_be_deleted.append(idx_vij_1) C2 = np.delete(C2, to_be_deleted, axis=0) b = np.zeros((C2.shape[0], 1)) return C2, b def copy(self): new = HeterogenousSet(self.N, self.d) new.points = self.points.copy() new.init() return new
class HeterogenousSet(PointSet): ''' Class containing heteregenous information in the form of direction vectors. :param self.m: Number of edges. :param self.V: Matrix of edges (self.m x self.d) :param self.KE: dissimilarity matrix (self.m x self.m) :param self.C: matrix for getting edges from points (self.V = self.C.dot(self.X)) :param self.dm: vector containing lengths of edges (self.m x 1) :param self.Om: Matrix containing cosines of inner angles (self.m x self.m) ''' def __init__(self, N, d): pass def init(self): pass def create_V(self): pass def create_Om(self): pass def get_KE_constraints(self): '''Get linear constraints on KE matrix. ''' pass def copy(self): pass
7
2
11
0
10
0
2
0.16
1
2
0
0
6
6
6
15
79
7
62
34
55
10
57
34
50
4
1
3
12
144,404
LCAV/pylocus
LCAV_pylocus/pylocus/lateration.py
pylocus.lateration.GeometryError
class GeometryError(Exception): pass
class GeometryError(Exception): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
10
2
0
2
1
1
0
2
1
1
0
3
0
0
144,405
LCAV/pylocus
LCAV_pylocus/test/test_srls.py
test.test_srls.TestSRLS
class TestSRLS(BaseCommon.TestAlgorithms): def setUp(self): BaseCommon.TestAlgorithms.setUp(self) self.create_points() # for d=3, N_missing=2, need at least 6 anchors (no rescale) or 7 anchors (rescaled). self.N_relaxed = range(6, 10) self.methods = ['normal', 'rescale', 'fixed'] self.eps = 1e-8 def create_points(self, N=10, d=2): self.pts = PointSet(N, d) self.pts.set_points('random') self.pts.init() self.n = 1 def call_method(self, method=''): print('TestSRLS:call_method') if method == '' or method == 'normal': return reconstruct_srls(self.pts.edm, self.pts.points, W=np.ones(self.pts.edm.shape)) elif method == 'rescale': return reconstruct_srls(self.pts.edm, self.pts.points, W=np.ones(self.pts.edm.shape), rescale=True) elif method == 'fixed' and self.pts.d == 3: return reconstruct_srls(self.pts.edm, self.pts.points, W=np.ones(self.pts.edm.shape), rescale=False, z=self.pts.points[0, 2]) def test_fail(self): # Example point set that used to fail. With the newer SRLS version this is fixed. # Status: July 16, 2018 points_fail = np.array([[0.00250654, 0.89508715, 0.35528746], [0.52509683, 0.88692205, 0.76633946], [0.64764605, 0.94040708, 0.20720253], [0.69637586, 0.99566993, 0.49537693], [0.64455557, 0.46856155, 0.80050257], [0.90556836, 0.75831552, 0.81982037], [0.86634135, 0.5139182 , 0.14738743], [0.29145628, 0.54500108, 0.6586396 ]]) method = 'rescale' self.pts.set_points(points=points_fail) points_estimate = self.call_method(method=method) error = np.linalg.norm(self.pts.points - points_estimate) self.assertTrue(error < self.eps, 'error: {} not smaller than {}'.format(error, self.eps)) points_fail = np.array([[0.63, 0.45], [0.35, 0.37], [0.69, 0.71], [0.71, 0.73], [0.43, 0.44], [0.58, 0.59]]) method = 'normal' self.pts.set_points(points=points_fail) points_estimate = self.call_method(method=method) error = np.linalg.norm(self.pts.points - points_estimate) self.assertTrue(error < self.eps, 'error: {} not smaller than {}'.format(error, self.eps)) def test_multiple_weights(self): print('TestSRLS:test_multiple_weights') for i in range(self.n_it): self.create_points() self.zero_weights(0.0) self.zero_weights(0.1) self.zero_weights(1.0) def test_srls_rescale(self): print('TestSRLS:test_srls_rescale') anchors = np.array([[0., 8.44226166, 0.29734295], [1., 7.47840264, 1.41311759], [2., 8.08093318, 2.21959719], [3., 4.55126532, 0.0456345], [4., 5.10971446, -0.01223217], [5., 2.95745961, -0.77572604], [6., 3.12145804, 0.80297295], [7., 2.29152331, -0.48021431], [8., 1.53137609, -0.03621697], [9., 0.762208, 0.70329037]]) sigma = 3. N, d = anchors.shape w = np.ones((N, 1)) x = np.ones(d) * 4. r2 = np.linalg.norm(anchors - x[None, :], axis=1)**2 r2.resize((len(r2), 1)) # Normal ranging x_srls = SRLS(anchors, w, r2) np.testing.assert_allclose(x, x_srls) # Rescaled ranging x_srls_resc, scale = SRLS(anchors, w, sigma * r2, rescale=True) self.assertLess(abs(1/scale - sigma), self.eps, 'not equal: {}, {}'.format(scale, sigma)) np.testing.assert_allclose(x, x_srls_resc) def test_srls_fixed(self): print('TestSRLS:test_srls_fixed') self.create_points(N=10, d=3) zreal = self.pts.points[0, 2] xhat = reconstruct_srls(self.pts.edm, self.pts.points, W=np.ones(self.pts.edm.shape), rescale=False, z=zreal) if xhat is not None: np.testing.assert_allclose(xhat[0, 2], zreal) np.testing.assert_allclose(xhat, self.pts.points) def test_srls_fail(self): anchors = np.array([[11.881, 3.722, 1.5 ], [11.881, 14.85, 1.5 ], [11.881, 7.683, 1.5 ]]) w = np.ones((3, 1)) distances = [153.32125426, 503.96654466, 234.80741129] z = 1.37 self.assertRaises(GeometryError, SRLS, anchors, w, distances, False, z) def zero_weights(self, noise=0.1): index = np.arange(self.n) other = np.delete(range(self.pts.N), index) edm_noisy = create_noisy_edm(self.pts.edm, noise) # missing anchors N_missing = 2 indices = np.random.choice(other, size=N_missing, replace=False) reduced_points = np.delete(self.pts.points, indices, axis=0) points_missing = create_from_points(reduced_points, PointSet) edm_anchors = np.delete(edm_noisy, indices, axis=0) edm_anchors = np.delete(edm_anchors, indices, axis=1) missing_anchors = reconstruct_srls( edm_anchors, points_missing.points, W=None, print_out=False) # missing distances weights = np.ones(edm_noisy.shape) weights[indices, index] = 0.0 weights[index, indices] = 0.0 missing_distances = reconstruct_srls( edm_noisy, self.pts.points, W=weights) left_distances = np.delete(range(self.pts.N), indices) self.assertTrue(np.linalg.norm( missing_distances[left_distances, :] - missing_anchors) < self.eps, 'anchors moved.') self.assertTrue(np.linalg.norm( missing_distances[index, :] - missing_anchors[index, :]) < self.eps, 'point moved.') if noise == 0.0: error = np.linalg.norm(missing_anchors - points_missing.points) u, s, v = np.linalg.svd(self.pts.points[other, :]) try: self.assertTrue(error < self.eps, 'error {}'.format(error)) except: print('failed with anchors (this can be due to unlucky geometry):', points_missing.points) raise
class TestSRLS(BaseCommon.TestAlgorithms): def setUp(self): pass def create_points(self, N=10, d=2): pass def call_method(self, method=''): pass def test_fail(self): pass def test_multiple_weights(self): pass def test_srls_rescale(self): pass def test_srls_fixed(self): pass def test_srls_fail(self): pass def zero_weights(self, noise=0.1): pass
10
0
16
1
14
1
2
0.05
1
4
3
0
9
5
9
106
155
17
131
48
121
7
92
48
82
4
5
2
16
144,406
LCAV/pylocus
LCAV_pylocus/test/test_sdr.py
test.test_sdr.TestSDP
class TestSDP(BaseCommon.TestAlgorithms): def setUp(self): print('TestSDP:setUp') BaseCommon.TestAlgorithms.setUp(self) self.eps = 1e-8 self.success_rate = 50 self.n_it = 1 self.N_zero = [6] self.N_relaxed = [6] def create_points(self, N=10, d=3): print('TestSDP:create_points') self.pts = PointSet(N, d) self.pts.set_points('normal') def call_method(self, method=''): print('TestSDP:call_method') Xhat, edm = reconstruct_sdp(self.pts.edm, all_points=self.pts.points, solver='CVXOPT', method='maximize') return Xhat def test_parameters(self): print('TestSDP:test_parameters') self.create_points() epsilons = [1e-3, 1e-5, 1e-7] options_list = [{}, {'solver': 'CVXOPT', 'abstol': 1e-5, 'reltol': 1e-6, 'feastol': 1e-7}] for options, eps in zip(options_list, epsilons): print('testing options', options, eps) self.eps = eps points_estimate, __ = reconstruct_sdp( self.pts.edm, all_points=self.pts.points, method='maximize', **options) error = np.linalg.norm(self.pts.points - points_estimate) self.assertTrue(error < self.eps, 'with options {} \nerror: {} not smaller than {}'.format( options, error, self.eps))
class TestSDP(BaseCommon.TestAlgorithms): def setUp(self): pass def create_points(self, N=10, d=3): pass def call_method(self, method=''): pass def test_parameters(self): pass
5
0
9
0
9
0
1
0
1
3
2
0
4
6
4
101
38
3
35
17
30
0
28
17
23
2
5
1
5
144,407
LEMS/pylems
lems/model/simulation.py
lems.model.simulation.Run
class Run(LEMSBase): """ Stores the description of an object to be run according to an independent variable (usually time). """ def __init__(self, component, variable, increment, total): """ Constructor. See instance variable documentation for information on parameters. """ self.component = component """ Name of the target component to be run according to the specification given for an independent state variable. :type: str """ self.variable = variable """ The name of an independent state variable according to which the target component will be run. :type: str """ self.increment = increment """ Increment of the state variable on each step. :type: str """ self.total = total """ Final value of the state variable. :type: str """ def toxml(self): """ Exports this object into a LEMS XML object """ return ( '<Run component="{0}" variable="{1}" increment="{2}" total="{3}"/>'.format( self.component, self.variable, self.increment, self.total ) )
class Run(LEMSBase): ''' Stores the description of an object to be run according to an independent variable (usually time). ''' def __init__(self, component, variable, increment, total): ''' Constructor. See instance variable documentation for information on parameters. ''' pass def toxml(self): ''' Exports this object into a LEMS XML object ''' pass
3
3
19
5
6
9
1
1.75
1
0
0
0
2
4
2
4
45
12
12
7
9
21
8
7
5
1
2
0
2
144,408
LEMS/pylems
lems/model/component.py
lems.model.component.Fixed
class Fixed(Parameter): """ Stores a fixed parameter specification. """ def __init__(self, parameter, value, description=""): """ Constructor. See instance variable documentation for more details on parameters. """ Parameter.__init__(self, parameter, "__dimension_inherited__", description) self.fixed = True self.fixed_value = value def toxml(self): """ Exports this object into a LEMS XML object """ return ( '<Fixed parameter="{0}"'.format(self.name) + ' value="{0}"'.format(self.fixed_value) + "/>" )
class Fixed(Parameter): ''' Stores a fixed parameter specification. ''' def __init__(self, parameter, value, description=""): ''' Constructor. See instance variable documentation for more details on parameters. ''' pass def toxml(self): ''' Exports this object into a LEMS XML object ''' pass
3
3
11
2
5
4
1
0.91
1
0
0
0
2
2
2
8
27
6
11
5
8
10
7
5
4
1
3
0
2
144,409
LEMS/pylems
lems/model/component.py
lems.model.component.Requirement
class Requirement(LEMSBase): """ Stores a requirement specification. """ def __init__(self, name, dimension, description=""): """ Constructor. See instance variable documentation for more details on parameters. """ self.name = name """ Name of the requirement. :type: str """ self.dimension = dimension """ Physical dimension of the requirement. :type: str """ self.description = description """ Description of this requirement. :type: str """ def toxml(self): """ Exports this object into a LEMS XML object """ return ( '<Requirement name="{0}" dimension="{1}"'.format(self.name, self.dimension) + ( ' description = "{0}"'.format(self.description) if self.description else "" ) + "/>" )
class Requirement(LEMSBase): ''' Stores a requirement specification. ''' def __init__(self, name, dimension, description=""): ''' Constructor. See instance variable documentation for more details on parameters. ''' pass def toxml(self): ''' Exports this object into a LEMS XML object ''' pass
3
3
18
4
7
7
2
1.07
1
0
0
0
2
3
2
4
41
10
15
6
12
16
7
6
4
2
2
0
3
144,410
LEMS/pylems
lems/model/component.py
lems.model.component.Text
class Text(LEMSBase): """ Stores a text entry specification. """ def __init__(self, name, description=""): """ Constructor. See instance variable documentation for more details on parameters. """ self.name = name """ Name of the text entry. :type: str """ self.description = description """ Description of the text entry. :type: str """ self.value = None """ Value of the text entry. :type: str """ def toxml(self): """ Exports this object into a LEMS XML object """ return ( '<Text name="{0}"'.format(self.name) + ( ' description = "{0}"'.format(self.description) if self.description else "" ) + "/>" ) def __str__(self): return ( "Text, name: {0}".format(self.name) + ( ', description = "{0}"'.format(self.description) if self.description else "" ) + (', value = "{0}"'.format(self.value) if self.value else "") ) def __repr__(self): return self.__str__()
class Text(LEMSBase): ''' Stores a text entry specification. ''' def __init__(self, name, description=""): ''' Constructor. See instance variable documentation for more details on parameters. ''' pass def toxml(self): ''' Exports this object into a LEMS XML object ''' pass def __str__(self): pass def __repr__(self): pass
5
3
12
2
7
3
2
0.59
1
0
0
0
4
3
4
6
55
12
27
8
22
16
11
8
6
3
2
0
7
144,411
LEMS/pylems
lems/model/dynamics.py
lems.model.dynamics.Behavioral
class Behavioral(LEMSBase): """ Store dynamic behavioral attributes. """ def __init__(self): """ Constructor. See instance variable documentation for more details on parameters. """ self.parent_behavioral = None """ Parent behavioral object. :type: lems.model.dynamics.Behavioral """ self.state_variables = Map() """ Map of state variables in this behavior regime. :type: dict(str, lems.model.dynamics.StateVariable """ self.derived_variables = Map() """ Map of derived variables in this behavior regime. :type: dict(str, lems.model.dynamics.DerivedVariable """ self.conditional_derived_variables = Map() """ Map of conditional derived variables in this behavior regime. :type: dict(str, lems.model.dynamics.ConditionalDerivedVariable """ self.time_derivatives = Map() """ Map of time derivatives in this behavior regime. :type: dict(str, lems.model.dynamics.TimeDerivative) """ self.event_handlers = list() """ List of event handlers in this behavior regime. :type: list(lems.model.dynamics.EventHandler) """ self.kinetic_schemes = Map() """ Map of kinetic schemes in this behavior regime. :type: dict(str, lems.model.dynamics.KineticScheme) """ def has_content(self): if ( len(self.state_variables) == 0 and len(self.derived_variables) == 0 and len(self.conditional_derived_variables) == 0 and len(self.time_derivatives) == 0 and len(self.event_handlers) == 0 and len(self.kinetic_schemes) == 0 ): return False else: return True def clear(self): """ Clear behavioral entities. """ self.time_derivatives = Map() def add_state_variable(self, sv): """ Adds a state variable to this behavior regime. :param sv: State variable. :type sv: lems.model.dynamics.StateVariable """ self.state_variables[sv.name] = sv def add_derived_variable(self, dv): """ Adds a derived variable to this behavior regime. :param dv: Derived variable. :type dv: lems.model.dynamics.DerivedVariable """ self.derived_variables[dv.name] = dv def add_conditional_derived_variable(self, cdv): """ Adds a conditional derived variable to this behavior regime. :param cdv: Conditional Derived variable. :type cdv: lems.model.dynamics.ConditionalDerivedVariable """ self.conditional_derived_variables[cdv.name] = cdv def add_time_derivative(self, td): """ Adds a time derivative to this behavior regime. :param td: Time derivative. :type td: lems.model.dynamics.TimeDerivative """ self.time_derivatives[td.variable] = td def add_event_handler(self, eh): """ Adds an event handler to this behavior regime. :param eh: Event handler. :type eh: lems.model.dynamics.EventHandler """ self.event_handlers.append(eh) def add_kinetic_scheme(self, ks): """ Adds a kinetic scheme to this behavior regime. :param ks: Kinetic scheme. :type ks: lems.model.dynamics.KineticScheme """ self.kinetic_schemes[ks.name] = ks def add(self, child): """ Adds a typed child object to the behavioral object. :param child: Child object to be added. """ if isinstance(child, StateVariable): self.add_state_variable(child) elif isinstance(child, DerivedVariable): self.add_derived_variable(child) elif isinstance(child, ConditionalDerivedVariable): self.add_conditional_derived_variable(child) elif isinstance(child, TimeDerivative): self.add_time_derivative(child) elif isinstance(child, EventHandler): self.add_event_handler(child) elif isinstance(child, KineticScheme): self.add_kinetic_scheme(child) else: raise ModelError("Unsupported child element") def toxml(self): """ Exports this object into a LEMS XML object """ chxmlstr = "" for state_variable in self.state_variables: chxmlstr += state_variable.toxml() for derived_variable in self.derived_variables: chxmlstr += derived_variable.toxml() for conditional_derived_variable in self.conditional_derived_variables: chxmlstr += conditional_derived_variable.toxml() for time_derivative in self.time_derivatives: chxmlstr += time_derivative.toxml() for event_handler in self.event_handlers: chxmlstr += event_handler.toxml() for kinetic_scheme in self.kinetic_schemes: chxmlstr += kinetic_scheme.toxml() if isinstance(self, Dynamics): for regime in self.regimes: chxmlstr += regime.toxml() if isinstance(self, Dynamics): xmlprefix = "Dynamics" xmlsuffix = "Dynamics" xmlempty = "" else: xmlprefix = 'Regime name="{0}"'.format(self.name) + ( ' initial="true"' if self.initial else "" ) xmlsuffix = "Regime" xmlempty = "<{0}/>", format(xmlprefix) if chxmlstr: xmlstr = "<{0}>".format(xmlprefix) + chxmlstr + "</{0}>".format(xmlsuffix) else: xmlstr = xmlempty return xmlstr
class Behavioral(LEMSBase): ''' Store dynamic behavioral attributes. ''' def __init__(self): ''' Constructor. See instance variable documentation for more details on parameters. ''' pass def has_content(self): pass def clear(self): ''' Clear behavioral entities. ''' pass def add_state_variable(self, sv): ''' Adds a state variable to this behavior regime. :param sv: State variable. :type sv: lems.model.dynamics.StateVariable ''' pass def add_derived_variable(self, dv): ''' Adds a derived variable to this behavior regime. :param dv: Derived variable. :type dv: lems.model.dynamics.DerivedVariable ''' pass def add_conditional_derived_variable(self, cdv): ''' Adds a conditional derived variable to this behavior regime. :param cdv: Conditional Derived variable. :type cdv: lems.model.dynamics.ConditionalDerivedVariable ''' pass def add_time_derivative(self, td): ''' Adds a time derivative to this behavior regime. :param td: Time derivative. :type td: lems.model.dynamics.TimeDerivative ''' pass def add_event_handler(self, eh): ''' Adds an event handler to this behavior regime. :param eh: Event handler. :type eh: lems.model.dynamics.EventHandler ''' pass def add_kinetic_scheme(self, ks): ''' Adds a kinetic scheme to this behavior regime. :param ks: Kinetic scheme. :type ks: lems.model.dynamics.KineticScheme ''' pass def add_state_variable(self, sv): ''' Adds a typed child object to the behavioral object. :param child: Child object to be added. ''' pass def toxml(self): ''' Exports this object into a LEMS XML object ''' pass
12
11
16
4
7
5
3
0.74
1
10
9
2
11
7
11
13
195
52
82
31
70
61
64
31
52
12
2
2
29
144,412
LEMS/pylems
lems/model/dynamics.py
lems.model.dynamics.Case
class Case(LEMSBase): """ Store the specification of a case for a Conditional Derived Variable. """ def __init__(self, condition, value): """ Constructor. """ self.condition = condition """ Condition for this case. :type: str """ self.value = value """ Value if the condition is true. :type: str """ self.condition_expression_tree = None """ Parse tree for the case condition expression. :type: lems.parser.expr.ExprNode """ self.value_expression_tree = None """ Parse tree for the case condition expression. :type: lems.parser.expr.ExprNode """ try: self.value_expression_tree = ExprParser(self.value).parse() if not self.condition: self.condition_expression_tree = None else: self.condition_expression_tree = ExprParser(self.condition).parse() except: raise ParseError( "Parse error when parsing case with condition " "'{0}' and value {1}", self.condition, self.value, ) def toxml(self): """ Exports this object into a LEMS XML object """ return ( '<Case condition="{0}" value="{1}"'.format(self.condition, self.value) + "/>" )
class Case(LEMSBase): ''' Store the specification of a case for a Conditional Derived Variable. ''' def __init__(self, condition, value): ''' Constructor. ''' pass def toxml(self): ''' Exports this object into a LEMS XML object ''' pass
3
3
24
6
11
7
2
0.74
1
2
2
0
2
4
2
4
53
13
23
7
20
17
15
7
12
3
2
2
4
144,413
LEMS/pylems
lems/model/dynamics.py
lems.model.dynamics.ConditionalDerivedVariable
class ConditionalDerivedVariable(LEMSBase): """ Store the specification of a conditional derived variable. """ def __init__(self, name, dimension, exposure=None): """ Constructor. See instance variable documentation for more info on parameters. """ self.name = name """ Name of the derived variable. :type: str """ self.dimension = dimension """ Dimension of the state variable. :type: str """ self.exposure = exposure """ Exposure name for the state variable. :type: str """ self.cases = list() """ List of cases related to this conditional derived variable. :type: list(lems.model.dynamics.Case) """ def add_case(self, case): """ Adds a case to this conditional derived variable. :param case: Case to be added. :type case: lems.model.dynamics.Case """ self.cases.append(case) def add(self, child): """ Adds a typed child object to the conditional derived variable. :param child: Child object to be added. """ if isinstance(child, Case): self.add_case(child) else: raise ModelError("Unsupported child element") def toxml(self): """ Exports this object into a LEMS XML object """ xmlstr = ( '<ConditionalDerivedVariable name="{0}"'.format(self.name) + (' dimension="{0}"'.format(self.dimension) if self.dimension else "") + (' exposure="{0}"'.format(self.exposure) if self.exposure else "") ) chxmlstr = "" for case in self.cases: chxmlstr += case.toxml() if chxmlstr: xmlstr += ">" + chxmlstr + "</ConditionalDerivedVariable>" else: xmlstr += "/>" return xmlstr
class ConditionalDerivedVariable(LEMSBase): ''' Store the specification of a conditional derived variable. ''' def __init__(self, name, dimension, exposure=None): ''' Constructor. See instance variable documentation for more info on parameters. ''' pass def add_case(self, case): ''' Adds a case to this conditional derived variable. :param case: Case to be added. :type case: lems.model.dynamics.Case ''' pass def add_case(self, case): ''' Adds a typed child object to the conditional derived variable. :param child: Child object to be added. ''' pass def toxml(self): ''' Exports this object into a LEMS XML object ''' pass
5
5
17
5
7
6
2
1
1
3
2
0
4
4
4
6
76
22
27
12
22
27
21
12
16
5
2
1
9
144,414
LEMS/pylems
lems/model/dynamics.py
lems.model.dynamics.DerivedVariable
class DerivedVariable(LEMSBase): """ Store the specification of a derived variable. """ def __init__(self, name, **params): """ Constructor. See instance variable documentation for more info on parameters. """ self.name = name """ Name of the derived variable. :type: str """ self.dimension = params["dimension"] if "dimension" in params else None """ Dimension of the derived variable or None if computed. :type: str """ self.exposure = params["exposure"] if "exposure" in params else None """ Exposure name for the derived variable. :type: str """ self.select = params["select"] if "select" in params else None """ Selection path/expression for the derived variable. :type: str """ self.value = params["value"] if "value" in params else None """ Value of the derived variable. :type: str """ self.reduce = params["reduce"] if "reduce" in params else None """ Reduce method for the derived variable. :type: str """ self.required = params["required"] if "required" in params else None """ Requried or not. :type: str """ self.expression_tree = None """ Parse tree for the time derivative expression. :type: lems.parser.expr.ExprNode """ if self.value != None: try: self.expression_tree = ExprParser(self.value).parse() except: raise ParseError( "Parse error when parsing value expression " "'{0}' for derived variable {1}", self.value, self.name, ) def toxml(self): """ Exports this object into a LEMS XML object """ return ( '<DerivedVariable name="{0}"'.format(self.name) + (' dimension="{0}"'.format(self.dimension) if self.dimension else "") + (' exposure="{0}"'.format(self.exposure) if self.exposure else "") + (' select="{0}"'.format(self.select) if self.select else "") + (' value="{0}"'.format(self.value) if self.value else "") + (' reduce="{0}"'.format(self.reduce) if self.reduce else "") + (' required="{0}"'.format(self.required) if self.required else "") + "/>" )
class DerivedVariable(LEMSBase): ''' Store the specification of a derived variable. ''' def __init__(self, name, **params): ''' Constructor. See instance variable documentation for more info on parameters. ''' pass def toxml(self): ''' Exports this object into a LEMS XML object ''' pass
3
3
36
10
15
12
8
0.84
1
2
2
0
2
8
2
4
78
21
31
11
28
26
17
11
14
9
2
2
16
144,415
LEMS/pylems
lems/model/dynamics.py
lems.model.dynamics.Dynamics
class Dynamics(Behavioral): """ Stores behavioral dynamics specification for a component type. """ def __init__(self): """ Constructor. """ Behavioral.__init__(self) self.regimes = Map() """ Map of behavior regimes. :type: Map(str, lems.model.dynamics.Regime) """ def add_regime(self, regime): """ Adds a behavior regime to this dynamics object. :param regime: Behavior regime to be added. :type regime: lems.model.dynamics.Regime""" self.regimes[regime.name] = regime def add(self, child): """ Adds a typed child object to the dynamics object. :param child: Child object to be added. """ if isinstance(child, Regime): self.add_regime(child) else: Behavioral.add(self, child) def has_content(self): if len(self.regimes) > 0: return True else: return Behavioral.has_content(self)
class Dynamics(Behavioral): ''' Stores behavioral dynamics specification for a component type. ''' def __init__(self): ''' Constructor. ''' pass def add_regime(self, regime): ''' Adds a behavior regime to this dynamics object. :param regime: Behavior regime to be added. :type regime: lems.model.dynamics.Regime''' pass def add_regime(self, regime): ''' Adds a typed child object to the dynamics object. :param child: Child object to be added. ''' pass def has_content(self): pass
5
4
9
2
4
3
2
1
1
2
2
0
4
1
4
17
43
11
16
6
11
16
14
6
9
2
3
1
6
144,416
LEMS/pylems
lems/model/component.py
lems.model.component.Property
class Property(LEMSBase): """ Store the specification of a property. """ def __init__(self, name, dimension=None, default_value=None, description=""): """ Constructor. """ self.name = name """ Name of the property. :type: str """ self.dimension = dimension """ Physical dimensions of the property. :type: str """ self.description = description """ Description of the property. :type: str """ self.default_value = default_value """ Default value of the property. :type: float """ def toxml(self): """ Exports this object into a LEMS XML object """ return ( '<Property name="{0}"'.format(self.name) + (' dimension="{0}"'.format(self.dimension) if self.dimension else "none") + ( ' defaultValue = "{0}"'.format(self.default_value) if self.default_value else "" ) + "/>" )
class Property(LEMSBase): ''' Store the specification of a property. ''' def __init__(self, name, dimension=None, default_value=None, description=""): ''' Constructor. ''' pass def toxml(self): ''' Exports this object into a LEMS XML object ''' pass
3
3
20
5
8
7
2
1
1
0
0
0
2
4
2
4
45
11
17
7
14
17
8
7
5
3
2
0
4
144,417
LEMS/pylems
lems/model/dynamics.py
lems.model.dynamics.EventHandler
class EventHandler(LEMSBase): """ Base class for event handlers. """ def __init__(self): """ Constructor. """ self.actions = list() """ List of actions to be performed in response to this event. :type: list(lems.model.dynamics.Action) """ def __str__(self): istr = "EventHandler..." return istr def add_action(self, action): """ Adds an action to this event handler. :param action: Action to be added. :type action: lems.model.dynamics.Action """ self.actions.append(action) def add(self, child): """ Adds a typed child object to the event handler. :param child: Child object to be added. """ if isinstance(child, Action): self.add_action(child) else: raise ModelError("Unsupported child element")
class EventHandler(LEMSBase): ''' Base class for event handlers. ''' def __init__(self): ''' Constructor. ''' pass def __str__(self): pass def add_action(self, action): ''' Adds an action to this event handler. :param action: Action to be added. :type action: lems.model.dynamics.Action ''' pass def add_action(self, action): ''' Adds a typed child object to the event handler. :param child: Child object to be added. ''' pass
5
4
8
2
3
4
1
1.31
1
3
2
4
4
1
4
6
40
10
13
7
8
17
12
7
7
2
2
1
5
144,418
LEMS/pylems
lems/base/base.py
lems.base.base.LEMSBase
class LEMSBase(object): """ Base object for PyLEMS. """ def copy(self): return copy.deepcopy(self) def toxml(self): return ""
class LEMSBase(object): ''' Base object for PyLEMS. ''' def copy(self): pass def toxml(self): pass
3
1
2
0
2
0
1
0.6
1
0
0
53
2
0
2
2
10
2
5
3
2
3
5
3
2
1
1
0
2
144,419
LEMS/pylems
lems/model/dynamics.py
lems.model.dynamics.OnCondition
class OnCondition(EventHandler): """ Specification for event handler called upon satisfying a given condition. """ def __init__(self, test): """ Constructor. See instance variable documentation for more details on parameters. """ EventHandler.__init__(self) self.test = test """ Condition to be tested for. :type: str """ try: self.expression_tree = ExprParser(test).parse() except: raise ParseError("Parse error when parsing OnCondition test '{0}'", test) def __str__(self): istr = "OnCondition..." return istr def toxml(self): """ Exports this object into a LEMS XML object """ xmlstr = '<OnCondition test="{0}"'.format(self.test) chxmlstr = "" for action in self.actions: chxmlstr += action.toxml() if chxmlstr: xmlstr += ">" + chxmlstr + "</OnCondition>" else: xmlstr += "/>" return xmlstr
class OnCondition(EventHandler): ''' Specification for event handler called upon satisfying a given condition. ''' def __init__(self, test): ''' Constructor. See instance variable documentation for more details on parameters. ''' pass def __str__(self): pass def toxml(self): ''' Exports this object into a LEMS XML object ''' pass
4
3
13
3
7
3
2
0.57
1
2
2
0
3
2
3
9
46
13
21
10
17
12
20
10
16
3
3
1
6
144,420
LEMS/pylems
lems/model/dynamics.py
lems.model.dynamics.OnEntry
class OnEntry(EventHandler): """ Specification for event handler called upon entry into a new behavior regime. """ def __init__(self): """ Constructor. """ EventHandler.__init__(self) def toxml(self): """ Exports this object into a LEMS XML object """ xmlstr = "<OnEntry" chxmlstr = "" for action in self.actions: chxmlstr += action.toxml() if chxmlstr: xmlstr += ">" + chxmlstr + "</OnEntry>" else: xmlstr += "/>" return xmlstr
class OnEntry(EventHandler): ''' Specification for event handler called upon entry into a new behavior regime. ''' def __init__(self): ''' Constructor. ''' pass def toxml(self): ''' Exports this object into a LEMS XML object ''' pass
3
3
12
3
6
3
2
0.69
1
0
0
0
2
0
2
8
30
8
13
6
10
9
12
6
9
3
3
1
4
144,421
LEMS/pylems
lems/model/dynamics.py
lems.model.dynamics.OnEvent
class OnEvent(EventHandler): """ Specification for event handler called upon receiving en event sent by another component. """ def __init__(self, port): """ Constructor. See instance variable documentation for more details on parameters. """ EventHandler.__init__(self) self.port = port """ Port on which the event comes in. :type: str """ def __str__(self): istr = "OnEvent, port: %s" % self.port return istr def toxml(self): """ Exports this object into a LEMS XML object """ xmlstr = '<OnEvent port="{0}"'.format(self.port) chxmlstr = "" for action in self.actions: chxmlstr += action.toxml() if chxmlstr: xmlstr += ">" + chxmlstr + "</OnEvent>" else: xmlstr += "/>" return xmlstr
class OnEvent(EventHandler): ''' Specification for event handler called upon receiving en event sent by another component. ''' def __init__(self, port): ''' Constructor. See instance variable documentation for more details on parameters. ''' pass def __str__(self): pass def toxml(self): ''' Exports this object into a LEMS XML object ''' pass
4
3
11
3
5
3
2
0.71
1
0
0
0
3
1
3
9
41
12
17
9
13
12
16
9
12
3
3
1
5
144,422
LEMS/pylems
lems/model/dynamics.py
lems.model.dynamics.OnStart
class OnStart(EventHandler): """ Specification for event handler called upon initialization of the component. """ def __init__(self): """ Constructor. """ EventHandler.__init__(self) def __str__(self): istr = "OnStart: [" for action in self.actions: istr += str(action) istr += "]" return str(istr) def toxml(self): """ Exports this object into a LEMS XML object """ xmlstr = "<OnStart" chxmlstr = "" for action in self.actions: chxmlstr += action.toxml() if chxmlstr: xmlstr += ">" + chxmlstr + "</OnStart>" else: xmlstr += "/>" return xmlstr
class OnStart(EventHandler): ''' Specification for event handler called upon initialization of the component. ''' def __init__(self): ''' Constructor. ''' pass def __str__(self): pass def toxml(self): ''' Exports this object into a LEMS XML object ''' pass
4
3
10
2
6
2
2
0.47
1
1
0
0
3
0
3
9
37
9
19
9
15
9
18
9
14
3
3
1
6
144,423
LEMS/pylems
lems/model/dynamics.py
lems.model.dynamics.Regime
class Regime(Behavioral): """ Stores a single behavioral regime for a component type. """ def __init__(self, name, parent_behavioral, initial=False): """ Constructor. See instance variable documentation for more details on parameters. """ Behavioral.__init__(self) self.name = name """ Name of this behavior regime. :type: str """ self.parent_behavioral = parent_behavioral """ Parent behavioral object. :type: lems.model.dynamics.Behavioral """ self.initial = initial """ Initial behavior regime. :type: bool """
class Regime(Behavioral): ''' Stores a single behavioral regime for a component type. ''' def __init__(self, name, parent_behavioral, initial=False): ''' Constructor. See instance variable documentation for more details on parameters. ''' pass
2
2
23
8
5
10
1
2.17
1
0
0
0
1
3
1
14
28
9
6
5
4
13
6
5
4
1
3
0
1
144,424
LEMS/pylems
lems/model/dynamics.py
lems.model.dynamics.StateAssignment
class StateAssignment(Action): """ State assignment specification. """ def __init__(self, variable, value): """ Constructor. See instance variable documentation for more info on parameters. """ Action.__init__(self) self.variable = variable """ Name of the variable for which the time derivative is being specified. :type: str """ self.value = value """ Derivative expression. :type: str """ self.expression_tree = None """ Parse tree for the time derivative expression. :type: lems.parser.expr.ExprNode """ try: self.expression_tree = ExprParser(value).parse() except: raise ParseError( "Parse error when parsing state assignment " "value expression " "'{0}' for state variable {1}", self.value, self.variable, ) def toxml(self): """ Exports this object into a LEMS XML object """ return '<StateAssignment variable="{0}" value="{1}"/>'.format( self.variable, self.value )
class StateAssignment(Action): ''' State assignment specification. ''' def __init__(self, variable, value): ''' Constructor. See instance variable documentation for more info on parameters. ''' pass def toxml(self): ''' Exports this object into a LEMS XML object ''' pass
3
3
21
5
10
7
2
0.8
1
2
2
0
2
3
2
4
48
12
20
6
17
16
12
6
9
2
3
1
3
144,425
LEMS/pylems
lems/model/dynamics.py
lems.model.dynamics.EventOut
class EventOut(Action): """ Event transmission specification. """ def __init__(self, port): """ Constructor. See instance variable documentation for more details on parameters. """ Action.__init__(self) self.port = port """ Port on which the event comes in. :type: str """ def toxml(self): """ Exports this object into a LEMS XML object """ return '<EventOut port="{0}"/>'.format(self.port)
class EventOut(Action): ''' Event transmission specification. ''' def __init__(self, port): ''' Constructor. See instance variable documentation for more details on parameters. ''' pass def toxml(self): ''' Exports this object into a LEMS XML object ''' pass
3
3
10
3
3
5
1
2
1
0
0
0
2
1
2
4
25
7
6
4
3
12
6
4
3
1
3
0
2
144,426
LEMS/pylems
lems/model/component.py
lems.model.component.Path
class Path(LEMSBase): """ Stores a path entry specification. """ def __init__(self, name, description=""): """ Constructor. See instance variable documentation for more details on parameters. """ self.name = name """ Name of the path entry. :type: str """ self.description = description """ Description of the path entry. :type: str """ self.value = None """ Value of the path entry. :type: str """ def toxml(self): """ Exports this object into a LEMS XML object """ return ( '<Path name="{0}"'.format(self.name) + ( ' description = "{0}"'.format(self.description) if self.description else "" ) + "/>" )
class Path(LEMSBase): ''' Stores a path entry specification. ''' def __init__(self, name, description=""): ''' Constructor. See instance variable documentation for more details on parameters. ''' pass def toxml(self): ''' Exports this object into a LEMS XML object ''' pass
3
3
18
4
7
7
2
1.07
1
0
0
0
2
3
2
4
41
10
15
6
12
16
7
6
4
2
2
0
3
144,427
LEMS/pylems
lems/model/component.py
lems.model.component.Parameter
class Parameter(LEMSBase): """ Stores a parameter declaration. """ def __init__(self, name, dimension, description=""): """ Constructor. See instance variable documentation for more details on parameters. """ self.name = name """ Name of the parameter. :type: str """ self.dimension = dimension """ Physical dimension of the parameter. :type: str """ self.fixed = False """ Whether the parameter has been fixed or not. :type: bool """ self.fixed_value = None """ Value if fixed. :type: str """ self.value = None """ Value of the parameter. :type: str """ self.numeric_value = None """ Resolved numeric value. :type: float """ self.description = description """ Description of this parameter. :type: str """ def toxml(self): """ Exports this object into a LEMS XML object """ return ( '<{0} name="{1}" dimension="{2}"'.format( "Fixed" if self.fixed else "Parameter", self.name, self.dimension ) + ( ' description = "{0}"'.format(self.description) if self.description else "" ) + "/>" ) def __str__(self): return '{0}: name="{1}" dimension="{2}"'.format( "Fixed" if self.fixed else "Parameter", self.name, self.dimension ) + ( ' description = "{0}"'.format(self.description) if self.description else "" ) def __repr__(self): return self.__str__()
class Parameter(LEMSBase): ''' Stores a parameter declaration. ''' def __init__(self, name, dimension, description=""): ''' Constructor. See instance variable documentation for more details on parameters. ''' pass def toxml(self): ''' Exports this object into a LEMS XML object ''' pass def __str__(self): pass def __repr__(self): pass
5
3
16
4
7
5
2
0.83
1
0
0
1
4
7
4
6
73
20
29
12
24
24
15
12
10
3
2
0
8
144,428
LEMS/pylems
lems/model/component.py
lems.model.component.Link
class Link(LEMSBase): """ Stores a link specification. """ def __init__(self, name, type_, description=""): """ Constructor. See instance variable documentation for more details on parameters. """ self.name = name """ Name of the link entry. :type: str """ self.type = type_ """ Type of the link. :type: str """ self.description = description """ Description of the link. :type: str """ self.value = None """ Value of the link. :type: str """ def toxml(self): """ Exports this object into a LEMS XML object """ return ( '<Link name="{0}" type="{1}"'.format(self.name, self.type) + ( ' description = "{0}"'.format(self.description) if self.description else "" ) + "/>" )
class Link(LEMSBase): ''' Stores a link specification. ''' def __init__(self, name, type_, description=""): ''' Constructor. See instance variable documentation for more details on parameters. ''' pass def toxml(self): ''' Exports this object into a LEMS XML object ''' pass
3
3
20
5
8
8
2
1.13
1
0
0
0
2
4
2
4
46
12
16
7
13
18
8
7
5
2
2
0
3
144,429
LEMS/pylems
lems/base/errors.py
lems.base.errors.LEMSError
class LEMSError(Exception): """ Base exception class. """ def __init__(self, message, *params, **key_params): """ Constructor :param message: Error message. :type message: string :param params: Optional arguments for formatting. :type params: list :param key_params: Named arguments for formatting. :type key_params: dict """ self.message = None """ Error message :type: string """ if params: if key_params: self.message = message.format(*params, **key_params) else: self.message = message.format(*params) else: if key_params: self.message = message(**key_params) else: self.message = message def __str__(self): """ Returns the error message string. :return: The error message :rtype: string """ return self.message
class LEMSError(Exception): ''' Base exception class. ''' def __init__(self, message, *params, **key_params): ''' Constructor :param message: Error message. :type message: string :param params: Optional arguments for formatting. :type params: list :param key_params: Named arguments for formatting. :type key_params: dict ''' pass def __str__(self): ''' Returns the error message string. :return: The error message :rtype: string ''' pass
3
3
19
4
7
8
3
1.27
1
0
0
5
2
1
2
12
44
10
15
4
12
19
12
4
9
4
3
2
5
144,430
LEMS/pylems
lems/base/map.py
lems.base.map.Map
class Map(dict, LEMSBase): """ Map class. Same as dict, but iterates over values. """ def __init__(self, *params, **key_params): """ Constructor. """ dict.__init__(self, *params, **key_params) def __iter__(self): """ Returns an iterator. """ return iter(self.values())
class Map(dict, LEMSBase): ''' Map class. Same as dict, but iterates over values. ''' def __init__(self, *params, **key_params): ''' Constructor. ''' pass def __iter__(self): ''' Returns an iterator. ''' pass
3
3
6
1
2
3
1
2
2
0
0
0
2
0
2
31
20
5
5
3
2
10
5
3
2
1
2
0
2
144,431
LEMS/pylems
lems/base/stack.py
lems.base.stack.Stack
class Stack(LEMSBase): """ Basic stack implementation. """ def __init__(self): """ Constructor. """ self.stack = [] """ List used to store the stack contents. :type: list """ def push(self, val): """ Pushed a value onto the stack. :param val: Value to be pushed. :type val: * """ self.stack = [val] + self.stack def pop(self): """ Pops a value off the top of the stack. :return: Value popped off the stack. :rtype: * :raises StackError: Raised when there is a stack underflow. """ if self.stack: val = self.stack[0] self.stack = self.stack[1:] return val else: raise StackError("Stack empty") def top(self): """ Returns the value off the top of the stack without popping. :return: Value on the top of the stack. :rtype: * :raises StackError: Raised when there is a stack underflow. """ if self.stack: return self.stack[0] else: raise StackError("Stack empty") def is_empty(self): """ Checks if the stack is empty. :return: True if the stack is empty, otherwise False. :rtype: Boolean """ return self.stack == [] def __str__(self): """ Returns a string representation of the stack. @note: This assumes that the stack contents are capable of generating string representations. """ if len(self.stack) == 0: s = "[]" else: s = "[" + str(self.stack[0]) for i in range(1, len(self.stack)): s += ", " + str(self.stack[i]) s += "]" return s def __repr__(self): return self.__str__()
class Stack(LEMSBase): ''' Basic stack implementation. ''' def __init__(self): ''' Constructor. ''' pass def push(self, val): ''' Pushed a value onto the stack. :param val: Value to be pushed. :type val: * ''' pass def pop(self): ''' Pops a value off the top of the stack. :return: Value popped off the stack. :rtype: * :raises StackError: Raised when there is a stack underflow. ''' pass def top(self): ''' Returns the value off the top of the stack without popping. :return: Value on the top of the stack. :rtype: * :raises StackError: Raised when there is a stack underflow. ''' pass def is_empty(self): ''' Checks if the stack is empty. :return: True if the stack is empty, otherwise False. :rtype: Boolean ''' pass def __str__(self): ''' Returns a string representation of the stack. @note: This assumes that the stack contents are capable of generating string representations. ''' pass def __repr__(self): pass
8
7
11
2
4
5
2
1.17
1
3
1
0
7
1
7
9
86
21
30
12
22
35
27
12
19
3
2
2
11
144,432
LEMS/pylems
lems/model/component.py
lems.model.component.Attachments
class Attachments(LEMSBase): """ Stores an attachment type specification. """ def __init__(self, name, type_, description=""): """ Constructor. See instance variable documentation for more details on parameters. """ self.name = name """ Name of the attachment collection. :type: str """ self.type = type_ """ Type of attachment. :type: str """ self.description = description """ Description about the attachment. :type: str """ def toxml(self): """ Exports this object into a LEMS XML object """ return ( '<Attachments name="{0}" type="{1}"'.format(self.name, self.type) + ( ' description = "{0}"'.format(self.description) if self.description else "" ) + "/>" )
class Attachments(LEMSBase): ''' Stores an attachment type specification. ''' def __init__(self, name, type_, description=""): ''' Constructor. See instance variable documentation for more details on parameters. ''' pass def toxml(self): ''' Exports this object into a LEMS XML object ''' pass
3
3
18
4
7
7
2
1.07
1
0
0
0
2
3
2
4
41
10
15
6
12
16
7
6
4
2
2
0
3
144,433
LEMS/pylems
lems/model/component.py
lems.model.component.Children
class Children(LEMSBase): """ Stores children specification. """ def __init__(self, name, type_, description="", multiple=False): """ Constructor. See instance variable documentation for more details on parameters. """ self.name = name """ Name of the children. :type: str """ self.type = type_ """ Component type of the children. :type: str """ self.description = description """ Description of the children. :type: str """ self.multiple = multiple """ Single child / multiple children. :type: bool """ def toxml(self): """ Exports this object into a LEMS XML object """ return '<{3} name="{0}" type="{1}" description={2}/>'.format( self.name, self.type, quoteattr(self.description) if self.description else '""', "Children" if self.multiple else "Child", )
class Children(LEMSBase): ''' Stores children specification. ''' def __init__(self, name, type_, description="", multiple=False): ''' Constructor. See instance variable documentation for more details on parameters. ''' pass def toxml(self): ''' Exports this object into a LEMS XML object ''' pass
3
3
19
5
6
8
2
1.38
1
0
0
0
2
4
2
4
43
12
13
7
10
18
8
7
5
3
2
0
4
144,434
LEMS/pylems
lems/model/component.py
lems.model.component.Component
class Component(LEMSBase): """ Stores a component instantiation. """ def __init__(self, id_, type_, **params): """ Constructor. See instance variable documentation for more details on parameters. """ self.id = id_ """ ID of the component. :type: str """ self.type = type_ """ Type of the component. :type: str """ self.parameters = dict() """ Dictionary of parameter values. :type: str """ for key in params.keys(): self.parameters[key] = params[key] self.children = list() """ List of child components. :type: list(lems.model.component.Component) """ self.parent_id = None """ Optional id of parent :type: str """ def __str__(self): return "Component, id: {0}, type: {1},\n parameters: {2}\n parent: {3}\n".format( self.id, self.type, self.parameters, self.parent_id ) def __repr__(self): return self.__str__() def set_parameter(self, parameter, value): """ Set a parameter. :param parameter: Parameter to be set. :type parameter: str :param value: Value to be set to. :type value: str """ self.parameters[parameter] = value def add_child(self, child): """ Adds a child component. :param child: Child component to be added. :type child: lems.model.component.Component """ self.children.append(child) def add(self, child): """ Adds a typed child object to the component. :param child: Child object to be added. """ if isinstance(child, Component): self.add_child(child) else: raise ModelError("Unsupported child element") def set_parent_id(self, parent_id): """ Sets the id of the parent Component :param parent_id: id of the parent Component :type parent_id: str """ self.parent_id = parent_id def toxml(self): """ Exports this object into a LEMS XML object """ xmlstr = '<Component id="{0}" type="{1}"'.format(self.id, self.type) for k, v in self.parameters.items(): xmlstr += ' {0}="{1}"'.format(k, v) if self.children: xmlstr += ">" for child in self.children: xmlstr += child.toxml() xmlstr += "</Component>" else: xmlstr += "/>" return xmlstr
class Component(LEMSBase): ''' Stores a component instantiation. ''' def __init__(self, id_, type_, **params): ''' Constructor. See instance variable documentation for more details on parameters. ''' pass def __str__(self): pass def __repr__(self): pass def set_parameter(self, parameter, value): ''' Set a parameter. :param parameter: Parameter to be set. :type parameter: str :param value: Value to be set to. :type value: str ''' pass def add_child(self, child): ''' Adds a child component. :param child: Child component to be added. :type child: lems.model.component.Component ''' pass def add_child(self, child): ''' Adds a typed child object to the component. :param child: Child object to be added. ''' pass def set_parent_id(self, parent_id): ''' Sets the id of the parent Component :param parent_id: id of the parent Component :type parent_id: str ''' pass def toxml(self): ''' Exports this object into a LEMS XML object ''' pass
9
7
13
3
5
5
2
1.08
1
3
1
0
8
5
8
10
112
33
38
18
29
41
34
18
25
4
2
2
13
144,435
LEMS/pylems
lems/model/component.py
lems.model.component.ComponentReference
class ComponentReference(LEMSBase): """ Stores a component reference. """ def __init__(self, name, type_, local=None): """ Constructor. See instance variable documentation for more details on parameters. """ self.name = name """ Name of the component reference. :type: str """ self.type = type_ """ Type of the component reference. :type: str """ self.local = local """ ??? :type: str """ self.referenced_component = None """ Component being referenced. :type: FatComponent """ def toxml(self): """ Exports this object into a LEMS XML object """ return ( '<ComponentReference name="{0}" type="{1}"'.format(self.name, self.type) + (' local = "{0}"'.format(self.local) if self.local else "") + "/>" )
class ComponentReference(LEMSBase): ''' Stores a component reference. ''' def __init__(self, name, type_, local=None): ''' Constructor. See instance variable documentation for more details on parameters. ''' pass def toxml(self): ''' Exports this object into a LEMS XML object ''' pass
3
3
18
5
6
8
2
1.5
1
0
0
0
2
4
2
4
42
12
12
7
9
18
8
7
5
2
2
0
3
144,436
LEMS/pylems
lems/model/component.py
lems.model.component.ComponentRequirement
class ComponentRequirement(LEMSBase): """ Specifies a component that is required """ def __init__(self, name, description=""): """ Constructor. """ self.name = name """ Name of the Component required. :type: str """ self.description = description """ Description of this ComponentRequirement. :type: str """ def toxml(self): """ Exports this object into a LEMS XML object """ return ( '<ComponentRequirement name="{0}"'.format(self.name) + "" + ( ' description = "{0}"'.format(self.description) if self.description else "" ) + "/>" )
class ComponentRequirement(LEMSBase): ''' Specifies a component that is required ''' def __init__(self, name, description=""): ''' Constructor. ''' pass def toxml(self): ''' Exports this object into a LEMS XML object ''' pass
3
3
15
3
7
5
2
0.87
1
0
0
0
2
2
2
4
35
7
15
5
12
13
6
5
3
2
2
0
3
144,437
LEMS/pylems
lems/model/component.py
lems.model.component.ComponentType
class ComponentType(Fat): """ Stores a component type declaration. """ def __init__(self, name, description="", extends=None): """ Constructor. See instance variable documentation for more details on parameters. """ Fat.__init__(self) self.name = name """ Name of the component type. :type: str """ self.extends = extends """ Base component type. :type: str """ self.description = description """ Description of this component type. :type: str """ self.types.add(name) def __str__(self): return "ComponentType, name: {0}".format(self.name) def toxml(self): """ Exports this object into a LEMS XML object """ xmlstr = ( '<ComponentType name="{0}"'.format(self.name) + (' extends="{0}"'.format(self.extends) if self.extends else "") + ( " description={0}".format( quoteattr(self.description) if self.description else '""' ) ) ) chxmlstr = "" for property in self.properties: chxmlstr += property.toxml() for parameter in self.parameters: chxmlstr += parameter.toxml() for derived_parameter in self.derived_parameters: chxmlstr += derived_parameter.toxml() for index_parameter in self.index_parameters: chxmlstr += index_parameter.toxml() for constant in self.constants: chxmlstr += constant.toxml() childxml = "" childrenxml = "" for children in self.children: if children.multiple: childrenxml += children.toxml() else: childxml += children.toxml() chxmlstr += childxml chxmlstr += childrenxml for link in self.links: chxmlstr += link.toxml() for component_reference in self.component_references: chxmlstr += component_reference.toxml() for attachment in self.attachments: chxmlstr += attachment.toxml() for event_port in self.event_ports: chxmlstr += event_port.toxml() for exposure in self.exposures: chxmlstr += exposure.toxml() for requirement in self.requirements: chxmlstr += requirement.toxml() for component_requirement in self.component_requirements: chxmlstr += component_requirement.toxml() for instance_requirement in self.instance_requirements: chxmlstr += instance_requirement.toxml() for path in self.paths: chxmlstr += path.toxml() for text in self.texts: chxmlstr += text.toxml() chxmlstr += self.dynamics.toxml() chxmlstr += self.structure.toxml() chxmlstr += self.simulation.toxml() if chxmlstr: xmlstr += ">" + chxmlstr + "</ComponentType>" else: xmlstr += "/>" return xmlstr
class ComponentType(Fat): ''' Stores a component type declaration. ''' def __init__(self, name, description="", extends=None): ''' Constructor. See instance variable documentation for more details on parameters. ''' pass def __str__(self): pass def toxml(self): ''' Exports this object into a LEMS XML object ''' pass
4
3
37
11
22
4
8
0.24
1
0
0
0
3
3
3
23
118
35
67
27
63
16
57
27
53
21
3
2
23
144,438
LEMS/pylems
lems/model/component.py
lems.model.component.Constant
class Constant(LEMSBase): """ Stores a constant specification. """ def __init__(self, name, value, dimension=None, symbol=None, description=""): """ Constructor. See instance variable documentation for more details on parameters. """ self.name = name """ Name of the constant. :type: str """ self.symbol = symbol """ Symbol of the constant. :type: str """ self.value = value """ Value of the constant. :type: str """ self.dimension = dimension """ Physical dimensions of the constant. :type: str """ self.description = description """ Description of the constant. :type: str """ self.numeric_value = None """ Numeric value of the constant. :type: float """ def toxml(self): """ Exports this object into a LEMS XML object """ return ( "<Constant" + (' name = "{0}"'.format(self.name) if self.name else "") + (' symbol = "{0}"'.format(self.symbol) if self.symbol else "") + (' value = "{0}"'.format(self.value) if self.value else "") + (' dimension = "{0}"'.format(self.dimension) if self.dimension else "") + ( ' description = "{0}"'.format(self.description) if self.description else "" ) + "/>" )
class Constant(LEMSBase): ''' Stores a constant specification. ''' def __init__(self, name, value, dimension=None, symbol=None, description=""): ''' Constructor. See instance variable documentation for more details on parameters. ''' pass def toxml(self): ''' Exports this object into a LEMS XML object ''' pass
3
3
27
7
11
10
4
1
1
0
0
0
2
6
2
4
60
16
22
9
19
22
10
9
7
6
2
0
7
144,439
LEMS/pylems
lems/model/component.py
lems.model.component.DerivedParameter
class DerivedParameter(LEMSBase): """ Store the specification of a derived parameter. """ def __init__(self, name, value, dimension=None, description=""): """ Constructor. See instance variable documentation for more info on derived parameters. """ self.name = name """ Name of the derived parameter. :type: str """ self.dimension = dimension """ Physical dimensions of the derived parameter. :type: str """ self.value = value """ Value of the derived parameter. :type: str """ self.description = description """ Description of the derived parameter. :type: str """ try: ep = ExprParser(self.value) self.expression_tree = ep.parse() except: raise ParseError( "Parse error when parsing value expression " "'{0}' for derived parameter {1}", self.value, self.name, ) def toxml(self): """ Exports this object into a LEMS XML object """ return ( '<DerivedParameter name="{0}"'.format(self.name) + (' dimension="{0}"'.format(self.dimension) if self.dimension else "") + ( " description={0}".format( quoteattr(self.description) if self.description else '""' ) ) + (' value="{0}"'.format(self.value) if self.value else "") + "/>" )
class DerivedParameter(LEMSBase): ''' Store the specification of a derived parameter. ''' def __init__(self, name, value, dimension=None, description=""): ''' Constructor. See instance variable documentation for more info on derived parameters. ''' pass def toxml(self): ''' Exports this object into a LEMS XML object ''' pass
3
3
27
6
14
8
3
0.64
1
2
2
0
2
5
2
4
59
13
28
9
25
18
13
9
10
4
2
1
6
144,440
LEMS/pylems
lems/model/component.py
lems.model.component.EventPort
class EventPort(LEMSBase): """ Stores an event port specification. """ def __init__(self, name, direction, description=""): """ Constructor. See instance variable documentation for more details on parameters. """ self.name = name """ Name of the event port. :type: str """ d = direction.lower() if d != "in" and d != "out": raise ModelError( "Invalid direction '{0}' in event port '{1}'".format(direction, name) ) self.direction = direction """ Direction - IN/OUT . :type: str """ self.description = description """ Description of the event port. :type: str """ def toxml(self): """ Exports this object into a LEMS XML object """ return ( '<EventPort name="{0}" direction="{1}"'.format(self.name, self.direction) + ( ' description = "{0}"'.format(self.description) if self.description else "" ) + "/>" )
class EventPort(LEMSBase): ''' Stores an event port specification. ''' def __init__(self, name, direction, description=""): ''' Constructor. See instance variable documentation for more details on parameters. ''' pass def toxml(self): ''' Exports this object into a LEMS XML object ''' pass
3
3
21
5
10
7
2
0.8
1
1
1
0
2
3
2
4
47
11
20
7
17
16
10
7
7
2
2
1
4
144,441
LEMS/pylems
lems/model/component.py
lems.model.component.Exposure
class Exposure(LEMSBase): """ Stores a exposure specification. """ def __init__(self, name, dimension, description=""): """ Constructor. See instance variable documentation for more details on parameters. """ self.name = name """ Name of the exposure. :type: str """ self.dimension = dimension """ Physical dimension of the exposure. :type: str """ self.description = description """ Description of this exposure. :type: str """ def toxml(self): """ Exports this object into a LEMS XML object """ return ( '<Exposure name="{0}" dimension="{1}"'.format(self.name, self.dimension) + ( ' description = "{0}"'.format(self.description) if self.description else "" ) + "/>" )
class Exposure(LEMSBase): ''' Stores a exposure specification. ''' def __init__(self, name, dimension, description=""): ''' Constructor. See instance variable documentation for more details on parameters. ''' pass def toxml(self): ''' Exports this object into a LEMS XML object ''' pass
3
3
18
4
7
7
2
1.07
1
0
0
0
2
3
2
4
41
10
15
6
12
16
7
6
4
2
2
0
3
144,442
LEMS/pylems
lems/model/component.py
lems.model.component.Fat
class Fat(LEMSBase): """ Stores common elements for a component type / fat component. """ def __init__(self): """ Constructor. See instance variable documentation for more details on parameters. """ self.parameters = Map() """ Map of parameters in this component type. :type: Map(str, lems.model.component.Parameter) """ self.properties = Map() """ Map of properties in this component type. :type: Map(str, lems.model.component.Property) """ self.derived_parameters = Map() """ Map of derived_parameters in this component type. :type: Map(str, lems.model.component.Parameter) """ self.index_parameters = Map() """ Map of index_parameters in this component type. :type: Map(str, lems.model.component.IndexParameter) """ self.constants = Map() """ Map of constants in this component type. :type: Map(str, lems.model.component.Constant) """ self.exposures = Map() """ Map of exposures in this component type. :type: Map(str, lems.model.component.Exposure) """ self.requirements = Map() """ Map of requirements. :type: Map(str, lems.model.component.Requirement) """ self.component_requirements = Map() """ Map of component requirements. :type: Map(str, lems.model.component.ComponentRequirement) """ self.instance_requirements = Map() """ Map of instance requirements. :type: Map(str, lems.model.component.InstanceRequirement) """ self.children = Map() """ Map of children. :type: Map(str, lems.model.component.Children) """ self.texts = Map() """ Map of text entries. :type: Map(str, lems.model.component.Text) """ self.links = Map() """ Map of links. :type: Map(str, lems.model.component.Link) """ self.paths = Map() """ Map of path entries. :type: Map(str, lems.model.component.Path) """ self.event_ports = Map() """ Map of event ports. :type: Map(str, lems.model.component.EventPort """ self.component_references = Map() """ Map of component references. :type: Map(str, lems.model.component.ComponentReference) """ self.attachments = Map() """ Map of attachment type specifications. :type: Map(str, lems.model.component.Attachments) """ self.dynamics = Dynamics() """ Behavioural dynamics object. :type: lems.model.dynamics.Dynamics """ self.structure = Structure() """ Structural properties object. :type: lems.model.structure.Structure """ self.simulation = Simulation() """ Simulation attributes. :type: lems.model.simulation.Simulation """ self.types = set() """ Set of compatible component types. :type: set(str) """ def add_parameter(self, parameter): """ Adds a paramter to this component type. :param parameter: Parameter to be added. :type parameter: lems.model.component.Parameter """ self.parameters[parameter.name] = parameter def add_property(self, property): """ Adds a property to this component type. :param property: Property to be added. :type property: lems.model.component.Property """ self.properties[property.name] = property def add_derived_parameter(self, derived_parameter): """ Adds a derived_parameter to this component type. :param derived_parameter: Derived Parameter to be added. :type derived_parameter: lems.model.component.DerivedParameter """ self.derived_parameters[derived_parameter.name] = derived_parameter def add_index_parameter(self, index_parameter): """ Adds an index_parameter to this component type. :param index_parameter: Index Parameter to be added. :type index_parameter: lems.model.component.IndexParameter """ self.index_parameters[index_parameter.name] = index_parameter def add_constant(self, constant): """ Adds a paramter to this component type. :param constant: Constant to be added. :type constant: lems.model.component.Constant """ self.constants[constant.name] = constant def add_exposure(self, exposure): """ Adds a exposure to this component type. :param exposure: Exposure to be added. :type exposure: lems.model.component.Exposure """ self.exposures[exposure.name] = exposure def add_requirement(self, requirement): """ Adds a requirement to this component type. :param requirement: Requirement to be added. :type requirement: lems.model.component.Requirement """ self.requirements[requirement.name] = requirement def add_component_requirement(self, component_requirement): """ Adds a component requirement to this component type. :param component_requirement: ComponentRequirement to be added. :type component_requirement: lems.model.component.ComponentRequirement """ self.component_requirements[component_requirement.name] = component_requirement def add_instance_requirement(self, instance_requirement): """ Adds an instance requirement to this component type. :param instance_requirement: InstanceRequirement to be added. :type instance_requirement: lems.model.component.InstanceRequirement """ self.instance_requirements[instance_requirement.name] = instance_requirement def add_children(self, children): """ Adds children to this component type. :param children: Children to be added. :type children: lems.model.component.Children """ self.children[children.name] = children def add_text(self, text): """ Adds a text to this component type. :param text: Text to be added. :type text: lems.model.component.Text """ self.texts[text.name] = text def add_link(self, link): """ Adds a link to this component type. :param link: Link to be added. :type link: lems.model.component.Link """ self.links[link.name] = link def add_path(self, path): """ Adds a path to this component type. :param path: Path to be added. :type path: lems.model.component.Path """ self.paths[path.name] = path def add_event_port(self, event_port): """ Adds a event port to this component type. :param event_port: Event port to be added. :type event_port: lems.model.component.EventPort """ self.event_ports[event_port.name] = event_port def add_component_reference(self, component_reference): """ Adds a component reference to this component type. :param component_reference: Component reference to be added. :type component_reference: lems.model.component.ComponentReference """ self.component_references[component_reference.name] = component_reference def add_attachments(self, attachments): """ Adds an attachments type specification to this component type. :param attachments: Attachments specification to be added. :type attachments: lems.model.component.Attachments """ self.attachments[attachments.name] = attachments def add(self, child): """ Adds a typed child object to the component type. :param child: Child object to be added. """ if isinstance(child, Parameter): self.add_parameter(child) elif isinstance(child, Property): self.add_property(child) elif isinstance(child, DerivedParameter): self.add_derived_parameter(child) elif isinstance(child, IndexParameter): self.add_index_parameter(child) elif isinstance(child, Constant): self.add_constant(child) elif isinstance(child, Exposure): self.add_exposure(child) elif isinstance(child, Requirement): self.add_requirement(child) elif isinstance(child, ComponentRequirement): self.add_component_requirement(child) elif isinstance(child, InstanceRequirement): self.add_instance_requirement(child) elif isinstance(child, Children): self.add_children(child) elif isinstance(child, Text): self.add_text(child) elif isinstance(child, Link): self.add_link(child) elif isinstance(child, Path): self.add_path(child) elif isinstance(child, EventPort): self.add_event_port(child) elif isinstance(child, ComponentReference): self.add_component_reference(child) elif isinstance(child, Attachments): self.add_attachments(child) else: raise ModelError("Unsupported child element")
class Fat(LEMSBase): ''' Stores common elements for a component type / fat component. ''' def __init__(self): ''' Constructor. See instance variable documentation for more details on parameters. ''' pass def add_parameter(self, parameter): ''' Adds a paramter to this component type. :param parameter: Parameter to be added. :type parameter: lems.model.component.Parameter ''' pass def add_property(self, property): ''' Adds a property to this component type. :param property: Property to be added. :type property: lems.model.component.Property ''' pass def add_derived_parameter(self, derived_parameter): ''' Adds a derived_parameter to this component type. :param derived_parameter: Derived Parameter to be added. :type derived_parameter: lems.model.component.DerivedParameter ''' pass def add_index_parameter(self, index_parameter): ''' Adds an index_parameter to this component type. :param index_parameter: Index Parameter to be added. :type index_parameter: lems.model.component.IndexParameter ''' pass def add_constant(self, constant): ''' Adds a paramter to this component type. :param constant: Constant to be added. :type constant: lems.model.component.Constant ''' pass def add_exposure(self, exposure): ''' Adds a exposure to this component type. :param exposure: Exposure to be added. :type exposure: lems.model.component.Exposure ''' pass def add_requirement(self, requirement): ''' Adds a requirement to this component type. :param requirement: Requirement to be added. :type requirement: lems.model.component.Requirement ''' pass def add_component_requirement(self, component_requirement): ''' Adds a component requirement to this component type. :param component_requirement: ComponentRequirement to be added. :type component_requirement: lems.model.component.ComponentRequirement ''' pass def add_instance_requirement(self, instance_requirement): ''' Adds an instance requirement to this component type. :param instance_requirement: InstanceRequirement to be added. :type instance_requirement: lems.model.component.InstanceRequirement ''' pass def add_children(self, children): ''' Adds children to this component type. :param children: Children to be added. :type children: lems.model.component.Children ''' pass def add_text(self, text): ''' Adds a text to this component type. :param text: Text to be added. :type text: lems.model.component.Text ''' pass def add_link(self, link): ''' Adds a link to this component type. :param link: Link to be added. :type link: lems.model.component.Link ''' pass def add_path(self, path): ''' Adds a path to this component type. :param path: Path to be added. :type path: lems.model.component.Path ''' pass def add_event_port(self, event_port): ''' Adds a event port to this component type. :param event_port: Event port to be added. :type event_port: lems.model.component.EventPort ''' pass def add_component_reference(self, component_reference): ''' Adds a component reference to this component type. :param component_reference: Component reference to be added. :type component_reference: lems.model.component.ComponentReference ''' pass def add_attachments(self, attachments): ''' Adds an attachments type specification to this component type. :param attachments: Attachments specification to be added. :type attachments: lems.model.component.Attachments ''' pass def add_parameter(self, parameter): ''' Adds a typed child object to the component type. :param child: Child object to be added. ''' pass
19
19
16
4
5
7
2
1.47
1
22
21
2
18
20
18
20
313
93
89
39
70
131
73
39
54
17
2
1
34
144,443
LEMS/pylems
lems/model/component.py
lems.model.component.FatComponent
class FatComponent(Fat): """ Stores a resolved component. """ def __init__(self, id_, type_): """ Constructor. See instance variable documentation for more details on parameters. """ Fat.__init__(self) self.id = id_ """ ID of the component. :type: str """ self.type = type_ """ Type of the component. :type: str """ self.child_components = list() """ List of child components. :type: lems.model.component.FatComponent """ self.parent_id = None """ Optional id of parent :type: str """ def __str__(self): return "FatComponent, id: {0}, type: {1}, parent:{2}".format( self.id, self.type, self.parent_id ) + ( ", num children: {0}".format(len(self.child_components)) if len(self.child_components) > 0 else "" ) def add_child_component(self, child_component): """ Adds a child component to this fat component. :param child_component: Child component to be added. :type child_component: lems.model.component.FatComponent """ self.child_components.append(child_component) def add(self, child): """ Adds a typed child object to the component type. :param child: Child object to be added. """ if isinstance(child, FatComponent): self.add_child_component(child) else: Fat.add(self, child) def set_parent_id(self, parent_id): """ Sets the id of the parent Component :param parent_id: id of the parent Component :type parent_id: str """ self.parent_id = parent_id
class FatComponent(Fat): ''' Stores a resolved component. ''' def __init__(self, id_, type_): ''' Constructor. See instance variable documentation for more details on parameters. ''' pass def __str__(self): pass def add_child_component(self, child_component): ''' Adds a child component to this fat component. :param child_component: Child component to be added. :type child_component: lems.model.component.FatComponent ''' pass def add_child_component(self, child_component): ''' Adds a typed child object to the component type. :param child: Child object to be added. ''' pass def set_parent_id(self, parent_id): ''' Sets the id of the parent Component :param parent_id: id of the parent Component :type parent_id: str ''' pass
6
5
13
3
5
5
1
1.21
1
1
0
0
5
4
5
25
74
21
24
10
18
29
17
10
11
2
3
1
7
144,444
LEMS/pylems
lems/model/component.py
lems.model.component.IndexParameter
class IndexParameter(LEMSBase): """ Stores a parameter which is an index (integer > 0). """ def __init__(self, name, description=""): """ Constructor. """ self.name = name """ Name of the parameter. :type: str """ self.description = description """ Description of this parameter. :type: str """ def toxml(self): """ Exports this object into a LEMS XML object """ return ( '<IndexParameter name="{0}"'.format(self.name) + "" + ( ' description = "{0}"'.format(self.description) if self.description else "" ) + "/>" )
class IndexParameter(LEMSBase): ''' Stores a parameter which is an index (integer > 0). ''' def __init__(self, name, description=""): ''' Constructor. ''' pass def toxml(self): ''' Exports this object into a LEMS XML object ''' pass
3
3
15
3
7
5
2
0.87
1
0
0
0
2
2
2
4
35
7
15
5
12
13
6
5
3
2
2
0
3
144,445
LEMS/pylems
lems/model/component.py
lems.model.component.InstanceRequirement
class InstanceRequirement(LEMSBase): """ Stores an instance requirement specification. """ def __init__(self, name, type, description=""): """ Constructor. """ self.name = name """ Name of the instance requirement. :type: str """ self.type = type """ Type of the instance required. :type: str """ self.description = description """ Description of this InstanceRequirement. :type: str """ def toxml(self): """ Exports this object into a LEMS XML object """ return ( '<InstanceRequirement name="{0}" type="{1}"'.format(self.name, self.type) + ( ' description = "{0}"'.format(self.description) if self.description else "" ) + "/>" )
class InstanceRequirement(LEMSBase): ''' Stores an instance requirement specification. ''' def __init__(self, name, type, description=""): ''' Constructor. ''' pass def toxml(self): ''' Exports this object into a LEMS XML object ''' pass
3
3
17
4
7
6
2
1
1
0
0
0
2
3
2
4
39
9
15
6
12
15
7
6
4
2
2
0
3
144,446
LEMS/pylems
lems/model/dynamics.py
lems.model.dynamics.StateVariable
class StateVariable(LEMSBase): """ Store the specification of a state variable. """ def __init__(self, name, dimension, exposure=None): """ Constructor. See instance variable documentation for more info on parameters. """ self.name = name """ Name of the state variable. :type: str """ self.dimension = dimension """ Dimension of the state variable. :type: str """ self.exposure = exposure """ Exposure name for the state variable. :type: str """ def __str__(self): return 'StateVariable name="{0}" dimension="{1}"'.format( self.name, self.dimension ) + (' exposure="{0}"'.format(self.exposure) if self.exposure else "") def toxml(self): """ Exports this object into a LEMS XML object """ return ( '<StateVariable name="{0}" dimension="{1}"'.format( self.name, self.dimension ) + (' exposure="{0}"'.format(self.exposure) if self.exposure else "") + "/>" )
class StateVariable(LEMSBase): ''' Store the specification of a state variable. ''' def __init__(self, name, dimension, exposure=None): ''' Constructor. See instance variable documentation for more info on parameters. ''' pass def __str__(self): pass def toxml(self): ''' Exports this object into a LEMS XML object ''' pass
4
3
12
3
5
4
2
0.94
1
0
0
0
3
3
3
5
44
11
17
7
13
16
9
7
5
2
2
0
5
144,447
LEMS/pylems
lems/model/dynamics.py
lems.model.dynamics.TimeDerivative
class TimeDerivative(LEMSBase): """ Store the specification of a time derivative specifcation. """ def __init__(self, variable, value): """ Constructor. See instance variable documentation for more info on parameters. """ self.variable = variable """ Name of the variable for which the time derivative is being specified. :type: str """ self.value = value """ Derivative expression. :type: str """ self.expression_tree = None """ Parse tree for the time derivative expression. :type: lems.parser.expr.ExprNode """ try: self.expression_tree = ExprParser(value).parse() except: raise ParseError( "Parse error when parsing value expression " "'{0}' for state variable {1}", self.value, self.variable, ) def toxml(self): """ Exports this object into a LEMS XML object """ return '<TimeDerivative variable="{0}" value="{1}"/>'.format( self.variable, self.value )
class TimeDerivative(LEMSBase): ''' Store the specification of a time derivative specifcation. ''' def __init__(self, variable, value): ''' Constructor. See instance variable documentation for more info on parameters. ''' pass def toxml(self): ''' Exports this object into a LEMS XML object ''' pass
3
3
20
5
9
7
2
0.89
1
2
2
0
2
3
2
4
45
11
18
6
15
16
11
6
8
2
2
1
3