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
145,048
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/models/website.py
helpscout.models.website.Website
class Website(BaseModel): value = properties.String( 'URI', required=True, )
class Website(BaseModel): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
14
6
1
5
2
4
0
2
2
1
0
2
0
0
145,049
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/models/workflow.py
helpscout.models.workflow.Workflow
class Workflow(BaseModel): mailbox_id = properties.Integer( 'The mailbox ID that this workflow is associated with.', required=True, ) type = properties.StringChoice( 'The type of workflow.', choices=['automatic', 'manual'], default='manual', required=True, ) status = properties.StringChoice( 'The status of the workflow.', choices=['active', 'inactive', 'invalid'], default='invalid', required=True, ) order = properties.Integer( 'The order of the workflow.', default=1, required=True, ) name = properties.String( 'Workflow name.', required=True, ) created_at = properties.DateTime( 'UTC time when this workflow was created.', ) modified_at = properties.DateTime( 'UTC time when this workflow was modified.', )
class Workflow(BaseModel): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
14
33
1
32
8
31
0
8
8
7
0
2
0
0
145,050
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/tests/__init__.py
helpscout.tests.BaseModel
class BaseModel(properties.HasProperties): """This is the model that all other models inherit from. It provides some convenience functions, and the standard ``id`` property. """ id = properties.Integer( 'Unique identifier', )
class BaseModel(properties.HasProperties): '''This is the model that all other models inherit from. It provides some convenience functions, and the standard ``id`` property. ''' pass
1
1
0
0
0
0
0
0.75
1
0
0
0
0
0
0
0
9
2
4
1
3
3
2
1
1
0
1
0
0
145,051
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/tests/api_common.py
helpscout.tests.api_common.ApiCommon
class ApiCommon(unittest.TestCase): # This should be set to the API endpoint object in children __endpoint__ = None def setUp(self): super(ApiCommon, self).setUp() self.api = HelpScout( '06501c1e20bcb8a489f428b3b6a08c6bffaef190', ) self.mock_record = mock.MagicMock() self.mock_class = mock.MagicMock() self.mock_session = mock.MagicMock() self.mock_record.id = 1234 def _get_user(self, strip_id=False): """Return a User object.""" user = User.deserialize({ 'first_name': u'Dave', 'last_name': u'Lasley', 'created_at': '2017-08-25T20:01:06Z', 'modified_at': '2017-12-13T19:47:35Z', 'emails': [], 'id': 218639, 'role': 'owner', 'full_name': u'Dave Lasley', 'timezone': u'America/New_York', 'type': 'user', 'email': u'support@example.com', 'photo_url': u'https://d33v4339jhl8k0.cloudfront.net/' u'users/218639.95870.jpg', }) return self._strip_id(user, strip_id) def _get_person_user(self, strip_id=False): """Return a Person object for a user.""" user = Person.deserialize({ 'first_name': u'Dave', 'last_name': u'Lasley', 'emails': [], 'id': 218639, 'full_name': u'Dave Lasley', 'type': 'user', 'email': u'support@example.com', 'photo_url': u'https://d33v4339jhl8k0.cloudfront.net/' u'users/218639.95870.jpg', }) return self._strip_id(user, strip_id) def _get_customer(self, strip_id=False): """Return a Customer object.""" customer = Customer.deserialize({ 'chats': [], 'first_name': u'Test', 'last_name': u'User', 'phones': [], 'created_at': '2017-09-23T20:12:43Z', 'modified_at': '2017-12-13T22:39:59Z', 'websites': [], 'emails': [], 'full_name': u'Test User', 'gender': 'unknown', 'id': 144228647, 'organization': u'Test Company', 'type': 'user', 'social_profiles': [], 'job_title': u'CEO', }) return self._strip_id(customer, strip_id) def _get_person_customer(self, strip_id=False): """Return a Person object for a customer.""" customer = Person.deserialize({ 'first_name': u'Test', 'last_name': u'User', 'email': u'test@example.com', 'phone': u'1234567890', 'id': 144228647, 'type': 'customer', 'emails': [u'test@example.com'], 'photo_url': u'', }) return self._strip_id(customer, strip_id) def _get_mailbox_ref(self, strip_id=False): """Return a MailboxRef object.""" mailbox_ref = MailboxRef.deserialize({ 'id': 122867, 'name': u'Support', }) return self._strip_id(mailbox_ref, strip_id) def _get_thread(self, strip_id=False): thread = Thread.deserialize({ 'status': 'active', 'body': u'<p>Test conversation.</p>', 'created_by_customer': False, 'attachments': [], 'to': [], 'cc': [], 'created_at': '2017-12-07T21:08:20Z', 'created_by': self._get_person_user().serialize(), 'bcc': [], 'customer': self._get_person_customer().serialize(), 'state': 'published', 'source': { 'via': 'user', 'type': 'api', }, 'type': 'note', 'id': 1310543489, }) return self._strip_id(thread, strip_id) def _get_conversation(self, strip_id=False): """Return a Conversation object.""" conversation = Conversation.deserialize({ 'status': 'pending', 'customer': self._get_person_customer().serialize(), 'preview': u'Conversation exported from Odoo.', 'tags': [], 'thread_count': 1, 'type': 'email', 'created_at': '2017-12-07T21:08:20Z', 'number': 162, 'created_by': self._get_person_user().serialize(), 'mailbox': self._get_mailbox_ref().serialize(), 'source': { 'via': 'user', 'type': 'api', }, 'threads': [ self._get_thread(strip_id=strip_id).serialize(), ], 'folder_id': 1601748, 'owner': self._get_person_user().serialize(), 'bcc': [], 'is_draft': False, 'id': 448848612, 'cc': [], 'subject': u'Celebrate successful conversation.', }) return self._strip_id(conversation, strip_id) def _get_folder(self): return Folder.deserialize({ 'user_id': self._get_user().id, 'name': u'Mine', 'total_count': 2, 'modified_at': '2017-12-14T00:28:40Z', 'active_count': 1, 'type': 'mine', 'id': 1601748, }) def _get_team(self, strip_id=False): team = Person.deserialize({ 'first_name': u'Test Team', 'last_name': u'', 'created_at': '2017-12-14T01:18:46Z', 'modified_at': '2017-12-14T01:18:51Z', 'emails': [], 'full_name': u'Test Team ', 'id': 245377, 'type': 'team', 'email': u'', }) return self._strip_id(team, strip_id) def _new_attachment(self): return Attachment( raw_data='Test String', file_name='test.txt', mime_type='text/plain', ) def _strip_id(self, obj, do_strip): if do_strip: obj.id = False return obj def _test_create(self, record): """Generic create API endpoint test helper.""" response = self.__endpoint__.create(record) self.assertIsInstance(response, record.__class__) self.assertTrue(response.id) return response def _test_get(self, record): """Generic get API endpoint test helper.""" result = self.__endpoint__.get(record.id) self.assertEqual(result.id, record.id) return result def _test_delete(self, record): """Generic delete API endpoint test helper.""" record = self.__endpoint__.create(record) self.assertTrue(self.__endpoint__.get(record.id)) self.assertIsNone(self.__endpoint__.delete(record)) self.assertFalse(self.__endpoint__.get(record.id)) def _test_list(self, *args): """Generic list API endpoint test helper.""" self._assert_results( self.__endpoint__.list(*args), lambda r: isinstance(r, BaseModel), ) def _test_search(self, record): """Generic search API endpoint test helper.""" query = [('id', record.id)] result_ids = [r.id for r in self.__endpoint__.search(query)] self.assertIn(record.id, result_ids) def _test_update(self, record, update_attr, update_val): """Generic update API endpoint test helper.""" record = self.__endpoint__.create(record) setattr(record, update_attr, update_val) self.__endpoint__.update(record) self.assertEqual( getattr(self.__endpoint__.get(record.id), update_attr), update_val, ) def _assert_results(self, result_iterator, assert_method=None): result_counter = 0 for result in result_iterator: if assert_method is not None: self.assertTrue(assert_method(result)) result_counter += 1 self.assertTrue(result_counter)
class ApiCommon(unittest.TestCase): def setUp(self): pass def _get_user(self, strip_id=False): '''Return a User object.''' pass def _get_person_user(self, strip_id=False): '''Return a Person object for a user.''' pass def _get_customer(self, strip_id=False): '''Return a Customer object.''' pass def _get_person_customer(self, strip_id=False): '''Return a Person object for a customer.''' pass def _get_mailbox_ref(self, strip_id=False): '''Return a MailboxRef object.''' pass def _get_thread(self, strip_id=False): pass def _get_conversation(self, strip_id=False): '''Return a Conversation object.''' pass def _get_folder(self): pass def _get_team(self, strip_id=False): pass def _new_attachment(self): pass def _strip_id(self, obj, do_strip): pass def _test_create(self, record): '''Generic create API endpoint test helper.''' pass def _test_get(self, record): '''Generic get API endpoint test helper.''' pass def _test_delete(self, record): '''Generic delete API endpoint test helper.''' pass def _test_list(self, *args): '''Generic list API endpoint test helper.''' pass def _test_search(self, record): '''Generic search API endpoint test helper.''' pass def _test_update(self, record, update_attr, update_val): '''Generic update API endpoint test helper.''' pass def _assert_results(self, result_iterator, assert_method=None): pass
20
12
11
0
10
1
1
0.07
1
11
10
6
19
4
19
91
231
20
198
39
178
13
73
39
53
3
2
2
22
145,052
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/tests/test_auth_proxy.py
helpscout.tests.test_auth_proxy.ApiClass
class ApiClass(object): @classmethod def proxied(cls, session=None): raise EndTestException(session=session) @classmethod def not_proxied(cls, *args, **kwargs): raise Exception()
class ApiClass(object): @classmethod def proxied(cls, session=None): pass @classmethod def not_proxied(cls, *args, **kwargs): pass
5
0
2
0
2
0
1
0
1
2
1
0
0
0
2
2
9
2
7
5
2
0
5
3
2
1
1
0
2
145,053
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/exceptions.py
helpscout.exceptions.HelpScoutException
class HelpScoutException(Exception): """Base exception for HelpScout library errors.""" def __init__(self, message): self.message = message def __str__(self): return str(self.message)
class HelpScoutException(Exception): '''Base exception for HelpScout library errors.''' def __init__(self, message): pass def __str__(self): pass
3
1
2
0
2
0
1
0.2
1
1
0
3
2
1
2
12
8
2
5
4
2
1
5
4
2
1
3
0
2
145,054
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/tests/test_auth_proxy.py
helpscout.tests.test_auth_proxy.EndTestException
class EndTestException(Exception): def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs super(EndTestException, self).__init__()
class EndTestException(Exception): def __init__(self, *args, **kwargs): pass
2
0
4
0
4
0
1
0
1
1
0
0
1
2
1
11
5
0
5
4
3
0
5
4
3
1
3
0
1
145,055
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/models/option.py
helpscout.models.option.Option
class Option(BaseModel): """This represents option for a custom field of type ``DROPDOWN``.""" label = properties.String( 'Label of the option.', required=True, ) order = properties.Integer( 'Relative order of the custom field. Can be ``null`` or a number ' 'between ``0`` and ``255``.', min=0, max=255, )
class Option(BaseModel): '''This represents option for a custom field of type ``DROPDOWN``.''' pass
1
1
0
0
0
0
0
0.09
1
0
0
0
0
0
0
14
13
1
11
3
10
1
3
3
2
0
2
0
0
145,056
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/models/mailbox_ref.py
helpscout.models.mailbox_ref.MailboxRef
class MailboxRef(BaseModel): """The mailbox ref is a subset of the full Mailbox object.""" name = properties.String( 'Name of the Mailbox.', required=True, )
class MailboxRef(BaseModel): '''The mailbox ref is a subset of the full Mailbox object.''' pass
1
1
0
0
0
0
0
0.2
1
0
0
1
0
0
0
14
7
1
5
2
4
1
2
2
1
0
2
0
0
145,057
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/models/mailbox.py
helpscout.models.mailbox.Mailbox
class Mailbox(MailboxRef): slug = properties.String( 'Key used to represent this Mailbox.', required=True, ) email = properties.String( 'Email address', required=True, ) folders = properties.List( 'Folders that this mailbox contains.', prop=Folder, ) created_at = properties.DateTime( 'UTC time when this mailbox was created.', ) modified_at = properties.DateTime( 'UTC time when this mailbox was modified.', )
class Mailbox(MailboxRef): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
14
20
1
19
6
18
0
6
6
5
0
3
0
0
145,058
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/models/folder.py
helpscout.models.folder.Folder
class Folder(BaseModel): name = properties.String( 'Folder name', required=True, ) type = properties.StringChoice( 'The type of folder.', choices=['needsattention', 'drafts', 'assigned', 'open', 'closed', 'spam', 'mine', 'team', ], default='drafts', required=True, ) user_id = properties.Integer( 'If the folder type is ``MyTickets``, this represents the Help Scout ' 'user to which this folder belongs. Otherwise it is empty.', ) total_count = properties.Integer( 'Total number of conversations in this folder.', ) active_count = properties.Integer( 'Total number of conversations in this folder that are in an active ' 'state (vs pending).', ) modified_at = properties.DateTime( 'UTC time when this folder was modified.', )
class Folder(BaseModel): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
14
34
1
33
7
32
0
7
7
6
0
2
0
0
145,059
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/models/field.py
helpscout.models.field.Field
class Field(BaseModel): """The field object represents a user's response to a custom field in the context of a single conversation.""" field_id = properties.Integer( 'The field definition identifier; note that multiple conversations ' 'will each have values for the same field identifier.', ) name = properties.String( 'The name of the field; note that this may change if a field is ' 'renamed, but the ``field_id`` will not.', required=True, ) value = properties.String( 'The value the user specified for the field.', ) type = properties.StringChoice( 'Type of the custom field.', choices=['SINGLE_LINE', 'MULTI_LINE', 'DATE', 'NUMBER', 'DROPDOWN', ], ) label = properties.String( 'String representation of the custom field\'s value. Unlike ' '``value`` it contains the actual dropdown option value for ' '``DROPDOWN`` custom field.', )
class Field(BaseModel): '''The field object represents a user's response to a custom field in the context of a single conversation.''' pass
1
1
0
0
0
0
0
0.07
1
0
0
0
0
0
0
14
30
1
27
6
26
2
6
6
5
0
2
0
0
145,060
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/models/email.py
helpscout.models.email.Email
class Email(BaseModel): value = properties.String( 'Email Address', required=True, ) location = properties.StringChoice( 'Location for this email address.', choices=['home', 'work', 'other'], default='other', required=True, )
class Email(BaseModel): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
14
12
1
11
3
10
0
3
3
2
0
2
0
0
145,061
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/models/customer.py
helpscout.models.customer.Customer
class Customer(SearchCustomer): """This represents a customer, which is a type of person.""" background = properties.String( 'This is the Notes field from the user interface.', ) address = properties.Instance( 'The address for this customer.', instance_class=Address, ) social_profiles = properties.List( 'Social profiles that represent this customer.', prop=SocialProfile, ) emails = properties.List( 'Email addresses for this customer.', prop=Email, ) phones = properties.List( 'Phone numbers for this customer.', prop=Phone, ) chats = properties.List( 'Chat addresses for this customer.', prop=Chat, ) websites = properties.List( 'Websites for this customer.', prop=Website, )
class Customer(SearchCustomer): '''This represents a customer, which is a type of person.''' pass
1
1
0
0
0
0
0
0.04
1
0
0
0
0
0
0
17
30
1
28
8
27
1
8
8
7
0
4
0
0
145,062
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/tests/test_auth_proxy.py
helpscout.tests.test_auth_proxy.TestAuthProxy
class TestAuthProxy(unittest.TestCase): SESSION = 'session' def new_proxy(self, session=SESSION, proxy_class=ApiClass): return AuthProxy(session, proxy_class) def test_init_bad_api_class(self): """It should assert API class is a class.""" with self.assertRaises(AssertionError): AuthProxy(None, 'not a class') def test_init_sets_session(self): """It should set the session instance var.""" proxy = self.new_proxy() self.assertEqual(proxy.session, self.SESSION) def test_init_sets_proxy_class(self): """It should set the proxy_class instance var.""" proxy = self.new_proxy() self.assertEqual(proxy.proxy_class, ApiClass) def test_getattr_injects_session(self): """It should inject the session into the proxied method.""" proxy_method = self.new_proxy().proxied try: proxy_method() except EndTestException as e: self.assertEqual(e.kwargs['session'], self.SESSION) def test_getattr_whitelist(self): """It should not proxy methods that are in the whitelist.""" proxy = self.new_proxy() proxy.METHOD_NO_PROXY.append('not_proxied') with self.assertRaises(AttributeError): proxy.not_proxied()
class TestAuthProxy(unittest.TestCase): def new_proxy(self, session=SESSION, proxy_class=ApiClass): pass def test_init_bad_api_class(self): '''It should assert API class is a class.''' pass def test_init_sets_session(self): '''It should set the session instance var.''' pass def test_init_sets_proxy_class(self): '''It should set the proxy_class instance var.''' pass def test_getattr_injects_session(self): '''It should inject the session into the proxied method.''' pass def test_getattr_whitelist(self): '''It should not proxy methods that are in the whitelist.''' pass
7
5
5
0
4
1
1
0.21
1
5
3
0
6
0
6
78
36
7
24
13
17
5
24
12
17
2
2
1
7
145,063
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/tests/test_base_api.py
helpscout.tests.test_base_api.TestApi
class TestApi(BaseApi): __object__ = BaseModel
class TestApi(BaseApi): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
11
2
0
2
2
1
0
2
2
1
0
2
0
0
145,064
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/tests/test_base_model.py
helpscout.tests.test_base_model.TestBaseModel
class TestBaseModel(unittest.TestCase): def setUp(self): super(TestBaseModel, self).setUp() self.test_values = { 'aKey': 'value', 'subInstance': { 'id': 1234, }, 'list': [ {'id': 4321}, ], 'date': datetime(2017, 1, 1, 0, 0, 0), 'color': 'blue', } self.internal_values = { 'a_key': self.test_values['aKey'], 'sub_instance': self.test_values['subInstance'], 'list': self.test_values['list'], 'date': self.test_values['date'], 'color': self.test_values['color'], } def new_record(self): return TestModel.from_api(**self.test_values) def test_from_api_new_instance(self): """It should return a new instance of the class.""" self.assertIsInstance(self.new_record(), TestModel) def test_from_api_camel_to_snake(self): """It should call the init with snake cased keys.""" self.assertEqual(self.new_record().a_key, self.test_values['aKey']) def test_from_api_sub_instance(self): """It should properly instantiate sub-instances.""" self.assertIsInstance(self.new_record().sub_instance, BaseModel) def test_from_api_list(self): """It should properly convert lists of instances.""" res = self.new_record() self.assertIsInstance(res.list, list) self.assertIsInstance(res.list[0], BaseModel) def test_from_api_color_none(self): """It should parse 'none' API value in Color property as lightgrey.""" record = TestModel.from_api(**{'color': 'none'}) self.assertEqual(record.color, (211, 211, 211)) def test_from_api_invalid_attribute(self): """It should remove any invalid attributes.""" record = TestModel.from_api(**{'no_exist': 'value'}) with self.assertRaises(AttributeError): record.no_exist def test_to_api_camel_case(self): """It should properly camel case the API args.""" res = self.new_record().to_api() self.assertEqual(res['aKey'], self.internal_values['a_key']) def test_to_api_instance(self): """It should properly convert sub-instances to dict.""" res = self.new_record().to_api() self.assertIsInstance(res['subInstance'], dict) def test_to_api_list(self): """It should properly convert sub-instances within lists props.""" res = self.new_record().to_api() self.assertIsInstance(res['list'], list) self.assertIsInstance(res['list'][0], dict) def test_to_api_list_string(self): """It should properly handle naive lists.""" expect = ['1', '2'] self.test_values['list_string'] = expect res = self.new_record().to_api() self.assertIsInstance(res['listString'], list) self.assertIsInstance(res['listString'][0], string_types) def test_to_api_date(self): """It should return the serialized datetime.""" self.assertEqual( self.new_record().to_api()['date'], '2017-01-01T00:00:00Z', ) def test_get_non_empty_vals(self): """It should return the dict without NoneTypes.""" expect = { 'good_int': 1234, 'good_false': False, 'good_true': True, 'bad': None, } res = BaseModel.get_non_empty_vals(expect) del expect['bad'] self.assertDictEqual(res, expect) def test_parse_property_invalid_property(self): """It should raise an exception if property name is invalid.""" self.assertIsNone(BaseModel._parse_property('no exist', 'value')) def test_dict_lookup_exist(self): """It should return the attribute value when it exists.""" self.assertEqual( self.new_record()['a_key'], self.internal_values['a_key'], ) def test_dict_lookup_no_exist(self): """It should raise a KeyError when the attribute isn't a field.""" with self.assertRaises(KeyError): self.new_record()['not_a_field'] def test_dict_set_exist(self): """It should set the attribute via the items.""" expect = 'Test-Expect' record = self.new_record() record['a_key'] = expect self.assertEqual(record.a_key, expect) def test_dict_set_no_exist(self): """It should raise a KeyError and not change the non-field.""" record = self.new_record() with self.assertRaises(KeyError): record['not_a_field'] = False self.assertTrue(record.not_a_field) def test_get_exist(self): """It should return the attribute if it exists.""" self.assertEqual( self.new_record().get('a_key'), self.internal_values['a_key'], ) def test_get_no_exist(self): """It should return the default if the attribute doesn't exist.""" expect = 'Test' self.assertEqual( self.new_record().get('not_a_field', expect), expect, ) def test_from_api_list_no_model(self): """Test ``from_api`` when there is a list of non-property objects.""" self.test_values['list_string'] = [ 'test', 'again', ] self.assertEqual(self.new_record().list_string, self.test_values['list_string'])
class TestBaseModel(unittest.TestCase): def setUp(self): pass def new_record(self): pass def test_from_api_new_instance(self): '''It should return a new instance of the class.''' pass def test_from_api_camel_to_snake(self): '''It should call the init with snake cased keys.''' pass def test_from_api_sub_instance(self): '''It should properly instantiate sub-instances.''' pass def test_from_api_list(self): '''It should properly convert lists of instances.''' pass def test_from_api_color_none(self): '''It should parse 'none' API value in Color property as lightgrey.''' pass def test_from_api_invalid_attribute(self): '''It should remove any invalid attributes.''' pass def test_to_api_camel_case(self): '''It should properly camel case the API args.''' pass def test_to_api_instance(self): '''It should properly convert sub-instances to dict.''' pass def test_to_api_list(self): '''It should properly convert sub-instances within lists props.''' pass def test_to_api_list_string(self): '''It should properly handle naive lists.''' pass def test_to_api_date(self): '''It should return the serialized datetime.''' pass def test_get_non_empty_vals(self): '''It should return the dict without NoneTypes.''' pass def test_parse_property_invalid_property(self): '''It should raise an exception if property name is invalid.''' pass def test_dict_lookup_exist(self): '''It should return the attribute value when it exists.''' pass def test_dict_lookup_no_exist(self): '''It should raise a KeyError when the attribute isn't a field.''' pass def test_dict_set_exist(self): '''It should set the attribute via the items.''' pass def test_dict_set_no_exist(self): '''It should raise a KeyError and not change the non-field.''' pass def test_get_exist(self): '''It should return the attribute if it exists.''' pass def test_get_no_exist(self): '''It should return the default if the attribute doesn't exist.''' pass def test_from_api_list_no_model(self): '''Test ``from_api`` when there is a list of non-property objects.''' pass
23
20
6
0
5
1
1
0.19
1
8
2
0
22
2
22
94
146
22
104
39
81
20
72
39
49
1
2
1
22
145,065
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/tests/test_base_model.py
helpscout.tests.test_base_model.TestModel
class TestModel(BaseModel): a_key = properties.String('A key') sub_instance = properties.Instance( 'Sub Instance', instance_class=BaseModel, ) list = properties.List( 'List', prop=properties.Instance('List Instance', instance_class=BaseModel), ) list_string = properties.List( 'List of Strings', prop=properties.String('String'), ) date = properties.DateTime('DateTime') color = properties.Color('Color') not_a_field = True
class TestModel(BaseModel): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
14
15
0
15
8
14
0
8
8
7
0
2
0
0
145,066
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/tests/test_domain.py
helpscout.tests.test_domain.TestDomain
class TestDomain(unittest.TestCase): def test_init_adds_queries(self): """It should add queries if defined.""" with mock.patch.object(Domain, 'add_query') as add: Domain(['expect'], 'test') add.assert_called_once_with('expect', 'test') def test_from_tuple(self): """It should return the proper domain.""" data = [('status', 'active'), ('number', 1234), ('modified_at', datetime(2017, 1, 1), datetime(2017, 1, 2)), ('subject', 'Test1'), 'OR', ('subject', 'Test2')] res = Domain.from_tuple(data) self.assertEqual( str(res), '(' 'status:"active" ' 'AND number:1234 ' 'AND modifiedAt:[2017-01-01T00:00:00Z TO 2017-01-02T00:00:00Z] ' 'AND subject:"Test1" ' 'OR subject:"Test2"' ')', )
class TestDomain(unittest.TestCase): def test_init_adds_queries(self): '''It should add queries if defined.''' pass def test_from_tuple(self): '''It should return the proper domain.''' pass
3
2
12
0
11
1
1
0.09
1
3
1
0
2
0
2
74
27
2
23
6
20
2
9
5
6
1
2
1
2
145,067
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/tests/test_exceptions.py
helpscout.tests.test_exceptions.TestExceptions
class TestExceptions(unittest.TestCase): def test_helpscout_remote_exception(self): """It should have the proper str representation.""" code = 404 message = 'A Fail' e = HelpScoutRemoteException(code, message) self.assertEqual(str(e), '(404) A Fail') def test_helpscout_base_exception(self): """It should include the message in string.""" message = 'message' e = HelpScoutValidationException(message) self.assertEqual(str(e), message)
class TestExceptions(unittest.TestCase): def test_helpscout_remote_exception(self): '''It should have the proper str representation.''' pass def test_helpscout_base_exception(self): '''It should include the message in string.''' pass
3
2
6
0
5
1
1
0.2
1
3
2
0
2
0
2
74
14
2
10
8
7
2
10
8
7
1
2
0
2
145,068
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/models/phone.py
helpscout.models.phone.Phone
class Phone(BaseModel): value = properties.String( 'Phone Number', required=True, ) location = properties.StringChoice( 'Location for this phone number.', choices=['home', 'fax', 'mobile', 'pager', 'work', 'other', ], default='other', required=True, )
class Phone(BaseModel): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
14
18
1
17
3
16
0
3
3
2
0
2
0
0
145,069
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/exceptions.py
helpscout.exceptions.HelpScoutRemoteException
class HelpScoutRemoteException(HelpScoutException): """Indicates that an error occurred when communicating with the remote.""" def __init__(self, status_code, message): self.status_code = status_code super(HelpScoutRemoteException, self).__init__(message) def __str__(self): return '(%d) %s' % (self.status_code, self.message)
class HelpScoutRemoteException(HelpScoutException): '''Indicates that an error occurred when communicating with the remote.''' def __init__(self, status_code, message): pass def __str__(self): pass
3
1
3
0
3
0
1
0.17
1
1
0
0
2
1
2
14
9
2
6
4
3
1
6
4
3
1
4
0
2
145,070
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/domain/__init__.py
helpscout.domain.Domain
class Domain(properties.HasProperties): """This represents a full search query.""" OR = 'OR' AND = 'AND' def __init__(self, queries=None, join_with=AND): """Initialize a domain, with optional queries.""" self.query = [] if queries is not None: for query in queries: self.add_query(query, join_with) @classmethod def from_tuple(cls, queries): """Create a ``Domain`` given a set of complex query tuples. Args: queries (iter): An iterator of complex queries. Each iteration should contain either: * A data-set compatible with :func:`~domain.Domain.add_query` * A string to switch the join type Example:: [('subject', 'Test1'), 'OR', ('subject', 'Test2')', ('subject', 'Test3')', ] # The above is equivalent to: # subject:'Test1' OR subject:'Test2' OR subject:'Test3' [('modified_at', datetime(2017, 01, 01)), ('status', 'active'), ] # The above is equivalent to: # modified_at:[2017-01-01T00:00:00Z TO *] # AND status:"active" Returns: Domain: A domain representing the input queries. """ domain = cls() join_with = cls.AND for query in queries: if query in [cls.OR, cls.AND]: join_with = query else: domain.add_query(query, join_with) return domain def add_query(self, query, join_with=AND): """Join a new query to existing queries on the stack. Args: query (tuple or list or DomainCondition): The condition for the query. If a ``DomainCondition`` object is not provided, the input should conform to the interface defined in :func:`~.domain.DomainCondition.from_tuple`. join_with (str): The join string to apply, if other queries are already on the stack. """ if not isinstance(query, DomainCondition): query = DomainCondition.from_tuple(query) if len(self.query): self.query.append(join_with) self.query.append(query) def __str__(self): """Return a string usable as the query in an API request.""" if not self.query: return '*' return '(%s)' % ' '.join([str(q) for q in self.query])
class Domain(properties.HasProperties): '''This represents a full search query.''' def __init__(self, queries=None, join_with=AND): '''Initialize a domain, with optional queries.''' pass @classmethod def from_tuple(cls, queries): '''Create a ``Domain`` given a set of complex query tuples. Args: queries (iter): An iterator of complex queries. Each iteration should contain either: * A data-set compatible with :func:`~domain.Domain.add_query` * A string to switch the join type Example:: [('subject', 'Test1'), 'OR', ('subject', 'Test2')', ('subject', 'Test3')', ] # The above is equivalent to: # subject:'Test1' OR subject:'Test2' OR subject:'Test3' [('modified_at', datetime(2017, 01, 01)), ('status', 'active'), ] # The above is equivalent to: # modified_at:[2017-01-01T00:00:00Z TO *] # AND status:"active" Returns: Domain: A domain representing the input queries. ''' pass def add_query(self, query, join_with=AND): '''Join a new query to existing queries on the stack. Args: query (tuple or list or DomainCondition): The condition for the query. If a ``DomainCondition`` object is not provided, the input should conform to the interface defined in :func:`~.domain.DomainCondition.from_tuple`. join_with (str): The join string to apply, if other queries are already on the stack. ''' pass def __str__(self): '''Return a string usable as the query in an API request.''' pass
6
5
16
2
6
9
3
1.25
1
2
1
0
3
1
4
4
75
12
28
13
22
35
26
12
21
3
1
2
11
145,071
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/models/rating.py
helpscout.models.rating.Rating
class Rating(BaseModel): customer = properties.Instance( 'Partial customer object.', instance_class=Customer, required=True, ) ticket_id = properties.Integer( 'Ticket ID', required=True, ) thread_id = properties.Integer( 'Thread ID', required=True, ) mailbox = properties.Instance( 'Reference to the mailbox that the conversation belongs to.', instance_class=MailboxRef, required=True, ) rating = properties.StringChoice( 'Satisfaction rating.', choices=['Great', 'Okay', 'Bad'], required=True, ) comments = properties.String( 'Additional comments', ) created_at = properties.DateTime( 'UTC time when this rating was created.', ) modified_at = properties.DateTime( 'UTC time when this rating was modified.', )
class Rating(BaseModel): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
14
34
1
33
9
32
0
9
9
8
0
2
0
0
145,072
LasLabs/python-helpscout
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LasLabs_python-helpscout/helpscout/models/person.py
helpscout.models.person.Person
class Person(BaseModel): """This is a subset of the data representing a Customer, User or Team. The ``type`` property will specify if this person is represented by a ``user``, ``customer`` or ``team``. """ def __init__(self, **kwargs): value = kwargs.pop('customer_person_type', False) self.type = 'customer' if value else 'user' return super(Person, self).__init__(**kwargs) full_name = properties.String( 'Full name for the customer', ) first_name = properties.String( 'First name', required=True, ) last_name = properties.String( 'Last name', required=True, ) email = properties.String( 'Email', ) emails = properties.List( 'Email addresses for this person.', prop=properties.String( 'Email Address', ), ) phone = properties.String( 'Phone is only populated when the Person is a customer associated ' 'with a Conversation of type ``phone`` and a phone number was ' 'specified at the time the conversation was created.', ) type = properties.StringChoice( 'The type of person.', choices=['user', 'customer', 'team'], default='customer', required=True, ) photo_url = properties.String( 'The user\'s photo, if one exists.', ) created_at = properties.DateTime( 'UTC time when this customer was created.', ) modified_at = properties.DateTime( 'UTC time when this customer was modified.', ) @properties.Bool('customer boolean') def customer_person_type(self): return self.type == 'customer' @customer_person_type.setter def customer_person_type(self, value): self.type = 'customer' if value else 'user'
class Person(BaseModel): '''This is a subset of the data representing a Customer, User or Team. The ``type`` property will specify if this person is represented by a ``user``, ``customer`` or ``team``. ''' def __init__(self, **kwargs): pass @properties.Bool('customer boolean') def customer_person_type(self): pass @customer_person_type.setter def customer_person_type(self): pass
6
1
3
0
3
0
2
0.08
1
1
0
2
3
0
3
17
60
5
51
17
45
4
19
15
15
2
2
0
5
145,073
LasLabs/python-helpscout
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LasLabs_python-helpscout/helpscout/tests/test_apis_conversations.py
helpscout.tests.test_apis_conversations.TestApisConversations
class TestApisConversations(ApiCommon): """Tests the Conversations API endpoint.""" def setUp(self): super(TestApisConversations, self).setUp() self.__endpoint__ = self.api.Conversations def _test_attachment(self): attachment = self.api.Conversations.create_attachment( self._new_attachment(), ) self.assertIsInstance(attachment, Attachment) self.assertTrue(attachment.hash) return attachment def _conversation_with_attachment(self, conversation, thread): thread['attachments'] = [self._test_attachment()] conversation = self.api.Conversations.create_thread( conversation, thread, ) return conversation, conversation['threads'][0]['attachments'][0] @recorder.use_cassette() def test_apis_conversations_create(self): """It should create and return a Conversation.""" self._test_create(self._get_conversation(strip_id=True)) @recorder.use_cassette() def test_apis_conversations_create_attachment(self): """It should create and return the Attachment.""" self._test_attachment() @recorder.use_cassette() def test_apis_conversations_create_thread(self): """It should create the thread and return the conversation.""" conversation = self._test_create( self._get_conversation(strip_id=True), ) thread_count = conversation.thread_count thread = self._get_thread(strip_id=True) conversation = self.api.Conversations.create_thread( conversation, thread, ) self.assertEqual( len(conversation.threads), thread_count + 1, ) @recorder.use_cassette() def test_apis_conversations_get(self): """It should return the conversation.""" self._test_get(self._get_conversation()) @recorder.use_cassette() def test_apis_conversations_delete(self): """It should delete the conversation.""" self._test_delete(self._get_conversation(strip_id=True)) @recorder.use_cassette() def test_apis_conversations_list(self): """It should list the conversations in the mailbox.""" mailbox = self._get_mailbox_ref() self._test_list(mailbox) @recorder.use_cassette() def test_apis_conversations_search(self): """It should search for and return the conversation.""" self._test_search(self._get_conversation()) @recorder.use_cassette() def test_apis_conversations_update(self): """It should update the conversation.""" self._test_update( self._get_conversation(strip_id=True), 'subject', 'A new subject', ) @recorder.use_cassette() def test_apis_conversations_find_customer(self): """It should only return conversations for the customer.""" mailbox = self._get_mailbox_ref() customer = self._get_customer() self._assert_results( self.api.Conversations.find_customer(mailbox, customer), lambda result: result.customer.id == customer.id, ) @recorder.use_cassette() def test_apis_conversations_find_user(self): """It should only return conversations for the user.""" mailbox = self._get_mailbox_ref() user = self._get_user() self._assert_results( self.api.Conversations.find_user(mailbox, user), lambda result: result.owner.id == user.id, ) @recorder.use_cassette() def test_apis_conversations_get_attachment_data(self): """It should return the proper attachment.""" _, attachment = self._conversation_with_attachment( self._get_conversation(), self._get_thread(strip_id=True), ) response = self.api.Conversations.get_attachment_data(attachment.id) self.assertEqual(response.raw_data, self._new_attachment().raw_data) @recorder.use_cassette() def test_apis_conversations_delete_attachment(self): """It should return None after a success.""" _, attachment = self._conversation_with_attachment( self._get_conversation(), self._get_thread(strip_id=True), ) self.assertIsNone( self.api.Conversations.delete_attachment(attachment), ) @recorder.use_cassette() def test_apis_conversations_list_folder(self): """It should return conversations specific to a folder.""" mailbox = self._get_mailbox_ref() folder = self._get_folder() self._assert_results( self.api.Conversations.list_folder(mailbox, folder), lambda record: record.folder_id == folder.id, ) @recorder.use_cassette() def test_apis_conversations_update_thread(self): """It should update the thread.""" conversation, _ = self._conversation_with_attachment( self._get_conversation(), self._get_thread(strip_id=True), ) thread = conversation['threads'][0] thread.body = 'expect' conversation = self.api.Conversations.update_thread( conversation, thread, ) self.assertEqual( conversation['threads'][0].body, 'expect', )
class TestApisConversations(ApiCommon): '''Tests the Conversations API endpoint.''' def setUp(self): pass def _test_attachment(self): pass def _conversation_with_attachment(self, conversation, thread): pass @recorder.use_cassette() def test_apis_conversations_create(self): '''It should create and return a Conversation.''' pass @recorder.use_cassette() def test_apis_conversations_create_attachment(self): '''It should create and return the Attachment.''' pass @recorder.use_cassette() def test_apis_conversations_create_thread(self): '''It should create the thread and return the conversation.''' pass @recorder.use_cassette() def test_apis_conversations_get(self): '''It should return the conversation.''' pass @recorder.use_cassette() def test_apis_conversations_delete(self): '''It should delete the conversation.''' pass @recorder.use_cassette() def test_apis_conversations_list(self): '''It should list the conversations in the mailbox.''' pass @recorder.use_cassette() def test_apis_conversations_search(self): '''It should search for and return the conversation.''' pass @recorder.use_cassette() def test_apis_conversations_update(self): '''It should update the conversation.''' pass @recorder.use_cassette() def test_apis_conversations_find_customer(self): '''It should only return conversations for the customer.''' pass @recorder.use_cassette() def test_apis_conversations_find_user(self): '''It should only return conversations for the user.''' pass @recorder.use_cassette() def test_apis_conversations_get_attachment_data(self): '''It should return the proper attachment.''' pass @recorder.use_cassette() def test_apis_conversations_delete_attachment(self): '''It should return None after a success.''' pass @recorder.use_cassette() def test_apis_conversations_list_folder(self): '''It should return conversations specific to a folder.''' pass @recorder.use_cassette() def test_apis_conversations_update_thread(self): '''It should update the thread.''' pass
32
15
6
0
6
1
1
0.14
1
2
1
0
17
1
17
108
143
17
111
49
79
15
59
35
41
1
3
0
17
145,074
LasLabs/python-helpscout
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LasLabs_python-helpscout/helpscout/tests/test_apis_customers.py
helpscout.tests.test_apis_customers.TestApisCustomers
class TestApisCustomers(ApiCommon): """Tests the Customers API endpoint.""" def setUp(self): super(TestApisCustomers, self).setUp() self.__endpoint__ = self.api.Customers @recorder.use_cassette() def test_apis_customers_create(self): """It should create and return a Customer.""" self._test_create(self._get_customer(strip_id=True)) @recorder.use_cassette() def test_apis_customers_get(self): """It should return the customer.""" self._test_get(self._get_customer()) @recorder.use_cassette() def test_apis_customers_delete(self): """It should not be implemented.""" with self.assertRaises(NotImplementedError): self.__endpoint__.delete(self._get_customer()) @recorder.use_cassette() def test_apis_customers_list(self): """It should list the customers in the mailbox.""" self._test_list() @recorder.use_cassette() def test_apis_customers_search(self): """It should search for and return the customer.""" self._test_search(self._get_customer()) @recorder.use_cassette() def test_apis_customers_update(self): """It should update the customer.""" self._test_update( self._get_customer(strip_id=True), 'first_name', 'A new name', )
class TestApisCustomers(ApiCommon): '''Tests the Customers API endpoint.''' def setUp(self): pass @recorder.use_cassette() def test_apis_customers_create(self): '''It should create and return a Customer.''' pass @recorder.use_cassette() def test_apis_customers_get(self): '''It should return the customer.''' pass @recorder.use_cassette() def test_apis_customers_delete(self): '''It should not be implemented.''' pass @recorder.use_cassette() def test_apis_customers_list(self): '''It should list the customers in the mailbox.''' pass @recorder.use_cassette() def test_apis_customers_search(self): '''It should search for and return the customer.''' pass @recorder.use_cassette() def test_apis_customers_update(self): '''It should update the customer.''' pass
14
7
4
0
3
1
1
0.26
1
2
0
0
7
1
7
98
41
7
27
15
13
7
17
9
9
1
3
1
7
145,075
LasLabs/python-helpscout
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LasLabs_python-helpscout/helpscout/tests/test_apis_mailboxes.py
helpscout.tests.test_apis_mailboxes.TestApisMailboxes
class TestApisMailboxes(ApiCommon): """Tests the Mailboxes API endpoint.""" def setUp(self): super(TestApisMailboxes, self).setUp() self.__endpoint__ = self.api.Mailboxes @recorder.use_cassette() def test_apis_mailboxes_get(self): """It should return the mailbox.""" self._test_get(self._get_mailbox_ref()) @recorder.use_cassette() def test_apis_mailboxes_delete(self): """It should not be implemented.""" with self.assertRaises(NotImplementedError): self.__endpoint__.delete(self._get_mailbox_ref()) @recorder.use_cassette() def test_apis_mailboxes_update(self): """It should not be implemented.""" with self.assertRaises(NotImplementedError): self.__endpoint__.update(self._get_mailbox_ref()) @recorder.use_cassette() def test_apis_mailboxes_create(self): """It should not be implemented.""" with self.assertRaises(NotImplementedError): self.__endpoint__.create(self._get_mailbox_ref()) @recorder.use_cassette() def test_apis_mailboxes_list(self): """It should list the mailboxes in the mailbox.""" self._test_list() @recorder.use_cassette() def test_apis_mailboxes_search(self): """It should not be implemented.""" with self.assertRaises(NotImplementedError): self.__endpoint__.search([], None)
class TestApisMailboxes(ApiCommon): '''Tests the Mailboxes API endpoint.''' def setUp(self): pass @recorder.use_cassette() def test_apis_mailboxes_get(self): '''It should return the mailbox.''' pass @recorder.use_cassette() def test_apis_mailboxes_delete(self): '''It should not be implemented.''' pass @recorder.use_cassette() def test_apis_mailboxes_update(self): '''It should not be implemented.''' pass @recorder.use_cassette() def test_apis_mailboxes_create(self): '''It should not be implemented.''' pass @recorder.use_cassette() def test_apis_mailboxes_list(self): '''It should list the mailboxes in the mailbox.''' pass @recorder.use_cassette() def test_apis_mailboxes_search(self): '''It should not be implemented.''' pass
14
7
4
0
3
1
1
0.27
1
2
0
0
7
1
7
98
40
7
26
15
12
7
20
9
12
1
3
1
7
145,076
LasLabs/python-helpscout
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LasLabs_python-helpscout/helpscout/tests/test_apis_teams.py
helpscout.tests.test_apis_teams.TestApisTeams
class TestApisTeams(ApiCommon): """Tests the Teams API endpoint.""" def setUp(self): super(TestApisTeams, self).setUp() self.__endpoint__ = self.api.Teams @recorder.use_cassette() def test_apis_teams_get(self): """It should return the team.""" self._test_get(self._get_team()) @recorder.use_cassette() def test_apis_teams_delete(self): """It should not be implemented.""" with self.assertRaises(NotImplementedError): self.__endpoint__.delete(None) @recorder.use_cassette() def test_apis_teams_update(self): """It should not be implemented.""" with self.assertRaises(NotImplementedError): self.__endpoint__.update(None) @recorder.use_cassette() def test_apis_teams_create(self): """It should not be implemented.""" with self.assertRaises(NotImplementedError): self.__endpoint__.create(None) @recorder.use_cassette() def test_apis_teams_list(self): """It should list the teams in the team.""" self._test_list() @recorder.use_cassette() def test_apis_teams_search(self): """It should not be implemented.""" with self.assertRaises(NotImplementedError): self.__endpoint__.search([], None) @recorder.use_cassette() def test_apis_teams_get_members(self): """It should get the team members.""" team = self._get_team() user_ids = [u.id for u in self.api.Teams.get_members(team)] self.assertIn(self._get_user().id, user_ids)
class TestApisTeams(ApiCommon): '''Tests the Teams API endpoint.''' def setUp(self): pass @recorder.use_cassette() def test_apis_teams_get(self): '''It should return the team.''' pass @recorder.use_cassette() def test_apis_teams_delete(self): '''It should not be implemented.''' pass @recorder.use_cassette() def test_apis_teams_update(self): '''It should not be implemented.''' pass @recorder.use_cassette() def test_apis_teams_create(self): '''It should not be implemented.''' pass @recorder.use_cassette() def test_apis_teams_list(self): '''It should list the teams in the team.''' pass @recorder.use_cassette() def test_apis_teams_search(self): '''It should not be implemented.''' pass @recorder.use_cassette() def test_apis_teams_get_members(self): '''It should get the team members.''' pass
16
8
4
0
3
1
1
0.26
1
2
0
0
8
1
8
99
47
8
31
19
15
8
24
12
15
1
3
1
8
145,077
LasLabs/python-helpscout
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LasLabs_python-helpscout/helpscout/tests/test_apis_users.py
helpscout.tests.test_apis_users.TestApisUsers
class TestApisUsers(ApiCommon): """Tests the Users API endpoint.""" def setUp(self): super(TestApisUsers, self).setUp() self.__endpoint__ = self.api.Users @recorder.use_cassette() def test_apis_users_get(self): """It should return the user.""" self._test_get(self._get_user()) @recorder.use_cassette() def test_apis_users_delete(self): """It should not be implemented.""" with self.assertRaises(NotImplementedError): self.__endpoint__.delete(self._get_user()) @recorder.use_cassette() def test_apis_users_update(self): """It should not be implemented.""" with self.assertRaises(NotImplementedError): self.__endpoint__.update(self._get_user()) @recorder.use_cassette() def test_apis_users_create(self): """It should not be implemented.""" with self.assertRaises(NotImplementedError): self.__endpoint__.create(self._get_user()) @recorder.use_cassette() def test_apis_users_list(self): """It should list the users in the user.""" self._test_list() @recorder.use_cassette() def test_apis_users_search(self): """It should not be implemented.""" with self.assertRaises(NotImplementedError): self.__endpoint__.search([], None) @recorder.use_cassette() def test_apis_users_get_me(self): """It should return the current users.""" self.assertEqual(self.api.Users.get_me().id, self._get_user().id) @recorder.use_cassette() def test_apis_users_find_in_mailbox(self): """It should return the users associated with the mailbox.""" results = list( self.api.Users.find_in_mailbox(self._get_mailbox_ref()) ) self._assert_results(results) self.assertIn(self._get_user().id, [u.id for u in results])
class TestApisUsers(ApiCommon): '''Tests the Users API endpoint.''' def setUp(self): pass @recorder.use_cassette() def test_apis_users_get(self): '''It should return the user.''' pass @recorder.use_cassette() def test_apis_users_delete(self): '''It should not be implemented.''' pass @recorder.use_cassette() def test_apis_users_update(self): '''It should not be implemented.''' pass @recorder.use_cassette() def test_apis_users_create(self): '''It should not be implemented.''' pass @recorder.use_cassette() def test_apis_users_list(self): '''It should list the users in the user.''' pass @recorder.use_cassette() def test_apis_users_search(self): '''It should not be implemented.''' pass @recorder.use_cassette() def test_apis_users_get_me(self): '''It should return the current users.''' pass @recorder.use_cassette() def test_apis_users_find_in_mailbox(self): '''It should return the users associated with the mailbox.''' pass
18
9
4
0
3
1
1
0.25
1
3
0
0
9
1
9
100
54
9
36
20
18
9
26
12
16
1
3
1
9
145,078
LasLabs/python-helpscout
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LasLabs_python-helpscout/helpscout/tests/test_apis_tags.py
helpscout.tests.test_apis_tags.TestApisTags
class TestApisTags(ApiCommon): """Tests the Tags API endpoint.""" def setUp(self): super(TestApisTags, self).setUp() self.__endpoint__ = self.api.Tags @recorder.use_cassette() def test_apis_tags_get(self): """It should not be implemented.""" with self.assertRaises(NotImplementedError): self.__endpoint__.update(None) @recorder.use_cassette() def test_apis_tags_delete(self): """It should not be implemented.""" with self.assertRaises(NotImplementedError): self.__endpoint__.delete(None) @recorder.use_cassette() def test_apis_tags_update(self): """It should not be implemented.""" with self.assertRaises(NotImplementedError): self.__endpoint__.update(None) @recorder.use_cassette() def test_apis_tags_create(self): """It should not be implemented.""" with self.assertRaises(NotImplementedError): self.__endpoint__.create(None) @recorder.use_cassette() def test_apis_tags_list(self): """It should list the tags in the tag.""" self._test_list() @recorder.use_cassette() def test_apis_tags_search(self): """It should not be implemented.""" with self.assertRaises(NotImplementedError): self.__endpoint__.search([], None)
class TestApisTags(ApiCommon): '''Tests the Tags API endpoint.''' def setUp(self): pass @recorder.use_cassette() def test_apis_tags_get(self): '''It should not be implemented.''' pass @recorder.use_cassette() def test_apis_tags_delete(self): '''It should not be implemented.''' pass @recorder.use_cassette() def test_apis_tags_update(self): '''It should not be implemented.''' pass @recorder.use_cassette() def test_apis_tags_create(self): '''It should not be implemented.''' pass @recorder.use_cassette() def test_apis_tags_list(self): '''It should list the tags in the tag.''' pass @recorder.use_cassette() def test_apis_tags_search(self): '''It should not be implemented.''' pass
14
7
4
0
3
1
1
0.26
1
2
0
0
7
1
7
98
41
7
27
15
13
7
21
9
13
1
3
1
7
145,079
LasLabs/python-helpscout
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LasLabs_python-helpscout/helpscout/tests/test_request_paginator.py
helpscout.tests.test_request_paginator.TestRequestPaginator
class TestRequestPaginator(unittest.TestCase): REQUEST_TYPES = ['get', 'delete', 'post', 'put'] def setUp(self): self.vals = { 'endpoint': 'endpoint', 'data': {'param': 1}, 'output_type': dict, } self.test_responses = [ { 'page': 1, 'pages': 3, 'items': [{ 'page': 1, }], }, { 'page': 2, 'pages': 3, 'items': [{ 'page': 2, }], }, { 'page': 3, 'pages': 3, # This one emulates a singleton 'item': { 'page': 3, }, }, ] self.paginator = RequestPaginator(**self.vals) @contextmanager def mock_session(self, response_code=200, responses=None, mock_attrs=None): if mock_attrs is None: mock_attrs = ['get', 'delete', 'post', 'put'] elif isinstance(mock_attrs, str): mock_attrs = [mock_attrs] with mock.patch.object(self.paginator, 'session') as session: response = mock.MagicMock() response.status_code = response_code response.json.side_effect = responses response.json.return_value = responses session.request.return_value = response yield session def do_call(self, request_type='get', responses=None): self.params = {'param_test': 23234} with self.mock_session(mock_attrs=request_type, responses=responses) as session: return session, getattr(self.paginator, request_type)(self.params) def _test_result(self, res): self.assertEqual(len(res), 1) self.assertDictEqual(res[0], self.test_responses[0]['items'][0]) def _test_session_call_json(self, session, request_type): session.request.assert_called_once_with( request_type, url=self.vals['endpoint'], json=self.params, verify=True, ) def test_init_attrs(self): """ It should correctly assign instance attributes. """ attrs = { attr: getattr(self.paginator, attr) for attr in self.vals.keys() } self.assertDictEqual(attrs, self.vals) @mock.patch('helpscout.request_paginator.requests') def test_init_session(self, requests): """ It should initialize a requests session. """ paginator = RequestPaginator(**self.vals) self.assertEqual(paginator.session, requests.Session()) def test_get_gets(self): """ It should call the session with proper args. """ session, _ = self.do_call(responses=self.test_responses) session.request.assert_called_once_with( 'get', url=self.vals['endpoint'], params=self.params, verify=True, ) def test_returns(self): """The returns should all return properly.""" for request_type in self.REQUEST_TYPES: _, res = self.do_call(request_type, self.test_responses) self._test_result(res) def test_delete_return_null_response_body(self): """The delete return should be None if response body is null.""" _, res = self.do_call('delete', None) self.assertEqual(res, None) def test_session_calls(self): """The calls should all be handled properly (tests all but GET).""" self.REQUEST_TYPES.remove('get') for request_type in self.REQUEST_TYPES: session, _ = self.do_call(request_type, self.test_responses) self._test_session_call_json(session, request_type) def test_call_get(self): """It should get when the request type is GET.""" params = {'param_test': 23234} self.paginator.request_type = self.paginator.GET with mock.patch.object(self.paginator, 'get') as get: self.paginator.call(params) get.assert_called_once_with(params) def test_call_post(self): """It should post when the request type is POST.""" params = {'param_test': 23234} self.paginator.request_type = self.paginator.POST with mock.patch.object(self.paginator, 'post') as post: self.paginator.call(params) post.assert_called_once_with(params) def test_iter(self): """ It should iterate until the end & yield data. """ with self.mock_session() as session: session.request().json.side_effect = self.test_responses res = list(self.paginator) expect = [{'page': 1}, {'page': 2}, {'page': 3}] self.assertEqual(res, expect)
class TestRequestPaginator(unittest.TestCase): def setUp(self): pass @contextmanager def mock_session(self, response_code=200, responses=None, mock_attrs=None): pass def do_call(self, request_type='get', responses=None): pass def _test_result(self, res): pass def _test_session_call_json(self, session, request_type): pass def test_init_attrs(self): ''' It should correctly assign instance attributes. ''' pass @mock.patch('helpscout.request_paginator.requests') def test_init_session(self, requests): ''' It should initialize a requests session. ''' pass def test_get_gets(self): ''' It should call the session with proper args. ''' pass def test_returns(self): '''The returns should all return properly.''' pass def test_delete_return_null_response_body(self): '''The delete return should be None if response body is null.''' pass def test_session_calls(self): '''The calls should all be handled properly (tests all but GET).''' pass def test_call_get(self): '''It should get when the request type is GET.''' pass def test_call_post(self): '''It should post when the request type is POST.''' pass def test_iter(self): ''' It should iterate until the end & yield data. ''' pass
17
9
8
0
7
1
1
0.09
1
4
1
0
14
4
14
86
133
15
108
41
90
10
65
33
50
3
2
1
18
145,080
LasLabs/python-helpscout
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LasLabs_python-helpscout/helpscout/tests/test_base_api.py
helpscout.tests.test_base_api.TestBaseApi
class TestBaseApi(unittest.TestCase): ENDPOINT = '/endpoint' DATA = {'test': 1234} REQUEST_TYPE = RequestPaginator.POST def new_api(self, endpoint=ENDPOINT, data=DATA, request_type=REQUEST_TYPE, singleton=False, session=None, out_type=None): return TestApi( endpoint, data, request_type, singleton, session, out_type, ) def test_new(self): """It should return a new TestApi instance.""" self.assertIsInstance(self.new_api(), TestApi) def test_new_paginator(self): """It should return a new API object with a paginator.""" self.assertIsInstance(self.new_api().paginator, RequestPaginator) def test_new_paginator_create(self): """It should create the paginator with the proper args.""" session = 'session' with mock.patch.object(RequestPaginator, '__init__') as init: init.return_value = None self.new_api(session=session) init.assert_called_once_with( endpoint='https://api.helpscout.net/v1%s' % self.ENDPOINT, data=self.DATA, output_type=TestApi.__object__.from_api, request_type=self.REQUEST_TYPE, session=session, ) @mock.patch(PAGINATOR) def test_new_paginator_singleton(self, paginator): """It should return the record if singleton and found.""" paginator().call.return_value = [{'id': 9876}] res = self.new_api(singleton=True) self.assertIsInstance(res, BaseModel) self.assertEqual(res.id, 9876) @mock.patch(PAGINATOR) def test_new_paginator_singleton_not_found(self, paginator): """It should return None if singleton and not found.""" paginator().call.return_value = [] res = self.new_api(singleton=True) self.assertIs(res, None) @mock.patch(PAGINATOR) def test_new_paginator_singleton_none(self, paginator): """It should return None if singleton and return value is None.""" paginator().call.return_value = None res = self.new_api(singleton=True) self.assertIs(res, None) @mock.patch(PAGINATOR) def test_base_api_iterates_paginator(self, paginator): """It should pass iteration to the paginator.""" expect = [BaseModel(id=1), BaseModel(id=2)] paginator().call.return_value = expect for idx, value in enumerate(self.new_api()): self.assertEqual(value, expect[idx]) @mock.patch(PAGINATOR) def test_new_paginator_singleton_out_type(self, paginator): """It should return an object of the correct type if defined.""" paginator().call.return_value = [{'id': 9876}] res = self.new_api(singleton=True, out_type=mock.MagicMock()) self.assertIsInstance(res, mock.MagicMock) def test_get_search_domain_domain(self): """It should return the input if it is a `Domain` obj.""" expect = Domain() self.assertEqual(BaseApi.get_search_domain(expect), expect) def test_get_search_domain_tuple(self): """It should return the input if it is a `Domain` obj.""" expect = [('state', True)] with mock.patch.object(Domain, 'from_tuple') as from_tuple: res = BaseApi.get_search_domain(expect) from_tuple.assert_called_once_with(expect) self.assertEqual(res, from_tuple()) def test_new_object(self): """It should return the proper object.""" expect = 123 res = BaseApi.new_object({'id': expect}) self.assertIsInstance(res, BaseModel) self.assertEqual(res.id, expect)
class TestBaseApi(unittest.TestCase): def new_api(self, endpoint=ENDPOINT, data=DATA, request_type=REQUEST_TYPE, singleton=False, session=None, out_type=None): pass def test_new(self): '''It should return a new TestApi instance.''' pass def test_new_paginator(self): '''It should return a new API object with a paginator.''' pass def test_new_paginator_create(self): '''It should create the paginator with the proper args.''' pass @mock.patch(PAGINATOR) def test_new_paginator_singleton(self, paginator): '''It should return the record if singleton and found.''' pass @mock.patch(PAGINATOR) def test_new_paginator_singleton_not_found(self, paginator): '''It should return None if singleton and not found.''' pass @mock.patch(PAGINATOR) def test_new_paginator_singleton_none(self, paginator): '''It should return None if singleton and return value is None.''' pass @mock.patch(PAGINATOR) def test_base_api_iterates_paginator(self, paginator): '''It should pass iteration to the paginator.''' pass @mock.patch(PAGINATOR) def test_new_paginator_singleton_out_type(self, paginator): '''It should return an object of the correct type if defined.''' pass def test_get_search_domain_domain(self): '''It should return the input if it is a `Domain` obj.''' pass def test_get_search_domain_tuple(self): '''It should return the input if it is a `Domain` obj.''' pass def test_new_object(self): '''It should return the proper object.''' pass
18
11
6
0
5
1
1
0.17
1
6
5
0
12
0
12
84
90
13
66
36
47
11
52
28
39
2
2
1
13
145,081
Laufire/ec
Laufire_ec/ec/types/adv.py
ec.types.adv.chain
class chain(CustomType): """Combines mutiple types into one. Args: *Types (Type): The types to chain. Kwargs: type_str (str): The description for the chain. Example: @arg(type=chain(exists, isabs), type_str="an existing abs path") """ def __init__(self, *Types, **Kwargs): CustomType.__init__(self, type_str=Kwargs.get('type_str', 'a chain of types (%s)' % ', '.join([getTypeStr(_type) for _type in Types]))) self.Types = Types self.CurrentType = None def __call__(self, val): for Type in self.Types: self.CurrentType = Type val = Type(val) return val def __str__(self): return getattr(self, 'type_str', str(self.CurrentType) if self.CurrentType else '')
class chain(CustomType): '''Combines mutiple types into one. Args: *Types (Type): The types to chain. Kwargs: type_str (str): The description for the chain. Example: @arg(type=chain(exists, isabs), type_str="an existing abs path") ''' def __init__(self, *Types, **Kwargs): pass def __call__(self, val): pass def __str__(self): pass
4
1
5
1
4
0
2
0.67
1
1
0
0
3
2
3
6
29
9
12
7
8
8
12
7
8
2
1
1
5
145,082
Laufire/ec
Laufire_ec/ec/types/multi.py
ec.types.multi.one_of
class one_of(CustomType): """Get a single item from a list of values. """ def __init__(self, choices, **Config): if not 'type_str' in Config: Config['type_str'] = 'one of %s' % Config.get('sep', ' / ').join(choices) CustomType.__init__(self, **Config) self.choices = choices def __call__(self, val): if not val in self.choices: raise ValueError() return val
class one_of(CustomType): '''Get a single item from a list of values. ''' def __init__(self, choices, **Config): pass def __call__(self, val): pass
3
1
6
2
5
0
2
0.2
1
1
0
0
2
1
2
5
16
4
10
4
7
2
10
4
7
2
1
1
4
145,083
Laufire/ec
Laufire_ec/ec/modules/classes.py
ec.modules.classes.Task
class Task(Member): r"""A callable class that allows the calling of the underlying function as a task. """ def __init__(self, Underlying, Args, Config): Member.__init__(self, Underlying, Config) self.Args = self.__load_args__(Args) def __load_args__(self, Args): r"""Prepares the task for excecution. """ FuncArgs = _getFuncArgs(self.Underlying) OrderedArgs = OrderedDict() # Note: the order of configuration (through decorators) is prefered over the order of declaration (within the function body) for Arg in Args: argName = Arg.get('name') if argName is None: if not FuncArgs: raise HandledException('Excess args while configuring "%s".' % self.Config['name']) FuncArg = FuncArgs.iteritems().next() # get the next free arg argName = FuncArg[0] FuncArg = FuncArg[1] else: validateName(argName) FuncArg = FuncArgs.get(argName) if FuncArg is None: raise HandledException('Unknown arg "%s" while configuring "%s".' % (argName, self.Config['name'])) FuncArg['name'] = argName FuncArg.update(Arg) # prefer Args config over the values given while defining the function. OrderedArgs[argName] = reconfigArg(FuncArg) del FuncArgs[argName] for name, Config in FuncArgs.iteritems(): # process the unconfigured arguments Config['name'] = name OrderedArgs[name] = reconfigArg(Config) return OrderedArgs def __confirm_known_args__(self, InArgs): r"""Confirms that only known args are passed to the underlying. """ ArgKeys = self.Args.keys() for k in InArgs.keys(): if k not in ArgKeys: raise HandledException('Unknown arg: %s.' % k, Member=self) def __digest_args__(self, InArgs, InKwArgs): r"""Digests the given Args and KwArgs and returns a KwArgs dictionary. """ KwArgs = {} ArgKeys = self.Args.keys() for arg in InArgs: key = ArgKeys.pop(0) if key in InKwArgs: raise HandledException('Multiple assignments for the arg "%s".' % key) KwArgs[key] = arg KwArgs.update(InKwArgs) self.__confirm_known_args__(KwArgs) return KwArgs def __call__(self, *InArgs, **InKwArgs): KwArgs = self.__digest_args__(InArgs, InKwArgs) for name, Arg in self.Args.items(): _type = Arg.get('type') if not name in KwArgs: if 'default' in Arg: default = Arg['default'] KwArgs[name] = default else: type_str = Arg.get('type_str') raise HandledException('Missing argument: "%s"%s.' % (name, (', expected %s' % type_str) if type_str else ''), Member=self) else: if _type: try: KwArgs[name] = _type(KwArgs[name]) except (ValueError, TypeError): raise HandledException('Invalid value for "%s", expected %s; got "%s".' % (name, Arg.get('type_str', _type), KwArgs[name]), help_type='task', Member=self) return self.Underlying(**KwArgs) def __collect_n_call__(self, *InArgs, **InKwArgs): r"""Helps with collecting all the args and call the Task. """ KwArgs = self.__digest_args__(InArgs, InKwArgs) for name, Arg in self.Args.items(): if not name in KwArgs: KwArgs[name] = gatherInput(**Arg) else: _type = Arg.get('type') try: KwArgs[name] = _type(KwArgs[name]) if _type else KwArgs[name] except (ValueError, TypeError): KwArgs[name] = gatherInput(**Arg) return self.Underlying(**KwArgs)
class Task(Member): '''A callable class that allows the calling of the underlying function as a task. ''' def __init__(self, Underlying, Args, Config): pass def __load_args__(self, Args): '''Prepares the task for excecution. ''' pass def __confirm_known_args__(self, InArgs): '''Confirms that only known args are passed to the underlying. ''' pass def __digest_args__(self, InArgs, InKwArgs): '''Digests the given Args and KwArgs and returns a KwArgs dictionary. ''' pass def __call__(self, *InArgs, **InKwArgs): pass def __collect_n_call__(self, *InArgs, **InKwArgs): '''Helps with collecting all the args and call the Task. ''' pass
7
5
18
5
12
2
4
0.19
1
4
1
0
6
1
6
7
118
34
74
28
67
14
70
28
63
7
1
4
25
145,084
Laufire/ec
Laufire_ec/ec/modules/classes.py
ec.modules.classes.Member
class Member(): r"""The base class for the classes Task and Group. It brands the given underlying with the __ec_member__ attr, which is used to identify the Underlying as processable by ec. """ def __init__(self, Underlying, Config): __ec_member__ = getattr(Underlying, '__ec_member__', None) if 'name' in Config: validateName(Config['name']) else: Config['name'] = getattr(Underlying, 'func_name', Underlying.__name__).rsplit('.', 1)[-1] if __ec_member__: __ec_member__.Config.update(Config) self.Config = __ec_member__.Config else: Underlying.__ec_member__ = self self.Config = Config self.Underlying = Underlying
class Member(): '''The base class for the classes Task and Group. It brands the given underlying with the __ec_member__ attr, which is used to identify the Underlying as processable by ec. ''' def __init__(self, Underlying, Config): pass
2
1
17
4
13
0
3
0.21
0
0
0
2
1
2
1
1
22
5
14
5
12
3
12
5
10
3
0
1
3
145,085
Laufire/ec
Laufire_ec/ec/modules/classes.py
ec.modules.classes.HandledException
class HandledException(Exception): r"""A custom error class for ec's internal exceptions, which are handled within ec. """ def __init__(self, e, **Info): self.Info = Info super(HandledException, self).__init__(getattr(e, 'message', e))
class HandledException(Exception): '''A custom error class for ec's internal exceptions, which are handled within ec. ''' def __init__(self, e, **Info): pass
2
1
3
0
3
0
1
0.5
1
1
0
0
1
1
1
11
7
1
4
3
2
2
4
3
2
1
3
0
1
145,086
Laufire/ec
Laufire_ec/ec/modules/classes.py
ec.modules.classes.Group
class Group(Member): r"""Groups can contain other Members (Tasks / Groups). Note: Groups that have modules as their underlying would have it's members loaded by ec.start. """ def __init__(self, Underlying, Config): Member.__init__(self, Underlying, Config or {})
class Group(Member): '''Groups can contain other Members (Tasks / Groups). Note: Groups that have modules as their underlying would have it's members loaded by ec.start. ''' def __init__(self, Underlying, Config): pass
2
1
2
0
2
0
1
1.33
1
0
0
0
1
0
1
2
8
1
3
2
1
4
3
2
1
1
1
0
1
145,087
Laufire/ec
Laufire_ec/ec/types/adv.py
ec.types.adv.invert
class invert(CustomType): """Inverts the given type. ie: Only failed values are qualified. Args: type_str (str): The description for the type. Example: @arg(type=invert(exists), type_str="a free path") """ def __init__(self, Type, type_str=None): CustomType.__init__(self, type_str=type_str or 'anything but, %s' % getTypeStr(Type)) self.Type = Type def __call__(self, val): try: self.Type(val) except (ValueError, TypeError): return val raise ValueError()
class invert(CustomType): '''Inverts the given type. ie: Only failed values are qualified. Args: type_str (str): The description for the type. Example: @arg(type=invert(exists), type_str="a free path") ''' def __init__(self, Type, type_str=None): pass def __call__(self, val): pass
3
1
7
2
5
0
2
0.7
1
2
0
0
2
1
2
5
26
9
10
4
7
7
10
4
7
2
1
1
3
145,088
Laufire/ec
Laufire_ec/ec/types/adv.py
ec.types.adv.t2t
class t2t(CustomType): """Convert a ec task into a type. Args: __ec__task__: Any ec task. """ def __init__(self, __ec__task__, **Defaults): __ec_member__ = __ec__task__.__ec_member__ Config = __ec_member__.Config CustomType.__init__(self, type_str=Config['desc']) self.Task = __ec_member__ self.Defaults = Defaults def __call__(self, val): KwArgs = self.Defaults.copy() DigestableArgs = getDigestableArgs(shlex.split(val)) KwArgs.update(**DigestableArgs[1]) return self.Task.__collect_n_call__(*DigestableArgs[0], **KwArgs)
class t2t(CustomType): '''Convert a ec task into a type. Args: __ec__task__: Any ec task. ''' def __init__(self, __ec__task__, **Defaults): pass def __call__(self, val): pass
3
1
7
2
6
0
1
0.33
1
0
0
0
2
2
2
5
21
5
12
9
9
4
12
9
9
1
1
0
2
145,089
Laufire/ec
Laufire_ec/ec/types/basics.py
ec.types.basics.YN
class YN(CustomType): """The classic y/n input that returns a truthy/falsy value. """ def __init__(self, **Config): if not 'type_str' in Config: Config['type_str'] = 'y/n' CustomType.__init__(self, **Config) def __ec_config__(self, ArgConfig): default = ArgConfig.get('default') ArgConfig['type_str'] = '%s%s' % (self.str, (' (%s)' % ('y' if default else 'n' if isinstance(default, bool) else default)) if 'default' in ArgConfig else '') return ArgConfig def __call__(self, val): if not val: # we've got an empty string raise ValueError() if val in 'yY': return True elif val in 'nN': return False raise ValueError()
class YN(CustomType): '''The classic y/n input that returns a truthy/falsy value. ''' def __init__(self, **Config): pass def __ec_config__(self, ArgConfig): pass def __call__(self, val): pass
4
1
7
2
5
0
3
0.18
1
2
0
0
3
0
3
6
27
8
17
5
13
3
16
5
12
4
1
1
10
145,090
Laufire/ec
Laufire_ec/ec/types/multi.py
ec.types.multi.menu
class menu(CustomType): """A numbered menu. """ def __init__(self, choices, **Config): if not 'type_str' in Config: Config['type_str'] = self._get_str(choices) CustomType.__init__(self, **Config) self.choices = choices def __call__(self, val): try: val = int(val) if not 0 < val <= len(self.choices): raise Exception('') return self.choices[val - 1] except: raise ValueError() def _get_str(self, choices): ret = 'Menu:\n' n = 0 for n in range(0, len(choices)): ret += '\t%s: %s\n' % (n + 1, choices[n]) return ret
class menu(CustomType): '''A numbered menu. ''' def __init__(self, choices, **Config): pass def __call__(self, val): pass def _get_str(self, choices): pass
4
1
9
2
6
0
2
0.1
1
4
0
0
3
1
3
6
31
9
20
7
16
2
20
7
16
3
1
2
7
145,091
Laufire/ec
Laufire_ec/ec/types/multi.py
ec.types.multi.multi
class multi(CustomType): """Get a list of inputs, separated by the given separator. """ def __init__(self, separator=', ', **Config): if not 'type_str' in Config: Config['type_str'] = 'a list of strings separated by \'%s\'' % separator CustomType.__init__(self, **Config) self.separator = separator def __call__(self, val): return val.split(self.separator)
class multi(CustomType): '''Get a list of inputs, separated by the given separator. ''' def __init__(self, separator=', ', **Config): pass def __call__(self, val): pass
3
1
5
1
4
0
2
0.25
1
0
0
0
2
1
2
5
13
3
8
4
5
2
8
4
5
2
1
1
3
145,092
Laufire/ec
Laufire_ec/ec/types/multi.py
ec.types.multi.some_of
class some_of(CustomType): """Get mutilple items from a list of choices. """ def __init__(self, choices, separator=', ', **Config): if not 'type_str' in Config: Config['type_str'] = 'some of: %s' % separator.join(choices) CustomType.__init__(self, **Config) self.choices = choices self.separator = separator def __call__(self, val): values = val.split(self.separator) if [value for value in values if value not in self.choices]: raise ValueError() return values
class some_of(CustomType): '''Get mutilple items from a list of choices. ''' def __init__(self, choices, separator=', ', **Config): pass def __call__(self, val): pass
3
1
8
2
6
0
2
0.17
1
1
0
0
2
2
2
5
19
5
12
6
9
2
12
6
9
2
1
1
4
145,093
Laufire/ec
Laufire_ec/tests/support/helpers.py
tests.support.helpers.RawInputHook
class RawInputHook: """Hooks into __builtin__.raw_input and returns the values provided by Hook.values, on by one untill the values are exhausted; then the hook is removed. """ def __init__(self): self.origCall = __builtin__.raw_input self._values = None def _hookOnce(self, dummy): value = self._values.pop(0) if not self._values: # reset the hooks __builtin__.raw_input = self.origCall return value def values(self, *val): self._values = list(val) __builtin__.raw_input = self._hookOnce
class RawInputHook: '''Hooks into __builtin__.raw_input and returns the values provided by Hook.values, on by one untill the values are exhausted; then the hook is removed. ''' def __init__(self): pass def _hookOnce(self, dummy): pass def values(self, *val): pass
4
1
4
1
4
0
1
0.25
0
1
0
0
3
2
3
3
18
4
12
7
8
3
12
7
8
2
0
1
4
145,094
Laufire/ec
Laufire_ec/ec/types/path.py
ec.types.path.PathBase
class PathBase(CustomType): """The base class for several path types. Args: func (callable): The function to process the value. ret : The expected return value from func. The values that ail the expectation are invalid. **Config (kwargs): Configuration for the custom type. """ def __init__(self, func, ret=True, **Config): CustomType.__init__(self, **Config) self.func = func self.ret = ret def __call__(self, val): if self.func(val) == self.ret: return val raise ValueError()
class PathBase(CustomType): '''The base class for several path types. Args: func (callable): The function to process the value. ret : The expected return value from func. The values that ail the expectation are invalid. **Config (kwargs): Configuration for the custom type. ''' def __init__(self, func, ret=True, **Config): pass def __call__(self, val): pass
3
1
5
1
4
0
2
0.67
1
1
0
0
2
2
2
5
19
4
9
5
6
6
9
5
6
2
1
1
3
145,095
Laufire/ec
Laufire_ec/ec/types/regex.py
ec.types.regex.pattern
class pattern(CustomType): r"""Get inputs that fit a specific pattern. """ def __init__(self, pattern, flags=0, converter=None, **Config): self.exp = re.compile(pattern, flags) if not 'type_str' in Config: Config['type_str'] = 'a string matching the pattern \'%s\'' % self.exp.pattern self.converter = converter CustomType.__init__(self, **Config) def __call__(self, val): if not self.exp.match(val): raise ValueError() converter = self.converter return converter(val) if converter else val
class pattern(CustomType): '''Get inputs that fit a specific pattern. ''' def __init__(self, pattern, flags=0, converter=None, **Config): pass def __call__(self, val): pass
3
1
8
3
6
0
3
0.17
1
1
0
0
2
2
2
5
20
6
12
6
9
2
12
6
9
3
1
1
5
145,096
Laufire/ec
Laufire_ec/ec/utils.py
ec.utils.custom
class custom(CustomType): r"""Helps with creating dynamic CustomTypes on the fly. Args: validator (callable): Validates the input. converter (callable): Converts the input. Defaults to None. \*\*Config (kwargs): The configuration of the CustomType. #Later: Think of merging the validator and the converter. """ def __init__(self, validator=None, converter=None, **Config): CustomType.__init__(self, **Config) self.validator = validator self.converter = converter def __call__(self, val): if self.converter: val = self.converter(val) if self.validator and not self.validator(val): raise ValueError() return val
class custom(CustomType): '''Helps with creating dynamic CustomTypes on the fly. Args: validator (callable): Validates the input. converter (callable): Converts the input. Defaults to None. \*\*Config (kwargs): The configuration of the CustomType. #Later: Think of merging the validator and the converter. ''' def __init__(self, validator=None, converter=None, **Config): pass def __call__(self, val): pass
3
1
7
2
5
0
2
0.64
1
1
0
0
2
2
2
5
24
6
11
5
8
7
11
5
8
3
1
1
4
145,097
Laufire/ec
Laufire_ec/ec/modules/classes.py
ec.modules.classes.CustomType
class CustomType: r"""The base class for custom types. Args: **Config (kwargs): Configuration for the custom type. Config: type_str (str, optional): The string representation of the type. Note: Config supports the same keywords as config.arg, with some additions to it. While inheriting the class, these keywords shouldn't be used as variable names. """ def __init__(self, **Config): self._Config = Config self.str = Config['type_str'] if 'type_str' in Config else 'custom type' def __str__(self): r"""Used to represent the type as a string, in messages and queries. """ return getattr(self, 'str', 'custom type') def __ec_config__(self, ArgConfig): r"""Used to reconfigure arg configurations. Args: ArgConfig (dict): The configuration to be modified. Returns: ArgConfig (dict): The modified configuration. Notes: * This method allows CustomTypes to modify the configuration of the calling arg. * This is the signature method used for duck typing CustomType. * With custom implementations the method should set the key 'type_str', as well as return the modified ArgConfig. """ if not 'type_str' in ArgConfig: ArgConfig['type_str'] = self.str return ArgConfig
class CustomType: '''The base class for custom types. Args: **Config (kwargs): Configuration for the custom type. Config: type_str (str, optional): The string representation of the type. Note: Config supports the same keywords as config.arg, with some additions to it. While inheriting the class, these keywords shouldn't be used as variable names. ''' def __init__(self, **Config): pass def __str__(self): '''Used to represent the type as a string, in messages and queries. ''' pass def __ec_config__(self, ArgConfig): '''Used to reconfigure arg configurations. Args: ArgConfig (dict): The configuration to be modified. Returns: ArgConfig (dict): The modified configuration. Notes: * This method allows CustomTypes to modify the configuration of the calling arg. * This is the signature method used for duck typing CustomType. * With custom implementations the method should set the key 'type_str', as well as return the modified ArgConfig. ''' pass
4
3
9
2
3
4
2
2
0
0
0
12
3
2
3
3
40
10
10
6
6
20
10
6
6
2
0
1
5
145,098
Laufire/ec
Laufire_ec/tests/test_configuration.py
tests.test_configuration.TestConfiguration
class TestConfiguration(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_verify_configuration(self): Members = simple.__ec_member__.Members assert(set(['task1', 't1', 'group1', 'ex', 'hex']) == set(Members.keys())) assert(set(['task1']) == set(Members['group1'].Members.keys()))
class TestConfiguration(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_verify_configuration(self): pass
4
0
3
0
3
0
1
0
1
1
0
0
3
0
3
75
12
3
9
5
5
0
9
5
5
1
2
0
3
145,099
Laufire/ec
Laufire_ec/tests/test_dir_group.py
tests.test_dir_group.TestDirGroupOnLaunchers
class TestDirGroupOnLaunchers(unittest.TestCase): def setUp(self): self.checkResult = lambda *args: checkResult(self, *args) def tearDown(self): pass def test_entry_point_launch(self): Result = shell_exec('ec tests/targets simple/task1 arg1=1') self.checkResult(Result, Result['code'] == 0, Result['out'].strip().find('1 2') == 0, ) def test_module_launch(self): Result = shell_exec('python -m ec tests/targets simple/task1 arg1=1') self.checkResult(Result, Result['code'] == 0, Result['out'].strip().find('1 2') == 0, )
class TestDirGroupOnLaunchers(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_entry_point_launch(self): pass def test_module_launch(self): pass
5
0
5
1
4
0
1
0
1
0
0
0
4
1
4
76
23
6
17
8
12
0
11
8
6
1
2
0
4
145,100
Laufire/ec
Laufire_ec/tests/test_dispatch.py
tests.test_dispatch.TestDispatch
class TestDispatch(unittest.TestCase): def setUp(self): self.checkResult = lambda *args: checkResult(self, *args) def tearDown(self): pass def launch_ec(self, argStr='', input='', flag=''): r"""Dispatches command to the target script. """ command = 'python tests/targets/simple.py' if flag: command += ' %s' % flag if argStr: command += ' %s' % argStr return shell_exec(command, input=input) def test_dispatch(self): Result = self.launch_ec('task1 arg1=1') self.checkResult(Result, Result['code'] == 0, Result['out'].strip() == '1 2', ) def test_multiple_args(self): Result = self.launch_ec('task1 arg1=1 arg2=1') self.checkResult(Result, Result['code'] == 0, Result['out'].strip() == '1 1', ) def test_positional_args(self): Result = self.launch_ec('task1 1') self.checkResult(Result, Result['code'] == 0, Result['out'].strip() == '1 2', ) def test_mixed_args(self): Result = self.launch_ec('task1 1 arg2=1') self.checkResult(Result, Result['code'] == 0, Result['out'].strip() == '1 1', ) def test_flag_help(self): Result = self.launch_ec(flag='-h') self.checkResult(Result, Result['code'] == 0, Result['out'].strip()[:5] == 'Usage', ) def test_flag_help_task(self): Result = self.launch_ec(flag='-h', argStr='task1') self.checkResult(Result, Result['code'] == 0, Result['out'].find('Args:') > -1, ) def test_flag_help_group(self): Result = self.launch_ec(flag='-h', argStr='group1') self.checkResult(Result, Result['code'] == 0, Result['out'].find('task1') > -1, ) def test_flag_help_subgroup(self): Result = self.launch_ec(flag='-h', argStr='group1/task1') self.checkResult(Result, Result['code'] == 0, Result['out'].find('Args:') > -1, ) def test_flag_partial(self): Result = self.launch_ec('task1 arg1=1', '1', '-p') self.checkResult(Result, Result['code'] == 0, Result['out'][-5:-1].strip() == '1 1' ) def test_absent_task(self): Result = self.launch_ec('task2') self.checkResult(Result, Result['code'] == 1, Result['err'].strip()[:2] == 'No', Result['err'].find('------') > -1, # check whether a help string is presented ) def test_nested_task(self): Result = self.launch_ec('group1/task1 arg1=1') self.checkResult(Result, Result['code'] == 0, Result['out'].strip() == '1', ) def test_default_arg(self): Result = self.launch_ec('task1 arg1=1') self.checkResult(Result, Result['code'] == 0, Result['out'].strip() == '1 2', ) def test_alias(self): Result = self.launch_ec('t1 arg1=1') self.checkResult(Result, Result['code'] == 0, Result['out'].strip() == '1 2', ) def test_handled_exception(self): Result = self.launch_ec('hex') err = Result['err'] self.checkResult(Result, Result['code'] == 1, err.find('Invalid') > -1, err.find('arg1') > -1, err.find('int') > -1, err.find('got') > -1, ) def test_exception(self): Result = self.launch_ec('ex') self.checkResult(Result, Result['code'] == 1, Result['err'].strip() == 'integer division or modulo by zero', ) def test_exit_hook(self): Result = shell_exec('python tests/targets/allied.py t1 1') self.checkResult(Result, Result['code'] == 0, Result['out'].find(str(range(1, 10))) > -1, )
class TestDispatch(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def launch_ec(self, argStr='', input='', flag=''): '''Dispatches command to the target script. ''' pass def test_dispatch(self): pass def test_multiple_args(self): pass def test_positional_args(self): pass def test_mixed_args(self): pass def test_flag_help(self): pass def test_flag_help_task(self): pass def test_flag_help_group(self): pass def test_flag_help_subgroup(self): pass def test_flag_partial(self): pass def test_absent_task(self): pass def test_nested_task(self): pass def test_default_arg(self): pass def test_alias(self): pass def test_handled_exception(self): pass def test_exception(self): pass def test_exit_hook(self): pass
20
1
7
1
6
0
1
0.03
1
2
0
3
19
1
19
91
153
38
113
39
93
3
61
39
41
3
2
1
21
145,101
Laufire/ec
Laufire_ec/tests/test_entry_point_launch.py
tests.test_entry_point_launch.TestEntryPointLaunch
class TestEntryPointLaunch(TestDispatch): def launch_ec(self, argStr='', input='', flag=''): r"""Dispatches command to the target script. """ command = 'ec tests/targets/simple.py' if flag: command += ' %s' % flag if argStr: command += ' %s' % argStr return shell_exec(command, input=input)
class TestEntryPointLaunch(TestDispatch): def launch_ec(self, argStr='', input='', flag=''): '''Dispatches command to the target script. ''' pass
2
1
13
4
7
2
3
0.25
1
0
0
0
1
0
1
92
14
4
8
3
6
2
8
3
6
3
3
1
3
145,102
Laufire/ec
Laufire_ec/tests/test_inscript_calls.py
tests.test_inscript_calls.TestInscriptCalls
class TestInscriptCalls(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_task_call(self): r"""Test whether the tasks are callable as functions. """ assert(task1(1) == (1, 2)) def test_group_task_call(self): r"""Test whether the group tasks are callable as (static) functions. """ assert(group1.task1(1) == 1) def test_ec_call(self): r"""Test ec.call with partial arguments """ RIH.values(2, 3) assert(call(task1, arg1=1) == (1, 2))
class TestInscriptCalls(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_task_call(self): '''Test whether the tasks are callable as functions. ''' pass def test_group_task_call(self): '''Test whether the group tasks are callable as (static) functions. ''' pass def test_ec_call(self): '''Test ec.call with partial arguments ''' pass
6
3
3
0
2
1
1
0.5
1
2
2
0
5
0
5
77
22
4
12
6
6
6
12
6
6
1
2
0
5
145,103
Laufire/ec
Laufire_ec/tests/test_interface.py
tests.test_interface.TestInterface
class TestInterface(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_call(self): assert(interface.call('task1 arg1=1') == (1, 2)) def test_positional_args(self): assert(interface.call('task1 1') == (1, 2)) def test_mixed_args(self): assert(interface.call('task1 1 arg2=1') == (1, 1)) def test_handled_exception(self): assert(expect_exception(lambda: interface.call('task2'), HandledException)) def test_unhandled_exception(self): assert(expect_exception(lambda: interface.call('ex'), ZeroDivisionError)) def test_call_with_input(self): from support.helpers import RawInputHook as RIH RIH.values(2, 3) assert(interface.call('task1 arg1=1', True) == (1, 2)) def test_resolve(self): assert(interface.resolve('task1').Config['name'] == 'task1') def test_args(self): Args = interface.resolve('task1').Args assert(len(Args.keys()) == 3) # Check Arg Order Order = ['arg1', 'arg2', 'arg3'] for k in Args.keys(): assert(k == Order.pop(0)) arg1 = Args['arg1'] assert(arg1['desc'] == 'Value for arg1') assert(arg1['type'] == int) def test_group(self): Group1 = interface.resolve('group1') Config = Group1.Config Members = Group1.Members Members = Group1.Members assert(len(Members.keys()) == 1) assert(Members['task1'] is not None) assert(Config['desc'] == 'Description for group1') def test_force_config(self): # ToDo: Test ec.interface.force_config. It needs to be tested within a ec script. pass def test_add(self): interface.add(simple, lambda arg1: arg1, dict(name='added'), [dict(name='arg1', type=int)]) assert(interface.call('added arg1=1') == 1) assert(expect_exception(lambda: interface.call('added arg1=a'), HandledException)) del simple.__ec_member__.Members['added']
class TestInterface(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_call(self): pass def test_positional_args(self): pass def test_mixed_args(self): pass def test_handled_exception(self): pass def test_unhandled_exception(self): pass def test_call_with_input(self): pass def test_resolve(self): pass def test_args(self): pass def test_group(self): pass def test_force_config(self): pass def test_add(self): pass
14
0
4
1
3
0
1
0.07
1
5
2
0
13
0
13
85
67
21
45
22
30
3
45
22
30
2
2
1
14
145,104
Laufire/ec
Laufire_ec/tests/test_module_launch.py
tests.test_module_launch.TestModuleLaunch
class TestModuleLaunch(TestDispatch): #pylint: disable=R0801 def launch_ec(self, argStr='', input='', flag=''): r"""Dispatches command to ec (loaded as a module). """ command = 'python -m ec tests/targets/simple.py' if flag: command += ' %s' % flag if argStr: command += ' %s' % argStr return shell_exec(command, input=input)
class TestModuleLaunch(TestDispatch): def launch_ec(self, argStr='', input='', flag=''): '''Dispatches command to ec (loaded as a module). ''' pass
2
1
13
4
7
2
3
0.38
1
0
0
0
1
0
1
92
14
4
8
3
6
3
8
3
6
3
3
1
3
145,105
Laufire/ec
Laufire_ec/tests/test_nested.py
tests.test_nested.TestNested
class TestNested(TestDispatch): def launch_ec(self, argStr='', input='', flag=''): """Dispatches command to a nested script. """ command = 'python tests/targets/nester.py' if flag: command += ' %s' % flag if argStr: command += ' simple/%s' % argStr return shell_exec(command, input=input)
class TestNested(TestDispatch): def launch_ec(self, argStr='', input='', flag=''): '''Dispatches command to a nested script. ''' pass
2
1
14
5
7
2
3
0.25
1
0
0
0
1
0
1
92
15
5
8
3
6
2
8
3
6
3
3
1
3
145,106
Laufire/ec
Laufire_ec/ec/types/num.py
ec.types.num.between
class between(CustomType): """Get a number within two numbers. """ def __init__(self, min, max, num_type=int, **Config): if not 'type_str' in Config: Config['type_str'] = 'a number between %s and %s' % (min, max) CustomType.__init__(self, **Config) self._min = min self._max = max self._num_type = num_type def __call__(self, val): value = self._num_type(val) if value < self._min or value > self._max: raise ValueError() return value
class between(CustomType): '''Get a number within two numbers. ''' def __init__(self, min, max, num_type=int, **Config): pass def __call__(self, val): pass
3
1
9
3
6
0
2
0.15
1
2
0
0
2
3
2
5
21
6
13
7
10
2
13
7
10
2
1
1
4
145,107
Laufire/ec
Laufire_ec/tests/test_shell.py
tests.test_shell.TestShell
class TestShell(unittest.TestCase): def setUp(self): self.checkResult = lambda *args: checkResult(self, *args) def tearDown(self): pass def test_task(self): Result = launch_ec('task1', '1', '2', '3') self.checkResult(Result, Result['code'] == 0, Result['out'].find('(1, 2)') > -1, ) def test_multiple_args(self): Result = launch_ec('task1 arg1=1 arg2=1') self.checkResult(Result, Result['code'] == 0, Result['out'].find('(1, 1)') > -1, ) def test_help(self): Result = launch_ec('h', '') out = Result['out'] self.checkResult(Result, Result['code'] == 0, out.find('task1') > -1, out.find('group1') > -1, out.find('task1') > -1, ) def test_absent_task(self): Result = launch_ec('task2') self.checkResult(Result, Result['code'] == 0, Result['err'].strip()[:2] == 'No', ) def test_nested_task(self): Result = launch_ec('group1/task1 arg1=100000') self.checkResult(Result, Result['code'] == 0, Result['out'].find('100000') > -1, ) def test_default_arg(self): Result = launch_ec('task1 arg1=1', '') self.checkResult(Result, Result['code'] == 0, Result['out'].find('(1, 2)') > -1, ) def test_alias(self): Result = launch_ec('t1 arg1=1', '') self.checkResult(Result, Result['code'] == 0, Result['out'].find('(1, 2)') > -1, )
class TestShell(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_task(self): pass def test_multiple_args(self): pass def test_help(self): pass def test_absent_task(self): pass def test_nested_task(self): pass def test_default_arg(self): pass def test_alias(self): pass
10
0
6
1
5
0
1
0
1
0
0
0
9
1
9
81
65
15
50
19
40
0
27
19
17
1
2
0
9
145,108
Laufire/ec
Laufire_ec/tests/test_utils.py
tests.test_utils.TestUtils
class TestUtils(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_get(self): Inputs = 'a', 1 RIH.values(*Inputs) # test the call assert(get('str') == Inputs[0]) assert(get('int', type=int) == Inputs[1]) def test_static(self): @static class cls: #pylint: disable=W0232 def method(val): return val assert(cls.method(1) == 1) def test_custom(self): _type = custom(lambda v: v%2 == 1, int, type_str='an odd number') assert(_type(1) == 1) assert(expect_exception(lambda: _type(2), ValueError)) assert(expect_exception(lambda: _type('a'), ValueError)) def test_walk(self): from targets import simple from ec import interface interface.setBase(simple) expected = set(['task1', 'group1', 'ex', 'hex']) got = set() for Member in walk(simple.__ec_member__): got.add(Member.Config['name']) assert(expected == got)
class TestUtils(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_get(self): pass def test_static(self): pass @static class cls: def method(val): pass def test_custom(self): pass def test_walk(self): pass
10
0
6
1
4
0
1
0.07
1
6
3
0
6
0
6
78
44
13
30
17
18
2
29
16
18
2
2
1
8
145,109
Laufire/ec
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Laufire_ec/tests/test_utils.py
tests.test_utils.TestUtils.test_static.cls
class cls: # pylint: disable=W0232 def method(val): return val
class cls: def method(val): pass
2
0
2
0
2
0
1
0.33
0
0
0
0
1
0
1
1
3
0
3
2
1
1
3
2
1
1
0
0
1
145,110
LeKono/pyhgnc
LeKono_pyhgnc/src/pyhgnc/manager/models.py
pyhgnc.manager.models.AliasSymbol
class AliasSymbol(Base, MasterModel): """Other symbols used to refer to this gene as seen in the "SYNONYMS" field in the symbol report. .. attention:: Symbols previously approved by the HGNC for this gene are tagged with `is_previous_symbol==True`. Equates to the "PREVIOUS SYMBOLS & NAMES" field within the gene symbol report. :cvar str alias_symbol: other symbol :cvar bool is_previous_symbol: previously approved :cvar hgnc: back populates to :class:`.HGNC` """ alias_symbol = Column(Unicode(255)) is_previous_symbol = Column(Boolean, default=False) hgnc_id = foreign_key_to('hgnc') hgnc = relationship('HGNC', back_populates='alias_symbols') def to_dict(self): return self.to_dict_with_hgnc() def __repr__(self): return self.alias_symbol
class AliasSymbol(Base, MasterModel): '''Other symbols used to refer to this gene as seen in the "SYNONYMS" field in the symbol report. .. attention:: Symbols previously approved by the HGNC for this gene are tagged with `is_previous_symbol==True`. Equates to the "PREVIOUS SYMBOLS & NAMES" field within the gene symbol report. :cvar str alias_symbol: other symbol :cvar bool is_previous_symbol: previously approved :cvar hgnc: back populates to :class:`.HGNC` ''' def to_dict(self): pass def __repr__(self): pass
3
1
2
0
2
0
1
1
2
0
0
0
2
0
2
7
25
7
9
7
6
9
9
7
6
1
2
0
2
145,111
LeKono/pyhgnc
LeKono_pyhgnc/src/pyhgnc/manager/models.py
pyhgnc.manager.models.PubMed
class PubMed(Base, MasterModel): """PubMed and Europe PubMed Central PMID :cvar str pubmedid: Pubmed identifier :cvar list hgncs: back populates to :class:`.HGNC` """ pubmedid = Column(Integer) hgncs = relationship( "HGNC", secondary=hgnc_pubmed, back_populates="pubmeds" ) def to_dict(self): return self.to_dict_with_hgncs() def __repr__(self): return str(self.pubmedid)
class PubMed(Base, MasterModel): '''PubMed and Europe PubMed Central PMID :cvar str pubmedid: Pubmed identifier :cvar list hgncs: back populates to :class:`.HGNC` ''' def to_dict(self): pass def __repr__(self): pass
3
1
2
0
2
0
1
0.36
2
1
0
0
2
0
2
7
19
4
11
5
8
4
7
5
4
1
2
0
2
145,112
LeKono/pyhgnc
LeKono_pyhgnc/src/pyhgnc/manager/models.py
pyhgnc.manager.models.OrthologyPrediction
class OrthologyPrediction(Base, MasterModel): """Orthology Predictions .. warning:: OrthologyPrediction is still not correctly normalized and documented. :cvar int ortholog_species: NCBI taxonomy identifier :cvar int human_entrez_gene: Human Entrey gene identifier :cvar str human_ensembl_gene: Human Ensembl gene identifier :cvar str human_name: Human gene name :cvar str human_symbol: Human gene symbol :cvar str human_chr: Human gene chromosome location :cvar str human_assert_ids: :cvar str ortholog_species_entrez_gene: Ortholog species Entrez gene identifier :cvar str ortholog_species_ensembl_gene: Ortholog species Ensembl gene identifier :cvar str ortholog_species_db_id: Ortholog species database identifier :cvar str ortholog_species_name: Ortholog species gene name :cvar str ortholog_species_symbol: Ortholog species gene symbol :cvar str ortholog_species_chr: Ortholog species gene chromosome location :cvar str ortholog_species_assert_ids: :cvar str support: :cvar hgnc: back populates to :class:`.HGNC` """ ortholog_species = Column(Integer) human_entrez_gene = Column(Integer) human_ensembl_gene = Column(String(255)) human_name = Column(String(255)) human_symbol = Column(Unicode(255)) human_chr = Column(String(255)) human_assert_ids = Column(String(255)) ortholog_species_entrez_gene = Column(Integer) ortholog_species_ensembl_gene = Column(String(255)) ortholog_species_db_id = Column(String(255)) ortholog_species_name = Column(Text) ortholog_species_symbol = Column(Unicode(255), index=True) ortholog_species_chr = Column(String(255)) ortholog_species_assert_ids = Column(String(255)) support = Column(String(255)) hgnc_id = foreign_key_to('hgnc') hgnc = relationship('HGNC', back_populates='orthology_predictions') def to_dict(self): return self.to_dict_with_hgnc() def __repr__(self): return '{}: {}: {}'.format(self.ortholog_species, self.ortholog_species_name, self.ortholog_species_symbol)
class OrthologyPrediction(Base, MasterModel): '''Orthology Predictions .. warning:: OrthologyPrediction is still not correctly normalized and documented. :cvar int ortholog_species: NCBI taxonomy identifier :cvar int human_entrez_gene: Human Entrey gene identifier :cvar str human_ensembl_gene: Human Ensembl gene identifier :cvar str human_name: Human gene name :cvar str human_symbol: Human gene symbol :cvar str human_chr: Human gene chromosome location :cvar str human_assert_ids: :cvar str ortholog_species_entrez_gene: Ortholog species Entrez gene identifier :cvar str ortholog_species_ensembl_gene: Ortholog species Ensembl gene identifier :cvar str ortholog_species_db_id: Ortholog species database identifier :cvar str ortholog_species_name: Ortholog species gene name :cvar str ortholog_species_symbol: Ortholog species gene symbol :cvar str ortholog_species_chr: Ortholog species gene chromosome location :cvar str ortholog_species_assert_ids: :cvar str support: :cvar hgnc: back populates to :class:`.HGNC` ''' def to_dict(self): pass def __repr__(self): pass
3
1
2
0
2
0
1
0.91
2
0
0
0
2
0
2
7
49
7
22
20
19
20
22
20
19
1
2
0
2
145,113
LeKono/pyhgnc
LeKono_pyhgnc/src/pyhgnc/manager/models.py
pyhgnc.manager.models.OMIM
class OMIM(Base, MasterModel): """Online Mendelian Inheritance in Man (OMIM) ID :cvar str omimid: OMIM ID :cvar hgnc: back populates to `pyhgnc.manager.models.HGNC` """ omimid = Column(Integer) hgnc_id = foreign_key_to('hgnc') hgnc = relationship('HGNC', back_populates='omims') def to_dict(self): return self.to_dict_with_hgnc() def __repr__(self): return str(self.omimid)
class OMIM(Base, MasterModel): '''Online Mendelian Inheritance in Man (OMIM) ID :cvar str omimid: OMIM ID :cvar hgnc: back populates to `pyhgnc.manager.models.HGNC` ''' def to_dict(self): pass def __repr__(self): pass
3
1
2
0
2
0
1
0.5
2
1
0
0
2
0
2
7
16
4
8
6
5
4
8
6
5
1
2
0
2
145,114
LeKono/pyhgnc
LeKono_pyhgnc/src/pyhgnc/manager/models.py
pyhgnc.manager.models.MasterModel
class MasterModel(object): """This class is the parent class of all models in PyHGNC. Automatic creation of table name by class name with project prefix""" @declared_attr def __tablename__(self): return TABLE_PREFIX + self.__name__.lower() __mapper_args__ = {'always_refresh': True} id = Column(Integer, primary_key=True) def _to_dict(self): data_dict = self.__dict__.copy() del data_dict['_sa_instance_state'] del data_dict['id'] for k, v in data_dict.items(): if isinstance(v, datetime.date): data_dict[k] = data_dict[k].strftime('%Y-%m-%d') return data_dict def to_dict(self): return self._to_dict() def to_dict_with_hgnc(self): ret_dict = self._to_dict() del ret_dict['hgnc_id'] ret_dict['hgnc_identifier'] = self.hgnc.identifier ret_dict['hgnc_symbol'] = self.hgnc.symbol return ret_dict def to_dict_with_hgncs(self): ret_dict = self._to_dict() ret_dict['hgnc_symbols'] = [x.symbol for x in self.hgncs] return ret_dict
class MasterModel(object): '''This class is the parent class of all models in PyHGNC. Automatic creation of table name by class name with project prefix''' @declared_attr def __tablename__(self): pass def _to_dict(self): pass def to_dict(self): pass def to_dict_with_hgnc(self): pass def to_dict_with_hgncs(self): pass
7
1
4
0
4
0
1
0.08
1
1
0
16
5
0
5
5
35
7
26
12
19
2
25
11
19
3
1
2
7
145,115
LeKono/pyhgnc
LeKono_pyhgnc/src/pyhgnc/manager/models.py
pyhgnc.manager.models.MGD
class MGD(Base, MasterModel): """Mouse genome informatics database ID. Found within the "HOMOLOGS" section of the gene symbol report :cvar str mgdid: Mouse genome informatics database ID :cvar list hgncs: back populates to :class:`.HGNC` """ mgdid = Column(Integer) hgncs = relationship( "HGNC", secondary=hgnc_mgd, back_populates="mgds" ) def to_dict(self): return self.to_dict_with_hgncs() def __repr__(self): return str(self.mgdid)
class MGD(Base, MasterModel): '''Mouse genome informatics database ID. Found within the "HOMOLOGS" section of the gene symbol report :cvar str mgdid: Mouse genome informatics database ID :cvar list hgncs: back populates to :class:`.HGNC` ''' def to_dict(self): pass def __repr__(self): pass
3
1
2
0
2
0
1
0.36
2
1
0
0
2
0
2
7
19
4
11
5
8
4
7
5
4
1
2
0
2
145,116
LeKono/pyhgnc
LeKono_pyhgnc/src/pyhgnc/manager/models.py
pyhgnc.manager.models.LSDB
class LSDB(Base, MasterModel): """The name of the Locus Specific Mutation Database and URL :cvar str lsdb: name of the Locus Specific Mutation Database :cvar str url: URL to database :cvar hgnc: back populates to :class:`.HGNC` """ lsdb = Column(String(255)) url = Column(Text) hgnc_id = foreign_key_to('hgnc') hgnc = relationship('HGNC', back_populates='lsdbs') def to_dict(self): return self.to_dict_with_hgnc() def __repr__(self): return self.lsdb
class LSDB(Base, MasterModel): '''The name of the Locus Specific Mutation Database and URL :cvar str lsdb: name of the Locus Specific Mutation Database :cvar str url: URL to database :cvar hgnc: back populates to :class:`.HGNC` ''' def to_dict(self): pass def __repr__(self): pass
3
1
2
0
2
0
1
0.56
2
0
0
0
2
0
2
7
19
5
9
7
6
5
9
7
6
1
2
0
2
145,117
LeKono/pyhgnc
LeKono_pyhgnc/src/pyhgnc/manager/models.py
pyhgnc.manager.models.HGNC
class HGNC(Base, MasterModel): """Root class (table, model) for all other classes (tables, models) in PyHGNC. Basic information with 1:1 relationship to identifier are stored here .. warning:: - homeodb (Homeobox Database ID) - horde_id (Symbol used within HORDE for the gene) described in `README <ftp://ftp.ebi.ac.uk/pub/databases/genenames/README.txt>`_, but not found in `HGNC JSON file <ftp://ftp.ebi.ac.uk/pub/databases/genenames/new/json/hgnc_complete_set.json>`_ .. hint:: To link to IUPHAR/BPS Guide to PHARMACOLOGY database only use the number (only use 1 from the result objectId:1) :cvar str name: HGNC approved name for the gene. Equates to the "APPROVED NAME" field within the gene symbol report :cvar str symbol: The HGNC approved gene symbol. Equates to the "APPROVED SYMBOL" field within the gene symbol report :cvar int orphanet: Orphanet ID :cvar str identifier: Unique ID created by the HGNC for every approved symbol (HGNC ID) :cvar str status: Status of the symbol report, which can be either "Approved" or "Entry Withdrawn" :cvar str uuid: universally unique identifier :cvar str locus_group: Group name for a set of related locus types as defined by the HGNC (e.g. non-coding RNA) :cvar str locus_type: Locus type as defined by the HGNC (e.g. RNA, transfer) :cvar date date_name_changed: date the gene name was last changed :cvar date date_modified: date the entry was last modified :cvar date date_symbol_changed: date the gene symbol was last changed :cvar date date_approved_reserved: date the entry was first approved :cvar str ensembl_gene: Ensembl gene ID. Found within the "GENE RESOURCES" section of the gene symbol report :cvar str horde: symbol used within HORDE for the gene (not available in JSON) :cvar str vega: Vega gene ID. Found within the "GENE RESOURCES" section of the gene symbol report :cvar str lncrnadb: Long Noncoding RNA Database identifier :cvar str entrez: Entrez gene ID. Found within the "GENE RESOURCES" section of the gene symbol report :cvar str mirbase: miRBase ID :cvar str iuphar: The objectId used to link to the IUPHAR/BPS Guide to PHARMACOLOGY database :cvar str ucsc: UCSC gene ID. Found within the "GENE RESOURCES" section of the gene symbol report :cvar str snornabase: snoRNABase ID :cvar str imgt: Symbol used within international ImMunoGeneTics information system :cvar str pseudogeneorg: Pseudogene.org ID :cvar str bioparadigmsslc: Symbol used to link to the SLC tables database at bioparadigms.org for the gene :cvar str locationsortable: locations sortable :cvar str merops: ID used to link to the MEROPS peptidase database :cvar str location: Cytogenetic location of the gene (e.g. 2q34). :cvar str cosmic: Symbol used within the Catalogue of somatic mutations in cancer for the gene :cvar list rgds: relationship to `RGD <#rgd>`__ :cvar list omims: relationship to OMIM :cvar list ccdss: relationship to CCDS :cvar list lsdbs: relationship to LSDB :cvar list orthology_predictions: relationship to OrthologyPrediction :cvar list enzymes: relationship to Enzyme :cvar list gene_families: relationship to GeneFamily :cvar list refseq_accessions: relationship to RefSeq :cvar list mgds: relationship to MGD :cvar list uniprots: relationship to UniProt :cvar list pubmeds: relationship to PubMed :cvar list enas: relationship to ENA """ name = Column(String(255), nullable=True) symbol = Column(Unicode(255), index=True) identifier = Column(Integer, unique=True) status = Column(String(255)) uuid = Column(String(255)) orphanet = Column(Integer, nullable=True) locus_group = Column(String(255)) locus_type = Column(String(255)) # Date information date_name_changed = Column(Date, nullable=True) date_modified = Column(Date, nullable=True) date_symbol_changed = Column(Date, nullable=True) date_approved_reserved = Column(Date, nullable=True) ensembl_gene = Column(String(255), nullable=True) horde = Column(String(255), nullable=True) vega = Column(String(255), nullable=True) lncrnadb = Column(String(255), nullable=True) entrez = Column(String(255), nullable=True) mirbase = Column(String(255), nullable=True) iuphar = Column(String(255), nullable=True) ucsc = Column(String(255), nullable=True) snornabase = Column(String(255), nullable=True) pseudogeneorg = Column(String(255), nullable=True) bioparadigmsslc = Column(String(255), nullable=True) locationsortable = Column(String(255), nullable=True) merops = Column(String(255), nullable=True) location = Column(String(255), nullable=True) cosmic = Column(String(255), nullable=True) imgt = Column(String(255), nullable=True) alias_symbols = relationship('AliasSymbol') alias_names = relationship('AliasName') omims = relationship('OMIM') ccdss = relationship('CCDS') lsdbs = relationship('LSDB') orthology_predictions = relationship('OrthologyPrediction') enzymes = relationship( "Enzyme", secondary=hgnc_enzyme, back_populates="hgncs" ) gene_families = relationship( 'GeneFamily', secondary=hgnc_gene_family, back_populates="hgncs" ) refseqs = relationship( 'RefSeq', secondary=hgnc_refseq, back_populates="hgncs" ) mgds = relationship( 'MGD', secondary=hgnc_mgd, back_populates="hgncs" ) pubmeds = relationship( 'PubMed', secondary=hgnc_pubmed, back_populates="hgncs" ) enas = relationship( 'ENA', secondary=hgnc_ena, back_populates="hgncs" ) uniprots = relationship( 'UniProt', secondary=hgnc_uniprot, back_populates="hgncs" ) rgds = relationship( 'RGD', secondary=hgnc_rgd, back_populates="hgncs" ) def __repr__(self): return self.symbol
class HGNC(Base, MasterModel): '''Root class (table, model) for all other classes (tables, models) in PyHGNC. Basic information with 1:1 relationship to identifier are stored here .. warning:: - homeodb (Homeobox Database ID) - horde_id (Symbol used within HORDE for the gene) described in `README <ftp://ftp.ebi.ac.uk/pub/databases/genenames/README.txt>`_, but not found in `HGNC JSON file <ftp://ftp.ebi.ac.uk/pub/databases/genenames/new/json/hgnc_complete_set.json>`_ .. hint:: To link to IUPHAR/BPS Guide to PHARMACOLOGY database only use the number (only use 1 from the result objectId:1) :cvar str name: HGNC approved name for the gene. Equates to the "APPROVED NAME" field within the gene symbol report :cvar str symbol: The HGNC approved gene symbol. Equates to the "APPROVED SYMBOL" field within the gene symbol report :cvar int orphanet: Orphanet ID :cvar str identifier: Unique ID created by the HGNC for every approved symbol (HGNC ID) :cvar str status: Status of the symbol report, which can be either "Approved" or "Entry Withdrawn" :cvar str uuid: universally unique identifier :cvar str locus_group: Group name for a set of related locus types as defined by the HGNC (e.g. non-coding RNA) :cvar str locus_type: Locus type as defined by the HGNC (e.g. RNA, transfer) :cvar date date_name_changed: date the gene name was last changed :cvar date date_modified: date the entry was last modified :cvar date date_symbol_changed: date the gene symbol was last changed :cvar date date_approved_reserved: date the entry was first approved :cvar str ensembl_gene: Ensembl gene ID. Found within the "GENE RESOURCES" section of the gene symbol report :cvar str horde: symbol used within HORDE for the gene (not available in JSON) :cvar str vega: Vega gene ID. Found within the "GENE RESOURCES" section of the gene symbol report :cvar str lncrnadb: Long Noncoding RNA Database identifier :cvar str entrez: Entrez gene ID. Found within the "GENE RESOURCES" section of the gene symbol report :cvar str mirbase: miRBase ID :cvar str iuphar: The objectId used to link to the IUPHAR/BPS Guide to PHARMACOLOGY database :cvar str ucsc: UCSC gene ID. Found within the "GENE RESOURCES" section of the gene symbol report :cvar str snornabase: snoRNABase ID :cvar str imgt: Symbol used within international ImMunoGeneTics information system :cvar str pseudogeneorg: Pseudogene.org ID :cvar str bioparadigmsslc: Symbol used to link to the SLC tables database at bioparadigms.org for the gene :cvar str locationsortable: locations sortable :cvar str merops: ID used to link to the MEROPS peptidase database :cvar str location: Cytogenetic location of the gene (e.g. 2q34). :cvar str cosmic: Symbol used within the Catalogue of somatic mutations in cancer for the gene :cvar list rgds: relationship to `RGD <#rgd>`__ :cvar list omims: relationship to OMIM :cvar list ccdss: relationship to CCDS :cvar list lsdbs: relationship to LSDB :cvar list orthology_predictions: relationship to OrthologyPrediction :cvar list enzymes: relationship to Enzyme :cvar list gene_families: relationship to GeneFamily :cvar list refseq_accessions: relationship to RefSeq :cvar list mgds: relationship to MGD :cvar list uniprots: relationship to UniProt :cvar list pubmeds: relationship to PubMed :cvar list enas: relationship to ENA ''' def __repr__(self): pass
2
1
2
0
2
0
1
0.69
2
0
0
0
1
0
1
6
158
28
77
44
75
53
45
44
43
1
2
0
1
145,118
LeKono/pyhgnc
LeKono_pyhgnc/src/pyhgnc/manager/models.py
pyhgnc.manager.models.GeneFamily
class GeneFamily(Base, MasterModel): """Name and identifier given to a gene family or group the gene has been assigned to. Equates to the "GENE FAMILY" field within the gene symbol report. :cvar int familyid: family identifier :cvar str familyname: family name :cvar list hgncs: back populates to :class:`.HGNC` """ family_identifier = Column(Integer, unique=True) family_name = Column(String(255)) hgncs = relationship( "HGNC", secondary=hgnc_gene_family, back_populates="gene_families" ) def to_dict(self): return self.to_dict_with_hgncs() def __repr__(self): return self.family_name
class GeneFamily(Base, MasterModel): '''Name and identifier given to a gene family or group the gene has been assigned to. Equates to the "GENE FAMILY" field within the gene symbol report. :cvar int familyid: family identifier :cvar str familyname: family name :cvar list hgncs: back populates to :class:`.HGNC` ''' def to_dict(self): pass def __repr__(self): pass
3
1
2
0
2
0
1
0.5
2
0
0
0
2
0
2
7
23
5
12
6
9
6
8
6
5
1
2
0
2
145,119
LeKono/pyhgnc
LeKono_pyhgnc/src/pyhgnc/manager/models.py
pyhgnc.manager.models.Enzyme
class Enzyme(Base, MasterModel): """Enzyme Commission number (EC number) :cvar str ec_number: EC number :cvar list hgncs: back populates to :class:`.HGNC` """ ec_number = Column(String(255)) hgncs = relationship( "HGNC", secondary=hgnc_enzyme, back_populates="enzymes" ) def to_dict(self): return self.to_dict_with_hgncs() def __repr__(self): return self.ec_number
class Enzyme(Base, MasterModel): '''Enzyme Commission number (EC number) :cvar str ec_number: EC number :cvar list hgncs: back populates to :class:`.HGNC` ''' def to_dict(self): pass def __repr__(self): pass
3
1
2
0
2
0
1
0.36
2
0
0
0
2
0
2
7
20
5
11
5
8
4
7
5
4
1
2
0
2
145,120
LeKono/pyhgnc
LeKono_pyhgnc/src/pyhgnc/manager/models.py
pyhgnc.manager.models.ENA
class ENA(Base, MasterModel): """International Nucleotide Sequence Database Collaboration (GenBank, ENA and DDBJ) accession number(s). Found within the "NUCLEOTIDE SEQUENCES" section of the gene symbol report. :cvar str enaid: European Nucleotide Archive (ENA) identifier :cvar list hgncs: back populates to :class:`.HGNC` """ enaid = Column(String(255)) hgncs = relationship( "HGNC", secondary=hgnc_ena, back_populates="enas" ) def to_dict(self): return self.to_dict_with_hgncs() def __repr__(self): return self.enaid
class ENA(Base, MasterModel): '''International Nucleotide Sequence Database Collaboration (GenBank, ENA and DDBJ) accession number(s). Found within the "NUCLEOTIDE SEQUENCES" section of the gene symbol report. :cvar str enaid: European Nucleotide Archive (ENA) identifier :cvar list hgncs: back populates to :class:`.HGNC` ''' def to_dict(self): pass def __repr__(self): pass
3
1
2
0
2
0
1
0.45
2
0
0
0
2
0
2
7
21
5
11
5
8
5
7
5
4
1
2
0
2
145,121
LeKono/pyhgnc
LeKono_pyhgnc/src/pyhgnc/manager/models.py
pyhgnc.manager.models.CCDS
class CCDS(Base, MasterModel): """Consensus CDS ID. Found within the "NUCLEOTIDE SEQUENCES" section of the gene symbol report. See also `CCDS <https://www.ncbi.nlm.nih.gov/projects/CCDS>`_ for more information. :cvar str ccdsid: CCDS identifier :cvar hgnc: back populates to :class:`.HGNC` """ ccdsid = Column(String(255)) hgnc_id = foreign_key_to('hgnc') hgnc = relationship('HGNC', back_populates='ccdss') def to_dict(self): return self.to_dict_with_hgnc() def __repr__(self): return self.ccdsid
class CCDS(Base, MasterModel): '''Consensus CDS ID. Found within the "NUCLEOTIDE SEQUENCES" section of the gene symbol report. See also `CCDS <https://www.ncbi.nlm.nih.gov/projects/CCDS>`_ for more information. :cvar str ccdsid: CCDS identifier :cvar hgnc: back populates to :class:`.HGNC` ''' def to_dict(self): pass def __repr__(self): pass
3
1
2
0
2
0
1
0.63
2
0
0
0
2
0
2
7
19
6
8
6
5
5
8
6
5
1
2
0
2
145,122
LeKono/pyhgnc
LeKono_pyhgnc/src/pyhgnc/manager/models.py
pyhgnc.manager.models.RefSeq
class RefSeq(Base, MasterModel): """RefSeq nucleotide accession(s). Found within the"NUCLEOTIDE SEQUENCES" section of the gene symbol report. See also `RefSeq database <https://www.ncbi.nlm.nih.gov/refseq/>`_ for more information. :cvar str accession: RefSeq accession number :cvar list hgncs: back populates to :class:`.HGNC` """ accession = Column(String(255)) hgncs = relationship( "HGNC", secondary=hgnc_refseq, back_populates="refseqs" ) def to_dict(self): return self.to_dict_with_hgncs() def __repr__(self): return self.accession
class RefSeq(Base, MasterModel): '''RefSeq nucleotide accession(s). Found within the"NUCLEOTIDE SEQUENCES" section of the gene symbol report. See also `RefSeq database <https://www.ncbi.nlm.nih.gov/refseq/>`_ for more information. :cvar str accession: RefSeq accession number :cvar list hgncs: back populates to :class:`.HGNC` ''' def to_dict(self): pass def __repr__(self): pass
3
1
2
0
2
0
1
0.45
2
0
0
0
2
0
2
7
21
5
11
5
8
5
7
5
4
1
2
0
2
145,123
LeKono/pyhgnc
LeKono_pyhgnc/src/pyhgnc/manager/models.py
pyhgnc.manager.models.AliasName
class AliasName(Base, MasterModel): """Other names used to refer to this gene as seen in the "SYNONYMS" field in the gene symbol report. .. attention:: Gene names previously approved by the HGNC for this gene are tagged with `is_previous_name==True`.. Equates to the "PREVIOUS SYMBOLS & NAMES" field within the gene symbol report. :cvar str alias_name: other name :cvar bool is_previous_name: previously approved :cvar hgnc: back populates to :class:`.HGNC` """ alias_name = Column(String(255)) is_previous_name = Column(Boolean, default=False) hgnc_id = foreign_key_to('hgnc') hgnc = relationship('HGNC', back_populates='alias_names') def to_dict(self): return self.to_dict_with_hgnc() def __repr__(self): return '{}; is_previous:{}'.format(self.alias_name, self.is_previous_name)
class AliasName(Base, MasterModel): '''Other names used to refer to this gene as seen in the "SYNONYMS" field in the gene symbol report. .. attention:: Gene names previously approved by the HGNC for this gene are tagged with `is_previous_name==True`.. Equates to the "PREVIOUS SYMBOLS & NAMES" field within the gene symbol report. :cvar str alias_name: other name :cvar bool is_previous_name: previously approved :cvar hgnc: back populates to :class:`.HGNC` ''' def to_dict(self): pass def __repr__(self): pass
3
1
2
0
2
0
1
1
2
0
0
0
2
0
2
7
24
6
9
7
6
9
9
7
6
1
2
0
2
145,124
LeKono/pyhgnc
LeKono_pyhgnc/src/pyhgnc/manager/database.py
pyhgnc.manager.database.DbManager
class DbManager(BaseDbManager): enzymes = {} gene_families = {} refseqs = {} mgds = {} uniprots = {} pubmeds = {} enas = {} rgds = {} def __init__(self, connection=None): """The DbManager implements all function to upload HGNC data into the database. Prefered SQL Alchemy database is MySQL with pymysql. :param connection: custom database connection SQL Alchemy string :type connection: str """ super(DbManager, self).__init__(connection=connection) def db_import(self, silent=False, hgnc_file_path=None, hcop_file_path=None, low_memory=False): self._drop_tables() self._create_tables() json_data = DbManager.load_hgnc_json(hgnc_file_path=hgnc_file_path) self.insert_hgnc(hgnc_dict=json_data, silent=silent, low_memory=low_memory) self.insert_hcop(silent=silent, hcop_file_path=hcop_file_path) @classmethod def get_date(cls, hgnc, key): date_value = hgnc.get(key) if date_value: return datetime.strptime(date_value, "%Y-%m-%d",).date() @classmethod def get_alias_symbols(cls, hgnc): alias_symbols = [] if 'alias_symbol' in hgnc: for alias in hgnc['alias_symbol']: alias_symbols.append(models.AliasSymbol(alias_symbol=alias)) if 'prev_symbol' in hgnc: for prev in hgnc['prev_symbol']: alias_symbols.append(models.AliasSymbol(alias_symbol=prev, is_previous_symbol=True)) return alias_symbols @classmethod def get_alias_names(cls, hgnc): alias_names = [] if 'alias_name' in hgnc: for alias in hgnc['alias_name']: alias_names.append(models.AliasName(alias_name=alias)) if 'prev_name' in hgnc: for prev in hgnc['prev_name']: alias_names.append(models.AliasName(alias_name=prev, is_previous_name=True)) return alias_names def get_gene_families(self, hgnc): gene_families = [] if 'gene_family' in hgnc: for i, family in enumerate(hgnc['gene_family']): family_identifier = hgnc['gene_family_id'][i] if family_identifier not in self.gene_families: gene_family = models.GeneFamily(family_identifier=family_identifier, family_name=family) self.gene_families[family_identifier] = gene_family gene_families.append(self.gene_families[family_identifier]) return gene_families def get_refseq(self, hgnc): refseqs = [] if 'refseq_accession' in hgnc: for accession in hgnc['refseq_accession']: if accession not in self.refseqs: self.refseqs[accession] = models.RefSeq(accession=accession) refseqs.append(self.refseqs[accession]) return refseqs def get_mgds(self, hgnc): mgds = [] regex_mgdid = re.compile("MGI:(?P<mgdid>\d+)") if 'mgd_id' in hgnc: for mgd in hgnc['mgd_id']: mgdid_found = regex_mgdid.search(mgd) if mgd not in self.mgds and mgdid_found: mgdid = mgdid_found.groupdict()['mgdid'] self.mgds[mgd] = models.MGD(mgdid=int(mgdid)) if mgdid_found: mgds.append(self.mgds[mgd]) return mgds def get_rgds(self, hgnc): rgds = [] if 'rgd_id' in hgnc: for rgd in hgnc['rgd_id']: if rgd not in self.rgds: rgdid = int(rgd.split(':')[-1]) self.rgds[rgd] = models.RGD(rgdid=rgdid) rgds.append(self.rgds[rgd]) return rgds def get_omims(self, hgnc): omims = [] if 'omim_id' in hgnc: for omim in hgnc['omim_id']: omims.append(models.OMIM(omimid=omim)) return omims def get_uniprots(self, hgnc): uniprots = [] if 'uniprot_ids' in hgnc: for uniprot in hgnc['uniprot_ids']: if uniprot not in self.uniprots: self.uniprots[uniprot] = models.UniProt(uniprotid=uniprot) uniprots.append(self.uniprots[uniprot]) return uniprots def get_ccds(self, hgnc): ccds = [] if 'ccds_id' in hgnc: for ccdsid in hgnc['ccds_id']: ccds.append(models.CCDS(ccdsid=ccdsid)) return ccds def get_pubmeds(self, hgnc): pubmeds = [] if 'pubmed_id' in hgnc: for pubmed in hgnc['pubmed_id']: if pubmed not in self.pubmeds: self.pubmeds[pubmed] = models.PubMed(pubmedid=int(pubmed)) pubmeds.append(self.pubmeds[pubmed]) return pubmeds def get_enas(self, hgnc): enas = [] if 'ena' in hgnc: for ena in hgnc['ena']: if ena not in self.enas: self.enas[ena] = models.ENA(enaid=ena) enas.append(self.enas[ena]) return enas def get_lsdbs(self, hgnc): lsdbs = [] if 'lsdb' in hgnc: for lsdb_url in hgnc['lsdb']: lsdb, url = lsdb_url.split('|') lsdbs.append(models.LSDB(lsdb=lsdb, url=url)) return lsdbs def get_enzymes(self, hgnc): enzymes = [] if 'enzyme_id' in hgnc: for ec_number in hgnc['enzyme_id']: if ec_number not in self.enzymes: self.enzymes[ec_number] = models.Enzyme(ec_number=ec_number) enzymes.append(self.enzymes[ec_number]) return enzymes def insert_hgnc(self, hgnc_dict, silent=False, low_memory=False): log.info('low_memory set to {}'.format(low_memory)) for hgnc_data in tqdm(hgnc_dict['docs'], disable=silent): hgnc_table = { 'symbol': hgnc_data['symbol'], 'identifier': int(hgnc_data['hgnc_id'].split(':')[-1]), 'name': hgnc_data['name'], 'status': hgnc_data['status'], 'orphanet': hgnc_data.get('orphanet'), 'uuid': hgnc_data['uuid'], 'locus_group': hgnc_data['locus_group'], 'locus_type': hgnc_data['locus_type'], 'ensembl_gene': hgnc_data.get('ensembl_gene_id'), 'horde': hgnc_data.get('horde_id'), 'vega': hgnc_data.get('vega_id'), 'lncrnadb': hgnc_data.get('lncrnadb'), 'entrez': hgnc_data.get('entrez_id'), 'mirbase': hgnc_data.get('mirbase'), 'iuphar': hgnc_data.get('iuphar'), 'ucsc': hgnc_data.get('ucsc_id'), 'snornabase': hgnc_data.get('snornabase'), 'pseudogeneorg': hgnc_data.get('pseudogene.org'), 'bioparadigmsslc': hgnc_data.get('bioparadigms_slc'), 'locationsortable': hgnc_data.get('location_sortable'), 'merops': hgnc_data.get('merops'), 'location': hgnc_data.get('location'), 'cosmic': hgnc_data.get('cosmic'), 'imgt': hgnc_data.get('imgt'), 'date_name_changed': self.get_date(hgnc_data, 'date_name_changed'), 'date_modified': self.get_date(hgnc_data, 'date_modified'), 'date_symbol_changed': self.get_date(hgnc_data, 'date_symbol_changed'), 'date_approved_reserved': self.get_date(hgnc_data, 'date_approved_reserved'), 'alias_symbols': self.get_alias_symbols(hgnc_data), 'alias_names': self.get_alias_names(hgnc_data), 'gene_families': self.get_gene_families(hgnc_data), 'refseqs': self.get_refseq(hgnc_data), 'mgds': self.get_mgds(hgnc_data), 'rgds': self.get_rgds(hgnc_data), 'omims': self.get_omims(hgnc_data), 'uniprots': self.get_uniprots(hgnc_data), 'ccdss': self.get_ccds(hgnc_data), 'pubmeds': self.get_pubmeds(hgnc_data), 'enas': self.get_enas(hgnc_data), 'lsdbs': self.get_lsdbs(hgnc_data), 'enzymes': self.get_enzymes(hgnc_data) } self.session.add(models.HGNC(**hgnc_table)) if low_memory: self.session.flush() if not silent: print('Insert HGNC data into database') self.session.commit() def insert_hcop(self, silent=False, hcop_file_path=None): log_text = 'Load OrthologyPrediction data from {}'.format((hcop_file_path or constants.HCOP_GZIP)) log.info(log_text) if not silent: print(log_text) df_hcop = pandas.read_table((hcop_file_path or constants.HCOP_GZIP), low_memory=False) df_hcop.replace('-', numpy.NaN, inplace=True) df_hcop.replace(to_replace={'hgnc_id': 'HGNC:'}, value='', regex=True, inplace=True) df_hcop.hgnc_id = df_hcop.hgnc_id.fillna(-1).astype(int) df_hcop.rename(columns={'hgnc_id': 'identifier'}, inplace=True) df_hcop.set_index('identifier', inplace=True) log_text = 'Join HGNC with HGNC' log.info(log_text) if not silent: print(log_text) data = self.session.query(models.HGNC).options(load_only(models.HGNC.id, models.HGNC.identifier)) data = [{'hgnc_id': x.id, 'identifier': x.identifier} for x in data] df_hgnc = pandas.DataFrame(data) df_hgnc.set_index('identifier', inplace=True) df_hcnp4db = df_hcop.join(df_hgnc) df_hcnp4db.reset_index(inplace=True) df_hcnp4db.index += 1 df_hcnp4db.drop('identifier', axis=1, inplace=True) df_hcnp4db.index.rename('id', inplace=True) log_text = 'Load OrthologyPrediction data in database' log.info(log_text) if not silent: print(log_text) df_hcnp4db.to_sql(name=models.OrthologyPrediction.__tablename__, con=self.connection, if_exists='append') @staticmethod def load_hgnc_json(hgnc_file_path=None): if hgnc_file_path: with open(hgnc_file_path) as response: log.info('loading json data from {}'.format(hgnc_file_path)) hgnc_dict = json.loads(response.read()) else: response = urlopen(HGNC_JSON) hgnc_dict = json.loads(response.read().decode()) return hgnc_dict['response']
class DbManager(BaseDbManager): def __init__(self, connection=None): '''The DbManager implements all function to upload HGNC data into the database. Prefered SQL Alchemy database is MySQL with pymysql. :param connection: custom database connection SQL Alchemy string :type connection: str ''' pass def db_import(self, silent=False, hgnc_file_path=None, hcop_file_path=None, low_memory=False): pass @classmethod def get_date(cls, hgnc, key): pass @classmethod def get_alias_symbols(cls, hgnc): pass @classmethod def get_alias_names(cls, hgnc): pass def get_gene_families(self, hgnc): pass def get_refseq(self, hgnc): pass def get_mgds(self, hgnc): pass def get_rgds(self, hgnc): pass def get_omims(self, hgnc): pass def get_uniprots(self, hgnc): pass def get_ccds(self, hgnc): pass def get_pubmeds(self, hgnc): pass def get_enas(self, hgnc): pass def get_lsdbs(self, hgnc): pass def get_enzymes(self, hgnc): pass def insert_hgnc(self, hgnc_dict, silent=False, low_memory=False): pass def insert_hcop(self, silent=False, hcop_file_path=None): pass @staticmethod def load_hgnc_json(hgnc_file_path=None): pass
24
1
15
3
11
0
3
0.02
1
20
15
0
15
1
19
23
311
83
223
79
199
5
176
73
156
5
2
3
66
145,125
LeKono/pyhgnc
LeKono_pyhgnc/src/pyhgnc/manager/database.py
pyhgnc.manager.database.BaseDbManager
class BaseDbManager(object): """Creates a connection to database and a persistient session using SQLAlchemy""" def __init__(self, connection=None, echo=False): """ :param str connection: SQLAlchemy :param bool echo: True or False for SQL output of SQLAlchemy engine """ try: self.connection = self.get_connection_string(connection) self.engine = create_engine(self.connection, echo=echo) self.sessionmaker = sessionmaker(bind=self.engine, autoflush=False, expire_on_commit=False) self.session = scoped_session(self.sessionmaker) except: log.warning('No valid database connection. Execute `pyhgnc connection` on command line') def _create_tables(self, checkfirst=True): """creates all tables from models in your database :param checkfirst: True or False check if tables already exists :type checkfirst: bool :return: """ log.info('create tables in {}'.format(self.engine.url)) models.Base.metadata.create_all(self.engine, checkfirst=checkfirst) def _drop_tables(self): """drops all tables in the database :return: """ log.info('drop tables in {}'.format(self.engine.url)) models.Base.metadata.drop_all(self.engine) @staticmethod def get_connection_string(connection=None): """return sqlalchemy connection string if it is set :param connection: get the SQLAlchemy connection string #TODO :return: """ if not connection: config = ConfigParser() cfp = defaults.config_file_path if os.path.exists(cfp): log.info('fetch database configuration from {}'.format(cfp)) config.read(cfp) connection = config['database']['sqlalchemy_connection_string'] log.info('load connection string from {}: {}'.format(cfp, connection)) else: with open(cfp, 'w') as config_file: connection = defaults.sqlalchemy_connection_string_default config['database'] = {'sqlalchemy_connection_string': connection} config.write(config_file) log.info('create configuration file {}'.format(cfp)) return connection
class BaseDbManager(object): '''Creates a connection to database and a persistient session using SQLAlchemy''' def __init__(self, connection=None, echo=False): ''' :param str connection: SQLAlchemy :param bool echo: True or False for SQL output of SQLAlchemy engine ''' pass def _create_tables(self, checkfirst=True): '''creates all tables from models in your database :param checkfirst: True or False check if tables already exists :type checkfirst: bool :return: ''' pass def _drop_tables(self): '''drops all tables in the database :return: ''' pass @staticmethod def get_connection_string(connection=None): '''return sqlalchemy connection string if it is set :param connection: get the SQLAlchemy connection string #TODO :return: ''' pass
6
5
12
1
8
4
2
0.53
1
1
0
2
3
4
4
4
56
7
32
13
26
17
30
11
25
3
1
3
7
145,126
LeKono/pyhgnc
LeKono_pyhgnc/src/pyhgnc/manager/models.py
pyhgnc.manager.models.UniProt
class UniProt(Base, MasterModel): """Universal Protein Resource (UniProt) protein accession. Found within the "PROTEIN RESOURCES" section of the gene symbol report. See also `UniProt webpage <http://www.uniprot.org>`_ for more information. :cvar str uniprotid: UniProt identifier :cvar list hgncs: back populates to :class:`.HGNC` """ uniprotid = Column(String(255)) hgncs = relationship( "HGNC", secondary=hgnc_uniprot, back_populates="uniprots" ) def to_dict(self): return self.to_dict_with_hgncs() def __repr__(self): return self.uniprotid
class UniProt(Base, MasterModel): '''Universal Protein Resource (UniProt) protein accession. Found within the "PROTEIN RESOURCES" section of the gene symbol report. See also `UniProt webpage <http://www.uniprot.org>`_ for more information. :cvar str uniprotid: UniProt identifier :cvar list hgncs: back populates to :class:`.HGNC` ''' def to_dict(self): pass def __repr__(self): pass
3
1
2
0
2
0
1
0.55
2
0
0
0
2
0
2
7
23
6
11
5
8
6
7
5
4
1
2
0
2
145,127
LeKono/pyhgnc
LeKono_pyhgnc/src/pyhgnc/manager/query.py
pyhgnc.manager.query.QueryManager
class QueryManager(BaseDbManager): """Query interface to database.""" def _limit_and_df(self, query, limit, as_df=False): """adds a limit (limit==None := no limit) to any query and allow a return as pandas.DataFrame :param bool as_df: if is set to True results return as pandas.DataFrame :param `sqlalchemy.orm.query.Query` query: SQL Alchemy query :param int,tuple limit: maximum number of results :return: query result of pyhgnc.manager.models.XY objects """ if limit: if isinstance(limit, int): query = query.limit(limit) if isinstance(limit, Iterable) and len(limit) == 2 and [int, int] == [type(x) for x in limit]: page, page_size = limit query = query.limit(page_size) query = query.offset(page * page_size) if as_df: results = read_sql(query.statement, self.engine) else: try: results = query.all() except: query.session.rollback() results = query.all() return results def get_model_queries(self, query_obj, model_queries_config): """use this if your are searching for a field in the same model""" for search4, model_attrib in model_queries_config: if search4 is not None: query_obj = self._model_query(query_obj, search4, model_attrib) return query_obj def get_many_to_many_queries(self, query_obj, many_to_many_queries_config): for search4, model_attrib, many2many_attrib in many_to_many_queries_config: if search4 is not None: query_obj = self._many_to_many_query(query_obj, search4, model_attrib, many2many_attrib) return query_obj def get_one_to_many_queries(self, query_obj, one_to_many_queries): for search4, model_attrib in one_to_many_queries: if search4 is not None: query_obj = self._one_to_many_query(query_obj, search4, model_attrib) return query_obj @classmethod def _one_to_many_query(cls, query_obj, search4, model_attrib): """extends and returns a SQLAlchemy query object to allow one-to-many queries :param query_obj: SQL Alchemy query object :param str search4: search string :param model_attrib: attribute in model """ model = model_attrib.parent.class_ already_joined_tables = [mapper.class_ for mapper in query_obj._join_entities] if isinstance(search4, (str, int, Iterable)) and model not in already_joined_tables: query_obj = query_obj.join(model) if isinstance(search4, str): query_obj = query_obj.filter(model_attrib.like(search4)) elif isinstance(search4, int): query_obj = query_obj.filter(model_attrib == search4) elif isinstance(search4, Iterable): query_obj = query_obj.filter(model_attrib.in_(search4)) return query_obj @classmethod def _many_to_many_query(cls, query_obj, search4, join_attrib, many2many_attrib): model = join_attrib.property.mapper.class_ already_joined_tables = [mapper.class_ for mapper in query_obj._join_entities] if isinstance(search4, (str, int, Iterable)) and model not in already_joined_tables: query_obj = query_obj.join(join_attrib) if isinstance(search4, str): query_obj = query_obj.filter(many2many_attrib.like(search4)) elif isinstance(search4, int): query_obj = query_obj.filter(many2many_attrib == search4) elif isinstance(search4, Iterable): query_obj = query_obj.filter(many2many_attrib.in_(search4)) return query_obj @classmethod def _model_query(cls, query_obj, search4, model_attrib): if isinstance(search4, str): query_obj = query_obj.filter(model_attrib.like(search4)) elif isinstance(search4, int): query_obj = query_obj.filter(model_attrib == search4) elif isinstance(search4, Iterable): query_obj = query_obj.filter(model_attrib.in_(search4)) return query_obj def hgnc(self, name=None, symbol=None, identifier=None, status=None, uuid=None, locus_group=None, orphanet=None, locus_type=None, date_name_changed=None, date_modified=None, date_symbol_changed=None, pubmedid=None, date_approved_reserved=None, ensembl_gene=None, horde=None, vega=None, lncrnadb=None, uniprotid=None, entrez=None, mirbase=None, iuphar=None, ucsc=None, snornabase=None, gene_family_name=None, mgdid=None, pseudogeneorg=None, bioparadigmsslc=None, locationsortable=None, ec_number=None, refseq_accession=None, merops=None, location=None, cosmic=None, imgt=None, enaid=None, alias_symbol=None, alias_name=None, rgdid=None, omimid=None, ccdsid=None, lsdbs=None, ortholog_species=None, gene_family_identifier=None, limit=None, as_df=False): """Method to query :class:`pyhgnc.manager.models.Pmid` :param name: HGNC approved name for the gene :type name: str or tuple(str) or None :param symbol: HGNC approved gene symbol :type symbol: str or tuple(str) or None :param identifier: HGNC ID. A unique ID created by the HGNC for every approved symbol :type identifier: int or tuple(int) or None :param status: Status of the symbol report, which can be either "Approved" or "Entry Withdrawn" :type status: str or tuple(str) or None :param uuid: universally unique identifier :type uuid: str or tuple(str) or None :param locus_group: group name for a set of related locus types as defined by the HGNC :type locus_group: str or tuple(str) or None :param orphanet: Orphanet database identifier (related to rare diseases and orphan drugs) :type orphanet: int ot tuple(int) or None :param locus_type: locus type as defined by the HGNC (e.g. RNA, transfer) :type locus_type: str or tuple(str) or None :param date_name_changed: date the gene name was last changed (format: YYYY-mm-dd, e.g. 2017-09-29) :type date_name_changed: str or tuple(str) or None :param date_modified: date the entry was last modified (format: YYYY-mm-dd, e.g. 2017-09-29) :type date_modified: str or tuple(str) or None :param date_symbol_changed: date the gene symbol was last changed (format: YYYY-mm-dd, e.g. 2017-09-29) :type date_symbol_changed: str or tuple(str) or None :param date_approved_reserved: date the entry was first approved (format: YYYY-mm-dd, e.g. 2017-09-29) :type date_approved_reserved: str or tuple(str) or None :param pubmedid: PubMed identifier :type pubmedid: int ot tuple(int) or None :param ensembl_gene: Ensembl gene ID. Found within the "GENE RESOURCES" section of the gene symbol report :type ensembl_gene: str or tuple(str) or None :param horde: symbol used within HORDE for the gene (not available in JSON) :type horde: str or tuple(str) or None :param vega: Vega gene ID. Found within the "GENE RESOURCES" section of the gene symbol report :type vega: str or tuple(str) or None :param lncrnadb: Noncoding RNA Database identifier :type lncrnadb: str or tuple(str) or None :param uniprotid: UniProt identifier :type uniprotid: str or tuple(str) or None :param entrez: Entrez gene ID. Found within the "GENE RESOURCES" section of the gene symbol report :type entrez: str or tuple(str) or None :param mirbase: miRBase ID :type mirbase: str or tuple(str) or None :param iuphar: The objectId used to link to the IUPHAR/BPS Guide to PHARMACOLOGY database :type iuphar: str or tuple(str) or None :param ucsc: UCSC gene ID. Found within the "GENE RESOURCES" section of the gene symbol report :type ucsc: str or tuple(str) or None :param snornabase: snoRNABase ID :type snornabase: str or tuple(str) or None :param gene_family_name: Gene family name :type gene_family_name: str or tuple(str) or None :param gene_family_identifier: Gene family identifier :type gene_family_name: int or tuple(int) or None :param mgdid: Mouse Genome Database identifier :type mgdid: int ot tuple(int) or None :param imgt: Symbol used within international ImMunoGeneTics information system :type imgt: str or tuple(str) or None :param enaid: European Nucleotide Archive (ENA) identifier :type enaid: str or tuple(str) or None :param alias_symbol: Other symbols used to refer to a gene :type alias_symbol: str or tuple(str) or None :param alias_name: Other names used to refer to a gene :type alias_name: str or tuple(str) or None :param pseudogeneorg: Pseudogene.org ID :type pseudogeneorg: str or tuple(str) or None :param bioparadigmsslc: Symbol used to link to the SLC tables database at bioparadigms.org for the gene :type bioparadigmsslc: str or tuple(str) or None :param locationsortable: locations sortable :type locationsortable: str or tuple(str) or None :param ec_number: Enzyme Commission number (EC number) :type ec_number: str or tuple(str) or None :param refseq_accession: RefSeq nucleotide accession(s) :type refseq_accession: str or tuple(str) or None :param merops: ID used to link to the MEROPS peptidase database :type merops: str or tuple(str) or None :param location: Cytogenetic location of the gene (e.g. 2q34). :type location: str or tuple(str) or None :param cosmic: Symbol used within the Catalogue of somatic mutations in cancer for the gene :type cosmic: str or tuple(str) or None :param rgdid: Rat genome database gene ID :type rgdid: int or tuple(int) or None :param omimid: Online Mendelian Inheritance in Man (OMIM) ID :type omimid: int or tuple(int) or None :param ccdsid: Consensus CDS ID :type ccdsid: str or tuple(str) or None :param lsdbs: Locus Specific Mutation Database Name :type lsdbs: str or tuple(str) or None :param ortholog_species: Ortholog species NCBI taxonomy identifier :type ortholog_species: int or tuple(int) or None :param limit: - if `isinstance(limit,int)==True` -> limit - if `isinstance(limit,tuple)==True` -> format:= tuple(page_number, results_per_page) - if limit == None -> all results :type limit: int or tuple(int) or None :param bool as_df: if `True` results are returned as :class:`pandas.DataFrame` :return: - if `as_df == False` -> list(:class:`.models.Keyword`) - if `as_df == True` -> :class:`pandas.DataFrame` :rtype: list[models.HGNC] """ q = self.session.query(models.HGNC) model_queries_config = ( (orphanet, models.HGNC.orphanet), (name, models.HGNC.name), (symbol, models.HGNC.symbol), (identifier, models.HGNC.identifier), (status, models.HGNC.status), (uuid, models.HGNC.uuid), (locus_group, models.HGNC.locus_group), (locus_type, models.HGNC.locus_type), (date_name_changed, models.HGNC.date_name_changed), (date_modified, models.HGNC.date_modified), (date_symbol_changed, models.HGNC.date_symbol_changed), (date_approved_reserved, models.HGNC.date_approved_reserved), (ensembl_gene, models.HGNC.ensembl_gene), (horde, models.HGNC.horde), (vega, models.HGNC.vega), (lncrnadb, models.HGNC.lncrnadb), (entrez, models.HGNC.entrez), (mirbase, models.HGNC.mirbase), (iuphar, models.HGNC.iuphar), (ucsc, models.HGNC.ucsc), (snornabase, models.HGNC.snornabase), (pseudogeneorg, models.HGNC.pseudogeneorg), (bioparadigmsslc, models.HGNC.bioparadigmsslc), (locationsortable, models.HGNC.locationsortable), (merops, models.HGNC.merops), (location, models.HGNC.location), (cosmic, models.HGNC.cosmic), (imgt, models.HGNC.imgt), ) q = self.get_model_queries(q, model_queries_config) many_to_many_queries_config = ( (ec_number, models.HGNC.enzymes, models.Enzyme.ec_number), (gene_family_name, models.HGNC.gene_families, models.GeneFamily.family_name), (gene_family_identifier, models.HGNC.gene_families, models.GeneFamily.family_identifier), (refseq_accession, models.HGNC.refseqs, models.RefSeq.accession), (mgdid, models.HGNC.mgds, models.MGD.mgdid), (uniprotid, models.HGNC.uniprots, models.UniProt.uniprotid), (pubmedid, models.HGNC.pubmeds, models.PubMed.pubmedid), (enaid, models.HGNC.enas, models.ENA.enaid), ) q = self.get_many_to_many_queries(q, many_to_many_queries_config) one_to_many_queries_config = ( (alias_symbol, models.AliasSymbol.alias_symbol), (alias_name, models.AliasName.alias_name), (rgdid, models.RGD.rgdid), (omimid, models.OMIM.omimid), (ccdsid, models.CCDS.ccdsid), (lsdbs, models.LSDB.lsdb), (ortholog_species, models.OrthologyPrediction.ortholog_species), ) q = self.get_one_to_many_queries(q, one_to_many_queries_config) return self._limit_and_df(q, limit, as_df) def orthology_prediction(self, ortholog_species=None, human_entrez_gene=None, human_ensembl_gene=None, human_name=None, human_symbol=None, human_chr=None, human_assert_ids=None, ortholog_species_entrez_gene=None, ortholog_species_ensembl_gene=None, ortholog_species_db_id=None, ortholog_species_name=None, ortholog_species_symbol=None, ortholog_species_chr=None, ortholog_species_assert_ids=None, support=None, hgnc_identifier=None, hgnc_symbol=None, limit=None, as_df=False): """Method to query :class:`pyhgnc.manager.models.OrthologyPrediction` :param int ortholog_species: NCBI taxonomy identifier :param str human_entrez_gene: Entrez gene identifier :param str human_ensembl_gene: Ensembl identifier :param str human_name: human gene name :param str human_symbol: human gene symbol :param str human_chr: human chromosome :param str human_assert_ids: :param str ortholog_species_entrez_gene: Entrez gene identifier for ortholog :param str ortholog_species_ensembl_gene: Ensembl gene identifier for ortholog :param str ortholog_species_db_id: Species specific database identifier (e.g. MGI:1920453) :param str ortholog_species_name: gene name of ortholog :param str ortholog_species_symbol: gene symbol of ortholog :param str ortholog_species_chr: chromosome identifier (ortholog) :param str ortholog_species_assert_ids: :param str support: :param int hgnc_identifier: HGNC identifier :param str hgnc_symbol: HGNC symbol :param limit: - if `isinstance(limit,int)==True` -> limit - if `isinstance(limit,tuple)==True` -> format:= tuple(page_number, results_per_page) - if limit == None -> all results :type limit: int or tuple(int) or None :param bool as_df: if `True` results are returned as :class:`pandas.DataFrame` :return: - if `as_df == False` -> list(:class:`.models.Keyword`) - if `as_df == True` -> :class:`pandas.DataFrame` :rtype: list(:class:`.models.Keyword`) or :class:`pandas.DataFrame` """ q = self.session.query(models.OrthologyPrediction) model_queries_config = ( (ortholog_species, models.OrthologyPrediction.ortholog_species), (human_entrez_gene, models.OrthologyPrediction.human_entrez_gene), (human_ensembl_gene, models.OrthologyPrediction.human_ensembl_gene), (human_name, models.OrthologyPrediction.human_name), (human_symbol, models.OrthologyPrediction.human_symbol), (human_chr, models.OrthologyPrediction.human_chr), (human_assert_ids, models.OrthologyPrediction.human_assert_ids), (ortholog_species_entrez_gene, models.OrthologyPrediction.ortholog_species_entrez_gene), (ortholog_species_ensembl_gene, models.OrthologyPrediction.ortholog_species_ensembl_gene), (ortholog_species_db_id, models.OrthologyPrediction.ortholog_species_db_id), (ortholog_species_name, models.OrthologyPrediction.ortholog_species_name), (ortholog_species_symbol, models.OrthologyPrediction.ortholog_species_symbol), (ortholog_species_chr, models.OrthologyPrediction.ortholog_species_chr), (ortholog_species_assert_ids, models.OrthologyPrediction.ortholog_species_assert_ids), (support, models.OrthologyPrediction.support), ) q = self.get_model_queries(q, model_queries_config) one_to_many_queries_config = ( (hgnc_identifier, models.HGNC.identifier), (hgnc_symbol, models.HGNC.symbol), ) q = self.get_one_to_many_queries(q, one_to_many_queries_config) return self._limit_and_df(q, limit, as_df) def alias_symbol(self, alias_symbol=None, is_previous_symbol=None, hgnc_symbol=None, hgnc_identifier=None, limit=None, as_df=False): """Method to query :class:`.models.AliasSymbol` objects in database :param alias_symbol: alias symbol(s) :type alias_symbol: str or tuple(str) or None :param is_previous_symbol: flag for 'is previous' :type is_previous_symbol: bool or tuple(bool) or None :param hgnc_symbol: HGNC symbol(s) :type hgnc_symbol: str or tuple(str) or None :param hgnc_identifier: identifiers(s) in :class:`.models.HGNC` :type hgnc_identifier: int or tuple(int) or None :param limit: - if `isinstance(limit,int)==True` -> limit - if `isinstance(limit,tuple)==True` -> format:= tuple(page_number, results_per_page) - if limit == None -> all results :type limit: int or tuple(int) or None :param bool as_df: if `True` results are returned as :class:`pandas.DataFrame` :return: - if `as_df == False` -> list(:class:`.models.AliasSymbol`) - if `as_df == True` -> :class:`pandas.DataFrame` :rtype: list(:class:`.models.AliasSymbol`) or :class:`pandas.DataFrame` """ q = self.session.query(models.AliasSymbol) model_queries_config = ( (alias_symbol, models.AliasSymbol.alias_symbol), (is_previous_symbol, models.AliasSymbol.is_previous_symbol), ) q = self.get_model_queries(q, model_queries_config) one_to_many_queries_config = ( (hgnc_symbol, models.HGNC.symbol), (hgnc_identifier, models.HGNC.identifier) ) q = self.get_one_to_many_queries(q, one_to_many_queries_config) return self._limit_and_df(q, limit, as_df) def alias_name(self, alias_name=None, is_previous_name=None, hgnc_symbol=None, hgnc_identifier=None, limit=None, as_df=False): """Method to query :class:`.models.AliasName` objects in database :param alias_name: alias name(s) :type alias_name: str or tuple(str) or None :param is_previous_name: flag for 'is previous' :type is_previous_name: bool or tuple(bool) or None :param hgnc_symbol: HGNC symbol(s) :type hgnc_symbol: str or tuple(str) or None :param hgnc_identifier: identifiers(s) in :class:`.models.HGNC` :type hgnc_identifier: int or tuple(int) or None :param limit: - if `isinstance(limit,int)==True` -> limit - if `isinstance(limit,tuple)==True` -> format:= tuple(page_number, results_per_page) - if limit == None -> all results :type limit: int or tuple(int) or None :param bool as_df: if `True` results are returned as :class:`pandas.DataFrame` :return: - if `as_df == False` -> list(:class:`.models.AliasSymbol`) - if `as_df == True` -> :class:`pandas.DataFrame` :rtype: list(:class:`.models.AliasSymbol`) or :class:`pandas.DataFrame` """ q = self.session.query(models.AliasName) model_queries_config = ( (alias_name, models.AliasName.alias_name), (is_previous_name, models.AliasName.is_previous_name), ) q = self.get_model_queries(q, model_queries_config) one_to_many_queries_config = ( (hgnc_symbol, models.HGNC.symbol), (hgnc_identifier, models.HGNC.identifier) ) q = self.get_one_to_many_queries(q, one_to_many_queries_config) return self._limit_and_df(q, limit, as_df) def gene_family(self, family_identifier=None, family_name=None, hgnc_symbol=None, hgnc_identifier=None, limit=None, as_df=False): """Method to query :class:`.models.GeneFamily` objects in database :param family_identifier: gene family identifier(s) :type family_identifier: int or tuple(int) or None :param family_name: gene family name(s) :type family_name: str or tuple(str) or None :param hgnc_symbol: HGNC symbol(s) :type hgnc_symbol: str or tuple(str) or None :param hgnc_identifier: identifiers(s) in :class:`.models.HGNC` :type hgnc_identifier: int or tuple(int) or None :param limit: - if `isinstance(limit,int)==True` -> limit - if `isinstance(limit,tuple)==True` -> format:= tuple(page_number, results_per_page) - if limit == None -> all results :type limit: int or tuple(int) or None :param bool as_df: if `True` results are returned as :class:`pandas.DataFrame` :return: - if `as_df == False` -> list(:class:`.models.AliasSymbol`) - if `as_df == True` -> :class:`pandas.DataFrame` :rtype: list(:class:`.models.AliasSymbol`) or :class:`pandas.DataFrame` """ q = self.session.query(models.GeneFamily) model_queries_config = ( (family_identifier, models.GeneFamily.family_identifier), (family_name, models.GeneFamily.family_name), ) q = self.get_model_queries(q, model_queries_config) many_to_many_queries_config = ( (hgnc_symbol, models.GeneFamily.hgncs, models.HGNC.symbol), (hgnc_identifier, models.GeneFamily.hgncs, models.HGNC.identifier), ) q = self.get_many_to_many_queries(q, many_to_many_queries_config) return self._limit_and_df(q, limit, as_df) def ref_seq(self, accession=None, hgnc_symbol=None, hgnc_identifier=None, limit=None, as_df=False): """Method to query :class:`.models.RefSeq` objects in database :param accession: RefSeq accessionl(s) :type accession: str or tuple(str) or None :param hgnc_symbol: HGNC symbol(s) :type hgnc_symbol: str or tuple(str) or None :param hgnc_identifier: identifiers(s) in :class:`.models.HGNC` :type hgnc_identifier: int or tuple(int) or None :param limit: - if `isinstance(limit,int)==True` -> limit - if `isinstance(limit,tuple)==True` -> format:= tuple(page_number, results_per_page) - if limit == None -> all results :type limit: int or tuple(int) or None :param bool as_df: if `True` results are returned as :class:`pandas.DataFrame` :return: - if `as_df == False` -> list(:class:`.models.RefSeq`) - if `as_df == True` -> :class:`pandas.DataFrame` :rtype: list(:class:`.models.RefSeq`) or :class:`pandas.DataFrame` """ q = self.session.query(models.RefSeq) model_queries_config = ( (accession, models.RefSeq.accession), ) q = self.get_model_queries(q, model_queries_config) many_to_many_queries_config = ( (hgnc_symbol, models.RefSeq.hgncs, models.HGNC.symbol), (hgnc_identifier, models.RefSeq.hgncs, models.HGNC.identifier), ) q = self.get_many_to_many_queries(q, many_to_many_queries_config) return self._limit_and_df(q, limit, as_df) def rgd(self, rgdid=None, hgnc_symbol=None, hgnc_identifier=None, limit=None, as_df=False): """Method to query :class:`.models.RGD` objects in database :param rgdid: Rat genome database gene ID(s) :type rgdid: str or tuple(str) or None :param hgnc_symbol: HGNC symbol(s) :type hgnc_symbol: str or tuple(str) or None :param hgnc_identifier: identifiers(s) in :class:`.models.HGNC` :type hgnc_identifier: int or tuple(int) or None :param limit: - if `isinstance(limit,int)==True` -> limit - if `isinstance(limit,tuple)==True` -> format:= tuple(page_number, results_per_page) - if limit == None -> all results :type limit: int or tuple(int) or None :param bool as_df: if `True` results are returned as :class:`pandas.DataFrame` :return: - if `as_df == False` -> list(:class:`.models.RGD`) - if `as_df == True` -> :class:`pandas.DataFrame` :rtype: list(:class:`.models.RGD`) or :class:`pandas.DataFrame` """ q = self.session.query(models.RGD) model_queries_config = ( (rgdid, models.RGD.rgdid), ) q = self.get_model_queries(q, model_queries_config) many_to_many_queries_config = ( (hgnc_symbol, models.RGD.hgncs, models.HGNC.symbol), (hgnc_identifier, models.RGD.hgncs, models.HGNC.identifier), ) q = self.get_many_to_many_queries(q, many_to_many_queries_config) return self._limit_and_df(q, limit, as_df) def omim(self, omimid=None, hgnc_symbol=None, hgnc_identifier=None, limit=None, as_df=False): """Method to query :class:`.models.OMIM` objects in database :param omimid: Online Mendelian Inheritance in Man (OMIM) ID(s) :type omimid: str or tuple(str) or None :param hgnc_symbol: HGNC symbol(s) :type hgnc_symbol: str or tuple(str) or None :param hgnc_identifier: identifiers(s) in :class:`.models.HGNC` :type hgnc_identifier: int or tuple(int) or None :param limit: - if `isinstance(limit,int)==True` -> limit - if `isinstance(limit,tuple)==True` -> format:= tuple(page_number, results_per_page) - if limit == None -> all results :type limit: int or tuple(int) or None :param bool as_df: if `True` results are returned as :class:`pandas.DataFrame` :return: - if `as_df == False` -> list(:class:`.models.OMIM`) - if `as_df == True` -> :class:`pandas.DataFrame` :rtype: list(:class:`.models.OMIM`) or :class:`pandas.DataFrame` """ q = self.session.query(models.OMIM) model_queries_config = ( (omimid, models.OMIM.omimid), ) q = self.get_model_queries(q, model_queries_config) one_to_many_queries_config = ( (hgnc_symbol, models.HGNC.symbol), (hgnc_identifier, models.HGNC.identifier) ) q = self.get_one_to_many_queries(q, one_to_many_queries_config) return self._limit_and_df(q, limit, as_df) def mgd(self, mgdid=None, hgnc_symbol=None, hgnc_identifier=None, limit=None, as_df=False): """Method to query :class:`.models.MGD` objects in database :param mgdid: Mouse genome informatics database ID(s) :type mgdid: str or tuple(str) or None :param hgnc_symbol: HGNC symbol(s) :type hgnc_symbol: str or tuple(str) or None :param hgnc_identifier: identifiers(s) in :class:`.models.HGNC` :type hgnc_identifier: int or tuple(int) or None :param limit: - if `isinstance(limit,int)==True` -> limit - if `isinstance(limit,tuple)==True` -> format:= tuple(page_number, results_per_page) - if limit == None -> all results :type limit: int or tuple(int) or None :param bool as_df: if `True` results are returned as :class:`pandas.DataFrame` :return: - if `as_df == False` -> list(:class:`.models.MGD`) - if `as_df == True` -> :class:`pandas.DataFrame` :rtype: list(:class:`.models.MGD`) or :class:`pandas.DataFrame` """ q = self.session.query(models.MGD) model_queries_config = ( (mgdid, models.MGD.mgdid), ) q = self.get_model_queries(q, model_queries_config) many_to_many_queries_config = ( (hgnc_symbol, models.MGD.hgncs, models.HGNC.symbol), (hgnc_identifier, models.MGD.hgncs, models.HGNC.identifier), ) q = self.get_many_to_many_queries(q, many_to_many_queries_config) return self._limit_and_df(q, limit, as_df) def uniprot(self, uniprotid=None, hgnc_symbol=None, hgnc_identifier=None, limit=None, as_df=False): """Method to query :class:`.models.UniProt` objects in database :param uniprotid: UniProt identifier(s) :type uniprotid: str or tuple(str) or None :param hgnc_symbol: HGNC symbol(s) :type hgnc_symbol: str or tuple(str) or None :param hgnc_identifier: identifiers(s) in :class:`.models.HGNC` :type hgnc_identifier: int or tuple(int) or None :param limit: - if `isinstance(limit,int)==True` -> limit - if `isinstance(limit,tuple)==True` -> format:= tuple(page_number, results_per_page) - if limit == None -> all results :type limit: int or tuple(int) or None :param bool as_df: if `True` results are returned as :class:`pandas.DataFrame` :return: - if `as_df == False` -> list(:class:`.models.UniProt`) - if `as_df == True` -> :class:`pandas.DataFrame` :rtype: list(:class:`.models.UniProt`) or :class:`pandas.DataFrame` """ q = self.session.query(models.UniProt) model_queries_config = ( (uniprotid, models.UniProt.uniprotid), ) q = self.get_model_queries(q, model_queries_config) many_to_many_queries_config = ( (hgnc_symbol, models.UniProt.hgncs, models.HGNC.symbol), (hgnc_identifier, models.UniProt.hgncs, models.HGNC.identifier), ) q = self.get_many_to_many_queries(q, many_to_many_queries_config) return self._limit_and_df(q, limit, as_df) def ccds(self, ccdsid=None, hgnc_symbol=None, hgnc_identifier=None, limit=None, as_df=False): """Method to query :class:`.models.CCDS` objects in database :param ccdsid: Consensus CDS ID(s) :type ccdsid: str or tuple(str) or None :param hgnc_symbol: HGNC symbol(s) :type hgnc_symbol: str or tuple(str) or None :param hgnc_identifier: identifiers(s) in :class:`.models.HGNC` :type hgnc_identifier: int or tuple(int) or None :param limit: - if `isinstance(limit,int)==True` -> limit - if `isinstance(limit,tuple)==True` -> format:= tuple(page_number, results_per_page) - if limit == None -> all results :type limit: int or tuple(int) or None :param bool as_df: if `True` results are returned as :class:`pandas.DataFrame` :return: - if `as_df == False` -> list(:class:`.models.CCDS`) - if `as_df == True` -> :class:`pandas.DataFrame` :rtype: list(:class:`.models.CCDS`) or :class:`pandas.DataFrame` """ q = self.session.query(models.CCDS) model_queries_config = ( (ccdsid, models.CCDS.ccdsid), ) q = self.get_model_queries(q, model_queries_config) one_to_many_queries_config = ( (hgnc_symbol, models.HGNC.symbol), (hgnc_identifier, models.HGNC.identifier) ) q = self.get_one_to_many_queries(q, one_to_many_queries_config) return self._limit_and_df(q, limit, as_df) def pubmed(self, pubmedid=None, hgnc_symbol=None, hgnc_identifier=None, limit=None, as_df=False): """Method to query :class:`.models.PubMed` objects in database :param pubmedid: alias symbol(s) :type pubmedid: str or tuple(str) or None :param hgnc_symbol: HGNC symbol(s) :type hgnc_symbol: str or tuple(str) or None :param hgnc_identifier: identifiers(s) in :class:`.models.HGNC` :type hgnc_identifier: int or tuple(int) or None :param limit: - if `isinstance(limit,int)==True` -> limit - if `isinstance(limit,tuple)==True` -> format:= tuple(page_number, results_per_page) - if limit == None -> all results :type limit: int or tuple(int) or None :param bool as_df: if `True` results are returned as :class:`pandas.DataFrame` :return: - if `as_df == False` -> list(:class:`.models.PubMed`) - if `as_df == True` -> :class:`pandas.DataFrame` :rtype: list(:class:`.models.PubMed`) or :class:`pandas.DataFrame` """ q = self.session.query(models.PubMed) model_queries_config = ( (pubmedid, models.PubMed.pubmedid), ) q = self.get_model_queries(q, model_queries_config) many_to_many_queries_config = ( (hgnc_symbol, models.PubMed.hgncs, models.HGNC.symbol), (hgnc_identifier, models.PubMed.hgncs, models.HGNC.identifier), ) q = self.get_many_to_many_queries(q, many_to_many_queries_config) return self._limit_and_df(q, limit, as_df) def ena(self, enaid=None, hgnc_symbol=None, hgnc_identifier=None, limit=None, as_df=False): """Method to query :class:`.models.ENA` objects in database :param enaid: European Nucleotide Archive (ENA) identifier(s) :type enaid: str or tuple(str) or None :param hgnc_symbol: HGNC symbol(s) :type hgnc_symbol: str or tuple(str) or None :param hgnc_identifier: identifiers(s) in :class:`.models.HGNC` :type hgnc_identifier: int or tuple(int) or None :param limit: - if `isinstance(limit,int)==True` -> limit - if `isinstance(limit,tuple)==True` -> format:= tuple(page_number, results_per_page) - if limit == None -> all results :type limit: int or tuple(int) or None :param bool as_df: if `True` results are returned as :class:`pandas.DataFrame` :return: - if `as_df == False` -> list(:class:`.models.ENA`) - if `as_df == True` -> :class:`pandas.DataFrame` :rtype: list(:class:`.models.ENA`) or :class:`pandas.DataFrame` """ q = self.session.query(models.ENA) model_queries_config = ( (enaid, models.ENA.enaid), ) q = self.get_model_queries(q, model_queries_config) many_to_many_queries_config = ( (hgnc_symbol, models.ENA.hgncs, models.HGNC.symbol), (hgnc_identifier, models.ENA.hgncs, models.HGNC.identifier), ) q = self.get_many_to_many_queries(q, many_to_many_queries_config) return self._limit_and_df(q, limit, as_df) def enzyme(self, ec_number=None, hgnc_symbol=None, hgnc_identifier=None, limit=None, as_df=False): """Method to query :class:`.models.Enzyme` objects in database :param ec_number: Enzyme Commission number (EC number)(s) :type ec_number: str or tuple(str) or None :param hgnc_symbol: HGNC symbol(s) :type hgnc_symbol: str or tuple(str) or None :param hgnc_identifier: identifiers(s) in :class:`.models.HGNC` :type hgnc_identifier: int or tuple(int) or None :param limit: - if `isinstance(limit,int)==True` -> limit - if `isinstance(limit,tuple)==True` -> format:= tuple(page_number, results_per_page) - if limit == None -> all results :type limit: int or tuple(int) or None :param bool as_df: if `True` results are returned as :class:`pandas.DataFrame` :return: - if `as_df == False` -> list(:class:`.models.Enzyme`) - if `as_df == True` -> :class:`pandas.DataFrame` :rtype: list(:class:`.models.Enzyme`) or :class:`pandas.DataFrame` """ q = self.session.query(models.Enzyme) model_queries_config = ( (ec_number, models.Enzyme.ec_number), ) q = self.get_model_queries(q, model_queries_config) many_to_many_queries_config = ( (hgnc_symbol, models.Enzyme.hgncs, models.HGNC.symbol), (hgnc_identifier, models.Enzyme.hgncs, models.HGNC.identifier), ) q = self.get_many_to_many_queries(q, many_to_many_queries_config) return self._limit_and_df(q, limit, as_df) def lsdb(self, lsdb=None, url=None, hgnc_symbol=None, hgnc_identifier=None, limit=None, as_df=False): """Method to query :class:`.models.LSDB` objects in database :param lsdb: name(s) of the Locus Specific Mutation Database :type lsdb: str or tuple(str) or None :param url: URL of the Locus Specific Mutation Database :type url: str or tuple(str) or None :param hgnc_symbol: HGNC symbol(s) :type hgnc_symbol: str or tuple(str) or None :param hgnc_identifier: identifiers(s) in :class:`.models.HGNC` :type hgnc_identifier: int or tuple(int) or None :param limit: - if `isinstance(limit,int)==True` -> limit - if `isinstance(limit,tuple)==True` -> format:= tuple(page_number, results_per_page) - if limit == None -> all results :type limit: int or tuple(int) or None :param bool as_df: if `True` results are returned as :class:`pandas.DataFrame` :return: - if `as_df == False` -> list(:class:`.models.LSDB`) - if `as_df == True` -> :class:`pandas.DataFrame` :rtype: list(:class:`.models.LSDB`) or :class:`pandas.DataFrame` """ q = self.session.query(models.LSDB) model_queries_config = ( (lsdb, models.LSDB.lsdb), (url, models.LSDB.url), ) q = self.get_model_queries(q, model_queries_config) one_to_many_queries_config = ( (hgnc_symbol, models.HGNC.symbol), (hgnc_identifier, models.HGNC.identifier) ) q = self.get_one_to_many_queries(q, one_to_many_queries_config) return self._limit_and_df(q, limit, as_df)
class QueryManager(BaseDbManager): '''Query interface to database.''' def _limit_and_df(self, query, limit, as_df=False): '''adds a limit (limit==None := no limit) to any query and allow a return as pandas.DataFrame :param bool as_df: if is set to True results return as pandas.DataFrame :param `sqlalchemy.orm.query.Query` query: SQL Alchemy query :param int,tuple limit: maximum number of results :return: query result of pyhgnc.manager.models.XY objects ''' pass def get_model_queries(self, query_obj, model_queries_config): '''use this if your are searching for a field in the same model''' pass def get_many_to_many_queries(self, query_obj, many_to_many_queries_config): pass def get_one_to_many_queries(self, query_obj, one_to_many_queries): pass @classmethod def _one_to_many_query(cls, query_obj, search4, model_attrib): '''extends and returns a SQLAlchemy query object to allow one-to-many queries :param query_obj: SQL Alchemy query object :param str search4: search string :param model_attrib: attribute in model ''' pass @classmethod def _many_to_many_query(cls, query_obj, search4, join_attrib, many2many_attrib): pass @classmethod def _model_query(cls, query_obj, search4, model_attrib): pass def hgnc(self, name=None, symbol=None, identifier=None, status=None, uuid=None, locus_group=None, orphanet=None, locus_type=None, date_name_changed=None, date_modified=None, date_symbol_changed=None, pubmedid=None, date_approved_reserved=None, ensembl_gene=None, horde=None, vega=None, lncrnadb=None, uniprotid=None, entrez=None, mirbase=None, iuphar=None, ucsc=None, snornabase=None, gene_family_name=None, mgdid=None, pseudogeneorg=None, bioparadigmsslc=None, locationsortable=None, ec_number=None, refseq_accession=None, merops=None, location=None, cosmic=None, imgt=None, enaid=None, alias_symbol=None, alias_name=None, rgdid=None, omimid=None, ccdsid=None, lsdbs=None, ortholog_species=None, gene_family_identifier=None, limit=None, as_df=False): '''Method to query :class:`pyhgnc.manager.models.Pmid` :param name: HGNC approved name for the gene :type name: str or tuple(str) or None :param symbol: HGNC approved gene symbol :type symbol: str or tuple(str) or None :param identifier: HGNC ID. A unique ID created by the HGNC for every approved symbol :type identifier: int or tuple(int) or None :param status: Status of the symbol report, which can be either "Approved" or "Entry Withdrawn" :type status: str or tuple(str) or None :param uuid: universally unique identifier :type uuid: str or tuple(str) or None :param locus_group: group name for a set of related locus types as defined by the HGNC :type locus_group: str or tuple(str) or None :param orphanet: Orphanet database identifier (related to rare diseases and orphan drugs) :type orphanet: int ot tuple(int) or None :param locus_type: locus type as defined by the HGNC (e.g. RNA, transfer) :type locus_type: str or tuple(str) or None :param date_name_changed: date the gene name was last changed (format: YYYY-mm-dd, e.g. 2017-09-29) :type date_name_changed: str or tuple(str) or None :param date_modified: date the entry was last modified (format: YYYY-mm-dd, e.g. 2017-09-29) :type date_modified: str or tuple(str) or None :param date_symbol_changed: date the gene symbol was last changed (format: YYYY-mm-dd, e.g. 2017-09-29) :type date_symbol_changed: str or tuple(str) or None :param date_approved_reserved: date the entry was first approved (format: YYYY-mm-dd, e.g. 2017-09-29) :type date_approved_reserved: str or tuple(str) or None :param pubmedid: PubMed identifier :type pubmedid: int ot tuple(int) or None :param ensembl_gene: Ensembl gene ID. Found within the "GENE RESOURCES" section of the gene symbol report :type ensembl_gene: str or tuple(str) or None :param horde: symbol used within HORDE for the gene (not available in JSON) :type horde: str or tuple(str) or None :param vega: Vega gene ID. Found within the "GENE RESOURCES" section of the gene symbol report :type vega: str or tuple(str) or None :param lncrnadb: Noncoding RNA Database identifier :type lncrnadb: str or tuple(str) or None :param uniprotid: UniProt identifier :type uniprotid: str or tuple(str) or None :param entrez: Entrez gene ID. Found within the "GENE RESOURCES" section of the gene symbol report :type entrez: str or tuple(str) or None :param mirbase: miRBase ID :type mirbase: str or tuple(str) or None :param iuphar: The objectId used to link to the IUPHAR/BPS Guide to PHARMACOLOGY database :type iuphar: str or tuple(str) or None :param ucsc: UCSC gene ID. Found within the "GENE RESOURCES" section of the gene symbol report :type ucsc: str or tuple(str) or None :param snornabase: snoRNABase ID :type snornabase: str or tuple(str) or None :param gene_family_name: Gene family name :type gene_family_name: str or tuple(str) or None :param gene_family_identifier: Gene family identifier :type gene_family_name: int or tuple(int) or None :param mgdid: Mouse Genome Database identifier :type mgdid: int ot tuple(int) or None :param imgt: Symbol used within international ImMunoGeneTics information system :type imgt: str or tuple(str) or None :param enaid: European Nucleotide Archive (ENA) identifier :type enaid: str or tuple(str) or None :param alias_symbol: Other symbols used to refer to a gene :type alias_symbol: str or tuple(str) or None :param alias_name: Other names used to refer to a gene :type alias_name: str or tuple(str) or None :param pseudogeneorg: Pseudogene.org ID :type pseudogeneorg: str or tuple(str) or None :param bioparadigmsslc: Symbol used to link to the SLC tables database at bioparadigms.org for the gene :type bioparadigmsslc: str or tuple(str) or None :param locationsortable: locations sortable :type locationsortable: str or tuple(str) or None :param ec_number: Enzyme Commission number (EC number) :type ec_number: str or tuple(str) or None :param refseq_accession: RefSeq nucleotide accession(s) :type refseq_accession: str or tuple(str) or None :param merops: ID used to link to the MEROPS peptidase database :type merops: str or tuple(str) or None :param location: Cytogenetic location of the gene (e.g. 2q34). :type location: str or tuple(str) or None :param cosmic: Symbol used within the Catalogue of somatic mutations in cancer for the gene :type cosmic: str or tuple(str) or None :param rgdid: Rat genome database gene ID :type rgdid: int or tuple(int) or None :param omimid: Online Mendelian Inheritance in Man (OMIM) ID :type omimid: int or tuple(int) or None :param ccdsid: Consensus CDS ID :type ccdsid: str or tuple(str) or None :param lsdbs: Locus Specific Mutation Database Name :type lsdbs: str or tuple(str) or None :param ortholog_species: Ortholog species NCBI taxonomy identifier :type ortholog_species: int or tuple(int) or None :param limit: - if `isinstance(limit,int)==True` -> limit - if `isinstance(limit,tuple)==True` -> format:= tuple(page_number, results_per_page) - if limit == None -> all results :type limit: int or tuple(int) or None :param bool as_df: if `True` results are returned as :class:`pandas.DataFrame` :return: - if `as_df == False` -> list(:class:`.models.Keyword`) - if `as_df == True` -> :class:`pandas.DataFrame` :rtype: list[models.HGNC] ''' pass def orthology_prediction(self, ortholog_species=None, human_entrez_gene=None, human_ensembl_gene=None, human_name=None, human_symbol=None, human_chr=None, human_assert_ids=None, ortholog_species_entrez_gene=None, ortholog_species_ensembl_gene=None, ortholog_species_db_id=None, ortholog_species_name=None, ortholog_species_symbol=None, ortholog_species_chr=None, ortholog_species_assert_ids=None, support=None, hgnc_identifier=None, hgnc_symbol=None, limit=None, as_df=False): '''Method to query :class:`pyhgnc.manager.models.OrthologyPrediction` :param int ortholog_species: NCBI taxonomy identifier :param str human_entrez_gene: Entrez gene identifier :param str human_ensembl_gene: Ensembl identifier :param str human_name: human gene name :param str human_symbol: human gene symbol :param str human_chr: human chromosome :param str human_assert_ids: :param str ortholog_species_entrez_gene: Entrez gene identifier for ortholog :param str ortholog_species_ensembl_gene: Ensembl gene identifier for ortholog :param str ortholog_species_db_id: Species specific database identifier (e.g. MGI:1920453) :param str ortholog_species_name: gene name of ortholog :param str ortholog_species_symbol: gene symbol of ortholog :param str ortholog_species_chr: chromosome identifier (ortholog) :param str ortholog_species_assert_ids: :param str support: :param int hgnc_identifier: HGNC identifier :param str hgnc_symbol: HGNC symbol :param limit: - if `isinstance(limit,int)==True` -> limit - if `isinstance(limit,tuple)==True` -> format:= tuple(page_number, results_per_page) - if limit == None -> all results :type limit: int or tuple(int) or None :param bool as_df: if `True` results are returned as :class:`pandas.DataFrame` :return: - if `as_df == False` -> list(:class:`.models.Keyword`) - if `as_df == True` -> :class:`pandas.DataFrame` :rtype: list(:class:`.models.Keyword`) or :class:`pandas.DataFrame` ''' pass def alias_symbol(self, alias_symbol=None, is_previous_symbol=None, hgnc_symbol=None, hgnc_identifier=None, limit=None, as_df=False): '''Method to query :class:`.models.AliasSymbol` objects in database :param alias_symbol: alias symbol(s) :type alias_symbol: str or tuple(str) or None :param is_previous_symbol: flag for 'is previous' :type is_previous_symbol: bool or tuple(bool) or None :param hgnc_symbol: HGNC symbol(s) :type hgnc_symbol: str or tuple(str) or None :param hgnc_identifier: identifiers(s) in :class:`.models.HGNC` :type hgnc_identifier: int or tuple(int) or None :param limit: - if `isinstance(limit,int)==True` -> limit - if `isinstance(limit,tuple)==True` -> format:= tuple(page_number, results_per_page) - if limit == None -> all results :type limit: int or tuple(int) or None :param bool as_df: if `True` results are returned as :class:`pandas.DataFrame` :return: - if `as_df == False` -> list(:class:`.models.AliasSymbol`) - if `as_df == True` -> :class:`pandas.DataFrame` :rtype: list(:class:`.models.AliasSymbol`) or :class:`pandas.DataFrame` ''' pass def alias_name(self, alias_name=None, is_previous_name=None, hgnc_symbol=None, hgnc_identifier=None, limit=None, as_df=False): '''Method to query :class:`.models.AliasName` objects in database :param alias_name: alias name(s) :type alias_name: str or tuple(str) or None :param is_previous_name: flag for 'is previous' :type is_previous_name: bool or tuple(bool) or None :param hgnc_symbol: HGNC symbol(s) :type hgnc_symbol: str or tuple(str) or None :param hgnc_identifier: identifiers(s) in :class:`.models.HGNC` :type hgnc_identifier: int or tuple(int) or None :param limit: - if `isinstance(limit,int)==True` -> limit - if `isinstance(limit,tuple)==True` -> format:= tuple(page_number, results_per_page) - if limit == None -> all results :type limit: int or tuple(int) or None :param bool as_df: if `True` results are returned as :class:`pandas.DataFrame` :return: - if `as_df == False` -> list(:class:`.models.AliasSymbol`) - if `as_df == True` -> :class:`pandas.DataFrame` :rtype: list(:class:`.models.AliasSymbol`) or :class:`pandas.DataFrame` ''' pass def gene_family(self, family_identifier=None, family_name=None, hgnc_symbol=None, hgnc_identifier=None, limit=None, as_df=False): '''Method to query :class:`.models.GeneFamily` objects in database :param family_identifier: gene family identifier(s) :type family_identifier: int or tuple(int) or None :param family_name: gene family name(s) :type family_name: str or tuple(str) or None :param hgnc_symbol: HGNC symbol(s) :type hgnc_symbol: str or tuple(str) or None :param hgnc_identifier: identifiers(s) in :class:`.models.HGNC` :type hgnc_identifier: int or tuple(int) or None :param limit: - if `isinstance(limit,int)==True` -> limit - if `isinstance(limit,tuple)==True` -> format:= tuple(page_number, results_per_page) - if limit == None -> all results :type limit: int or tuple(int) or None :param bool as_df: if `True` results are returned as :class:`pandas.DataFrame` :return: - if `as_df == False` -> list(:class:`.models.AliasSymbol`) - if `as_df == True` -> :class:`pandas.DataFrame` :rtype: list(:class:`.models.AliasSymbol`) or :class:`pandas.DataFrame` ''' pass def ref_seq(self, accession=None, hgnc_symbol=None, hgnc_identifier=None, limit=None, as_df=False): '''Method to query :class:`.models.RefSeq` objects in database :param accession: RefSeq accessionl(s) :type accession: str or tuple(str) or None :param hgnc_symbol: HGNC symbol(s) :type hgnc_symbol: str or tuple(str) or None :param hgnc_identifier: identifiers(s) in :class:`.models.HGNC` :type hgnc_identifier: int or tuple(int) or None :param limit: - if `isinstance(limit,int)==True` -> limit - if `isinstance(limit,tuple)==True` -> format:= tuple(page_number, results_per_page) - if limit == None -> all results :type limit: int or tuple(int) or None :param bool as_df: if `True` results are returned as :class:`pandas.DataFrame` :return: - if `as_df == False` -> list(:class:`.models.RefSeq`) - if `as_df == True` -> :class:`pandas.DataFrame` :rtype: list(:class:`.models.RefSeq`) or :class:`pandas.DataFrame` ''' pass def rgd(self, rgdid=None, hgnc_symbol=None, hgnc_identifier=None, limit=None, as_df=False): '''Method to query :class:`.models.RGD` objects in database :param rgdid: Rat genome database gene ID(s) :type rgdid: str or tuple(str) or None :param hgnc_symbol: HGNC symbol(s) :type hgnc_symbol: str or tuple(str) or None :param hgnc_identifier: identifiers(s) in :class:`.models.HGNC` :type hgnc_identifier: int or tuple(int) or None :param limit: - if `isinstance(limit,int)==True` -> limit - if `isinstance(limit,tuple)==True` -> format:= tuple(page_number, results_per_page) - if limit == None -> all results :type limit: int or tuple(int) or None :param bool as_df: if `True` results are returned as :class:`pandas.DataFrame` :return: - if `as_df == False` -> list(:class:`.models.RGD`) - if `as_df == True` -> :class:`pandas.DataFrame` :rtype: list(:class:`.models.RGD`) or :class:`pandas.DataFrame` ''' pass def omim(self, omimid=None, hgnc_symbol=None, hgnc_identifier=None, limit=None, as_df=False): '''Method to query :class:`.models.OMIM` objects in database :param omimid: Online Mendelian Inheritance in Man (OMIM) ID(s) :type omimid: str or tuple(str) or None :param hgnc_symbol: HGNC symbol(s) :type hgnc_symbol: str or tuple(str) or None :param hgnc_identifier: identifiers(s) in :class:`.models.HGNC` :type hgnc_identifier: int or tuple(int) or None :param limit: - if `isinstance(limit,int)==True` -> limit - if `isinstance(limit,tuple)==True` -> format:= tuple(page_number, results_per_page) - if limit == None -> all results :type limit: int or tuple(int) or None :param bool as_df: if `True` results are returned as :class:`pandas.DataFrame` :return: - if `as_df == False` -> list(:class:`.models.OMIM`) - if `as_df == True` -> :class:`pandas.DataFrame` :rtype: list(:class:`.models.OMIM`) or :class:`pandas.DataFrame` ''' pass def mgd(self, mgdid=None, hgnc_symbol=None, hgnc_identifier=None, limit=None, as_df=False): '''Method to query :class:`.models.MGD` objects in database :param mgdid: Mouse genome informatics database ID(s) :type mgdid: str or tuple(str) or None :param hgnc_symbol: HGNC symbol(s) :type hgnc_symbol: str or tuple(str) or None :param hgnc_identifier: identifiers(s) in :class:`.models.HGNC` :type hgnc_identifier: int or tuple(int) or None :param limit: - if `isinstance(limit,int)==True` -> limit - if `isinstance(limit,tuple)==True` -> format:= tuple(page_number, results_per_page) - if limit == None -> all results :type limit: int or tuple(int) or None :param bool as_df: if `True` results are returned as :class:`pandas.DataFrame` :return: - if `as_df == False` -> list(:class:`.models.MGD`) - if `as_df == True` -> :class:`pandas.DataFrame` :rtype: list(:class:`.models.MGD`) or :class:`pandas.DataFrame` ''' pass def uniprot(self, uniprotid=None, hgnc_symbol=None, hgnc_identifier=None, limit=None, as_df=False): '''Method to query :class:`.models.UniProt` objects in database :param uniprotid: UniProt identifier(s) :type uniprotid: str or tuple(str) or None :param hgnc_symbol: HGNC symbol(s) :type hgnc_symbol: str or tuple(str) or None :param hgnc_identifier: identifiers(s) in :class:`.models.HGNC` :type hgnc_identifier: int or tuple(int) or None :param limit: - if `isinstance(limit,int)==True` -> limit - if `isinstance(limit,tuple)==True` -> format:= tuple(page_number, results_per_page) - if limit == None -> all results :type limit: int or tuple(int) or None :param bool as_df: if `True` results are returned as :class:`pandas.DataFrame` :return: - if `as_df == False` -> list(:class:`.models.UniProt`) - if `as_df == True` -> :class:`pandas.DataFrame` :rtype: list(:class:`.models.UniProt`) or :class:`pandas.DataFrame` ''' pass def ccds(self, ccdsid=None, hgnc_symbol=None, hgnc_identifier=None, limit=None, as_df=False): '''Method to query :class:`.models.CCDS` objects in database :param ccdsid: Consensus CDS ID(s) :type ccdsid: str or tuple(str) or None :param hgnc_symbol: HGNC symbol(s) :type hgnc_symbol: str or tuple(str) or None :param hgnc_identifier: identifiers(s) in :class:`.models.HGNC` :type hgnc_identifier: int or tuple(int) or None :param limit: - if `isinstance(limit,int)==True` -> limit - if `isinstance(limit,tuple)==True` -> format:= tuple(page_number, results_per_page) - if limit == None -> all results :type limit: int or tuple(int) or None :param bool as_df: if `True` results are returned as :class:`pandas.DataFrame` :return: - if `as_df == False` -> list(:class:`.models.CCDS`) - if `as_df == True` -> :class:`pandas.DataFrame` :rtype: list(:class:`.models.CCDS`) or :class:`pandas.DataFrame` ''' pass def pubmed(self, pubmedid=None, hgnc_symbol=None, hgnc_identifier=None, limit=None, as_df=False): '''Method to query :class:`.models.PubMed` objects in database :param pubmedid: alias symbol(s) :type pubmedid: str or tuple(str) or None :param hgnc_symbol: HGNC symbol(s) :type hgnc_symbol: str or tuple(str) or None :param hgnc_identifier: identifiers(s) in :class:`.models.HGNC` :type hgnc_identifier: int or tuple(int) or None :param limit: - if `isinstance(limit,int)==True` -> limit - if `isinstance(limit,tuple)==True` -> format:= tuple(page_number, results_per_page) - if limit == None -> all results :type limit: int or tuple(int) or None :param bool as_df: if `True` results are returned as :class:`pandas.DataFrame` :return: - if `as_df == False` -> list(:class:`.models.PubMed`) - if `as_df == True` -> :class:`pandas.DataFrame` :rtype: list(:class:`.models.PubMed`) or :class:`pandas.DataFrame` ''' pass def ena(self, enaid=None, hgnc_symbol=None, hgnc_identifier=None, limit=None, as_df=False): '''Method to query :class:`.models.ENA` objects in database :param enaid: European Nucleotide Archive (ENA) identifier(s) :type enaid: str or tuple(str) or None :param hgnc_symbol: HGNC symbol(s) :type hgnc_symbol: str or tuple(str) or None :param hgnc_identifier: identifiers(s) in :class:`.models.HGNC` :type hgnc_identifier: int or tuple(int) or None :param limit: - if `isinstance(limit,int)==True` -> limit - if `isinstance(limit,tuple)==True` -> format:= tuple(page_number, results_per_page) - if limit == None -> all results :type limit: int or tuple(int) or None :param bool as_df: if `True` results are returned as :class:`pandas.DataFrame` :return: - if `as_df == False` -> list(:class:`.models.ENA`) - if `as_df == True` -> :class:`pandas.DataFrame` :rtype: list(:class:`.models.ENA`) or :class:`pandas.DataFrame` ''' pass def enzyme(self, ec_number=None, hgnc_symbol=None, hgnc_identifier=None, limit=None, as_df=False): '''Method to query :class:`.models.Enzyme` objects in database :param ec_number: Enzyme Commission number (EC number)(s) :type ec_number: str or tuple(str) or None :param hgnc_symbol: HGNC symbol(s) :type hgnc_symbol: str or tuple(str) or None :param hgnc_identifier: identifiers(s) in :class:`.models.HGNC` :type hgnc_identifier: int or tuple(int) or None :param limit: - if `isinstance(limit,int)==True` -> limit - if `isinstance(limit,tuple)==True` -> format:= tuple(page_number, results_per_page) - if limit == None -> all results :type limit: int or tuple(int) or None :param bool as_df: if `True` results are returned as :class:`pandas.DataFrame` :return: - if `as_df == False` -> list(:class:`.models.Enzyme`) - if `as_df == True` -> :class:`pandas.DataFrame` :rtype: list(:class:`.models.Enzyme`) or :class:`pandas.DataFrame` ''' pass def lsdb(self, lsdb=None, url=None, hgnc_symbol=None, hgnc_identifier=None, limit=None, as_df=False): '''Method to query :class:`.models.LSDB` objects in database :param lsdb: name(s) of the Locus Specific Mutation Database :type lsdb: str or tuple(str) or None :param url: URL of the Locus Specific Mutation Database :type url: str or tuple(str) or None :param hgnc_symbol: HGNC symbol(s) :type hgnc_symbol: str or tuple(str) or None :param hgnc_identifier: identifiers(s) in :class:`.models.HGNC` :type hgnc_identifier: int or tuple(int) or None :param limit: - if `isinstance(limit,int)==True` -> limit - if `isinstance(limit,tuple)==True` -> format:= tuple(page_number, results_per_page) - if limit == None -> all results :type limit: int or tuple(int) or None :param bool as_df: if `True` results are returned as :class:`pandas.DataFrame` :return: - if `as_df == False` -> list(:class:`.models.LSDB`) - if `as_df == True` -> :class:`pandas.DataFrame` :rtype: list(:class:`.models.LSDB`) or :class:`pandas.DataFrame` ''' pass
26
19
43
10
16
17
2
1.08
1
18
15
0
19
0
22
26
971
236
353
125
283
382
165
78
142
6
2
2
44
145,128
LeKono/pyhgnc
LeKono_pyhgnc/tests/test_query.py
test_query.TestQuery
class TestQuery(unittest.TestCase): @classmethod def setUpClass(cls): dir_path = os.path.dirname(os.path.realpath(__file__)) test_data = os.path.join(dir_path, 'data') hgnc_test_file = os.path.join(test_data, 'hgnc_test.json') hcop_test_file = os.path.join(test_data, 'hcop_test.txt') test_connection = sqlalchemy_connection_string_4_tests pyhgnc.update(connection=test_connection, hgnc_file_path=hgnc_test_file, hcop_file_path=hcop_test_file) cls.query = QueryManager(connection=test_connection) @classmethod def tearDownClass(cls): cls.query.session.close() if os.path.isfile(DEFAULT_TEST_DATABASE_LOCATION): os.remove(DEFAULT_TEST_DATABASE_LOCATION) def test_number_of_inserts(self): models_list = [ (models.HGNC, 3), (models.AliasSymbol, 7), # Alias symbol and previous symbol (models.AliasName, 1), # Alias name and previous name (models.GeneFamily, 3), (models.RefSeq, 3), (models.RGD, 3), (models.OMIM, 1), (models.MGD, 3), (models.UniProt, 3), (models.CCDS, 6), (models.PubMed, 4), (models.ENA, 2), (models.Enzyme, 0), (models.LSDB, 0), (models.OrthologyPrediction, 70), ] for model, num_of_results in models_list: self.assertEqual(num_of_results, self.query.session.query(model).count()) def test_query_hgnc(self): A1BG_dict = { 'bioparadigmsslc': None, 'cosmic': 'A1BG', 'date_approved_reserved': '1989-06-30', 'date_modified': '2015-07-13', 'date_name_changed': None, 'date_symbol_changed': None, 'ensembl_gene': 'ENSG00000121410', 'entrez': '1', 'horde': None, 'identifier': 5, 'imgt': None, 'iuphar': None, 'lncrnadb': None, 'location': '19q13.43', 'locationsortable': '19q13.43', 'locus_group': 'protein-coding gene', 'locus_type': 'gene with protein product', 'merops': 'I43.950', 'mirbase': None, 'name': 'alpha-1-B glycoprotein', 'orphanet': None, 'pseudogeneorg': None, 'snornabase': None, 'status': 'Approved', 'symbol': 'A1BG', 'ucsc': 'uc002qsd.5', 'uuid': 'fe3e34f6-c539-4337-82c1-1b4e8c115992', 'vega': 'OTTHUMG00000183507' } hgnc = self.query.hgnc(symbol="A1BG")[0] self.assertIsInstance(hgnc, models.HGNC) self.assertEqual(hgnc.symbol, "A1BG") self.assertEqual(hgnc.to_dict(), A1BG_dict) hgnc_df = self.query.hgnc(symbol="A1BG", as_df=True) self.assertIsInstance(hgnc_df, DataFrame) def test_query_orthology_prediction(self): orthology_predictions = self.query.orthology_prediction(hgnc_identifier=5) self.assertEqual(len(orthology_predictions), 24) for prediction in orthology_predictions: self.assertIsInstance(prediction, models.OrthologyPrediction) orthology_predictions_df = self.query.orthology_prediction(as_df=True) self.assertIsInstance(orthology_predictions_df, DataFrame) def test_query_alias_symbol(self): ZSWIM1_aliases = [ { 'hgnc_symbol': 'ZSWIM1', 'hgnc_identifier': 16155, 'alias_symbol': "dJ337O18.5", 'is_previous_symbol': False }, { 'hgnc_symbol': 'ZSWIM1', 'hgnc_identifier': 16155, 'alias_symbol': "C20orf162", 'is_previous_symbol': True } ] aliases = self.query.alias_symbol(hgnc_symbol="ZSWIM1") for alias in aliases: self.assertIsInstance(alias, models.AliasSymbol) self.assertIn(alias.to_dict(), ZSWIM1_aliases) def test_query_alias_name(self): ZSWIM1_aliases = [{ 'hgnc_symbol': 'ZSWIM1', 'hgnc_identifier': 16155, 'alias_name': "chromosome 20 open reading frame 162", 'is_previous_name': True }] alias = self.query.alias_name(hgnc_symbol="ZSWIM1")[0] self.assertIsInstance(alias, models.AliasName) self.assertIn(alias.to_dict(), ZSWIM1_aliases) def test_query_gene_family(self): families = [ { 'family_identifier': 594, 'family_name': 'Immunoglobulin like domain containing', 'hgnc_symbols': [ 'A1BG' ] }, { 'family_identifier': 90, 'family_name': 'Zinc fingers SWIM-type', 'hgnc_symbols': [ 'ZSWIM1' ] }, { 'family_identifier': 725, 'family_name': 'RNA binding motif containing', 'hgnc_symbols': [ 'A1CF' ] } ] gene_families = self.query.gene_family() for family in gene_families: self.assertIsInstance(family, models.GeneFamily) self.assertIn(family.to_dict(), families) A1BG_family = self.query.gene_family(hgnc_identifier=5)[0] self.assertEqual(A1BG_family.to_dict(), families[0]) ZSWIM1_family = self.query.gene_family(hgnc_symbol="ZSWIM1")[0] self.assertEqual(ZSWIM1_family.to_dict(), families[1]) A1CF_family = self.query.gene_family(family_identifier=725)[0] self.assertEqual(A1CF_family.to_dict(), families[2]) def test_query_ref_seq(self): A1CF_ref_seq = { 'hgnc_symbols': [ "A1CF" ], 'accession': "NM_014576" } ref_seq = self.query.ref_seq(hgnc_symbol="A1CF")[0] self.assertIsInstance(ref_seq, models.RefSeq) self.assertEqual(ref_seq.to_dict(), A1CF_ref_seq) def test_query_rgd(self): ZSQIM1_rgd = { 'rgdid': 1305715, 'hgnc_symbols': [ 'ZSWIM1' ] } rgd = self.query.rgd(rgdid=1305715)[0] self.assertIsInstance(rgd, models.RGD) self.assertEqual(rgd.to_dict(), ZSQIM1_rgd) def test_query_omim(self): A1BG_omim = { 'hgnc_symbol': "A1BG", 'hgnc_identifier': 5, 'omimid': 138670 } omim = self.query.omim(hgnc_identifier=5)[0] self.assertIsInstance(omim, models.OMIM) self.assertEqual(omim.to_dict(), A1BG_omim) def test_query_mgd(self): A1CF_mgd = { 'hgnc_symbols': [ "A1CF" ], 'mgdid': 1917115 } mgd = self.query.mgd(hgnc_symbol="A1CF")[0] self.assertIsInstance(mgd, models.MGD) self.assertEqual(mgd.to_dict(), A1CF_mgd) def test_query_uniprot(self): A1CF_uniprot = { 'hgnc_symbols': [ "A1CF" ], 'uniprotid': "Q9NQ94" } uniprot = self.query.uniprot(hgnc_identifier=24086)[0] self.assertIsInstance(uniprot, models.UniProt) self.assertEqual(uniprot.to_dict(), A1CF_uniprot) def test_query_ccds(self): A1CF_ccds = [ { 'hgnc_symbol': "A1CF", 'hgnc_identifier': 24086, 'ccdsid': "CCDS7241" }, { 'hgnc_symbol': "A1CF", 'hgnc_identifier': 24086, 'ccdsid': "CCDS7242" }, { 'hgnc_symbol': "A1CF", 'hgnc_identifier': 24086, 'ccdsid': "CCDS7243" }, { 'hgnc_symbol': "A1CF", 'hgnc_identifier': 24086, 'ccdsid': "CCDS73133" }, ] ccds = self.query.ccds(hgnc_identifier=24086) for ccd in ccds: self.assertIsInstance(ccd, models.CCDS) self.assertIn(ccd.to_dict(), A1CF_ccds) def test_query_pubmed(self): A1CF_pubmeds = [ { 'hgnc_symbols': [ "A1CF" ], 'pubmedid': 11815617 }, { 'hgnc_symbols': [ "A1CF" ], 'pubmedid': 11072063 } ] pubmeds = self.query.pubmed(hgnc_symbol="A1CF") for pubmed in pubmeds: self.assertIsInstance(pubmed, models.PubMed) self.assertIn(pubmed.to_dict(), A1CF_pubmeds) def test_query_ena(self): A1CF_ena = { 'hgnc_symbols': [ "A1CF" ], 'enaid': "AF271790" } ena = self.query.ena(hgnc_symbol="A1CF")[0] self.assertIsInstance(ena, models.ENA) self.assertEqual(ena.to_dict(), A1CF_ena)
class TestQuery(unittest.TestCase): @classmethod def setUpClass(cls): pass @classmethod def tearDownClass(cls): pass def test_number_of_inserts(self): pass def test_query_hgnc(self): pass def test_query_orthology_prediction(self): pass def test_query_alias_symbol(self): pass def test_query_alias_name(self): pass def test_query_gene_family(self): pass def test_query_ref_seq(self): pass def test_query_rgd(self): pass def test_query_omim(self): pass def test_query_mgd(self): pass def test_query_uniprot(self): pass def test_query_ccds(self): pass def test_query_pubmed(self): pass def test_query_ena(self): pass
19
0
17
1
15
0
1
0.01
1
17
16
0
14
0
16
88
282
35
247
61
228
2
97
59
80
2
2
1
23
145,129
LeKono/pyhgnc
LeKono_pyhgnc/src/pyhgnc/manager/models.py
pyhgnc.manager.models.RGD
class RGD(Base, MasterModel): """Rat genome database gene ID. Found within the "HOMOLOGS" section of the gene symbol report :cvar str rgdid: Rat genome database gene ID :cvar hgncs: back populates to :class:`.HGNC` """ rgdid = Column(Integer) hgncs = relationship( "HGNC", secondary=hgnc_rgd, back_populates="rgds" ) def to_dict(self): return self.to_dict_with_hgncs() def __repr__(self): return str(self.rgdid)
class RGD(Base, MasterModel): '''Rat genome database gene ID. Found within the "HOMOLOGS" section of the gene symbol report :cvar str rgdid: Rat genome database gene ID :cvar hgncs: back populates to :class:`.HGNC` ''' def to_dict(self): pass def __repr__(self): pass
3
1
2
0
2
0
1
0.36
2
1
0
0
2
0
2
7
19
4
11
5
8
4
7
5
4
1
2
0
2
145,130
LeadPages/gcloud_requests
LeadPages_gcloud_requests/tests/test_credentials_watcher.py
tests.test_credentials_watcher.BrokenCredentials
class BrokenCredentials(StubCredentials): def __init__(self, refresh_every=3600): super(BrokenCredentials, self).__init__(refresh_every) self.expiry = time.time() @property def valid(self): return True def refresh(self, request): raise RuntimeError("some coding error")
class BrokenCredentials(StubCredentials): def __init__(self, refresh_every=3600): pass @property def valid(self): pass def refresh(self, request): pass
5
0
2
0
2
0
1
0
1
2
0
0
3
1
3
7
11
2
9
6
4
0
8
5
4
1
2
0
3
145,131
LeadPages/gcloud_requests
LeadPages_gcloud_requests/tests/test_credentials_watcher.py
tests.test_credentials_watcher.StubCredentials
class StubCredentials(object): def __init__(self, refresh_every=3600): self.refresh_calls = 0 self.refresh_every = refresh_every self.expiry = None def refresh(self, request): self.refresh_calls += 1 self.expiry = datetime.utcnow() + timedelta(seconds=self.refresh_every) @property def valid(self): return self.expiry and not self.expired @property def expired(self): return (datetime.utcnow() - self.expiry).total_seconds() > 0
class StubCredentials(object): def __init__(self, refresh_every=3600): pass def refresh(self, request): pass @property def valid(self): pass @property def expired(self): pass
7
0
3
0
3
0
1
0
1
2
0
2
4
3
4
4
17
3
14
10
7
0
12
8
7
1
1
0
4
145,132
LeadPages/gcloud_requests
LeadPages_gcloud_requests/gcloud_requests/credentials_watcher.py
gcloud_requests.credentials_watcher.CredentialsWatcher
class CredentialsWatcher(Thread): """Watches Credentials objects in a background thread, periodically refreshing them. """ def __init__(self): super(CredentialsWatcher, self).__init__() self.setDaemon(True) self.watch_list_updated = Condition() self.watch_list = [] self.logger = logging.getLogger("gcloud_requests.CredentialsWatcher") self.start() def stop(self): self.logger.debug("Stopping watcher...") with self.watch_list_updated: self.running = False self.watch_list_updated.notify() self.logger.debug("Joining on watcher...") self.join() self.logger.debug("Watcher successfully stopped.") def run(self): self.running = True with self.watch_list_updated: while self.running: self.logger.debug("Ticking...") wait_time = self.tick() self.logger.debug("Sleeping for %.02f...", wait_time) self.watch_list_updated.wait(timeout=wait_time) def tick(self): wait_time = MAX_WAIT_TIME for credentials in self.watch_list: try: self._try_refresh(credentials) if credentials.expiry: # We don't need to skew this value backward because of # https://github.com/GoogleCloudPlatform/google-auth-library-python/blob/9281ca026019869bc5fb10ee288a5cd9e837808f/google/auth/credentials.py#L62 delta = (credentials.expiry - datetime.utcnow()).total_seconds() wait_time = min(wait_time, delta) except Exception: self.logger.exception("Unexpected error processing credentials %r.", credentials) self.watch_list.remove(credentials) return wait_time def watch(self, credentials): # Eagerly refresh the given credentials so that all the # requests machinery is invoked outside of the watcher thread. # This avoids deadlocking due to runtime imports in Python 2.x. # See also: https://github.com/requests/requests/issues/2925 # And: https://bugs.python.org/issue10923 self._try_refresh(credentials) with self.watch_list_updated: self.watch_list.append(credentials) self.watch_list_updated.notify() def unwatch(self, credentials): with self.watch_list_updated: self.watch_list.remove(credentials) self.watch_list_updated.notify() def _try_refresh(self, credentials): if not credentials.valid: try: self.logger.debug("Refreshing credentials %r...", credentials) credentials.refresh(AuthRequest()) except RefreshError: self.logger.warning("Failed to refresh credentials...", exc_info=True)
class CredentialsWatcher(Thread): '''Watches Credentials objects in a background thread, periodically refreshing them. ''' def __init__(self): pass def stop(self): pass def run(self): pass def tick(self): pass def watch(self, credentials): pass def unwatch(self, credentials): pass def _try_refresh(self, credentials): pass
8
1
9
0
7
1
2
0.19
1
4
0
0
7
4
7
32
72
10
52
16
44
10
52
16
44
4
1
3
13
145,133
LeadPages/gcloud_requests
LeadPages_gcloud_requests/gcloud_requests/proxy.py
gcloud_requests.proxy.RequestsProxy
class RequestsProxy(object): """Wraps a ``requests`` library :class:`.Session` instance and exposes a compatible `request` method. """ SCOPE = None #: Determines how connection and read timeouts should be handled #: by this proxy. TIMEOUT_CONFIG = (3.05, 30) #: Determines how retries should be handled by this proxy. RETRY_CONFIG = Retry( total=10, connect=10, read=5, method_whitelist=Retry.DEFAULT_METHOD_WHITELIST | frozenset(["POST"]) ) #: The number of connections to pool per Session. CONNECTION_POOL_SIZE = 32 # A mapping from numeric Google RPC error codes to known error # code strings. _PB_ERROR_CODES = { 2: "UNKNOWN", 4: "DEADLINE_EXCEEDED", 10: "ABORTED", 13: "INTERNAL", 14: "UNAVAILABLE", } # Fix for GCS client setting ALLOW_AUTO_SWITCH_TO_MTLS_URL to True # unless an api_endpoint client_option is set # https://github.com/googleapis/python-cloud-core/pull/75/files is_mtls = False def __init__(self, credentials=None, logger=None): if credentials is None: credentials = google.auth.default()[0] credentials = with_scopes_if_required(credentials, self.SCOPE) self.logger = logger or logging.getLogger(type(self).__name__) self.credentials = credentials _credentials_watcher.watch(credentials) def __del__(self): try: _credentials_watcher.unwatch(self.credentials) except TypeError: # This can happen when the daemon thread shuts down and # __del__() is implicitly ran. Crops up most commonly # in test suites as 'NoneType' object is not callable. pass def request(self, method, url, data=None, headers=None, retries=0, refresh_attempts=0, **kwargs): session = self._get_session() headers = headers.copy() if headers is not None else {} auth_request = AuthRequest(session=session) retry_auth = partial( self.request, url=url, method=method, data=data, headers=headers, refresh_attempts=refresh_attempts + 1, retries=0, # Retries intentionally get reset to 0. **kwargs ) try: self.credentials.before_request(auth_request, method, url, headers) except RefreshError: if refresh_attempts < _max_refresh_attempts: return retry_auth() raise # Do not allow multiple timeout kwargs. kwargs["timeout"] = self.TIMEOUT_CONFIG response = session.request(method, url, data=data, headers=headers, **kwargs) if response.status_code in _refresh_status_codes and refresh_attempts < _max_refresh_attempts: self.logger.info( "Refreshing credentials due to a %s response. Attempt %s/%s.", response.status_code, refresh_attempts + 1, _max_refresh_attempts ) try: self.credentials.refresh(auth_request) except RefreshError: pass return retry_auth() elif response.status_code >= 400: response = self._handle_response_error( response, retries, url=url, method=method, data=data, headers=headers, **kwargs ) return response def _get_session(self): # Ensure we use one connection-pooling session per thread and # make use of requests' internal retry mechanism. It will # safely retry any requests that failed due to DNS lookup, # socket errors, etc. session = getattr(_state, "session", None) if session is None: session = _state.session = requests.Session() adapter = _state.adapter = requests.adapters.HTTPAdapter( max_retries=self.RETRY_CONFIG, pool_connections=self.CONNECTION_POOL_SIZE, pool_maxsize=self.CONNECTION_POOL_SIZE, ) session.mount("http://", adapter) session.mount("https://", adapter) return session def _handle_response_error(self, response, retries, **kwargs): r"""Provides a way for each connection wrapper to handle error responses. Parameters: response(Response): An instance of :class:`.requests.Response`. retries(int): The number of times :meth:`.request` has been called so far. \**kwargs: The parameters with which :meth:`.request` was called. The `retries` parameter is excluded from `kwargs` intentionally. Returns: requests.Response """ error = self._convert_response_to_error(response) if error is None: return response max_retries = self._max_retries_for_error(error) if max_retries is None or retries >= max_retries: return response backoff = min(0.0625 * 2 ** retries, 1.0) self.logger.warning("Sleeping for %r before retrying failed request...", backoff) time.sleep(backoff) retries += 1 self.logger.warning("Retrying failed request. Attempt %d/%d.", retries, max_retries) return self.request(retries=retries, **kwargs) def _convert_response_to_error(self, response): """Subclasses may override this method in order to influence how errors are parsed from the response. Parameters: response(Response): The response object. Returns: object or None: Any object for which a max retry count can be retrieved or None if the error cannot be handled. """ content_type = response.headers.get("content-type", "") if "application/x-protobuf" in content_type: self.logger.debug("Decoding protobuf response.") data = status_pb2.Status.FromString(response.content) status = self._PB_ERROR_CODES.get(data.code) error = {"status": status} return error elif "application/json" in content_type: self.logger.debug("Decoding json response.") data = response.json() error = data.get("error") if not error or not isinstance(error, dict): self.logger.warning("Unexpected error response: %r", data) return None return error self.logger.warning("Unexpected response: %r", response.text) return None def _max_retries_for_error(self, error): """Subclasses may implement this method in order to influence how many times various error types should be retried. Parameters: error(dict): A dictionary containing a `status Returns: int or None: The max number of times this error should be retried or None if it shouldn't. """ return None
class RequestsProxy(object): '''Wraps a ``requests`` library :class:`.Session` instance and exposes a compatible `request` method. ''' def __init__(self, credentials=None, logger=None): pass def __del__(self): pass def request(self, method, url, data=None, headers=None, retries=0, refresh_attempts=0, **kwargs): pass def _get_session(self): pass def _handle_response_error(self, response, retries, **kwargs): '''Provides a way for each connection wrapper to handle error responses. Parameters: response(Response): An instance of :class:`.requests.Response`. retries(int): The number of times :meth:`.request` has been called so far. \**kwargs: The parameters with which :meth:`.request` was called. The `retries` parameter is excluded from `kwargs` intentionally. Returns: requests.Response ''' pass def _convert_response_to_error(self, response): '''Subclasses may override this method in order to influence how errors are parsed from the response. Parameters: response(Response): The response object. Returns: object or None: Any object for which a max retry count can be retrieved or None if the error cannot be handled. ''' pass def _max_retries_for_error(self, error): '''Subclasses may implement this method in order to influence how many times various error types should be retried. Parameters: error(dict): A dictionary containing a `status Returns: int or None: The max number of times this error should be retried or None if it shouldn't. ''' pass
8
4
22
3
14
5
3
0.44
1
5
0
3
7
2
7
7
192
33
111
29
103
49
81
29
73
7
1
2
21
145,134
LeadPages/gcloud_requests
LeadPages_gcloud_requests/gcloud_requests/datastore.py
gcloud_requests.datastore.DatastoreRequestsProxy
class DatastoreRequestsProxy(RequestsProxy): """A Datastore-specific RequestsProxy. This proxy handles retries according to [1]. [1]: https://cloud.google.com/datastore/docs/concepts/errors. """ SCOPE = ("https://www.googleapis.com/auth/datastore",) # A mapping from Datastore error states that can be retried to the # maximum number of times each one should be retried. _MAX_RETRIES = { "ABORTED": 5, "INTERNAL": 1, "UNKNOWN": 1, "UNAVAILABLE": 5, "DEADLINE_EXCEEDED": 5, } def _convert_response_to_error(self, response): content_type = response.headers.get("content-type", "") if response.status_code == 502 and content_type.startswith("text/html"): # The Datastore error handling docs don't mention anything # about how 502s should be handled so we just handle them # the same way we do 503s. return {"status": "UNAVAILABLE"} return super(DatastoreRequestsProxy, self)._convert_response_to_error(response) def _max_retries_for_error(self, error): """Handles Datastore response errors according to their documentation. Parameters: error(dict) Returns: int or None: The max number of times this error should be retried or None if it shouldn't. See also: https://cloud.google.com/datastore/docs/concepts/errors """ status = error.get("status") if status == "ABORTED" and get_transactions() > 0: # Avoids retrying Conflicts when inside a transaction. return None return self._MAX_RETRIES.get(status)
class DatastoreRequestsProxy(RequestsProxy): '''A Datastore-specific RequestsProxy. This proxy handles retries according to [1]. [1]: https://cloud.google.com/datastore/docs/concepts/errors. ''' def _convert_response_to_error(self, response): pass def _max_retries_for_error(self, error): '''Handles Datastore response errors according to their documentation. Parameters: error(dict) Returns: int or None: The max number of times this error should be retried or None if it shouldn't. See also: https://cloud.google.com/datastore/docs/concepts/errors ''' pass
3
2
14
2
5
7
2
1
1
1
0
0
2
0
2
9
48
10
19
7
16
19
13
7
10
2
2
1
4
145,135
LeadPages/gcloud_requests
LeadPages_gcloud_requests/tests/test_credentials_watcher.py
tests.test_credentials_watcher.FailingCredentials
class FailingCredentials(StubCredentials): def refresh(self, request): raise RefreshError("refresh failed")
class FailingCredentials(StubCredentials): def refresh(self, request): pass
2
0
2
0
2
0
1
0
1
0
0
0
1
0
1
5
3
0
3
2
1
0
3
2
1
1
2
0
1
145,136
LeadPages/gcloud_requests
LeadPages_gcloud_requests/gcloud_requests/storage.py
gcloud_requests.storage.CloudStorageRequestsProxy
class CloudStorageRequestsProxy(RequestsProxy): """A GCS-specific RequestsProxy. This proxy handles retries according to [1]. [1]: https://cloud.google.com/storage/docs/json_api/v1/status-codes """ SCOPE = ( "https://www.googleapis.com/auth/devstorage.full_control", "https://www.googleapis.com/auth/devstorage.read_only", "https://www.googleapis.com/auth/devstorage.read_write", ) #: Determines how connection and read timeouts should be handled #: by this proxy. TIMEOUT_CONFIG = (3.05, 30) # A mapping from GCS error codes that can be retried to the # maximum number of times each one should be retried. _MAX_RETRIES = { 429: 10, 500: 5, 502: 5, 503: 5, } def _convert_response_to_error(self, response): # Sometimes GCS 503s with no content so we handle that case here. if response.status_code == 503 and not response.text: return {"code": 503} return super(CloudStorageRequestsProxy, self)._convert_response_to_error(response) def _max_retries_for_error(self, error): """Handles Datastore response errors according to their documentation. Parameters: error(dict) Returns: int or None: The max number of times this error should be retried or None if it shouldn't. See also: https://cloud.google.com/storage/docs/json_api/v1/status-codes """ status = error.get("code") return self._MAX_RETRIES.get(status)
class CloudStorageRequestsProxy(RequestsProxy): '''A GCS-specific RequestsProxy. This proxy handles retries according to [1]. [1]: https://cloud.google.com/storage/docs/json_api/v1/status-codes ''' def _convert_response_to_error(self, response): pass def _max_retries_for_error(self, error): '''Handles Datastore response errors according to their documentation. Parameters: error(dict) Returns: int or None: The max number of times this error should be retried or None if it shouldn't. See also: https://cloud.google.com/storage/docs/json_api/v1/status-codes ''' pass
3
2
11
2
4
5
2
0.9
1
1
0
0
2
0
2
9
49
11
20
7
17
18
11
7
8
2
2
1
3
145,137
LeadPages/gcloud_requests
LeadPages_gcloud_requests/gcloud_requests/pubsub.py
gcloud_requests.pubsub.PubSubRequestsProxy
class PubSubRequestsProxy(RequestsProxy): """A PubSub-specific requests proxy. This proxy handles retries according to [1]. [1]: https://cloud.google.com/pubsub/docs/reference/error-codes """ SCOPE = ( "https://www.googleapis.com/auth/pubsub", "https://www.googleapis.com/auth/cloud-platform", ) # A mapping from PubSub error states that can be retried to the # maximum number of times each one should be retried. _MAX_RETRIES = { "RESOURCE_EXHAUSTED": 5, "INTERNAL": 3, "UNAVAILABLE": 5, "DEADLINE_EXCEEDED": 5, } def _max_retries_for_error(self, error): """Handles PubSub response errors according to their documentation. Parameters: error(dict) Returns: int or None: The max number of times this error should be retried or None if it shouldn't. See also: https://cloud.google.com/pubsub/docs/reference/error-codes """ return self._MAX_RETRIES.get(error.get("status"))
class PubSubRequestsProxy(RequestsProxy): '''A PubSub-specific requests proxy. This proxy handles retries according to [1]. [1]: https://cloud.google.com/pubsub/docs/reference/error-codes ''' def _max_retries_for_error(self, error): '''Handles PubSub response errors according to their documentation. Parameters: error(dict) Returns: int or None: The max number of times this error should be retried or None if it shouldn't. See also: https://cloud.google.com/pubsub/docs/reference/error-codes ''' pass
2
2
14
3
2
9
1
1.15
1
0
0
0
1
0
1
8
36
8
13
4
11
15
5
4
3
1
2
0
1
145,138
LeafSoftware/python-lambder
LeafSoftware_python-lambder/lambder/lambder.py
lambder.lambder.Entry
class Entry: name = None cron = None function_name = None input_event = {} enabled = True def __init__( self, Name=None, Cron=None, FunctionName=None, InputEvent={}, Enabled=True ): self.name = Name self.cron = Cron self.function_name = FunctionName self.input_event = InputEvent self.enabled = Enabled def __str__(self): return "\t".join([ self.name, self.cron, self.function_name, str(self.enabled) ])
class Entry: def __init__( self, Name=None, Cron=None, FunctionName=None, InputEvent={}, Enabled=True ): pass def __str__(self): pass
3
0
10
0
10
0
1
0
0
1
0
0
2
0
2
2
28
2
26
15
16
0
14
8
11
1
0
0
2
145,139
LeafSoftware/python-lambder
LeafSoftware_python-lambder/lambder/cli.py
lambder.cli.FunctionConfig
class FunctionConfig: def __init__(self, config_file): with open(config_file, 'r') as f: contents = f.read() config = json.loads(contents) self.name = config['name'] self.bucket = config['s3_bucket'] self.timeout = config['timeout'] self.memory = config['memory'] self.description = config['description'] self.subnet_ids = None self.security_group_ids = None if 'subnet_ids' in config: self.subnet_ids = config['subnet_ids'] if 'security_group_ids' in config: self.security_group_ids = config['security_group_ids']
class FunctionConfig: def __init__(self, config_file): pass
2
0
16
1
15
0
3
0
0
0
0
0
1
7
1
1
17
1
16
12
14
0
16
11
14
3
0
1
3
145,140
LeafSoftware/python-lambder
LeafSoftware_python-lambder/lambder/lambder.py
lambder.lambder.Lambder
class Lambder: NAME_PREFIX = 'Lambder-' def __init__(self): self.awslambda = boto3.client('lambda') session = botocore.session.get_session() self.events = session.create_client('events') def permit_rule_to_invoke_function(self, rule_arn, function_name): statement_id = function_name + "RulePermission" resp = self.awslambda.add_permission( FunctionName=function_name, StatementId=statement_id, Action='lambda:InvokeFunction', Principal='events.amazonaws.com', SourceArn=rule_arn ) def add_event( self, name, function_name, cron, input_event={}, enabled=True ): rule_name = self.NAME_PREFIX + name # events:put-rule resp = self.events.put_rule( Name=rule_name, ScheduleExpression=cron ) rule_arn = resp['RuleArn'] # try to add the permission, if we fail because it already # exists, move on. try: self.permit_rule_to_invoke_function(rule_arn, function_name) except botocore.exceptions.ClientError as e: if e.response['Error']['Code'] != 'ResourceConflictException': raise # retrieve the lambda arn resp = self.awslambda.get_function( FunctionName=function_name ) function_arn = resp['Configuration']['FunctionArn'] # events:put-targets (needs lambda arn) resp = self.events.put_targets( Rule=rule_name, Targets=[ { 'Id': name, 'Arn': function_arn, 'Input': json.dumps(input_event) } ] ) def list_events(self): # List all rules by prefix 'Lambder' resp = self.events.list_rules( NamePrefix=self.NAME_PREFIX ) rules = resp['Rules'] entries = [] # For each rule, list-targets-by-rule to get lambda arn for rule in rules: resp = self.events.list_targets_by_rule( Rule=rule['Name'] ) targets = resp['Targets'] # assume only one target for now name = targets[0]['Id'] arn = targets[0]['Arn'] function_name = arn.split(':')[-1] cron = rule['ScheduleExpression'] enabled = rule['State'] == 'ENABLED' entry = Entry( Name=name, Cron=cron, FunctionName=function_name, Enabled=enabled ) entries.append(entry) return entries def delete_event(self, name): rule_name = self.NAME_PREFIX + name # get the function name resp = self.events.list_targets_by_rule( Rule=rule_name ) targets = resp['Targets'] # assume only one target for now arn = targets[0]['Arn'] function_name = arn.split(':')[-1] statement_id = function_name + "RulePermission" # delete the target resp = self.events.remove_targets( Rule=rule_name, Ids=[name] ) # delete the permission resp = self.awslambda.remove_permission( FunctionName=function_name, StatementId=statement_id ) # delete the rule resp = self.events.delete_rule( Name=rule_name ) def disable_event(self, name): rule_name = self.NAME_PREFIX + name resp = self.events.disable_rule( Name=rule_name ) def enable_event(self, name): rule_name = self.NAME_PREFIX + name resp = self.events.enable_rule( Name=rule_name ) def load_events(self, data): entries = json.loads(data) for entry in entries: self.add( name=entry['name'], cron=entry['cron'], function_name=entry['function_name'], input_event=entry['input_event'], enabled=entry['enabled'] ) def create_project(self, name, bucket, config): context = { 'lambda_name': name, 'repo_name': 'lambder-' + name, 's3_bucket': bucket } context.update(config) cookiecutter( 'https://github.com/LeafSoftware/cookiecutter-lambder', no_input=True, extra_context=context ) # Recursively zip path, creating a zipfile with contents # relative to path. # e.g. lambda/foo/foo.py -> ./foo.py # e.g. lambda/foo/bar/bar.py -> ./bar/bar.py # def _zipdir(self, zfile, path): with zipfile.ZipFile(zfile, 'w') as ziph: for root, dirs, files in os.walk(path): # strip path from beginning of full path rel_path = root if rel_path.startswith(path): rel_path = rel_path[len(path):] for file in files: ziph.write( os.path.join(root, file), os.path.join(rel_path, file) ) def _s3_cp(self, src, dest_bucket, dest_key): s3 = boto3.client('s3') s3.upload_file(src, dest_bucket, dest_key) def _s3_rm(self, bucket, key): s3 = boto3.resource('s3') the_bucket = s3.Bucket(bucket) the_object = the_bucket.Object(key) the_object.delete() def _create_lambda_role(self, role_name): iam = boto3.resource('iam') role = iam.Role(role_name) # return the role if it already exists if role in iam.roles.all(): return role trust_policy = json.dumps( { "Statement": [ { "Effect": "Allow", "Principal": { "Service": ["lambda.amazonaws.com"] }, "Action": ["sts:AssumeRole"] } ] } ) role = iam.create_role( RoleName=role_name, AssumeRolePolicyDocument=trust_policy ) return role def _delete_lambda_role(self, name): iam = boto3.resource('iam') role_name = self._role_name(name) policy_name = self._policy_name(name) role_policy = iam.RolePolicy(role_name, policy_name) role = iam.Role(self._role_name(name)) # HACK: This 'if thing in things.all()' biz seems like # a very inefficient way to check for resource # existence... if role_policy in role.policies.all(): role_policy.delete() if role in iam.roles.all(): role.delete() def _put_role_policy(self, role, policy_name, policy_doc): iam = boto3.client('iam') policy = iam.put_role_policy( RoleName=role.name, PolicyName=policy_name, PolicyDocument=policy_doc ) def _attach_vpc_policy(self, role): iam = boto3.client('iam') iam.attach_role_policy( RoleName=role, PolicyArn='arn:aws:iam::aws:policy/service-role/\ AWSLambdaVPCAccessExecutionRole' ) def _lambda_exists(self, name): awslambda = boto3.client('lambda') try: resp = awslambda.get_function( FunctionName=self._long_name(name) ) except botocore.exceptions.ClientError as e: if e.response['Error']['Code'] == 'ResourceNotFoundException': return False else: raise return True def _update_lambda( self, name, bucket, key, timeout, memory, description, vpc_config ): awslambda = boto3.client('lambda') resp = awslambda.update_function_code( FunctionName=self._long_name(name), S3Bucket=bucket, S3Key=key ) resp = awslambda.update_function_configuration( FunctionName=self._long_name(name), Timeout=timeout, MemorySize=memory, Description=description, VpcConfig=vpc_config ) def _create_lambda( self, name, bucket, key, role_arn, timeout, memory, description, vpc_config ): awslambda = boto3.client('lambda') resp = awslambda.create_function( FunctionName=self._long_name(name), Runtime='python2.7', Role=role_arn, Handler="{}.handler".format(name), Code={ 'S3Bucket': bucket, 'S3Key': key }, Timeout=timeout, MemorySize=memory, Description=description, VpcConfig=vpc_config ) def _delete_lambda(self, name): awslambda = boto3.client('lambda') if self._lambda_exists(name): resp = awslambda.delete_function( FunctionName=self._long_name(name) ) def _long_name(self, name): return 'Lambder-' + name def _s3_key(self, name): return "lambder/lambdas/{}_lambda.zip".format(name) def _role_name(self, name): return self._long_name(name) + 'ExecuteRole' def _policy_name(self, name): return self._long_name(name) + 'ExecutePolicy' def deploy_function( self, name, bucket, timeout, memory, description, vpc_config ): long_name = self._long_name(name) s3_key = self._s3_key(name) role_name = self._role_name(name) policy_name = self._policy_name(name) policy_file = os.path.join('iam', 'policy.json') # zip up the lambda zfile = os.path.join( tempfile.gettempdir(), "{}_lambda.zip".format(name) ) self._zipdir(zfile, os.path.join('lambda', name)) # upload it to s3 self._s3_cp(zfile, bucket, s3_key) # remove tempfile os.remove(zfile) # create the lambda execute role if it does not already exist role = self._create_lambda_role(role_name) # update the role's policy from the document in the project policy_doc = None with open(policy_file, 'r') as f: policy_doc = f.read() self._put_role_policy(role, policy_name, policy_doc) # add the vpc policy to the role if vpc_config is set if vpc_config: self._attach_vpc_policy(role_name) # create or update the lambda function timeout_i = int(timeout) if self._lambda_exists(name): self._update_lambda( name, bucket, s3_key, timeout_i, memory, description, vpc_config ) else: time.sleep(5) # wait for role to be created self._create_lambda( name, bucket, s3_key, role.arn, timeout_i, memory, description, vpc_config ) # List only the lambder functions, i.e. ones starting with 'Lambder-' def list_functions(self): awslambda = boto3.client('lambda') resp = awslambda.list_functions() functions = resp['Functions'] return filter( lambda x: x['FunctionName'].startswith(self.NAME_PREFIX), functions ) def _delete_lambda_zip(self, name, bucket): key = self._s3_key(name) self._s3_rm(bucket, key) # delete all the things associated with this function def delete_function(self, name, bucket): self._delete_lambda(name) self._delete_lambda_role(name) self._delete_lambda_zip(name, bucket) def invoke_function(self, name, input_event): awslambda = boto3.client('lambda') payload = '{}' # default to empty event if input_event: with open(input_event, 'r') as f: payload = f.read() resp = awslambda.invoke( FunctionName=self._long_name(name), InvocationType='RequestResponse', Payload=payload ) results = resp['Payload'].read() # payload is a 'StreamingBody' return results
class Lambder: def __init__(self): pass def permit_rule_to_invoke_function(self, rule_arn, function_name): pass def add_event( self, name, function_name, cron, input_event={}, enabled=True ): pass def list_events(self): pass def delete_event(self, name): pass def disable_event(self, name): pass def enable_event(self, name): pass def load_events(self, data): pass def create_project(self, name, bucket, config): pass def _zipdir(self, zfile, path): pass def _s3_cp(self, src, dest_bucket, dest_key): pass def _s3_rm(self, bucket, key): pass def _create_lambda_role(self, role_name): pass def _delete_lambda_role(self, name): pass def _put_role_policy(self, role, policy_name, policy_doc): pass def _attach_vpc_policy(self, role): pass def _lambda_exists(self, name): pass def _update_lambda( self, name, bucket, key, timeout, memory, description, vpc_config ): pass def _create_lambda_role(self, role_name): pass def _delete_lambda_role(self, name): pass def _long_name(self, name): pass def _s3_key(self, name): pass def _role_name(self, name): pass def _policy_name(self, name): pass def deploy_function( self, name, bucket, timeout, memory, description, vpc_config ): pass def list_functions(self): pass def _delete_lambda_zip(self, name, bucket): pass def delete_function(self, name, bucket): pass def invoke_function(self, name, input_event): pass
30
0
14
1
12
1
2
0.1
0
4
1
0
29
2
29
29
440
64
344
146
280
35
171
107
141
4
0
4
45
145,141
LeastAuthority/txkube
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LeastAuthority_txkube/src/txkube/testing/test/test_matchers.py
txkube.testing.test.test_matchers.PClassEqualsTests.pclass
class pclass(PClass): foo = field() bar = field()
class pclass(PClass): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
3
0
3
3
2
0
3
3
2
0
1
0
0
145,142
LeastAuthority/txkube
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LeastAuthority_txkube/src/txkube/_model.py
txkube._model.define_behaviors.Service
class Service(object): """ ``Service`` instances model `Service objects <https://kubernetes.io/docs/api-reference/v1/definitions/#_v1_service>`_. """ def fill_defaults(self): # TODO Surely some stuff to fill. # See https://github.com/LeastAuthority/txkube/issues/36 return self def delete_from(self, collection): return collection.remove(self)
class Service(object): ''' ``Service`` instances model `Service objects <https://kubernetes.io/docs/api-reference/v1/definitions/#_v1_service>`_. ''' def fill_defaults(self): pass def delete_from(self, collection): pass
3
1
3
0
2
1
1
1.2
1
0
0
0
2
0
2
2
13
2
5
3
2
6
5
3
2
1
1
0
2
145,143
LeastAuthority/txkube
LeastAuthority_txkube/src/txkube/testing/test/test_matchers.py
txkube.testing.test.test_matchers.MappingEqualsTests
class MappingEqualsTests(TestCase): """ Tests for ``MappingEquals``. """ def test_equals(self): """ ``MappingEquals.match`` returns ``None`` when comparing two ``dict`` which compare equal with ``==``. """ self.assertThat( MappingEquals({u"foo": u"bar"}).match({u"foo": u"bar"}), Is(None), ) def test_mismatch(self): """ ``MappingEquals.match`` returns a mismatch when comparing two ``dict`` which do not compare equal with ``==``. """ # Same keys, different value. mismatch = MappingEquals({u"foo": u"bar"}).match({u"foo": u"baz"}) self.expectThat( mismatch.describe(), Equals( u"field mismatch:\n" u"field: foo\n" u"reference = bar\n" u"actual = baz\n" ), ) # Actual value missing a key. mismatch = MappingEquals({u"foo": u"bar"}).match({}) self.expectThat( mismatch.describe(), Equals( u"field mismatch:\n" u"field: foo\n" u"reference = bar\n" u"actual = <<missing>>\n" ), ) # Expected value missing a key. mismatch = MappingEquals({}).match({u"foo": u"baz"}) self.expectThat( mismatch.describe(), Equals( u"field mismatch:\n" u"field: foo\n" u"reference = <<missing>>\n" u"actual = baz\n" ), ) # The matcher has a nice string representation. self.expectThat( str(MappingEquals({})), Equals("MappingEquals({})"), ) def test_mismatch_py2(self): """ ``MappingEquals.match`` returns a mismatch when comparing two ``dict`` which do not compare equal with ``==``. """ if version_info >= (3,): self.skipTest("skipping test on Python 3") # Different types altogether. mismatch = MappingEquals(0).match({0: 1}) self.expectThat( mismatch.describe(), Equals( u"type mismatch:\n" u"reference = <type 'int'> (0)\n" u"actual = <type 'dict'> ({0: 1})\n" ), ) def test_mismatch_py3(self): """ ``MappingEquals.match`` returns a mismatch when comparing two ``dict`` which do not compare equal with ``==``. """ if version_info < (3,): self.skipTest("skipping test on Python 2") # Different types altogether. mismatch = MappingEquals(0).match({0: 1}) self.expectThat( mismatch.describe(), Equals( u"type mismatch:\n" u"reference = <class 'int'> (0)\n" u"actual = <class 'dict'> ({0: 1})\n" ), )
class MappingEqualsTests(TestCase): ''' Tests for ``MappingEquals``. ''' def test_equals(self): ''' ``MappingEquals.match`` returns ``None`` when comparing two ``dict`` which compare equal with ``==``. ''' pass def test_mismatch(self): ''' ``MappingEquals.match`` returns a mismatch when comparing two ``dict`` which do not compare equal with ``==``. ''' pass def test_mismatch_py2(self): ''' ``MappingEquals.match`` returns a mismatch when comparing two ``dict`` which do not compare equal with ``==``. ''' pass def test_mismatch_py3(self): ''' ``MappingEquals.match`` returns a mismatch when comparing two ``dict`` which do not compare equal with ``==``. ''' pass
5
5
23
1
16
6
2
0.38
1
2
1
0
4
0
4
6
102
12
65
8
60
25
21
8
16
2
2
1
6
145,144
LeastAuthority/txkube
LeastAuthority_txkube/src/txkube/testing/test/test_matchers.py
txkube.testing.test.test_matchers.AttrsEqualsTests
class AttrsEqualsTests(TestCase): """ Tests for ``AttrsEquals``. """ @attr.s class attrs(object): foo = attr.ib() def test_equals(self): """ ``AttrsEquals.match`` returns ``None`` when comparing two attrs-based instances which compare equal with ``==``. """ self.assertThat( AttrsEquals(self.attrs(u"bar")).match(self.attrs(u"bar")), Is(None), ) def test_equals_py2(self): """ ``AttrsEquals.match`` returns ``None`` when comparing two attrs-based instances which compare equal with ``==``. """ if version_info >= (3,): self.skipTest("skipping test on Python 3") # The matcher has a nice string representation. self.expectThat( str(AttrsEquals(self.attrs(u"bar"))), Equals("AttrsEquals(attrs(foo=u'bar'))"), ) def test_equals_py3(self): """ ``AttrsEquals.match`` returns ``None`` when comparing two attrs-based instances which compare equal with ``==``. """ if version_info < (3,): self.skipTest("skipping test on Python 2") # The matcher has a nice string representation. self.expectThat( str(AttrsEquals(self.attrs(u"bar"))), Equals("AttrsEquals(AttrsEqualsTests.attrs(foo='bar'))"), ) def test_mismatch(self): """ ``AttrsEquals.match`` returns a mismatch when comparing two attrs-based instances which do not compare equal with ``==``. """ # Different value for the single attribute. mismatch = AttrsEquals(self.attrs(u"bar")).match(self.attrs(u"baz")) self.expectThat( mismatch.describe(), Equals( u"field mismatch:\n" u"field: foo\n" u"reference = bar\n" u"actual = baz\n" ), ) def test_mismatch_py2(self): """ ``AttrsEquals.match`` returns ``None`` when comparing two attrs-based instances which compare equal with ``==``. """ if version_info >= (3,): self.skipTest("skipping test on Python 3") # Different types altogether. mismatch = AttrsEquals(self.attrs(0)).match(1) self.expectThat( mismatch.describe(), Equals( u"type mismatch:\n" u"reference = <class 'txkube.testing.test.test_matchers.attrs'> (attrs(foo=0))\n" u"actual = <type 'int'> (1)\n" ), ) def test_mismatch_py3(self): """ ``AttrsEquals.match`` returns ``None`` when comparing two attrs-based instances which compare equal with ``==``. """ if version_info < (3,): self.skipTest("skipping test on Python 2") # Different types altogether. mismatch = AttrsEquals(self.attrs(0)).match(1) self.expectThat( mismatch.describe(), Equals( u"type mismatch:\n" u"reference = <class 'txkube.testing.test.test_matchers.AttrsEqualsTests.attrs'> (AttrsEqualsTests.attrs(foo=0))\n" u"actual = <class 'int'> (1)\n" ), )
class AttrsEqualsTests(TestCase): ''' Tests for ``AttrsEquals``. ''' @attr.s class attrs(object): def test_equals(self): ''' ``AttrsEquals.match`` returns ``None`` when comparing two attrs-based instances which compare equal with ``==``. ''' pass def test_equals_py2(self): ''' ``AttrsEquals.match`` returns ``None`` when comparing two attrs-based instances which compare equal with ``==``. ''' pass def test_equals_py3(self): ''' ``AttrsEquals.match`` returns ``None`` when comparing two attrs-based instances which compare equal with ``==``. ''' pass def test_mismatch(self): ''' ``AttrsEquals.match`` returns a mismatch when comparing two attrs-based instances which do not compare equal with ``==``. ''' pass def test_mismatch_py2(self): ''' ``AttrsEquals.match`` returns ``None`` when comparing two attrs-based instances which compare equal with ``==``. ''' pass def test_mismatch_py3(self): ''' ``AttrsEquals.match`` returns ``None`` when comparing two attrs-based instances which compare equal with ``==``. ''' pass
9
7
14
0
9
5
2
0.55
1
3
2
0
6
0
6
8
104
14
58
13
49
32
26
12
18
2
2
1
10
145,145
LeastAuthority/txkube
LeastAuthority_txkube/src/txkube/testing/test/test_eliot.py
txkube.testing.test.test_eliot.CaptureEliotLogsTests
class CaptureEliotLogsTests(TestCase): """ Tests for ``txkube.testing._eliot.CaptureEliotLogs``. """ def test_logs_as_detail(self): """ Captured logs are available as details on the fixture. """ fixture = CaptureEliotLogs() fixture.setUp() try: with start_action(action_type=u"foo"): pass details = fixture.getDetails() finally: fixture.cleanUp() self.assertThat( details[fixture.LOG_DETAIL_NAME].as_text(), Equals(_eliottree(fixture.logs)), )
class CaptureEliotLogsTests(TestCase): ''' Tests for ``txkube.testing._eliot.CaptureEliotLogs``. ''' def test_logs_as_detail(self): ''' Captured logs are available as details on the fixture. ''' pass
2
2
16
0
13
3
1
0.43
1
1
1
0
1
0
1
3
20
0
14
4
12
6
10
4
8
1
2
2
1
145,146
LeastAuthority/txkube
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LeastAuthority_txkube/src/txkube/_model.py
txkube._model.define_behaviors.ServiceList
class ServiceList(_List): pass
class ServiceList(_List): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
6
2
0
2
1
1
0
2
1
1
0
2
0
0
145,147
LeastAuthority/txkube
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LeastAuthority_txkube/src/txkube/test/test_authentication.py
txkube.test.test_authentication.ClientCertificatePolicyForHTTPSTests
class ClientCertificatePolicyForHTTPSTests(TestCase): """ Tests for ``ClientCertificatePolicyForHTTPS``. """ def test_interface(self): """ ``ClientCertificatePolicyForHTTPS`` instances provide ``IPolicyForHTTPS``. """ policy = ClientCertificatePolicyForHTTPS( credentials={}, trust_roots={}, ) verifyObject(IPolicyForHTTPS, policy) @given(dns_subdomains(), dns_subdomains(), port_numbers(), port_numbers()) def test_creatorForNetLoc_interface(self, host_known, host_used, port_known, port_used): """ ``ClientCertificatePolicyForHTTPS.creatorForNetloc`` returns an object that provides ``IOpenSSLClientConnectionCreator``. """ netloc = NetLocation(host=host_known, port=port_known) cert = pem.parse(_CA_CERT_PEM)[0] policy = ClientCertificatePolicyForHTTPS( credentials={}, trust_roots={ netloc: cert, }, ) creator = policy.creatorForNetloc( host_used.encode("ascii"), port_used, ) verifyObject(IOpenSSLClientConnectionCreator, creator)
class ClientCertificatePolicyForHTTPSTests(TestCase): ''' Tests for ``ClientCertificatePolicyForHTTPS``. ''' def test_interface(self): ''' ``ClientCertificatePolicyForHTTPS`` instances provide ``IPolicyForHTTPS``. ''' pass @given(dns_subdomains(), dns_subdomains(), port_numbers(), port_numbers()) def test_creatorForNetLoc_interface(self, host_known, host_used, port_known, port_used): ''' ``ClientCertificatePolicyForHTTPS.creatorForNetloc`` returns an object that provides ``IOpenSSLClientConnectionCreator``. ''' pass
4
3
14
1
10
4
1
0.45
1
2
2
0
2
0
2
4
35
3
22
9
18
10
10
8
7
1
2
0
2