id
int64
0
843k
repository_name
stringlengths
7
55
file_path
stringlengths
9
332
class_name
stringlengths
3
290
human_written_code
stringlengths
12
4.36M
class_skeleton
stringlengths
19
2.2M
total_program_units
int64
1
9.57k
total_doc_str
int64
0
4.2k
AvgCountLine
float64
0
7.89k
AvgCountLineBlank
float64
0
300
AvgCountLineCode
float64
0
7.89k
AvgCountLineComment
float64
0
7.89k
AvgCyclomatic
float64
0
130
CommentToCodeRatio
float64
0
176
CountClassBase
float64
0
48
CountClassCoupled
float64
0
589
CountClassCoupledModified
float64
0
581
CountClassDerived
float64
0
5.37k
CountDeclInstanceMethod
float64
0
4.2k
CountDeclInstanceVariable
float64
0
299
CountDeclMethod
float64
0
4.2k
CountDeclMethodAll
float64
0
4.2k
CountLine
float64
1
115k
CountLineBlank
float64
0
9.01k
CountLineCode
float64
0
94.4k
CountLineCodeDecl
float64
0
46.1k
CountLineCodeExe
float64
0
91.3k
CountLineComment
float64
0
27k
CountStmt
float64
1
93.2k
CountStmtDecl
float64
0
46.1k
CountStmtExe
float64
0
90.2k
MaxCyclomatic
float64
0
759
MaxInheritanceTree
float64
0
16
MaxNesting
float64
0
34
SumCyclomatic
float64
0
6k
144,948
Lagg/steamodd
Lagg_steamodd/tests/testvdf.py
tests.testvdf.SyntaxTestCase
class SyntaxTestCase(unittest.TestCase): # Deserialization UNQUOTED_VDF = """ node { key value } """ QUOTED_VDF = """ "node" { "key" "value" } """ MACRO_UNQUOTED_VDF = """ node { key value [$MACRO] } """ MACRO_QUOTED_VDF = """ "node" { "key" "value" [$MACRO] } """ COMMENT_QUOTED_VDF = """ "node" { // Hi I'm a comment. "key" "value" [$MACRO] } """ SUBNODE_QUOTED_VDF = """ "node" { "subnode" { "key" "value" } } """ MIXED_VDF = """ node { "key" value key2 "value" "key3" "value" [$MACRO] // Comment "subnode" [$MACRO] { key value } "key4" "value" } """ MULTIKEY_KV = """ node { "key" "k1v1" "key" "k1v2" "key" "k1v3" "key2" "k2v1" "key3" "k3v1" "key3" "k3v2" } """ MULTIKEY_KNODE = """ node { "key" { "name" "k1v1" "extra" ":D" } "key" { "name" "k1v2" "extra" ":!" } "key" { "name" "k1v3" "extra" ":O" } "key2" { "name" "k2v1" "extra" "I'm lonely" } "key3" { "name" "k3v1" "extra" { "smiley" ":O" "comment" "Wow!" } } "key3" { "name" "k3v2" "extra" { "smiley" ":Z" "comment" "BZZ!" } } } """ # Expectations EXPECTED_DICT = { u"node": { u"key": u"value" } } EXPECTED_SUBNODE_DICT = { u"node": { u"subnode": { u"key": u"value" } } } EXPECTED_MIXED_DICT = { u"node": { u"key": u"value", u"key2": u"value", u"key3": u"value", u"subnode": { u"key": u"value" }, u"key4": u"value" } } EXPECTED_MULTIKEY_KV = { u"node": { u"key": [ u"k1v1", u"k1v2", u"k1v3" ], u"key2": u"k2v1", u"key3": [ u"k3v1", u"k3v2" ] } } EXPECTED_MULTIKEY_KNODE = { u"node": { u"key": [ { u"name": u"k1v1", u"extra": u":D" }, { u"name": u"k1v2", u"extra": u":!" }, { u"name": u"k1v3", u"extra": u":O" } ], u"key2": { u"name": u"k2v1", u"extra": u"I'm lonely", }, u"key3": [ { u"name": u"k3v1", u"extra": { u"smiley": u":O", u"comment": u"Wow!" } }, { u"name": u"k3v2", u"extra": { u"smiley": u":Z", u"comment": u"BZZ!" } } ] } } # Serialization SIMPLE_DICT = EXPECTED_DICT SUBNODE_DICT = EXPECTED_SUBNODE_DICT ARRAY_DICT = { u"array": [ u"a", u"b", u"c"] } NUMERICAL_DICT = { u"number": 1, u"number2": 2 } COMBINATION_DICT = { u"node": { u"key": u"value", u"subnode": { u"key": u"value" }, u"array": [u"a", u"b", u"c", 1, 2, 3], u"number": 1024 } } # Expectations EXPECTED_SIMPLE_DICT = SIMPLE_DICT EXPECTED_SUBNODE_DICT = SUBNODE_DICT EXPECTED_ARRAY_DICT = { "array": { "a": "1", "b": "1", "c": "1" } } EXPECTED_NUMERICAL_DICT = { "number": "1", "number2": "2" } EXPECTED_COMBINATION_DICT = { "node": { "key": "value", "subnode": { "key": "value" }, "array": { "a": "1", "b": "1", "c": "1", "1": "1", "2": "1", "3": "1" }, "number": "1024" } }
class SyntaxTestCase(unittest.TestCase): pass
1
0
0
0
0
0
0
0.02
1
0
0
2
0
0
0
72
261
29
228
24
227
4
25
24
24
0
2
0
0
144,949
Lagg/steamodd
Lagg_steamodd/tests/testvdf.py
tests.testvdf.SerializeTestCase
class SerializeTestCase(SyntaxTestCase): def test_simple_dict(self): self.assertEqual(self.EXPECTED_SIMPLE_DICT, vdf.loads(vdf.dumps(self.SIMPLE_DICT))) def test_subnode_dict(self): self.assertEqual(self.EXPECTED_SUBNODE_DICT, vdf.loads(vdf.dumps(self.SUBNODE_DICT))) def test_array_dict(self): self.assertEqual(self.EXPECTED_ARRAY_DICT, vdf.loads(vdf.dumps(self.ARRAY_DICT))) def test_numerical_dict(self): self.assertEqual(self.EXPECTED_NUMERICAL_DICT, vdf.loads(vdf.dumps(self.NUMERICAL_DICT))) def test_combination_dict(self): self.assertEqual(self.EXPECTED_COMBINATION_DICT, vdf.loads(vdf.dumps(self.COMBINATION_DICT)))
class SerializeTestCase(SyntaxTestCase): def test_simple_dict(self): pass def test_subnode_dict(self): pass def test_array_dict(self): pass def test_numerical_dict(self): pass def test_combination_dict(self): pass
6
0
2
0
2
0
1
0
1
0
0
0
5
0
5
77
15
4
11
6
5
0
11
6
5
1
3
0
5
144,950
Lagg/steamodd
Lagg_steamodd/tests/testvdf.py
tests.testvdf.DeserializeTestCase
class DeserializeTestCase(SyntaxTestCase): def test_unquoted(self): self.assertEqual(self.EXPECTED_DICT, vdf.loads(self.UNQUOTED_VDF)) def test_quoted(self): self.assertEqual(self.EXPECTED_DICT, vdf.loads(self.QUOTED_VDF)) def test_macro_unquoted(self): self.assertEqual(self.EXPECTED_DICT, vdf.loads(self.MACRO_UNQUOTED_VDF)) def test_macro_quoted(self): self.assertEqual(self.EXPECTED_DICT, vdf.loads(self.MACRO_QUOTED_VDF)) def test_comment_quoted(self): self.assertEqual(self.EXPECTED_DICT, vdf.loads(self.COMMENT_QUOTED_VDF)) def test_subnode_quoted(self): self.assertEqual(self.EXPECTED_SUBNODE_DICT, vdf.loads(self.SUBNODE_QUOTED_VDF)) def test_mixed(self): self.assertEqual(self.EXPECTED_MIXED_DICT, vdf.loads(self.MIXED_VDF)) def test_multikey_kv(self): self.assertEqual(self.EXPECTED_MULTIKEY_KV, vdf.loads(self.MULTIKEY_KV)) def test_multikey_knode(self): self.maxDiff = 80*80 self.assertEqual(self.EXPECTED_MULTIKEY_KNODE, vdf.loads(self.MULTIKEY_KNODE))
class DeserializeTestCase(SyntaxTestCase): def test_unquoted(self): pass def test_quoted(self): pass def test_macro_unquoted(self): pass def test_macro_quoted(self): pass def test_comment_quoted(self): pass def test_subnode_quoted(self): pass def test_mixed(self): pass def test_multikey_kv(self): pass def test_multikey_knode(self): pass
10
0
2
0
2
0
1
0
1
0
0
0
9
1
9
81
28
8
20
11
10
0
20
11
10
1
3
0
9
144,951
Lagg/steamodd
Lagg_steamodd/steam/user.py
steam.user.ProfileError
class ProfileError(api.APIError): pass
class ProfileError(api.APIError): pass
1
0
0
0
0
0
0
0
1
0
0
3
0
0
0
10
2
0
2
1
1
0
2
1
1
0
5
0
0
144,952
Lagg/steamodd
Lagg_steamodd/tests/testuser.py
tests.testuser.ProfileTestCase
class ProfileTestCase(unittest.TestCase): VALID_ID64 = 76561198811195748 VALID_ID32 = 850930020 INVALID_ID64 = 123 WEIRD_ID64 = (VALID_ID64 >> 33 << 33) ^ VALID_ID64 VALID_VANITY = "spacecadet01" INVALID_VANITY = "*F*SDF9"
class ProfileTestCase(unittest.TestCase): pass
1
0
0
0
0
0
0
0
1
0
0
5
0
0
0
72
8
1
7
7
6
0
7
7
6
0
2
0
0
144,953
Lagg/steamodd
Lagg_steamodd/tests/testuser.py
tests.testuser.ProfileLevelTestCase
class ProfileLevelTestCase(ProfileTestCase): def test_level(self): profile = user.profile(self.VALID_ID64) self.assertGreater(profile.level, 0)
class ProfileLevelTestCase(ProfileTestCase): def test_level(self): pass
2
0
3
0
3
0
1
0
1
1
1
0
1
0
1
73
4
0
4
3
2
0
4
3
2
1
3
0
1
144,954
Lagg/steamodd
Lagg_steamodd/tests/testuser.py
tests.testuser.ProfileIdTestCase
class ProfileIdTestCase(ProfileTestCase): def test_invalid_id(self): profile = user.profile(self.INVALID_ID64) self.assertRaises(user.ProfileNotFoundError, lambda: profile.id64) def test_pathed_id(self): profile = user.profile('/' + str(self.VALID_ID64) + '/') self.assertEqual(profile.id64, self.VALID_ID64) def test_valid_id(self): profile = user.profile(self.VALID_ID64) self.assertEqual(profile.id64, self.VALID_ID64) self.assertEqual(profile.id32, self.VALID_ID32) def test_weird_id(self): profile = user.profile(self.WEIRD_ID64) self.assertRaises(user.ProfileNotFoundError, lambda: profile.id64)
class ProfileIdTestCase(ProfileTestCase): def test_invalid_id(self): pass def test_pathed_id(self): pass def test_valid_id(self): pass def test_weird_id(self): pass
5
0
3
0
3
0
1
0
1
3
2
0
4
0
4
76
17
3
14
9
9
0
14
9
9
1
3
0
4
144,955
Lagg/steamodd
Lagg_steamodd/tests/testuser.py
tests.testuser.ProfileBatchTestCase
class ProfileBatchTestCase(ProfileTestCase): def test_big_list(self): # Test id64 now lagg-bot test account, might need friends list adds # TODO: Implement GetFriendList in steamodd proper friends = api.interface("ISteamUser").GetFriendList(steamid = self.VALID_ID64) testsids = [friend["steamid"] for friend in friends["friendslist"]["friends"]] self.assertEqual(set(testsids), set(map(lambda x: str(x.id64), user.profile_batch(testsids)))) self.assertEqual(set(testsids), set(map(lambda x: str(x.id64), user.bans_batch(testsids)))) def test_compatibility(self): userlist = [self.VALID_ID64, user.vanity_url("windpower"), user.vanity_url("rjackson"), user.profile(self.VALID_ID64)] resolvedids = set() for u in userlist: try: sid = u.id64 except AttributeError: sid = str(u) resolvedids.add(str(sid)) self.assertEqual(resolvedids, set(map(lambda x: str(x.id64), user.profile_batch(userlist)))) self.assertEqual(resolvedids, set(map(lambda x: str(x.id64), user.bans_batch(userlist))))
class ProfileBatchTestCase(ProfileTestCase): def test_big_list(self): pass def test_compatibility(self): pass
3
0
12
2
9
1
2
0.11
1
9
5
0
2
0
2
74
25
5
18
9
15
2
17
9
14
3
3
2
4
144,956
Lagg/steamodd
Lagg_steamodd/tests/testuser.py
tests.testuser.FriendListTestCase
class FriendListTestCase(ProfileTestCase): def test_sids(self): profile_batch_friends = api.interface("ISteamUser").GetFriendList(steamid = self.VALID_ID64) profile_batch_testsids = [friend["steamid"] for friend in profile_batch_friends["friendslist"]["friends"]] friend_list = user.friend_list(self.VALID_ID64) self.assertEqual(set(profile_batch_testsids), set(map(lambda x: str(x.steamid), friend_list)))
class FriendListTestCase(ProfileTestCase): def test_sids(self): pass
2
0
6
1
5
0
1
0
1
5
2
0
1
0
1
73
7
1
6
5
4
0
6
5
4
1
3
0
1
144,957
Lagg/steamodd
Lagg_steamodd/tests/testremote_storage.py
tests.testremote_storage.RemoteStorageTestCase
class RemoteStorageTestCase(unittest.TestCase): APPID = 440 INVALID_UGCID = "wobwobwobwob" VALID_UGCID = 650994986817657344 VALID_UGC_SIZE = 134620 VALID_UGC_FILENAME = "steamworkshop/tf2/_thumb.jpg" VALID_UGC_PATH = "/ugc/650994986817657344/D2ADAD7F19BFA9A99BD2B8850CC317DC6BA01BA9/" #Silly tea hat made by RJ @classmethod def setUpClass(cls): cls._test_file = remote_storage.ugc_file(cls.APPID, cls.VALID_UGCID) def test_invalid_ugcid(self): ugc_file = remote_storage.ugc_file(self.APPID, self.INVALID_UGCID) self.assertRaises(remote_storage.FileNotFoundError) def test_valid_ugcid_filename(self): self.assertEqual(self._test_file.filename, self.VALID_UGC_FILENAME) def test_valid_ugcid_size(self): self.assertEqual(self._test_file.size, self.VALID_UGC_SIZE) def test_valid_ugcid_url(self): parsed_url = urlparse(self._test_file.url) self.assertEqual(parsed_url.path, self.VALID_UGC_PATH)
class RemoteStorageTestCase(unittest.TestCase): @classmethod def setUpClass(cls): pass def test_invalid_ugcid(self): pass def test_valid_ugcid_filename(self): pass def test_valid_ugcid_size(self): pass def test_valid_ugcid_url(self): pass
7
0
2
0
2
0
1
0.05
1
2
2
0
4
0
5
77
26
6
20
15
13
1
19
14
13
1
2
0
5
144,958
Lagg/steamodd
Lagg_steamodd/tests/testloc.py
tests.testloc.LocTestCase
class LocTestCase(unittest.TestCase): DEFAULT_LANGUAGE_CODE = "en_US" VALID_LANGUAGE_CODE = "fi_FI" INVALID_LANGUAGE_CODE = "en_GB" def test_supported_language(self): lang = steam.loc.language(LocTestCase.VALID_LANGUAGE_CODE) self.assertEquals(lang._code, LocTestCase.VALID_LANGUAGE_CODE) def test_unsupported_language(self): self.assertRaises(steam.loc.LanguageUnsupportedError, steam.loc.language, LocTestCase.INVALID_LANGUAGE_CODE) def test_supported_language_via_environ(self): os.environ['LANG'] = LocTestCase.VALID_LANGUAGE_CODE lang = steam.loc.language(None) self.assertEquals(lang._code, LocTestCase.VALID_LANGUAGE_CODE) def test_unsupported_language_via_environ(self): os.environ['LANG'] = LocTestCase.INVALID_LANGUAGE_CODE lang = steam.loc.language(None) self.assertEquals(lang._code, LocTestCase.DEFAULT_LANGUAGE_CODE)
class LocTestCase(unittest.TestCase): def test_supported_language(self): pass def test_unsupported_language(self): pass def test_supported_language_via_environ(self): pass def test_unsupported_language_via_environ(self): pass
5
0
3
0
3
0
1
0
1
2
2
0
4
0
4
76
21
4
17
11
12
0
17
11
12
1
2
0
4
144,959
Lagg/steamodd
Lagg_steamodd/tests/testitems.py
tests.testitems.ItemTestCase
class ItemTestCase(InventoryBaseTestCase): def test_position(self): for item in self._inv: self.assertLessEqual(item.position, self._inv.cells_total) def test_equipped(self): for item in self._inv: self.assertNotIn(0, item.equipped.keys()) self.assertNotIn(65535, item.equipped.values()) def test_name(self): # Since sim names are generated by Valve we'll test against those for consistency # steamodd adds craft numbers to all names, valve doesn't, so they should be stripped # steamodd doesn't add crate series to names, valve does, so they should be stripped as well cn_exp = re.compile(r" (?:Series )?#\d+$") sim_names = set() for item in self._sim: # Removes quotes in case of custom name (steamodd leaves that aesthetic choice to the user) name = item.full_name.strip("'") # Don't even bother with strange items right now. I'm tired of unit tests failing whenever # the inventory does and no one from valve responds when I tell them of the issue. If it does # get fixed feel free to remove this as it is definitely a WORKAROUND. # Removes quotes in case of custom name (steamodd leaves that aesthetic choice to the user) if not name.startswith("Strange "): sim_names.add(cn_exp.sub('', name)) # See the above WORKAROUND about strange items and remove if/when it's fixed. our_names = set([cn_exp.sub('', item.custom_name or item.full_name) for item in self._inv if item.quality[1] != "strange" or item.custom_name]) self.assertEqual(our_names, sim_names) def test_attributes(self): # Similarly to the name, we'll test against Valve's strings to check for consistency in the math. schema_attr_exps = [] for attr in self._schema.attributes: if not attr.description: continue desc = attr.description.strip() exp = re.escape(desc).replace("\\%s1", r"[\d-]+") schema_attr_exps.append(re.compile(exp)) sim_attrs = {} for item in self._sim: sim_attrs.setdefault(item.id, set()) for attr in item: # Due to lack of contextual data, we'll have to do fuzzy matching to separate actual attrs from fluff/descriptions desc = attr.description.strip() if desc: # Stop processing if we hit item set attrs, for now if desc.startswith("Item Set Bonus:"): break # Valve for some reason insists on this being attached by the client, since they're not actually attached we skip it. if desc == "Given to valuable Community Contributors": continue for exp in schema_attr_exps: if exp.match(desc): sim_attrs[item.id].add(desc) break for item in self._inv: # Ignore hidden, special (for now) and date values (timestamp formatting is an eternal battle, let it not be fought on these hallowed testgrounds) attrs = set([attr.formatted_description for attr in item if not attr.hidden and not attr.formatted_description.startswith("Attrib_") and attr.value_type not in ("date", "particle_index")]) self.assertTrue(item.id in sim_attrs) self.assertEqual(attrs, sim_attrs[item.id])
class ItemTestCase(InventoryBaseTestCase): def test_position(self): pass def test_equipped(self): pass def test_name(self): pass def test_attributes(self): pass
5
0
17
3
11
4
5
0.33
1
1
0
0
4
0
4
79
73
14
45
19
40
15
43
19
38
11
4
5
18
144,960
Lagg/steamodd
Lagg_steamodd/tests/testitems.py
tests.testitems.InventoryTestCase
class InventoryTestCase(InventoryBaseTestCase): def test_cell_count(self): self.assertLessEqual(len(list(self._inv)), self._inv.cells_total)
class InventoryTestCase(InventoryBaseTestCase): def test_cell_count(self): pass
2
0
2
0
2
0
1
0
1
1
0
0
1
0
1
76
3
0
3
2
1
0
3
2
1
1
4
0
1
144,961
Lagg/steamodd
Lagg_steamodd/tests/testuser.py
tests.testuser.VanityTestCase
class VanityTestCase(ProfileTestCase): def test_invalid_vanity(self): vanity = user.vanity_url(self.INVALID_VANITY) self.assertRaises(user.VanityError, lambda: vanity.id64) def test_pathed_vanity(self): vanity = user.vanity_url('/' + self.VALID_VANITY + '/') self.assertEqual(vanity.id64, ProfileTestCase.VALID_ID64) def test_valid_vanity(self): vanity = user.vanity_url(self.VALID_VANITY) self.assertEqual(vanity.id64, ProfileTestCase.VALID_ID64)
class VanityTestCase(ProfileTestCase): def test_invalid_vanity(self): pass def test_pathed_vanity(self): pass def test_valid_vanity(self): pass
4
0
3
0
3
0
1
0
1
2
2
0
3
0
3
75
12
2
10
7
6
0
10
7
6
1
3
0
3
144,962
Lagg/steamodd
Lagg_steamodd/tests/testitems.py
tests.testitems.BaseTestCase
class BaseTestCase(unittest.TestCase): TEST_APP = (440, 'en_US') # TF2 English catalog ITEM_IN_CATALOG = 344 # Crocleather Slouch ITEM_NOT_IN_CATALOG = 1 # Bottle TEST_ID64 = 76561198811195748 # lagg-bot test acct TEST_APP_NO_TAGS = (570, 'en_US') # Dota 2 English catalog ITEM_IN_NO_TAGS_CATALOG = 4097
class BaseTestCase(unittest.TestCase): pass
1
0
0
0
0
0
0
0.86
1
0
0
2
0
0
0
72
8
1
7
7
6
6
7
7
6
0
2
0
0
144,963
Lagg/steamodd
Lagg_steamodd/tests/testitems.py
tests.testitems.AssetTestCase
class AssetTestCase(BaseTestCase): def test_asset_contains(self): assets = items.assets(*self.TEST_APP) self.assertTrue(self.ITEM_IN_CATALOG in assets) self.assertFalse(self.ITEM_NOT_IN_CATALOG in assets) schema = items.schema(*self.TEST_APP) self.assertTrue(schema[self.ITEM_IN_CATALOG] in assets) self.assertFalse(schema[self.ITEM_NOT_IN_CATALOG] in assets) def test_asset_has_tags(self): assets_with_tags = items.assets(*self.TEST_APP) self.assertGreater(len(assets_with_tags.tags), 0) def test_asset_has_no_tags(self): assets_without_tags = items.assets(*self.TEST_APP_NO_TAGS) self.assertEqual(len(assets_without_tags.tags), 0) def test_asset_item_has_tags(self): assets_with_tags = items.assets(*self.TEST_APP) asset_item_with_tags = assets_with_tags[self.ITEM_IN_CATALOG] self.assertGreater(len(asset_item_with_tags.tags), 0) def test_asset_item_has_no_tags(self): assets_without_tags = items.assets(*self.TEST_APP_NO_TAGS) asset_item_without_tags = assets_without_tags[self.ITEM_IN_NO_TAGS_CATALOG] self.assertEqual(len(asset_item_without_tags.tags), 0)
class AssetTestCase(BaseTestCase): def test_asset_contains(self): pass def test_asset_has_tags(self): pass def test_asset_has_no_tags(self): pass def test_asset_item_has_tags(self): pass def test_asset_item_has_no_tags(self): pass
6
0
4
0
4
0
1
0
1
2
2
0
5
2
5
77
26
4
22
16
16
0
22
14
16
1
3
0
5
144,964
Lagg/steamodd
Lagg_steamodd/tests/testapps.py
tests.testapps.AppsTestCase
class AppsTestCase(unittest.TestCase): @classmethod def setUpClass(cls): cls._apps = apps.app_list() def test_builtin_consistency(self): for app, name in self._apps._builtin.items(): self.assertIn(app, self._apps) self.assertEquals((app, name), self._apps[app]) def test_invalid_app(self): self.assertRaises(KeyError, self._apps.__getitem__, 12345678)
class AppsTestCase(unittest.TestCase): @classmethod def setUpClass(cls): pass def test_builtin_consistency(self): pass def test_invalid_app(self): pass
5
0
3
0
3
0
1
0
1
2
1
0
2
0
3
75
12
2
10
6
5
0
9
5
5
2
2
1
4
144,965
Lagg/steamodd
Lagg_steamodd/steam/user.py
steam.user.vanity_url
class vanity_url(object): """ Class for holding a vanity URL and its id64 """ @property def id64(self): if self._cache: return self._cache res = None try: res = self._api["response"] self._cache = int(res["steamid"]) except KeyError: if not self._cache: if res: raise VanityError(res.get("message", "Invalid vanity response")) else: raise VanityError("Empty vanity response") return self._cache def __str__(self): return str(self.id64) def __init__(self, vanity, **kwargs): """ Takes a vanity URL part and tries to resolve it. """ vanity = os.path.basename(str(vanity).strip('/')) self._cache = None self._api = api.interface("ISteamUser").ResolveVanityURL(vanityurl=vanity, **kwargs)
class vanity_url(object): ''' Class for holding a vanity URL and its id64 ''' @property def id64(self): pass def __str__(self): pass def __init__(self, vanity, **kwargs): ''' Takes a vanity URL part and tries to resolve it. ''' pass
5
2
9
1
7
1
2
0.13
1
5
2
0
3
2
3
3
32
6
23
8
18
3
20
7
16
5
1
3
7
144,966
Lagg/steamodd
Lagg_steamodd/steam/user.py
steam.user.profile_batch
class profile_batch(_batched_request): def __init__(self, sids): """ Fetches user profiles en masse and generates 'profile' objects. The length of the ID list can be indefinite, separate requests will be made if the length exceeds the API's ID cap and the list split into batches. """ super(profile_batch, self).__init__(sids) def _process_batch(self, batch): processed = set() for sid in batch: try: sid = sid.id64 except AttributeError: sid = os.path.basename(str(sid).strip('/')) processed.add(str(sid)) return processed def _call_method(self, batch): response = api.interface("ISteamUser").GetPlayerSummaries(version=2, steamids=','.join(batch)) return [profile.from_def(player) for player in response["response"]["players"]]
class profile_batch(_batched_request): def __init__(self, sids): ''' Fetches user profiles en masse and generates 'profile' objects. The length of the ID list can be indefinite, separate requests will be made if the length exceeds the API's ID cap and the list split into batches. ''' pass def _process_batch(self, batch): pass def _call_method(self, batch): pass
4
1
7
1
5
1
2
0.27
1
6
2
0
3
0
3
8
25
6
15
7
11
4
15
7
11
3
2
2
5
144,967
Lagg/steamodd
Lagg_steamodd/steam/user.py
steam.user.profile
class profile(object): """ Functions for reading user account data """ @property def id64(self): """ Returns the 64 bit steam ID (use with other API requests) """ return int(self._prof["steamid"]) @property def id32(self): """ Returns the 32 bit steam ID """ return int(self.id64) - 76561197960265728 @property def persona(self): """ Returns the user's persona (what you usually see in-game) """ return self._prof["personaname"] @property def profile_url(self): """ Returns a URL to the user's Community profile page """ return self._prof["profileurl"] @property def vanity(self): """ Returns the user's vanity url if it exists, None otherwise """ purl = self.profile_url.strip('/') if purl.find("/id/") != -1: return os.path.basename(purl) @property def avatar_small(self): return self._prof["avatar"] @property def avatar_medium(self): return self._prof["avatarmedium"] @property def avatar_large(self): return self._prof["avatarfull"] @property def status(self): """ Returns the user's status. 0: offline 1: online 2: busy 3: away 4: snooze 5: looking to trade 6: looking to play If player's profile is private, this will always be 0. """ return self._prof["personastate"] @property def persona_state_flags(self): """ personastateflags 0: NONE 1: Has Rich Presence 2: In Joinable Game 4: Golden 8: Remote Play Together 256: Client Type Web 512: Client Type Mobile 1024: Client Type Tenfoot 2048: Client Type VR 4096: Launch Type Gamepad 8182: Launch Type CompatTool """ return self._prof["personastateflags"] @property def visibility(self): """ Returns the visibility setting of the profile. 1: private 2: friends only 3: public """ return self._prof["communityvisibilitystate"] @property def configured(self): """ Returns true if the user has created a Community profile """ return bool(self._prof.get("profilestate")) @property def last_online(self): """ Returns the last time the user was online as a localtime time.struct_time struct """ return time.localtime(self._prof["lastlogoff"]) @property def comments_enabled(self): """ Returns true if the profile allows public comments """ return bool(self._prof.get("commentpermission")) @property def real_name(self): """ Returns the user's real name if it's set and public """ return self._prof.get("realname") @property def primary_group(self): """ Returns the user's primary group ID if set. """ return self._prof.get("primaryclanid") @property def creation_date(self): """ Returns the account creation date as a localtime time.struct_time struct if public""" timestamp = self._prof.get("timecreated") if timestamp: return time.localtime(timestamp) @property def current_game(self): """ Returns a tuple of 3 elements (each of which may be None if not available): Current game app ID, server ip:port, misc. extra info (eg. game title) """ obj = self._prof gameid = obj.get("gameid") gameserverip = obj.get("gameserverip") gameextrainfo = obj.get("gameextrainfo") return (int(gameid) if gameid else None, gameserverip, gameextrainfo) @property def location(self): """ Returns a tuple of 2 elements (each of which may be None if not available): State ISO code, country ISO code """ obj = self._prof return (obj.get("locstatecode"), obj.get("loccountrycode")) @property def lobbysteamid(self): """ Returns a lobbynumber as int from few Source games or 0 if not in lobby. """ return int(self._prof.get("lobbysteamid", 0)) @property def _prof(self): if not self._cache: try: res = self._api["response"]["players"] try: self._cache = res[0] except IndexError: raise ProfileNotFoundError("Profile not found") except KeyError: raise ProfileError("Bad player profile results returned") return self._cache @property def level(self): """ Returns the the user's profile level, note that this runs a separate request because the profile level data isn't in the standard player summary output even though it should be. Which is also why it's not implemented as a separate class. You won't need this output and not the profile output """ level_key = "player_level" if level_key in self._api["response"]: return self._api["response"][level_key] try: lvl = api.interface("IPlayerService").GetSteamLevel(steamid=self.id64)["response"][level_key] self._api["response"][level_key] = lvl return lvl except: return -1 @classmethod def from_def(cls, obj): """ Builds a profile object from a raw player summary object """ prof = cls(obj["steamid"]) prof._cache = obj return prof def __str__(self): return self.persona or str(self.id64) def __init__(self, sid, **kwargs): """ Creates a profile instance for the given user """ try: sid = sid.id64 except AttributeError: sid = os.path.basename(str(sid).strip('/')) self._cache = {} self._api = api.interface("ISteamUser").GetPlayerSummaries(version=2, steamids=sid, **kwargs)
class profile(object): ''' Functions for reading user account data ''' @property def id64(self): ''' Returns the 64 bit steam ID (use with other API requests) ''' pass @property def id32(self): ''' Returns the 32 bit steam ID ''' pass @property def persona(self): ''' Returns the user's persona (what you usually see in-game) ''' pass @property def profile_url(self): ''' Returns a URL to the user's Community profile page ''' pass @property def vanity(self): ''' Returns the user's vanity url if it exists, None otherwise ''' pass @property def avatar_small(self): pass @property def avatar_medium(self): pass @property def avatar_large(self): pass @property def status(self): ''' Returns the user's status. 0: offline 1: online 2: busy 3: away 4: snooze 5: looking to trade 6: looking to play If player's profile is private, this will always be 0. ''' pass @property def persona_state_flags(self): ''' personastateflags 0: NONE 1: Has Rich Presence 2: In Joinable Game 4: Golden 8: Remote Play Together 256: Client Type Web 512: Client Type Mobile 1024: Client Type Tenfoot 2048: Client Type VR 4096: Launch Type Gamepad 8182: Launch Type CompatTool ''' pass @property def visibility(self): ''' Returns the visibility setting of the profile. 1: private 2: friends only 3: public ''' pass @property def configured(self): ''' Returns true if the user has created a Community profile ''' pass @property def last_online(self): ''' Returns the last time the user was online as a localtime time.struct_time struct ''' pass @property def comments_enabled(self): ''' Returns true if the profile allows public comments ''' pass @property def real_name(self): ''' Returns the user's real name if it's set and public ''' pass @property def primary_group(self): ''' Returns the user's primary group ID if set. ''' pass @property def creation_date(self): ''' Returns the account creation date as a localtime time.struct_time struct if public''' pass @property def current_game(self): ''' Returns a tuple of 3 elements (each of which may be None if not available): Current game app ID, server ip:port, misc. extra info (eg. game title) ''' pass @property def location(self): ''' Returns a tuple of 2 elements (each of which may be None if not available): State ISO code, country ISO code ''' pass @property def lobbysteamid(self): ''' Returns a lobbynumber as int from few Source games or 0 if not in lobby. ''' pass @property def _prof(self): pass @property def level(self): ''' Returns the the user's profile level, note that this runs a separate request because the profile level data isn't in the standard player summary output even though it should be. Which is also why it's not implemented as a separate class. You won't need this output and not the profile output ''' pass @classmethod def from_def(cls, obj): ''' Builds a profile object from a raw player summary object ''' pass def __str__(self): pass def __init__(self, sid, **kwargs): ''' Creates a profile instance for the given user ''' pass
49
21
6
0
3
2
1
0.57
1
9
3
0
24
2
25
25
199
31
107
62
58
61
84
39
58
4
1
3
34
144,968
Lagg/steamodd
Lagg_steamodd/steam/user.py
steam.user.friend_list
class friend_list(object): """ Creates an iterator of friend objects fetched from given user's Steam ID. Allows for filtering by specyfing relationship argument in constructor, but API seems to always return items with friend relationship. Possible filter values: all, friend. """ def __init__(self, sid, relationship="all", **kwargs): try: sid = sid.id64 except AttributeError: sid = os.path.basename(str(sid).strip('/')) self._api = api.interface("ISteamUser").GetFriendList(steamid=sid, relationship=relationship, **kwargs) try: self._friends = self._api["friendslist"]["friends"] except api.HTTPFileNotFoundError: raise ProfileNotFoundError("Profile not found") except api.HTTPInternalServerError: raise ProfileNotFoundError("Invalid Steam ID given") self.index = 0 @property def count(self): """ Returns number of friends """ return len(self._friends) def __iter__(self): return self def __next__(self): if self.index < len(self._friends): self.index += 1 return friend(self._friends[self.index - 1]) else: self.index = 0 raise StopIteration next = __next__
class friend_list(object): ''' Creates an iterator of friend objects fetched from given user's Steam ID. Allows for filtering by specyfing relationship argument in constructor, but API seems to always return items with friend relationship. Possible filter values: all, friend. ''' def __init__(self, sid, relationship="all", **kwargs): pass @property def count(self): ''' Returns number of friends ''' pass def __iter__(self): pass def __next__(self): pass
6
2
7
1
7
0
2
0.24
1
8
5
0
4
3
4
4
42
6
29
9
23
7
25
8
20
4
1
1
8
144,969
Lagg/steamodd
Lagg_steamodd/steam/user.py
steam.user.friend
class friend(object): """ Class used to store friend obtained from GetFriendList. """ def __init__(self, friend_dict): self._friend_dict = friend_dict @property def steamid(self): """ Returns the 64 bit Steam ID """ return int(self._friend_dict["steamid"]) @property def relationship(self): """ Returns relationship qualifier """ return self._friend_dict["relationship"] @property def since(self): """ Returns date when relationship was created as a localtime time.struct_time """ return time.localtime(self._friend_dict["friend_since"])
class friend(object): ''' Class used to store friend obtained from GetFriendList. ''' def __init__(self, friend_dict): pass @property def steamid(self): ''' Returns the 64 bit Steam ID ''' pass @property def relationship(self): ''' Returns relationship qualifier ''' pass @property def since(self): ''' Returns date when relationship was created as a localtime time.struct_time ''' pass
8
4
3
0
2
1
1
0.5
1
1
0
0
4
1
4
4
21
3
12
9
4
6
9
6
4
1
1
0
4
144,970
Lagg/steamodd
Lagg_steamodd/steam/user.py
steam.user.bans_batch
class bans_batch(_batched_request): def __init__(self, sids): super(bans_batch, self).__init__(sids) def _process_batch(self, batch): processed = set() for sid in batch: try: sid = sid.id64 except AttributeError: sid = os.path.basename(str(sid).strip('/')) processed.add(str(sid)) return processed def _call_method(self, batch): response = api.interface("ISteamUser").GetPlayerBans(steamids=','.join(batch)) return [bans.from_def(player) for player in response["players"]]
class bans_batch(_batched_request): def __init__(self, sids): pass def _process_batch(self, batch): pass def _call_method(self, batch): pass
4
0
6
1
5
0
2
0
1
6
2
0
3
0
3
8
21
6
15
7
11
0
15
7
11
3
2
2
5
144,971
Lagg/steamodd
Lagg_steamodd/steam/user.py
steam.user.VanityError
class VanityError(ProfileError): pass
class VanityError(ProfileError): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
10
2
0
2
1
1
0
2
1
1
0
6
0
0
144,972
Lagg/steamodd
Lagg_steamodd/tests/testitems.py
tests.testitems.InventoryBaseTestCase
class InventoryBaseTestCase(BaseTestCase): _inv_cache = None _schema_cache = None _sim_cache = None @property def _inv(self): if not InventoryBaseTestCase._inv_cache: InventoryBaseTestCase._inv_cache = items.inventory(self.TEST_ID64, self.TEST_APP[0], self._schema) return InventoryBaseTestCase._inv_cache @property def _schema(self): if not InventoryBaseTestCase._schema_cache: InventoryBaseTestCase._schema_cache = items.schema(*self.TEST_APP) return InventoryBaseTestCase._schema_cache @property def _sim(self): if not InventoryBaseTestCase._sim_cache: InventoryBaseTestCase._sim_cache = sim.inventory(self.TEST_ID64, 440, 2, None, 2000) return InventoryBaseTestCase._sim_cache
class InventoryBaseTestCase(BaseTestCase): @property def _inv(self): pass @property def _schema(self): pass @property def _sim(self): pass
7
0
5
1
4
0
2
0
1
3
3
2
3
0
3
75
25
6
19
10
12
0
16
7
12
2
3
1
6
144,973
Lagg/steamodd
Lagg_steamodd/steam/user.py
steam.user.bans
class bans(object): def __init__(self, sid, **kwargs): """ Fetch user ban information """ try: sid = sid.id64 except AttributeError: sid = os.path.basename(str(sid).strip('/')) self._cache = {} self._api = api.interface("ISteamUser").GetPlayerBans(steamids=sid, **kwargs) @property def _bans(self): if not self._cache: try: res = self._api["players"] try: self._cache = res[0] except IndexError: raise BansNotFoundError("No ban results for this profile") except KeyError: raise BansError("Bad ban data returned") return self._cache @property def id64(self): return int(self._bans["SteamId"]) @property def community(self): """ Community banned """ return self._bans["CommunityBanned"] @property def vac(self): """ User is currently VAC banned """ return self._bans["VACBanned"] @property def vac_count(self): """ Number of VAC bans on record """ return self._bans["NumberOfVACBans"] @property def days_unbanned(self): """ Number of days since the last ban. Note that users without a ban on record will have this set to 0 so make sure to test bans.vac """ return self._bans["DaysSinceLastBan"] @property def economy(self): """ Economy ban status which is a string for whatever reason """ return self._bans["EconomyBan"] @property def game_count(self): """ Number of bans in games, this includes CS:GO Overwatch bans """ return self._bans["NumberOfGameBans"] @classmethod def from_def(cls, obj): instance = cls(int(obj["SteamId"])) instance._cache = obj return instance
class bans(object): def __init__(self, sid, **kwargs): ''' Fetch user ban information ''' pass @property def _bans(self): pass @property def id64(self): pass @property def community(self): ''' Community banned ''' pass @property def vac(self): ''' User is currently VAC banned ''' pass @property def vac_count(self): ''' Number of VAC bans on record ''' pass @property def days_unbanned(self): ''' Number of days since the last ban. Note that users without a ban on record will have this set to 0 so make sure to test bans.vac ''' pass @property def economy(self): ''' Economy ban status which is a string for whatever reason ''' pass @property def game_count(self): ''' Number of bans in games, this includes CS:GO Overwatch bans ''' pass @classmethod def from_def(cls, obj): pass
20
7
5
0
4
1
1
0.22
1
8
3
0
9
2
10
10
68
12
46
24
26
10
37
15
26
4
1
3
14
144,974
LandRegistry/lr-utils
LandRegistry_lr-utils/lrutils/address/address_utils.py
lrutils.address.address_utils.Address
class Address(object): def __init__(self, string_address): self.structured = None self.string = StringAddress(string_address)
class Address(object): def __init__(self, string_address): pass
2
0
3
0
3
0
1
0
1
1
1
0
1
2
1
1
5
1
4
4
2
0
4
4
2
1
1
0
1
144,975
LandRegistry/lr-utils
LandRegistry_lr-utils/lrutils/address/address_utils.py
lrutils.address.address_utils.AddressBuilder
class AddressBuilder(object): def __init__(self, house_no, street_name, town, postcode, postal_county, region_name, country, full_address): self.house_no = house_no self.street_name = street_name self.town = town self.postcode = postcode self.postal_county = postal_county self.region_name = region_name self.country = country self.full_address = full_address self.minimal_viable_address_fields = ["house_no", "street_name", "town", "postcode"] def build(self): address = Address(self.full_address) have_minimum_required_data = True for field in self.minimal_viable_address_fields: if not self.__dict__[field] or self.__dict__[field].isspace() : have_minimum_required_data = False break if have_minimum_required_data and self.county_and_region_empty(): have_minimum_required_data = False if have_minimum_required_data: address.structured = StructuredAddress(self.house_no, self.street_name, self.town, self.postcode, self.postal_county, self.region_name, self.country) return address def county_and_region_empty(self): county = self.postal_county.replace(" ","") region = self.region_name.replace(" ","") if not county and not region: return True return False
class AddressBuilder(object): def __init__(self, house_no, street_name, town, postcode, postal_county, region_name, country, full_address): pass def build(self): pass def county_and_region_empty(self): pass
4
0
11
1
10
0
3
0
1
2
2
0
3
9
3
3
38
8
30
18
26
0
29
18
25
5
1
2
8
144,976
LandRegistry/lr-utils
LandRegistry_lr-utils/lrutils/address/address_utils.py
lrutils.address.address_utils.StringAddress
class StringAddress(object): def __init__(self, string_address): self.string_address = string_address def get_fields(self): fields = self.string_address.split(',') fields = [item.strip() for item in fields] return fields def get_string(self): return self.string_address
class StringAddress(object): def __init__(self, string_address): pass def get_fields(self): pass def get_string(self): pass
4
0
3
0
3
0
1
0
1
0
0
0
3
1
3
3
12
3
9
6
5
0
9
6
5
1
1
0
3
144,977
LandRegistry/lr-utils
LandRegistry_lr-utils/lrutils/address/address_utils.py
lrutils.address.address_utils.StructuredAddress
class StructuredAddress(object): def __init__(self, house_no, street_name, town, postcode, postal_county, region_name, country): self.house_no = house_no self.street_name = street_name self.town = town self.postcode = postcode self.postal_county = postal_county self.region_name = region_name self.country = country
class StructuredAddress(object): def __init__(self, house_no, street_name, town, postcode, postal_county, region_name, country): pass
2
0
8
0
8
0
1
0
1
0
0
0
1
7
1
1
10
1
9
9
7
0
9
9
7
1
1
0
1
144,978
LandRegistry/lr-utils
LandRegistry_lr-utils/lrutils/password/password_utils.py
lrutils.password.password_utils.PasswordUtils
class PasswordUtils(object): def __init__(self, config): self.salt = config.get('SECURITY_PASSWORD_SALT', None) self.pw_hash = config.get('SECURITY_PASSWORD_HASH', None) if self.salt is None: raise RuntimeError("The configuration value 'SECURITY_PASSWORD_SALT' must be set") if self.pw_hash is None: raise RuntimeError("The configuration value 'SECURITY_PASSWORD_HASH' must be set") self.pwd_context = CryptContext(schemes=[self.pw_hash]) def get_hmac(self, password): h = hmac.new(self.encode_string(self.salt), self.encode_string(password), hashlib.sha512) return base64.b64encode(h.digest()) def encrypt_password(self, password): signed = self.get_hmac(password).decode('ascii') return self.pwd_context.encrypt(signed) def verify_password(self, password, password_hash): password = self.get_hmac(password) return self.pwd_context.verify(password, password_hash) def encode_string(self, string): if isinstance(string, unicode): string = string.encode('utf-8') return string
class PasswordUtils(object): def __init__(self, config): pass def get_hmac(self, password): pass def encrypt_password(self, password): pass def verify_password(self, password, password_hash): pass def encode_string(self, string): pass
6
0
5
1
4
0
2
0
1
1
0
0
5
3
5
5
34
12
22
11
16
0
22
11
16
3
1
1
8
144,979
LandRegistry/lr-utils
LandRegistry_lr-utils/tests/test_address_builder.py
tests.test_address_builder.AddressTestCase
class AddressTestCase(unittest.TestCase): def setUp(self): self.minimal_address = { "full_address": "8 Miller Way, Plymouth, Devon, PL6 8UQ", "house_no" : "8", "street_name" : "Miller Way", "town" : "Plymouth", "postal_county" : "Devon", "region_name" : "", "country" : "", "postcode":"PL6 8UQ" } def test_structured_address_created_minimal_required_fields_not_empty(self): address = build_address(self.minimal_address) self.assertEquals("8", address.structured.house_no) self.assertEquals("Miller Way", address.structured.street_name) self.assertEquals("Plymouth", address.structured.town) self.assertEquals("Devon", address.structured.postal_county) def test_structured_address_not_created_if_a_required_field_empty(self): self.minimal_address["town"] = "" address = build_address(self.minimal_address) self.assertIsNone(address.structured) def test_structured_address_not_created_if_both_postal_country_and_region_name_empty(self): self.minimal_address["postal_county"] = "" self.minimal_address["region_name"] = " " address = build_address(self.minimal_address) self.assertIsNone(address.structured) def test_string_address_is_present_even_when_required_field_is_empty(self): self.minimal_address["house_no"] = "" address = build_address(self.minimal_address) self.assertIsNone(address.structured) self.assertEquals("8 Miller Way, Plymouth, Devon, PL6 8UQ", address.string.get_string()) self.assertEquals(["8 Miller Way", "Plymouth", "Devon", "PL6 8UQ"], address.string.get_fields())
class AddressTestCase(unittest.TestCase): def setUp(self): pass def test_structured_address_created_minimal_required_fields_not_empty(self): pass def test_structured_address_not_created_if_a_required_field_empty(self): pass def test_structured_address_not_created_if_both_postal_country_and_region_name_empty(self): pass def test_string_address_is_present_even_when_required_field_is_empty(self): pass
6
0
8
2
6
0
1
0
1
0
0
0
5
1
5
77
51
18
33
11
27
0
24
11
18
1
2
0
5
144,980
LandRegistry/lr-utils
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LandRegistry_lr-utils/lrutils/errorhandler/errorhandler_utils.py
lrutils.errorhandler.errorhandler_utils.ErrorHandler
class ErrorHandler(object): def __init__(self, app=None, tasks=None): self.tasks = tasks if tasks is not None else [setup_errors] if app is not None: self.init_app(app) def __str__(self): return repr(self.code) def init_app(self, app): """Runs each of the tasks added via the :meth:`task` decorator.""" for task in self.tasks: task(app) def task(self, func, *args, **kwargs): def decorator(f): @wraps(f) def inner(app): return f(app, *args, **kwargs) return inner if not callable(func) or len(args) > 0 or len(kwargs) > 0: def wrapper(func): task = decorator(func) self.tasks.append(task) return task return wrapper else: task = decorator(func) self.tasks.append(task) return task
class ErrorHandler(object): def __init__(self, app=None, tasks=None): pass def __str__(self): pass def init_app(self, app): '''Runs each of the tasks added via the :meth:`task` decorator.''' pass def task(self, func, *args, **kwargs): pass def decorator(f): pass @wraps(f) def inner(app): pass def wrapper(func): pass
9
1
6
1
5
0
2
0.04
1
0
0
0
3
1
3
3
34
7
26
13
17
1
24
12
16
3
1
1
11
144,981
LandRegistry/lr-utils
LandRegistry_lr-utils/tests/test_errorhandler.py
tests.test_errorhandler.ErrorHandlerTestCase
class ErrorHandlerTestCase(unittest.TestCase): def setUp(self): self.app = Flask('tests') ErrorHandler(self.app) self.client = self.app.test_client() def test_headers(self): response = self.app.make_response("error.html") eh_after_request(response) assert response.headers.get('Content-Security-Policy') assert response.headers.get('X-Frame-Options') assert response.headers.get('X-Content-Type-Options') assert response.headers.get('X-XSS-Protection') def test_404(self): rv = self.client.get('/pagedoesnotexist') assert rv.status == '404 NOT FOUND'
class ErrorHandlerTestCase(unittest.TestCase): def setUp(self): pass def test_headers(self): pass def test_404(self): pass
4
0
5
0
5
0
1
0
1
1
1
0
3
2
3
75
19
4
15
8
11
0
15
8
11
1
2
0
3
144,982
LandRegistry/lr-utils
LandRegistry_lr-utils/tests/test_password_hashing.py
tests.test_password_hashing.PasswordUtilsTestCase
class PasswordUtilsTestCase(unittest.TestCase): def test_password_hash_verifies(self): config = {'SECURITY_PASSWORD_SALT' : 'no-secret', 'SECURITY_PASSWORD_HASH' : 'bcrypt'} pass_util = PasswordUtils(config) self.assertTrue( pass_util.verify_password('dummy', pass_util.encrypt_password('dummy')) ) self.assertFalse( pass_util.verify_password('dumbass', pass_util.encrypt_password('dummy')) ) def test_salt_must_be_in_config(self): config = {'SECURITY_PASSWORD_SALT' : None, 'SECURITY_PASSWORD_HASH' : 'bcrypt'} self.assertRaisesRegexp(RuntimeError, "The configuration value 'SECURITY_PASSWORD_SALT' must be set", PasswordUtils, config) def test_hash_must_be_in_config(self): config = {'SECURITY_PASSWORD_SALT' : 'no-secret', 'SECURITY_PASSWORD_HASH' : None} self.assertRaisesRegexp(RuntimeError, "The configuration value 'SECURITY_PASSWORD_HASH' must be set", PasswordUtils, config)
class PasswordUtilsTestCase(unittest.TestCase): def test_password_hash_verifies(self): pass def test_salt_must_be_in_config(self): pass def test_hash_must_be_in_config(self): pass
4
0
4
1
4
0
1
0
1
2
1
0
3
0
3
75
20
8
12
8
8
0
12
8
8
1
2
0
3
144,983
LandRegistry/lr-utils
LandRegistry_lr-utils/tests/test_template_filters.py
tests.test_template_filters.TemplateFiltersTestCase
class TemplateFiltersTestCase(unittest.TestCase): def test_dateformat(self): formatted = dateformat('14/01/2014') self.assertEquals(formatted, '14 January 2014') formatted = dateformat('01/01/2014') self.assertEquals(formatted, '1 January 2014') formatted = dateformat('02/01/2014') self.assertEquals(formatted, '2 January 2014') formatted = dateformat('2014-01-02') self.assertEquals(formatted, '2 January 2014') formatted = dateformat('2014/01/02') self.assertEquals(formatted, '2 January 2014') formatted = dateformat('14.01.02') self.assertEquals(formatted, '14 January 2002') formatted = dateformat('99.01.02') self.assertEquals(formatted, '2 January 1999') formatted = dateformat('02 January 2014') self.assertEquals(formatted, '2 January 2014') def test_datetimeformat(self): formatted = datetimeformat('14/06/2014 23:23:25.1231+01:00') self.assertEquals(formatted, '14 June 2014 at 23:23:25') formatted = datetimeformat('14/01/14 23:23:25.1231+01:00') self.assertEquals(formatted, '14 January 2014 at 22:23:25') formatted = datetimeformat('2013-01-02 08:23:25.1231+00:00') self.assertEquals(formatted, '2 January 2013 at 08:23:25') def test_timezones(self): formatted = datetimeformat('2014-03-30 03:23:25.1231+01:00') self.assertEquals(formatted, '30 March 2014 at 03:23:25') formatted = datetimeformat('2014-03-29 01:23:25.1231+00:00') self.assertEquals(formatted, '29 March 2014 at 01:23:25') formatted = datetimeformat('2013-06-06 08:23:25.1231+01:00') self.assertEquals(formatted, '6 June 2013 at 08:23:25') formatted = datetimeformat('2013-06-06 12:23:25.1231+05:00') self.assertEquals(formatted, '6 June 2013 at 08:23:25') def test_currency(self): self.assertEquals(currency(80000), '80,000.00')
class TemplateFiltersTestCase(unittest.TestCase): def test_dateformat(self): pass def test_datetimeformat(self): pass def test_timezones(self): pass def test_currency(self): pass
5
0
12
4
9
0
1
0
1
0
0
0
4
0
4
76
57
21
36
8
31
0
36
8
31
1
2
0
4
144,984
LandRegistry/lr-utils
LandRegistry_lr-utils/lrutils/audit/__init__.py
lrutils.audit.Audit
class Audit(object): def __init__(self, app): try: # check if the client has Flask-Login from flask.ext.login import current_user request_started.connect(audit_user, app) except: request_started.connect(audit_anon, app)
class Audit(object): def __init__(self, app): pass
2
0
7
0
6
1
2
0.14
1
0
0
0
1
0
1
1
9
1
7
3
4
1
7
3
4
2
1
1
2
144,985
LaoLiulaoliu/pgwrapper
LaoLiulaoliu_pgwrapper/pgwrapper/pgpool.py
pgwrapper.pgpool.PGPool
class PGPool(object): def __init__(self, dbname='postgres', user='postgres', password='', host='127.0.0.1', port=5432, poolsize=3, maxretries=5, debug=False, fetch_size=400): """ .. :py:class:: pg_hba.conf: host trust """ self.dbname = dbname self.user = user self.password = password self.host = host self.port = port self.poolsize = poolsize self.maxretries = maxretries self.debug = debug self.fetch_size = fetch_size self.queue = queue.Queue(self.poolsize) self.connection_in_use = 0 def clear(self): while not self.queue.empty(): self.connection_in_use -= 1 self.queue.get().close() def get(self): if self.queue.empty() or self.connection_in_use < self.poolsize: self.connection_in_use += 1 return self._create_connection() return self.queue.get() def put(self, conn): if self.queue.full(): conn.close() self.queue.put(conn) def _create_connection(self): """.. :py:method:: If we hava several hosts, we can random choice one to connect """ db = psycopg2.connect(database=self.dbname, user=self.user, password=self.password, host=self.host, port=self.port) if 'psycopg2.extras' in sys.modules: psycopg2.extras.register_hstore(db) return db @contextmanager def connection(self, dryrun=False): yielded = False retry = 0 while yielded is False and retry < self.maxretries: try: conn = self.get() cur = conn.cursor() yield cur except Exception as e: conn = None retry += 1 print(e) else: yielded = True retry = 0 if not dryrun: conn.commit() # commit `insert`, `update` and `delete` finally: if cur: cur.close() if conn: self.put(conn) if yielded is False: raise Exception('Could not obtain cursor, max retry {} reached.'.format(retry)) def execute(self, query, vars=None, result=False, dryrun=False): """.. :py:method:: :param bool result: whether query return result :param bool dryrun: whether just return sql :rtype: sql str for dryrun, QueryResult for result .. note:: True for `select`, False for `insert` and `update` """ with self.connection(dryrun) as cur: if dryrun: return cur.mogrify(query, vars) resp = cur.execute(query, vars) if result == False: return resp else: columns = [i[0] for i in cur.description] results = cur.fetchall() return QueryResult(columns, results) def execute_generator(self, query, vars=None, result=False, dryrun=False): """.. :py:method:: :param bool result: whether query return result :rtype: bool .. note:: True for `select`, False for `insert` and `update` """ with self.connection(dryrun) as cur: if dryrun: return cur.mogrify(query, vars) resp = cur.execute(query, vars) if result == True: columns = [i[0] for i in cur.description] results = cur.fetchmany(1000) while results: yield QueryResult(columns, results) results = cur.fetchmany(1000) def batch(self, queries): """.. :py:method:: :param tuple queries: [(sql, vars), (sql, vars), ...] .. note:: batch execute queries. only support `insert` and `update`, have more efficiency """ with self.connection() as cur: for sql, vars in queries: if self.debug: print(cur.mogrify(sql, vars)) cur.execute(sql, vars) def transaction(self, sqls): with self.connection() as cur: for sql in sqls: if isinstance(sql, tuple): cur.execute(sql[0], sql[1]) else: cur.execute(sql)
class PGPool(object): def __init__(self, dbname='postgres', user='postgres', password='', host='127.0.0.1', port=5432, poolsize=3, maxretries=5, debug=False, fetch_size=400): ''' .. :py:class:: pg_hba.conf: host trust ''' pass def clear(self): pass def get(self): pass def put(self, conn): pass def _create_connection(self): '''.. :py:method:: If we hava several hosts, we can random choice one to connect ''' pass @contextmanager def connection(self, dryrun=False): pass def execute(self, query, vars=None, result=False, dryrun=False): '''.. :py:method:: :param bool result: whether query return result :param bool dryrun: whether just return sql :rtype: sql str for dryrun, QueryResult for result .. note:: True for `select`, False for `insert` and `update` ''' pass def execute_generator(self, query, vars=None, result=False, dryrun=False): '''.. :py:method:: :param bool result: whether query return result :rtype: bool .. note:: True for `select`, False for `insert` and `update` ''' pass def batch(self, queries): '''.. :py:method:: :param tuple queries: [(sql, vars), (sql, vars), ...] .. note:: batch execute queries. only support `insert` and `update`, have more efficiency ''' pass def transaction(self, sqls): pass
12
5
14
2
10
3
3
0.25
1
2
0
1
10
11
10
10
153
26
102
50
81
26
87
35
76
7
1
3
29
144,986
LaoLiulaoliu/pgwrapper
LaoLiulaoliu_pgwrapper/pgwrapper/pgwrap.py
pgwrapper.pgwrap.PGWrapper
class PGWrapper(PGPool): def __init__(self, dbname='postgres', user='postgres', password='', host='127.0.0.1', port=5432, poolsize=3, maxretries=5, debug=False): super(PGWrapper, self).__init__(dbname, user, password, host, port, poolsize, maxretries, debug) def select(self, table, args='*', condition=None, control=None, dryrun=False): """.. :py:method:: select General select form of select Usage:: >>> select('hospital', 'id, city', control='limit 1') select id, city from hospital limit 1; >>> select('hospital', 'id', 'address is null') select id from hospital where address is null; """ sql = f'select {args} from {table}' sql += self.parse_condition(condition) + (f' {control};' if control else ';') if dryrun: return sql return super(PGWrapper, self).execute(sql, result=True).results def update(self, table, kwargs, condition=None, dryrun=False): """.. :py:method:: update All module update can user this function. condition only support string and dictionary. Usage:: >>> update('dept', {'name': 'design', 'quantity': 3}, {'id': 'we4d'}) update dept set name='design', quantity=3 where id='we4d'; >>> update('dept', {'name': 'design', 'quantity': 3}, 'introduction is null') update dept set name='design', quantity=3 where introduction is null; >>> update('physician', {'$inc': {'status': -10}, 'present': 0}, {'id': 'someid'}) update physician set status=status+-10, present=0 where id='someid'; """ equations = [] values = [] for k, v in kwargs.items(): if k == '$inc' and isinstance(v, dict): for ik, iv in v.items(): equations.append(f'{ik}={ik}+{iv}') else: equations.append(f'{k}=%s') values.append(v) sql = (f"update {table} set {', '.join(equations)}" f"{self.parse_condition(condition)};") if dryrun: return sql, values super(PGWrapper, self).execute(sql, values, result=False) def insert(self, table, kwargs, returning=False, dryrun=False): """.. :py:method:: Usage:: >>> insert('hospital', {'id': '12de3wrv', 'province': 'shanghai'}) insert into hospital (id, province) values ('12de3wrv', 'shanghai'); :param string table: table name :param dict kwargs: name and value :param bool dryrun: if dryrun, return sql and variables :rtype: tuple """ keys, values = [], [] [(keys.append(k), values.append(v)) for k, v in kwargs.items()] sql = (f"insert into {table} ({', '.join(keys)}) values " f"({', '.join(['%s'] * len(values))});") sql = sql[:-1] + ' returning *;' if returning else sql if dryrun: return sql, values if returning: return super(PGWrapper, self).execute(sql, values, result=True) else: super(PGWrapper, self).execute(sql, values, result=False) def insert_list(self, table, names, values, returning=False, dryrun=False): """.. :py:method:: Usage:: >>> insert_list('hospital', ['id', 'province'], ['12de3wrv', 'shanghai']) insert into hospital (id, province) values ('12de3wrv', 'shanghai'); :param string table: table name :param list names: name :param list values: value :param bool dryrun: if dryrun, return sql and variables :rtype: tuple """ sql = (f"insert into {table} ({', '.join(names)}) values " f"({', '.join(['%s'] * len(values))});") sql = sql[:-1] + ' returning *;' if returning else sql if dryrun: return sql, values if returning: return super(PGWrapper, self).execute(sql, values, result=True) else: super(PGWrapper, self).execute(sql, values, result=False) def delete(self, table, condition, dryrun=False): """.. :py:method:: Usage:: >>> delete('hospital', {'id': '12de3wrv'}) delete from hospital where id='12de3wrv'; """ sql = f'delete from {table}{self.parse_condition(condition)};' if dryrun: return sql super(PGWrapper, self).execute(sql, result=False) def insert_inexistence(self, table, kwargs, condition, returning=False, dryrun=False): """.. :py:method:: Usage:: >>> insert_inexistence('hospital', {'id': '12de3wrv', 'province': 'shanghai'}, {'id': '12de3wrv'}) insert into hospital (id, province) select '12de3wrv', 'shanghai' where not exists (select 1 from hospital where id='12de3wrv' limit 1); """ keys, values = [], [] [(keys.append(k), values.append(v)) for k, v in kwargs.items()] sql = (f"insert into {table} ({', '.join(keys)}) " f"select {', '.join(['%s'] * len(values))} " f"where not exists (select 1 from {table}" f"{self.parse_condition(condition)} limit 1);") sql = sql[:-1] + ' returning *;' if returning else sql if dryrun: return sql, values if returning: return super(PGWrapper, self).execute(sql, values, result=True) else: super(PGWrapper, self).execute(sql, values, result=False) def parse_condition(self, condition): """.. :py:method:: parse the condition, support string and dictonary """ if isinstance(condition, str): sql = f' where {condition}' elif isinstance(condition, dict): conditions = [] for k, v in condition.items(): s = f"{k}='{v}'" if isinstance(v, str) else f'{k}={v}' conditions.append(s) sql = f" where {' and '.join(conditions)}" else: sql = '' return sql def select_join(self, table, field, join_table, join_field, dryrun=False): """.. :py:method:: Usage:: >>> select_join('hospital', 'id', 'department', 'hospid') select hospital.id from hospital left join department on hospital.id=department.hospid where department.hospid is null; """ sql = "select {table}.{field} from {table} left join {join_table} " \ "on {table}.{field}={join_table}.{join_field} " \ "where {join_table}.{join_field} is null;".format(table=table, field=field, join_table=join_table, join_field=join_field) if dryrun: return sql return super(PGWrapper, self).execute(sql, result=True).results def joint(self, table, fields, join_table, join_fields, condition_field, condition_join_field, join_method='left_join', dryrun=False): """.. :py:method:: Usage:: >>> joint('user', 'name, id_number', 'medical_card', 'number', 'id', 'user_id', 'inner_join') select u.name, u.id_number, v.number from user as u inner join medical_card as v on u.id=v.user_id; """ import string fields = map(string.strip, fields.split(',')) select = ', '.join(['u.{}'.format(field) for field in fields]) join_fields = map(string.strip, join_fields.split(',')) join_select = ', '.join(['v.{}'.format(field) for field in join_fields]) sql = "select {select}, {join_select} from {table} as u {join_method}" \ " {join_table} as v on u.{condition_field}=" \ "v.{condition_join_field};".format(select=select, join_select=join_select, table=table, join_method=join_method, join_table=join_table, condition_field=condition_field, condition_join_field=condition_join_field) if dryrun: return sql return super(PGWrapper, self).execute(sql, result=True).results
class PGWrapper(PGPool): def __init__(self, dbname='postgres', user='postgres', password='', host='127.0.0.1', port=5432, poolsize=3, maxretries=5, debug=False): pass def select(self, table, args='*', condition=None, control=None, dryrun=False): '''.. :py:method:: select General select form of select Usage:: >>> select('hospital', 'id, city', control='limit 1') select id, city from hospital limit 1; >>> select('hospital', 'id', 'address is null') select id from hospital where address is null; ''' pass def update(self, table, kwargs, condition=None, dryrun=False): '''.. :py:method:: update All module update can user this function. condition only support string and dictionary. Usage:: >>> update('dept', {'name': 'design', 'quantity': 3}, {'id': 'we4d'}) update dept set name='design', quantity=3 where id='we4d'; >>> update('dept', {'name': 'design', 'quantity': 3}, 'introduction is null') update dept set name='design', quantity=3 where introduction is null; >>> update('physician', {'$inc': {'status': -10}, 'present': 0}, {'id': 'someid'}) update physician set status=status+-10, present=0 where id='someid'; ''' pass def insert(self, table, kwargs, returning=False, dryrun=False): '''.. :py:method:: Usage:: >>> insert('hospital', {'id': '12de3wrv', 'province': 'shanghai'}) insert into hospital (id, province) values ('12de3wrv', 'shanghai'); :param string table: table name :param dict kwargs: name and value :param bool dryrun: if dryrun, return sql and variables :rtype: tuple ''' pass def insert_list(self, table, names, values, returning=False, dryrun=False): '''.. :py:method:: Usage:: >>> insert_list('hospital', ['id', 'province'], ['12de3wrv', 'shanghai']) insert into hospital (id, province) values ('12de3wrv', 'shanghai'); :param string table: table name :param list names: name :param list values: value :param bool dryrun: if dryrun, return sql and variables :rtype: tuple ''' pass def delete(self, table, condition, dryrun=False): '''.. :py:method:: Usage:: >>> delete('hospital', {'id': '12de3wrv'}) delete from hospital where id='12de3wrv'; ''' pass def insert_inexistence(self, table, kwargs, condition, returning=False, dryrun=False): '''.. :py:method:: Usage:: >>> insert_inexistence('hospital', {'id': '12de3wrv', 'province': 'shanghai'}, {'id': '12de3wrv'}) insert into hospital (id, province) select '12de3wrv', 'shanghai' where not exists (select 1 from hospital where id='12de3wrv' limit 1); ''' pass def parse_condition(self, condition): '''.. :py:method:: parse the condition, support string and dictonary ''' pass def select_join(self, table, field, join_table, join_field, dryrun=False): '''.. :py:method:: Usage:: >>> select_join('hospital', 'id', 'department', 'hospid') select hospital.id from hospital left join department on hospital.id=department.hospid where department.hospid is null; ''' pass def joint(self, table, fields, join_table, join_fields, condition_field, condition_join_field, join_method='left_join', dryrun=False): '''.. :py:method:: Usage:: >>> joint('user', 'name, id_number', 'medical_card', 'number', 'id', 'user_id', 'inner_join') select u.name, u.id_number, v.number from user as u inner join medical_card as v on u.id=v.user_id; ''' pass
11
9
22
4
12
6
3
0.5
1
4
0
0
10
0
10
20
233
49
123
48
95
61
80
32
68
5
2
3
32
144,987
LasLabs/python-five9
LasLabs_python-five9/five9/tests/test_base_model.py
five9.tests.test_base_model.TestModel
class TestModel(BaseModel): id = properties.Integer('ID') not_a_field = True
class TestModel(BaseModel): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
16
3
0
3
2
2
0
3
2
2
0
2
0
0
144,988
LasLabs/python-five9
LasLabs_python-five9/five9/tests/test_disposition.py
five9.tests.test_disposition.TestDisposition
class TestDisposition(CommonCrud, unittest.TestCase): Model = Disposition def setUp(self): super(TestDisposition, self).setUp() self.method_names['delete'] = 'remove%(model_name)s'
class TestDisposition(CommonCrud, unittest.TestCase): def setUp(self): pass
2
0
3
0
3
0
1
0
2
1
0
0
1
0
1
81
7
2
5
3
3
0
5
3
3
1
2
0
1
144,989
LasLabs/python-five9
LasLabs_python-five9/five9/tests/test_environment.py
five9.tests.test_environment.TestEnvironment
class TestEnvironment(unittest.TestCase): def setUp(self): super(TestEnvironment, self).setUp() self.five9 = mock.MagicMock(spec=Five9) self.records = [ mock.MagicMock(spec=WebConnector), mock.MagicMock(spec=WebConnector), ] self.model = mock.MagicMock(spec=WebConnector) self.model.__name__ = 'name' self.env = Environment(self.five9, self.model, self.records) def _test_iter_method(self, method_name): getattr(self.env, method_name)() for record in self.records: getattr(record, method_name).assert_called_once_with(self.five9) def test_new_gets_models(self): """It should assign the ``__models__`` class attribute.""" self.assertIsInstance(Environment.__models__, dict) self.assertGreater(len(Environment.__models__), 1) def test_init_sets_five9(self): """It should set the __five9__ attribute.""" self.assertEqual(self.env.__five9__, self.five9) def test_init_sets_records(self): """It should set the __records__ attribute.""" self.assertEqual(self.env.__records__, self.records) def test_init_sets_model(self): """It should set the __model__ attribute.""" self.assertEqual(self.env.__model__, self.model) def test_getattr_pass_through_to_model(self): """It should return the correct model environment.""" self.assertEqual(self.env.WebConnector.__model__, WebConnector) def test_iter(self): """It should iterate the records in the set.""" for idx, record in enumerate(self.env): self.assertEqual(record, self.records[idx]) self.assertEqual(self.env.__record__, self.records[idx]) def test_create_creates(self): """It should create the record on the remote.""" expect = {'test': 1234} self.env.create(expect) self.model.create.assert_called_once_with(self.five9, expect) def test_create_return_refreshed(self): """It should create the refreshed record when True.""" expect = {'name': 1234} with mock.patch.object(self.env, 'read') as read: res = self.env.create(expect, True) read.assert_called_once_with(expect[self.model.__name__]) self.assertEqual(res, read()) def test_create_return_deserialized(self): """It should return a deserialized memory record if no refresh.""" expect = {'test': 1234} res = self.env.create(expect, False) self.model._get_non_empty_dict.assert_called_once_with(expect) self.model.deserialize.assert_called_once_with( self.model._get_non_empty_dict(), ) self.assertEqual(len(res.__records__), 1) self.assertEqual(res.__records__[0], self.model.deserialize()) def test_read(self): """It should call and return properly.""" expect = 1234 res = self.env.read(expect) self.model.read.assert_called_once_with(self.five9, expect) self.assertEqual(res, self.model.read()) def test_write(self): """It should iterate and write the recordset.""" self._test_iter_method('write') def test_delete(self): """It should iterate and delete the recordset.""" self._test_iter_method('delete') def test_search(self): """It should call search on the model and return a recordset.""" expect = {'test': 1234} results = self.env.search(expect) self.model.search.assert_called_once_with(self.five9, expect) self.assertEqual(results.__records__, self.model.search())
class TestEnvironment(unittest.TestCase): def setUp(self): pass def _test_iter_method(self, method_name): pass def test_new_gets_models(self): '''It should assign the ``__models__`` class attribute.''' pass def test_init_sets_five9(self): '''It should set the __five9__ attribute.''' pass def test_init_sets_records(self): '''It should set the __records__ attribute.''' pass def test_init_sets_model(self): '''It should set the __model__ attribute.''' pass def test_getattr_pass_through_to_model(self): '''It should return the correct model environment.''' pass def test_iter(self): '''It should iterate the records in the set.''' pass def test_create_creates(self): '''It should create the record on the remote.''' pass def test_create_return_refreshed(self): '''It should create the refreshed record when True.''' pass def test_create_return_deserialized(self): '''It should return a deserialized memory record if no refresh.''' pass def test_read(self): '''It should call and return properly.''' pass def test_write(self): '''It should iterate and write the recordset.''' pass def test_delete(self): '''It should iterate and delete the recordset.''' pass def test_search(self): '''It should call search on the model and return a recordset.''' pass
16
13
5
0
4
1
1
0.21
1
6
3
0
15
4
15
87
91
15
63
32
47
13
58
31
42
2
2
1
17
144,990
LasLabs/python-five9
LasLabs_python-five9/five9/tests/test_api.py
five9.tests.test_api.TestApi
class TestApi(unittest.TestCase): def setUp(self): super(TestApi, self).setUp() self.record = TestRecord() def test_model_bad(self): """It should raise ValidationError when no model.""" with self.assertRaises(ValidationError): self.record.model() def test_recordset_bad(self): """It should raise ValidationError when no recordset.""" self.record.__model__ = False with self.assertRaises(ValidationError): self.record.recordset() def test_recordset_model(self): """It should raise ValidationError when recordset but no model.""" with self.assertRaises(ValidationError): self.record.__records__ = [1] self.record.recordset() def test_recordset_valid(self): """It should return True when valid recordset method.""" self.record.__records__ = [1] self.record.__model__ = True self.assertTrue(self.record.recordset()) def test_model_valid(self): """It should return True when valid model method.""" self.record.__model__ = True self.assertTrue(self.record.model())
class TestApi(unittest.TestCase): def setUp(self): pass def test_model_bad(self): '''It should raise ValidationError when no model.''' pass def test_recordset_bad(self): '''It should raise ValidationError when no recordset.''' pass def test_recordset_model(self): '''It should raise ValidationError when recordset but no model.''' pass def test_recordset_valid(self): '''It should return True when valid recordset method.''' pass def test_model_valid(self): '''It should return True when valid model method.''' pass
7
5
4
0
4
1
1
0.23
1
3
2
0
6
1
6
78
33
6
22
8
15
5
22
8
15
1
2
1
6
144,991
LasLabs/python-five9
LasLabs_python-five9/five9/tests/common_crud.py
five9.tests.common_crud.CommonCrud
class CommonCrud(object): Model = BaseModel five9_api = 'configuration' def setUp(self): super(CommonCrud, self).setUp() self.data = { 'description': 'Test', self.Model.__uid_field__: 'Test', } self.five9 = mock.MagicMock() self.model_name = self.Model.__name__ self.method_names = { 'create': 'create%(model_name)s', 'write': 'modify%(model_name)s', 'search': 'get%(model_name)ss', 'delete': 'delete%(model_name)s', } def _get_method(self, method_type): method_name = self.method_names[method_type] % { 'model_name': self.model_name, } api = getattr(self.five9, self.five9_api) return getattr(api, method_name) def test_create(self): """It should use the proper method and args on the API with.""" self.Model.create(self.five9, self.data) self._get_method('create').assert_called_once_with(self.data) def test_search(self): """It should search the remote for the name.""" self.Model.search(self.five9, self.data) self._get_method('search').assert_called_once_with( self.data[self.Model.__uid_field__], ) def test_search_multiple(self): """It should search the remote for the conjoined names.""" self.data['name'] = ['Test1', 'Test2'] self.Model.search(self.five9, self.data) self._get_method('search').assert_called_once_with( r'(Test1|Test2)', ) def test_search_return(self): """It should return a list of the result objects.""" self._get_method('search').return_value = [ self.data, self.data, ] results = self.Model.search(self.five9, self.data) self.assertEqual(len(results), 2) expect = self.Model(**self.data).serialize() for result in results: self.assertIsInstance(result, self.Model) self.assertDictEqual(result.serialize(), expect) def test_delete(self): """It should call the delete method and args on the API.""" self.Model(**self.data).delete(self.five9) self._get_method('delete').assert_called_once_with( self.data[self.Model.__uid_field__], ) def test_write(self): """It should call the write method on the API.""" self.Model(**self.data).write(self.five9) self._get_method('write').assert_called_once_with( self.Model(**self.data).serialize(), )
class CommonCrud(object): def setUp(self): pass def _get_method(self, method_type): pass def test_create(self): '''It should use the proper method and args on the API with.''' pass def test_search(self): '''It should search the remote for the name.''' pass def test_search_multiple(self): '''It should search the remote for the conjoined names.''' pass def test_search_return(self): '''It should return a list of the result objects.''' pass def test_delete(self): '''It should call the delete method and args on the API.''' pass def test_write(self): '''It should call the write method on the API.''' pass
9
6
8
0
7
1
1
0.11
1
1
0
2
8
4
8
8
72
9
57
20
48
6
37
20
28
2
1
1
9
144,992
LasLabs/python-five9
LasLabs_python-five9/five9/tests/common.py
five9.tests.common.Common
class Common(unittest.TestCase): def setUp(self): super(Common, self).setUp() self.user = 'username@something.com' self.password = 'password' self.five9 = Five9(self.user, self.password)
class Common(unittest.TestCase): def setUp(self): pass
2
0
5
0
5
0
1
0
1
2
1
1
1
3
1
73
7
1
6
5
4
0
6
5
4
1
2
0
1
144,993
LasLabs/python-five9
LasLabs_python-five9/five9/models/web_connector.py
five9.models.web_connector.WebConnector
class WebConnector(BaseModel): """Contains the configuration details of a web connector.""" addWorksheet = properties.Bool( 'Applies only to POST requests. Whether to pass worksheet ' 'answers as parameters.', ) agentApplication = properties.StringChoice( 'If ``executeInBrowser==True``, this parameter specifies whether ' 'to open the URL in an external or an embedded browser.', default='EmbeddedBrowser', required=True, choices=['EmbeddedBrowser', 'ExternalBrowser'], descriptions={ 'EmbeddedBrowser': 'Embedded browser window.', 'ExternalBrowser': 'External browser window.', }, ) clearTriggerDispositions = properties.Bool( 'When modifying an existing connector, whether to clear the existing ' 'triggers.' ) constants = properties.List( 'List of parameters passed with constant values.', prop=KeyValuePair, ) ctiWebServices = properties.StringChoice( 'In the Internet Explorer toolbar, whether to open the HTTP request ' 'in the current or a new browser window.', default='CurrentBrowserWindow', required=True, choices=['CurrentBrowserWindow', 'NewBrowserWindow'], descriptions={ 'CurrentBrowserWindow': 'Current browser window.', 'NewBrowserWindow': 'New browser window.', }, ) description = properties.String( 'Purpose of the connector.', required=True, ) executeInBrowser = properties.Bool( 'When enabling the agent to view or enter data, whether to open ' 'the URL in an embedded or external browser window.', required=True, ) name = properties.String( 'Name of the connector', required=True, ) postConstants = properties.List( 'When using the POST method, constant parameters to pass in the URL.', prop=KeyValuePair, ) postMethod = properties.Bool( 'Whether the HTTP request type is POST.', ) postVariables = properties.List( 'When using the POST method, variable parameters to pass in the URL.', prop=KeyValuePair, ) startPageText = properties.String( 'When using the POST method, enables the administrator to enter text ' 'to be displayed in the browser (or agent Browser tab) while waiting ' 'for the completion of the connector.', ) trigger = properties.StringChoice( 'Available trigger during a call when the request is sent.', required=True, choices=['OnCallAccepted', 'OnCallDisconnected', 'ManuallyStarted', 'ManuallyStartedAllowDuringPreviews', 'OnPreview', 'OnContactSelection', 'OnWarmTransferInitiation', 'OnCallDispositioned', 'OnChatArrival', 'OnChatTransfer', 'OnChatTermination', 'OnChatClose', 'OnEmailArrival', 'OnEmailTransfer', 'OnEmailClose', ], descriptions={ 'OnCallAccepted': 'Triggered when the call is accepted.', 'OnCallDisconnected': 'Triggered when the call is disconnected.', 'ManuallyStarted': 'Connector is started manually.', 'ManuallyStartedAllowDuringPreviews': 'Connector is started ' 'manually during call ' 'preview.', 'OnPreview': 'Triggered when the call is previewed.', 'OnContactSelection': 'Triggered when a contact is selected.', 'OnWarmTransferInitiation': 'Triggered when a warm transfer is ' 'initiated.', 'OnCallDispositioned': 'Triggered when a disposition is ' 'selected.', 'OnChatArrival': 'Triggered when a chat message is delivered to ' 'an agent.', 'OnChatTransfer': 'Triggered when a chat session is transferred.', 'OnChatTermination': 'Triggered when the customer or the agent ' 'closed the session, but the agent has not ' 'yet set the disposition.', 'OnChatClose': 'Triggered when the disposition is set.', 'OnEmailArrival': 'Triggered when an email message is delivered ' 'to the agent.', 'OnEmailTransfer': 'Triggered when an email message is ' 'transferred.', 'OnEmailClose': 'Triggered when the disposition is set.', } ) triggerDispositions = properties.List( 'When the trigger is OnCallDispositioned, specifies the trigger ' 'dispositions.', prop=Disposition, ) url = properties.String( 'URI of the external web site.', ) variables = properties.List( 'When using the POST method, connectors can include worksheet data ' 'as parameter values. The variable placeholder values are surrounded ' 'by @ signs. For example, the parameter ANI has the value @Call.ANI@', prop=KeyValuePair, ) @classmethod def create(cls, five9, data, refresh=False): return cls._call_and_serialize( five9.configuration.createWebConnector, data, refresh, ) @classmethod def search(cls, five9, filters): """Search for a record on the remote and return the results. Args: five9 (five9.Five9): The authenticated Five9 remote. filters (dict): A dictionary of search parameters, keyed by the name of the field to search. This should conform to the schema defined in :func:`five9.Five9.create_criteria`. Returns: list[BaseModel]: A list of records representing the result. """ return cls._name_search(five9.configuration.getWebConnectors, filters) def delete(self, five9): """Delete the record from the remote. Args: five9 (five9.Five9): The authenticated Five9 remote. """ five9.configuration.deleteWebConnector(self.name) def write(self, five9): """Update the record on the remote. Args: five9 (five9.Five9): The authenticated Five9 remote. """ five9.configuration.modifyWebConnector(self.serialize())
class WebConnector(BaseModel): '''Contains the configuration details of a web connector.''' @classmethod def create(cls, five9, data, refresh=False): pass @classmethod def search(cls, five9, filters): '''Search for a record on the remote and return the results. Args: five9 (five9.Five9): The authenticated Five9 remote. filters (dict): A dictionary of search parameters, keyed by the name of the field to search. This should conform to the schema defined in :func:`five9.Five9.create_criteria`. Returns: list[BaseModel]: A list of records representing the result. ''' pass def delete(self, five9): '''Delete the record from the remote. Args: five9 (five9.Five9): The authenticated Five9 remote. ''' pass def write(self, five9): '''Update the record on the remote. Args: five9 (five9.Five9): The authenticated Five9 remote. ''' pass
7
4
8
1
3
4
1
0.13
1
0
0
0
2
0
4
20
163
9
136
23
129
18
25
21
20
1
2
0
4
144,994
LasLabs/python-five9
LasLabs_python-five9/five9/models/disposition_type_params.py
five9.models.disposition_type_params.DispositionTypeParams
class DispositionTypeParams(BaseModel): allowChangeTimer = properties.Bool( 'Whether the agent can change the redial timer for this disposition.', ) attempts = properties.Integer( 'Number of redial attempts.', ) timer = properties.Instance( 'Redial timer.', instance_class=Timer, ) useTimer = properties.Bool( 'Whether this disposition uses a redial timer.', )
class DispositionTypeParams(BaseModel): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
16
15
1
14
5
13
0
5
5
4
0
2
0
0
144,995
LasLabs/python-five9
LasLabs_python-five9/five9/models/key_value_pair.py
five9.models.key_value_pair.KeyValuePair
class KeyValuePair(BaseModel): key = properties.String( 'Name used to identify the pair.', required=True, ) value = properties.String( 'Value that corresponds to the name.', required=True, ) def __init__(self, key, value, **kwargs): """Allow for positional key, val pairs.""" super(KeyValuePair, self).__init__( key=key, value=value, **kwargs )
class KeyValuePair(BaseModel): def __init__(self, key, value, **kwargs): '''Allow for positional key, val pairs.''' pass
2
1
5
0
4
1
1
0.08
1
1
0
0
1
0
1
17
16
2
13
4
11
1
5
4
3
1
2
0
1
144,996
LasLabs/python-five9
LasLabs_python-five9/five9/models/disposition.py
five9.models.disposition.Disposition
class Disposition(BaseModel): agentMustCompleteWorksheet = properties.Bool( 'Whether the agent needs to complete a worksheet before selecting ' 'a disposition.', ) agentMustConfirm = properties.Bool( 'Whether the agent is prompted to confirm the selection of the ' 'disposition.', ) description = properties.String( 'Description of the disposition.', ) name = properties.String( 'Name of the disposition.', required=True, ) resetAttemptsCounter = properties.Bool( 'Whether assigning the disposition resets the number of dialing ' 'attempts for this contact.', ) sendEmailNotification = properties.Bool( 'Whether call details are sent as an email notification when the ' 'disposition is used by an agent.', ) sendIMNotification = properties.Bool( 'Whether call details are sent as an instant message in the Five9 ' 'system when the disposition is used by an agent.', ) trackAsFirstCallResolution = properties.Bool( 'Whether the call is included in the first call resolution ' 'statistics (customer\'s needs addressed in the first call). Used ' 'primarily for inbound campaigns.', ) type = properties.StringChoice( 'Disposition type.', choices=['FinalDisp', 'FinalApplyToCampaigns', 'AddActiveNumber', 'AddAndFinalize', 'AddAllNumbers', 'DoNotDial', 'RedialNumber', ], descriptions={ 'FinalDisp': 'Any contact number of the contact is not dialed again by ' 'the current campaign.', 'FinalApplyToCampaigns': 'Contact is not dialed again by any campaign that contains ' 'the disposition.', 'AddActiveNumber': 'Adds the number dialed to the DNC list.', 'AddAndFinalize': 'Adds the call results to the campaign history. This record ' 'is no longer dialing in this campaign. Does not add the ' 'contact\'s other phone numbers to the DNC list.', 'AddAllNumbers': 'Adds all the contact\'s phone numbers to the DNC list.', 'DoNotDial': 'Number is not dialed in the campaign, but other numbers ' 'from the CRM record can be dialed.', 'RedialNumber': 'Number is dialed again when the list to dial is completed, ' 'and the dialer starts again from the beginning.', }, ) typeParameters = properties.Instance( 'Parameters that apply to the disposition type.', instance_class=DispositionTypeParams, ) @classmethod def create(cls, five9, data, refresh=False): """Create a record on Five9. Args: five9 (five9.Five9): The authenticated Five9 remote. data (dict): A data dictionary that can be fed to ``deserialize``. refresh (bool, optional): Set to ``True`` to get the record data from Five9 before returning the record. Returns: BaseModel: The newly created record. If ``refresh`` is ``True``, this will be fetched from Five9. Otherwise, it's the data record that was sent to the server. """ return cls._call_and_serialize( five9.configuration.createDisposition, data, refresh, ) @classmethod def search(cls, five9, filters): """Search for a record on the remote and return the results. Args: five9 (five9.Five9): The authenticated Five9 remote. filters (dict): A dictionary of search parameters, keyed by the name of the field to search. This should conform to the schema defined in :func:`five9.Five9.create_criteria`. Returns: list[BaseModel]: A list of records representing the result. """ return cls._name_search(five9.configuration.getDispositions, filters) def delete(self, five9): """Delete the record from the remote. Args: five9 (five9.Five9): The authenticated Five9 remote. """ five9.configuration.removeDisposition(self.name) def write(self, five9): """Update the record on the remote. Args: five9 (five9.Five9): The authenticated Five9 remote. """ five9.configuration.modifyDisposition(self.serialize())
class Disposition(BaseModel): @classmethod def create(cls, five9, data, refresh=False): '''Create a record on Five9. Args: five9 (five9.Five9): The authenticated Five9 remote. data (dict): A data dictionary that can be fed to ``deserialize``. refresh (bool, optional): Set to ``True`` to get the record data from Five9 before returning the record. Returns: BaseModel: The newly created record. If ``refresh`` is ``True``, this will be fetched from Five9. Otherwise, it's the data record that was sent to the server. ''' pass @classmethod def search(cls, five9, filters): '''Search for a record on the remote and return the results. Args: five9 (five9.Five9): The authenticated Five9 remote. filters (dict): A dictionary of search parameters, keyed by the name of the field to search. This should conform to the schema defined in :func:`five9.Five9.create_criteria`. Returns: list[BaseModel]: A list of records representing the result. ''' pass def delete(self, five9): '''Delete the record from the remote. Args: five9 (five9.Five9): The authenticated Five9 remote. ''' pass def write(self, five9): '''Update the record on the remote. Args: five9 (five9.Five9): The authenticated Five9 remote. ''' pass
7
4
11
2
3
7
1
0.34
1
0
0
0
2
0
4
20
121
11
82
17
75
28
19
15
14
1
2
0
4
144,997
LasLabs/python-five9
LasLabs_python-five9/five9/five9.py
five9.five9.Five9
class Five9(object): WSDL_CONFIGURATION = 'https://api.five9.com/wsadmin/v9_5/' \ 'AdminWebService?wsdl&user=%s' WSDL_SUPERVISOR = 'https://api.five9.com/wssupervisor/v9_5/' \ 'SupervisorWebService?wsdl&user=%s' # These attributes are used to create the supervisor session. force_logout_session = True rolling_period = 'Minutes30' statistics_range = 'CurrentWeek' shift_start_hour = 8 time_zone_offset = -7 # API Objects _api_configuration = None _api_supervisor = None _api_supervisor_session = None @property def configuration(self): """Return an authenticated connection for use, open new if required. Returns: AdminWebService: New or existing session with the Five9 Admin Web Services API. """ return self._cached_client('configuration') @property def supervisor(self): """Return an authenticated connection for use, open new if required. Returns: SupervisorWebService: New or existing session with the Five9 Statistics API. """ supervisor = self._cached_client('supervisor') if not self._api_supervisor_session: self._api_supervisor_session = self.__create_supervisor_session( supervisor, ) return supervisor def __init__(self, username, password): self.username = username self.auth = requests.auth.HTTPBasicAuth(username, password) self.env = Environment(self) @staticmethod def create_mapping(record, keys): """Create a field mapping for use in API updates and creates. Args: record (BaseModel): Record that should be mapped. keys (list[str]): Fields that should be mapped as keys. Returns: dict: Dictionary with keys: * ``field_mappings``: Field mappings as required by API. * ``data``: Ordered data dictionary for input record. """ ordered = OrderedDict() field_mappings = [] for key, value in record.items(): ordered[key] = value field_mappings.append({ 'columnNumber': len(ordered), # Five9 is not zero indexed. 'fieldName': key, 'key': key in keys, }) return { 'field_mappings': field_mappings, 'data': ordered, 'fields': list(ordered.values()), } @staticmethod def parse_response(fields, records): """Parse an API response into usable objects. Args: fields (list[str]): List of strings indicating the fields that are represented in the records, in the order presented in the records.:: [ 'number1', 'number2', 'number3', 'first_name', 'last_name', 'company', 'street', 'city', 'state', 'zip', ] records (list[dict]): A really crappy data structure representing records as returned by Five9:: [ { 'values': { 'data': [ '8881234567', None, None, 'Dave', 'Lasley', 'LasLabs Inc', None, 'Las Vegas', 'NV', '89123', ] } } ] Returns: list[dict]: List of parsed records. """ data = [i['values']['data'] for i in records] return [ {fields[idx]: row for idx, row in enumerate(d)} for d in data ] @classmethod def create_criteria(cls, query): """Return a criteria from a dictionary containing a query. Query should be a dictionary, keyed by field name. If the value is a list, it will be divided into multiple criteria as required. """ criteria = [] for name, value in query.items(): if isinstance(value, list): for inner_value in value: criteria += cls.create_criteria({name: inner_value}) else: criteria.append({ 'criteria': { 'field': name, 'value': value, }, }) return criteria or None def _get_authenticated_client(self, wsdl): """Return an authenticated SOAP client. Returns: zeep.Client: Authenticated API client. """ return zeep.Client( wsdl % quote(self.username), transport=zeep.Transport( session=self._get_authenticated_session(), ), ) def _get_authenticated_session(self): """Return an authenticated requests session. Returns: requests.Session: Authenticated session for use. """ session = requests.Session() session.auth = self.auth return session def _cached_client(self, client_type): attribute = '_api_%s' % client_type if not getattr(self, attribute, None): wsdl = getattr(self, 'WSDL_%s' % client_type.upper()) client = self._get_authenticated_client(wsdl) setattr(self, attribute, client) return getattr(self, attribute).service def __create_supervisor_session(self, supervisor): """Create a new session on the supervisor service. This is required in order to use most methods for the supervisor, so it is called implicitly when generating a supervisor session. """ session_params = { 'forceLogoutSession': self.force_logout_session, 'rollingPeriod': self.rolling_period, 'statisticsRange': self.statistics_range, 'shiftStart': self.__to_milliseconds( self.shift_start_hour, ), 'timeZone': self.__to_milliseconds( self.time_zone_offset, ), } supervisor.setSessionParameters(session_params) return session_params @staticmethod def __to_milliseconds(hour): return hour * 60 * 60 * 1000
class Five9(object): @property def configuration(self): '''Return an authenticated connection for use, open new if required. Returns: AdminWebService: New or existing session with the Five9 Admin Web Services API. ''' pass @property def supervisor(self): '''Return an authenticated connection for use, open new if required. Returns: SupervisorWebService: New or existing session with the Five9 Statistics API. ''' pass def __init__(self, username, password): pass @staticmethod def create_mapping(record, keys): '''Create a field mapping for use in API updates and creates. Args: record (BaseModel): Record that should be mapped. keys (list[str]): Fields that should be mapped as keys. Returns: dict: Dictionary with keys: * ``field_mappings``: Field mappings as required by API. * ``data``: Ordered data dictionary for input record. ''' pass @staticmethod def parse_response(fields, records): '''Parse an API response into usable objects. Args: fields (list[str]): List of strings indicating the fields that are represented in the records, in the order presented in the records.:: [ 'number1', 'number2', 'number3', 'first_name', 'last_name', 'company', 'street', 'city', 'state', 'zip', ] records (list[dict]): A really crappy data structure representing records as returned by Five9:: [ { 'values': { 'data': [ '8881234567', None, None, 'Dave', 'Lasley', 'LasLabs Inc', None, 'Las Vegas', 'NV', '89123', ] } } ] Returns: list[dict]: List of parsed records. ''' pass @classmethod def create_criteria(cls, query): '''Return a criteria from a dictionary containing a query. Query should be a dictionary, keyed by field name. If the value is a list, it will be divided into multiple criteria as required. ''' pass def _get_authenticated_client(self, wsdl): '''Return an authenticated SOAP client. Returns: zeep.Client: Authenticated API client. ''' pass def _get_authenticated_session(self): '''Return an authenticated requests session. Returns: requests.Session: Authenticated session for use. ''' pass def _cached_client(self, client_type): pass def __create_supervisor_session(self, supervisor): '''Create a new session on the supervisor service. This is required in order to use most methods for the supervisor, so it is called implicitly when generating a supervisor session. ''' pass @staticmethod def __to_milliseconds(hour): pass
18
8
16
2
7
7
2
0.77
1
5
1
0
7
3
11
11
209
31
101
44
83
78
59
38
47
4
1
3
17
144,998
LasLabs/python-five9
LasLabs_python-five9/five9/exceptions.py
five9.exceptions.ValidationError
class ValidationError(Five9Exception): """Indicated an error validating user supplied data."""
class ValidationError(Five9Exception): '''Indicated an error validating user supplied data.''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
10
2
0
1
1
0
1
1
1
0
0
4
0
0
144,999
LasLabs/python-five9
LasLabs_python-five9/five9/exceptions.py
five9.exceptions.Five9Exception
class Five9Exception(Exception): """Base Five9 Exceptions."""
class Five9Exception(Exception): '''Base Five9 Exceptions.''' pass
1
1
0
0
0
0
0
1
1
0
0
1
0
0
0
10
2
0
1
1
0
1
1
1
0
0
3
0
0
145,000
LasLabs/python-five9
LasLabs_python-five9/five9/environment.py
five9.environment.Environment
class Environment(object): """Represents a container for models with a back-reference to Five9. """ # The authenticated ``five9.Five9`` object. __five9__ = None # A dictionary of models, keyed by class name. __models__ = None # The currently selected model. __model__ = None # A list of records represented by this environment. __records__ = None # The current record represented by this environment. __record__ = None @classmethod def __new__(cls, *args, **kwargs): """Find and cache all model objects, if not already done.""" if cls.__models__ is None: models = __import__('five9').models cls.__models__ = { model: getattr(models, model) for model in models.__all__ if not model.startswith('_') } return object.__new__(cls) def __init__(self, five9, model=None, records=None): """Instantiate a new environment.""" self.__five9__ = five9 self.__model__ = model self.__records__ = records def __getattribute__(self, item): try: return super(Environment, self).__getattribute__(item) except AttributeError: return self.__class__(self.__five9__, self.__models__[item]) @Api.recordset def __iter__(self): """Pass iteration through to the records. Yields: BaseModel: The next record in the iterator. Raises: StopIterationError: When all records have been iterated. """ for record in self.__records__: self.__record__ = record yield record raise StopIteration() @Api.model def create(self, data, refresh=False): """Create the data on the remote, optionally refreshing.""" self.__model__.create(self.__five9__, data) if refresh: return self.read(data[self.__model__.__name__]) else: return self.new(data) @Api.model def new(self, data): """Create a new memory record, but do not create on the remote.""" data = self.__model__._get_non_empty_dict(data) return self.__class__( self.__five9__, self.__model__, records=[self.__model__.deserialize(data)], ) @Api.model def read(self, external_id): """Perform a lookup on the current model for the provided external ID. """ return self.__model__.read(self.__five9__, external_id) @Api.recordset def write(self): """Write the records to the remote.""" return self._iter_call('write') @Api.recordset def delete(self): """Delete the records from the remote.""" return self._iter_call('delete') @Api.model def search(self, filters): """Search Five9 given a filter. Args: filters (dict): A dictionary of search strings, keyed by the name of the field to search. Returns: Environment: An environment representing the recordset. """ records = self.__model__.search(self.__five9__, filters) return self.__class__( self.__five9__, self.__model__, records, ) @Api.recordset def _iter_call(self, method_name): return [ getattr(r, method_name)(self.__five9__) for r in self.__records__ ]
class Environment(object): '''Represents a container for models with a back-reference to Five9. ''' @classmethod def __new__(cls, *args, **kwargs): '''Find and cache all model objects, if not already done.''' pass def __init__(self, five9, model=None, records=None): '''Instantiate a new environment.''' pass def __getattribute__(self, item): pass @Api.recordset def __iter__(self): '''Pass iteration through to the records. Yields: BaseModel: The next record in the iterator. Raises: StopIterationError: When all records have been iterated. ''' pass @Api.model def create(self, data, refresh=False): '''Create the data on the remote, optionally refreshing.''' pass @Api.model def new(self, data): '''Create a new memory record, but do not create on the remote.''' pass @Api.model def read(self, external_id): '''Perform a lookup on the current model for the provided external ID. ''' pass @Api.recordset def write(self): '''Write the records to the remote.''' pass @Api.recordset def delete(self): '''Delete the records from the remote.''' pass @Api.model def search(self, filters): '''Search Five9 given a filter. Args: filters (dict): A dictionary of search strings, keyed by the name of the field to search. Returns: Environment: An environment representing the recordset. ''' pass @Api.recordset def _iter_call(self, method_name): pass
21
10
7
0
5
2
1
0.42
1
3
0
0
10
0
11
11
110
16
66
29
45
28
44
20
32
2
1
1
15
145,001
LasLabs/python-five9
LasLabs_python-five9/five9/tests/test_key_value_pair.py
five9.tests.test_key_value_pair.TestKeyValuePair
class TestKeyValuePair(unittest.TestCase): def test_init_positional(self): """It should allow positional key, value pairs.""" res = KeyValuePair('key', 'value') self.assertEqual(res.key, 'key') self.assertEqual(res.value, 'value')
class TestKeyValuePair(unittest.TestCase): def test_init_positional(self): '''It should allow positional key, value pairs.''' pass
2
1
5
0
4
1
1
0.2
1
1
1
0
1
0
1
73
7
1
5
3
3
1
5
3
3
1
2
0
1
145,002
LasLabs/python-five9
LasLabs_python-five9/five9/tests/test_web_connector.py
five9.tests.test_web_connector.TestWebConnector
class TestWebConnector(CommonCrud, unittest.TestCase): Model = WebConnector def setUp(self): super(TestWebConnector, self).setUp() self.data['trigger'] = 'OnCallAccepted'
class TestWebConnector(CommonCrud, unittest.TestCase): def setUp(self): pass
2
0
3
0
3
0
1
0
2
1
0
0
1
0
1
81
7
2
5
3
3
0
5
3
3
1
2
0
1
145,003
LasLabs/python-five9
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LasLabs_python-five9/five9/tests/test_five9.py
five9.tests.test_five9.TestFive9
class TestFive9(Common): def test_create_criteria_flat(self): """It should return the proper criteria for the flat inputs.""" data = { 'first_name': 'Test', 'last_name': 'User', 'number1': 1234567890, } result = self.five9.create_criteria(data) self.assertEqual(len(result), len(data)) for key, value in data.items(): criteria = {'criteria': {'field': key, 'value': value}} self.assertIn(criteria, result) def test_create_criteria_list(self): """It should create multiple criteria for a list.""" data = { 'first_name': ['Test1', 'Test2'], } result = self.five9.create_criteria({ 'first_name': ['Test1', 'Test2'], }) self.assertEqual(len(result), 2) for name in data['first_name']: criteria = {'criteria': {'field': 'first_name', 'value': name}} self.assertIn(criteria, result) def test_create_mapping(self): """It should output the proper mapping.""" record = OrderedDict([ ('first_name', 'Test'), ('last_name', 'User'), ]) result = self.five9.create_mapping(record, ['last_name']) expect = { 'field_mappings': [ {'columnNumber': 1, 'fieldName': 'first_name', 'key': False}, {'columnNumber': 2, 'fieldName': 'last_name', 'key': True}, ], 'data': record, 'fields': ['Test', 'User'], } self.assertDictEqual(result, expect) def test_parse_response(self): """It should return the proper record.""" expect = [ OrderedDict([('first_name', 'Test'), ('last_name', 'User')]), OrderedDict([('first_name', 'First'), ('last_name', 'Last')]), ] fields = ['first_name', 'last_name'] records = [{'values': {'data': list(e.values())}} for e in expect] response = self.five9.parse_response(fields, records) for idx, row in enumerate(response): self.assertDictEqual(row, expect[idx]) def _test_cached_client(self, client_type): with mock.patch.object(self.five9, '_get_authenticated_client') as mk: response = getattr(self.five9, client_type) return response, mk def test_init_username(self): """It should assign the username during init.""" self.assertEqual(self.five9.username, self.user) def test_init_authentication(self): """It should create a BasicAuth object with proper args.""" self.assertIsInstance(self.five9.auth, requests.auth.HTTPBasicAuth) self.assertEqual(self.five9.auth.username, self.user) self.assertEqual(self.five9.auth.password, self.password) @mock.patch('five9.five9.zeep') def test_get_authenticated_client(self, zeep): """It should return a zeep client.""" wsdl = 'wsdl%s' response = self.five9._get_authenticated_client(wsdl) zeep.Client.assert_called_once_with( wsdl % self.user.replace('@', '%40'), transport=zeep.Transport(), ) self.assertEqual(response, zeep.Client()) def test_get_authenticated_session(self): """It should return a requests session with authentication.""" response = self.five9._get_authenticated_session() self.assertIsInstance(response, requests.Session) self.assertEqual(response.auth, self.five9.auth) def test_configuration(self): """It should return an authenticated configuration service.""" response, mk = self._test_cached_client('configuration') mk.assert_called_once_with(self.five9.WSDL_CONFIGURATION) self.assertEqual(response, mk().service) def test_supervisor(self): """It should return an authenticated supervisor service.""" response, mk = self._test_cached_client('supervisor') mk.assert_called_once_with(self.five9.WSDL_SUPERVISOR) self.assertEqual(response, mk().service) def test_supervisor_session(self): """It should automatically create a supervisor session.""" response, _ = self._test_cached_client('supervisor') response.setSessionParameters.assert_called_once_with( self.five9._api_supervisor_session, ) def test_supervisor_session_cached(self): """It should use a cached supervisor session after initial.""" response, _ = self._test_cached_client('supervisor') self._test_cached_client('supervisor') response.setSessionParameters.assert_called_once()
class TestFive9(Common): def test_create_criteria_flat(self): '''It should return the proper criteria for the flat inputs.''' pass def test_create_criteria_list(self): '''It should create multiple criteria for a list.''' pass def test_create_mapping(self): '''It should output the proper mapping.''' pass def test_parse_response(self): '''It should return the proper record.''' pass def _test_cached_client(self, client_type): pass def test_init_username(self): '''It should assign the username during init.''' pass def test_init_authentication(self): '''It should create a BasicAuth object with proper args.''' pass @mock.patch('five9.five9.zeep') def test_get_authenticated_client(self, zeep): '''It should return a zeep client.''' pass def test_get_authenticated_session(self): '''It should return a requests session with authentication.''' pass def test_configuration(self): '''It should return an authenticated configuration service.''' pass def test_supervisor(self): '''It should return an authenticated supervisor service.''' pass def test_supervisor_session(self): '''It should automatically create a supervisor session.''' pass def test_supervisor_session_cached(self): '''It should use a cached supervisor session after initial.''' pass
15
12
8
0
7
1
1
0.14
1
4
0
0
13
0
13
86
113
13
88
40
73
12
61
38
47
2
3
1
16
145,004
LasLabs/python-five9
LasLabs_python-five9/five9/tests/test_base_model.py
five9.tests.test_base_model.TestBaseModel
class TestBaseModel(unittest.TestCase): def setUp(self): super(TestBaseModel, self).setUp() self.called_with = None self.id = 1234 def new_record(self): return TestModel( id=self.id, ) def _test_method(self, data): self.called_with = data def test_read_none(self): """It should return None if no result.""" with mock.patch.object(BaseModel, 'search') as search: search.return_value = [] self.assertIsNone(BaseModel.read(None, None)) def _call_and_serialize(self, data=None, refresh=False): method = self._test_method result = BaseModel._call_and_serialize(method, data, refresh) return result def test_read_results(self): """It should return the first result.""" with mock.patch.object(BaseModel, 'search') as search: search.return_value = [1, 2] self.assertEqual(BaseModel.read(None, None), 1) def test_read_search(self): """It should perform the proper search.""" with mock.patch.object(BaseModel, 'search') as search: BaseModel.read('five9', 'external_id') search.assert_called_once_with('five9', {'name': 'external_id'}) def test_call_and_serialize_refresh_return(self): """It should return the refreshed object.""" data = {'name': 'test'} with mock.patch.object(BaseModel, 'read') as read: result = self._call_and_serialize(data, True) read.assert_called_once_with(self, data['name']) self.assertEqual(self.called_with, data) self.assertEqual(result, read()) def test_call_and_serialize_no_refresh(self): """It should return the deserialized data.""" data = {'name': 'test'} with mock.patch.object(BaseModel, 'deserialize') as deserialize: result = self._call_and_serialize(data, False) deserialize.assert_called_once_with(data) self.assertEqual(self.called_with, data) self.assertEqual(result, deserialize()) def test_update(self): """It should set the attributes to the provided values.""" data = {'test1': 12345, 'test2': 54321} record = self.new_record() record.update(data) for key, value in data.items(): self.assertEqual(getattr(record, key), value) def test__get_non_empty_dict(self): """It should return the dict without NoneTypes.""" expect = { 'good_int': 1234, 'good_false': False, 'good_true': True, 'bad': None, 'bad_dict': {'key': None}, 'bad_list': [None], 'bad_list_with_dict': [{'key': None}], 'good_list': [1, 2], 'good_list_with_dict': [{'key': 1}], } res = BaseModel._get_non_empty_dict(expect) del expect['bad'], \ expect['bad_dict'], \ expect['bad_list'], \ expect['bad_list_with_dict'] self.assertDictEqual(res, expect) def test_dict_lookup_exist(self): """It should return the attribute value when it exists.""" self.assertEqual( self.new_record()['id'], self.id, ) 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 = 4321 record = self.new_record() record['id'] = expect self.assertEqual(record.id, 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('id'), self.id, ) 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, )
class TestBaseModel(unittest.TestCase): def setUp(self): pass def new_record(self): pass def _test_method(self, data): pass def test_read_none(self): '''It should return None if no result.''' pass def _call_and_serialize(self, data=None, refresh=False): pass def test_read_results(self): '''It should return the first result.''' pass def test_read_search(self): '''It should perform the proper search.''' pass def test_call_and_serialize_refresh_return(self): '''It should return the refreshed object.''' pass def test_call_and_serialize_no_refresh(self): '''It should return the deserialized data.''' pass def test_update(self): '''It should set the attributes to the provided values.''' pass def test__get_non_empty_dict(self): '''It should return the dict without NoneTypes.''' 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
18
13
6
0
5
1
1
0.14
1
4
2
0
17
2
17
89
121
17
91
40
73
13
70
35
52
2
2
1
18
145,005
LasLabs/python-five9
LasLabs_python-five9/five9/models/timer.py
five9.models.timer.Timer
class Timer(BaseModel): days = properties.Integer( 'Number of days.' ) hours = properties.Integer( 'Number of hours.', ) minutes = properties.Integer( 'Number of minutes.', ) seconds = properties.Integer( 'Number of seconds.', )
class Timer(BaseModel): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
16
14
1
13
5
12
0
5
5
4
0
2
0
0
145,006
LasLabs/python-five9
LasLabs_python-five9/five9/environment.py
five9.environment.Api
class Api(object): """This is a set of decorators for model validators.""" @staticmethod def model(method): """Use this to decorate methods that expect a model.""" def wrapper(self, *args, **kwargs): if self.__model__ is None: raise ValidationError( 'You cannot perform CRUD operations without selecting a ' 'model first.', ) return method(self, *args, **kwargs) return wrapper @staticmethod def recordset(method): """Use this to decorate methods that expect a record set.""" def wrapper(self, *args, **kwargs): if self.__records__ is None: raise ValidationError( 'There are no records in the set.', ) return method(self, *args, **kwargs) return Api.model(wrapper)
class Api(object): '''This is a set of decorators for model validators.''' @staticmethod def model(method): '''Use this to decorate methods that expect a model.''' pass def wrapper(self, *args, **kwargs): pass @staticmethod def recordset(method): '''Use this to decorate methods that expect a record set.''' pass def wrapper(self, *args, **kwargs): pass
7
3
8
0
8
1
2
0.15
1
1
1
0
0
0
2
2
25
2
20
7
13
3
13
5
8
2
1
1
6
145,007
LasLabs/python-five9
LasLabs_python-five9/five9/tests/test_api.py
five9.tests.test_api.TestRecord
class TestRecord(object): __model__ = None __records__ = None @Api.model def model(self): return True @Api.recordset def recordset(self): return True
class TestRecord(object): @Api.model def model(self): pass @Api.recordset def recordset(self): pass
5
0
2
0
2
0
1
0
1
0
0
0
2
0
2
2
12
3
9
7
4
0
7
5
4
1
1
0
2
145,008
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/models/attachment.py
helpscout.models.attachment.Attachment
class Attachment(AttachmentData): hash = properties.String( 'Unique hash.', ) mime_type = properties.String( 'Mime Type', ) file_name = properties.String( 'File Name', required=True, ) size = properties.Integer( 'Size of the attachment in bytes.', ) width = properties.Integer( 'Image width', ) height = properties.Integer( 'Image height', ) url = properties.String( 'Public-facing url where attachment can be downloaded.', )
class Attachment(AttachmentData): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
17
24
1
23
7
22
0
8
7
7
0
3
0
0
145,009
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/web_hook/__init__.py
helpscout.web_hook.HelpScoutWebHook
class HelpScoutWebHook(WebHook): """This provides the ability to easily create & process web hook events. """ helpscout = properties.Instance( 'The authenticated HelpScout object. Used for create.', # This cannot be defined as a HelpScout object due to circular depends instance_class=object, ) def create(self): """Create the web hook on HelpScout.""" assert self.helpscout return self.helpscout.WebHook.create(self) def receive(self, event_type, signature, data_str): """Receive a web hook for the event and signature. Args: event_type (str): Name of the event that was received (from the request ``X-HelpScout-Event`` header). signature (str): The signature that was received, which serves as authentication (from the request ``X-HelpScout-Signature`` header). data_str (str): The raw data that was posted by HelpScout to the web hook. This must be the raw string, because if it is parsed with JSON it will lose its ordering and not pass signature validation. Raises: helpscout.exceptions.HelpScoutSecurityException: If an invalid signature is provided, and ``raise_if_invalid`` is ``True``. Returns: helpscout.web_hook.WebHookEvent: The authenticated web hook request. """ if not self.validate_signature(signature, data_str): raise HelpScoutSecurityException( 'The signature provided by this request was invalid.', ) return HelpScoutWebHookEvent( event_type=event_type, record=json.loads(data_str), ) def validate_signature(self, signature, data, encoding='utf8'): """Validate the signature for the provided data. Args: signature (str or bytes or bytearray): Signature that was provided for the request. data (str or bytes or bytearray): Data string to validate against the signature. encoding (str, optional): If a string was provided for ``data`` or ``signature``, this is the character encoding. Returns: bool: Whether the signature is valid for the provided data. """ if isinstance(data, string_types): data = bytearray(data, encoding) if isinstance(signature, string_types): signature = bytearray(signature, encoding) secret_key = bytearray(self.secret_key, 'utf8') hashed = hmac.new(secret_key, data, sha1) encoded = b64encode(hashed.digest()) return encoded.strip() == signature.strip()
class HelpScoutWebHook(WebHook): '''This provides the ability to easily create & process web hook events. ''' def create(self): '''Create the web hook on HelpScout.''' pass def receive(self, event_type, signature, data_str): '''Receive a web hook for the event and signature. Args: event_type (str): Name of the event that was received (from the request ``X-HelpScout-Event`` header). signature (str): The signature that was received, which serves as authentication (from the request ``X-HelpScout-Signature`` header). data_str (str): The raw data that was posted by HelpScout to the web hook. This must be the raw string, because if it is parsed with JSON it will lose its ordering and not pass signature validation. Raises: helpscout.exceptions.HelpScoutSecurityException: If an invalid signature is provided, and ``raise_if_invalid`` is ``True``. Returns: helpscout.web_hook.WebHookEvent: The authenticated web hook request. ''' pass def validate_signature(self, signature, data, encoding='utf8'): '''Validate the signature for the provided data. Args: signature (str or bytes or bytearray): Signature that was provided for the request. data (str or bytes or bytearray): Data string to validate against the signature. encoding (str, optional): If a string was provided for ``data`` or ``signature``, this is the character encoding. Returns: bool: Whether the signature is valid for the provided data. ''' pass
4
4
20
3
7
10
2
1.27
1
3
2
0
3
0
3
17
73
14
26
8
22
33
18
8
14
3
3
1
6
145,010
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/web_hook/__init__.py
helpscout.web_hook.HelpScoutWebHookEvent
class HelpScoutWebHookEvent(WebHookEvent): """This represents an authenticated web hook request. Note that this object is meant to represent an authenticated Web Hook, and therefore is completely naive of all things authentication. Any request authentication/validation should happen in the ``WebHook``. """ # Map the event prefixes to their corresponding data models. EVENT_PREFIX_TO_MODEL = { 'convo': Conversation, 'customer': Customer, 'satisfaction': Rating, } def __init__(self, *args, **kwargs): """Parse raw record data if required. Args: record (dict or BaseModel): The record data that was received for the request. If it is a ``dict``, the data will be parsed using the proper model's ``from_api`` method. """ if isinstance(kwargs.get('record'), dict): prefix, _ = kwargs['event_type'].split('.', 1) model = self.EVENT_PREFIX_TO_MODEL[prefix] kwargs['record'] = model.from_api(**kwargs['record']) super(WebHookEvent, self).__init__(*args, **kwargs)
class HelpScoutWebHookEvent(WebHookEvent): '''This represents an authenticated web hook request. Note that this object is meant to represent an authenticated Web Hook, and therefore is completely naive of all things authentication. Any request authentication/validation should happen in the ``WebHook``. ''' def __init__(self, *args, **kwargs): '''Parse raw record data if required. Args: record (dict or BaseModel): The record data that was received for the request. If it is a ``dict``, the data will be parsed using the proper model's ``from_api`` method. ''' pass
2
2
13
1
6
6
2
1
1
2
0
0
1
0
1
15
28
4
12
5
10
12
8
5
6
2
3
1
2
145,011
LasLabs/python-helpscout
LasLabs_python-helpscout/setup.py
setup.FailTestException
class FailTestException(Exception): """ It provides a failing build """ pass
class FailTestException(Exception): ''' It provides a failing build ''' pass
1
1
0
0
0
0
0
0.5
1
0
0
0
0
0
0
10
3
0
2
1
1
1
2
1
1
0
3
0
0
145,012
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/models/custom_field.py
helpscout.models.custom_field.CustomField
class CustomField(BaseModel): """This represents optional data that can defined for specific mailbox and filled when creating or updating a Conversation.""" field_name = properties.String( 'The name of the field; note that this may change if a field ' 'is renamed, but the ``id`` will not.', required=True, ) field_type = properties.StringChoice( 'Type of the field.', choices=['SINGLE_LINE', 'MULTI_LINE', 'DATA', 'NUMBER', 'DROPDOWN', ], default='SINGLE_LINE', required=True, ) required = properties.Bool( 'Flag for UI to mark the field as required.', ) order = properties.Integer( 'Relative order of the custom field. Can be ``null`` or a number ' 'between ``0`` and ``255``.', min=0, max=255, ) options = properties.List( 'Field options', prop=Option, )
class CustomField(BaseModel): '''This represents optional data that can defined for specific mailbox and filled when creating or updating a Conversation.'''
1
1
0
0
0
0
0
0.07
1
0
0
0
0
0
0
14
33
1
30
6
29
2
6
6
5
0
2
0
0
145,013
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/models/conversation.py
helpscout.models.conversation.Conversation
class Conversation(BaseConversation): """This represents a full conversation result.""" type = properties.StringChoice( 'The type of conversation.', choices=['email', 'chat', 'phone', 'spam'], required=True, ) folder_id = properties.Integer( 'ID of the Mailbox Folder to which this conversation resides.', required=True, ) is_draft = properties.Bool( 'Is this a draft conversation? This property duplicates ``draft``, ' 'but both are received in API responses at the same time so neither ' 'can be considered "deprecated".', ) draft = properties.Bool( 'Is this a draft conversation? This property duplicates ' '``is_draft``, but both are received in API responses at the same ' 'time so neither can be considered "deprecated".', ) owner = properties.Instance( 'The Help Scout user who is currently assigned to this conversation.', instance_class=Person, required=True, ) mailbox = properties.Instance( 'The mailbox to which this conversation belongs.', instance_class=MailboxRef, required=True, ) customer = properties.Instance( 'The customer who this conversation is associated with.', instance_class=Person, required=True, ) created_by = properties.Instance( 'The ``Person`` who created this conversation. The ``type`` property ' 'will specify whether it was created by a ``user`` or a ``customer``.', instance_class=Person, ) created_by_type = properties.String( 'The type of user that created this conversation.', ) created_at = properties.DateTime( 'UTC time when this conversation was created.', ) closed_at = properties.DateTime( 'UTC time when this conversation was closed. Null if not closed.', ) closed_by = properties.Instance( 'The Help Scout user who closed this conversation.', instance_class=Person, ) source = properties.Instance( 'Specifies the method in which this conversation was created.', instance_class=Source, ) threads = properties.List( 'Threads associated with the conversation.', prop=Thread, ) cc = properties.List( 'Emails that are CCd.', prop=properties.String( 'Email Address', ), ) bcc = properties.List( 'Emails that are BCCd.', prop=properties.String( 'Email Address', ), ) tags = properties.List( 'Tags for the conversation', prop=properties.String('Tag Name'), ) spam = properties.Bool( 'If this conversation is marked as SPAM.', ) locked = properties.Bool( 'If this conversation is locked from editing.' ) user_modified_at = properties.DateTime( 'Last time that this conversation was edited by a user.', )
class Conversation(BaseConversation): '''This represents a full conversation result.''' pass
1
1
0
0
0
0
0
0.01
1
0
0
0
0
0
0
14
88
1
86
21
85
1
21
21
20
0
3
0
0
145,014
LasLabs/python-helpscout
LasLabs_python-helpscout/setup.py
setup.Tests
class Tests(Command): """ Run test & coverage, save reports as XML """ user_options = [] # < For Command API compatibility def initialize_options(self, ): pass def finalize_options(self, ): pass def run(self, ): loader = TestLoader() tests = loader.discover('.', 'test_*.py') t = TextTestRunner(verbosity=1) res = t.run(tests) if not res.wasSuccessful(): raise FailTestException()
class Tests(Command): ''' Run test & coverage, save reports as XML ''' def initialize_options(self, ): pass def finalize_options(self, ): pass def run(self, ): pass
4
1
4
0
4
0
1
0.15
1
3
1
0
3
0
3
3
18
4
13
9
9
2
13
9
9
2
1
1
4
145,015
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/models/chat.py
helpscout.models.chat.Chat
class Chat(BaseModel): """This represents a chat (IM) address.""" value = properties.String( 'Value', required=True, ) type = properties.StringChoice( 'Type', choices=['aim', 'gtalk', 'icq', 'xmpp', 'msn', 'skype', 'yahoo', 'qq', 'other', ], default='other', required=True, )
class Chat(BaseModel): '''This represents a chat (IM) address.''' pass
1
1
0
0
0
0
0
0.05
1
0
0
0
0
0
0
14
22
1
20
3
19
1
3
3
2
0
2
0
0
145,016
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/models/base_conversation.py
helpscout.models.base_conversation.BaseConversation
class BaseConversation(BaseModel): """This represents a basic conversation, meant to be subclassed.""" number = properties.Integer( 'The conversation number displayed in the UI. This number can be used ' 'in combination with the id to construct a URI to the conversation on ' 'the Help Scout website. Example: ' '``https://secure.helpscout.net/conversation/<id>/<number>/``', required=True, ) subject = properties.String( 'The subject of the conversation.', required=True, ) status = properties.StringChoice( 'Status of the conversation.', choices=['active', 'pending', 'closed', 'spam'], default='pending', required=True, ) thread_count = properties.Integer( 'This count represents the number of published threads found on the ' 'conversation (it does not include line items, drafts or threads held ' 'for review by Traffic Cop).', required=True, ) preview = properties.String( 'Conversation preview.', ) modified_at = properties.DateTime( 'UTC time when a user last modified this conversation.', )
class BaseConversation(BaseModel): '''This represents a basic conversation, meant to be subclassed.''' pass
1
1
0
0
0
0
0
0.03
1
0
0
3
0
0
0
14
32
1
30
7
29
1
7
7
6
0
2
0
0
145,017
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/models/attachment_data.py
helpscout.models.attachment_data.AttachmentData
class AttachmentData(BaseModel): data = properties.String( 'base64 encoded data.', ) @property def raw_data(self): """Raw (decoded) attachment data (possibly binary).""" return self.data and base64.b64decode(self.data) @raw_data.setter def raw_data(self, value): """Set the base64 encoded data using a raw value or file object.""" if value: try: value = value.read() except AttributeError: pass b64 = base64.b64encode(value.encode('utf-8')) self.data = b64.decode('utf-8') @raw_data.deleter def raw_data(self): self.data = None
class AttachmentData(BaseModel): @property def raw_data(self): '''Raw (decoded) attachment data (possibly binary).''' pass @raw_data.setter def raw_data(self): '''Set the base64 encoded data using a raw value or file object.''' pass @raw_data.deleter def raw_data(self): pass
7
2
5
0
4
1
2
0.11
1
1
0
1
3
0
3
17
25
4
19
9
12
2
14
6
10
3
2
2
5
145,018
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/models/address.py
helpscout.models.address.Address
class Address(BaseModel): """This represents an address.""" lines = properties.List( 'Address line strings', prop=properties.String( 'Address line string', ), ) city = properties.String( 'City', required=True, ) state = properties.String( 'State', required=True, ) postal_code = properties.String( 'Postal Code', required=True, ) country = properties.String( 'Country', required=True, ) created_at = properties.DateTime( 'UTC time when this address was created.', ) modified_at = properties.DateTime( 'UTC time when this address was modified.', )
class Address(BaseModel): '''This represents an address.''' pass
1
1
0
0
0
0
0
0.03
1
0
0
0
0
0
0
14
31
1
29
8
28
1
8
8
7
0
2
0
0
145,019
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/exceptions.py
helpscout.exceptions.HelpScoutValidationException
class HelpScoutValidationException(HelpScoutException): """Indicates an error while validating user-supplied data."""
class HelpScoutValidationException(HelpScoutException): '''Indicates an error while validating user-supplied data.''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
12
2
0
1
1
0
1
1
1
0
0
4
0
0
145,020
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/exceptions.py
helpscout.exceptions.HelpScoutSecurityException
class HelpScoutSecurityException(HelpScoutException): """Indicates a security error; probably by an invalid web hook signature. """
class HelpScoutSecurityException(HelpScoutException): '''Indicates a security error; probably by an invalid web hook signature. ''' pass
1
1
0
0
0
0
0
2
1
0
0
0
0
0
0
12
3
0
1
1
0
2
1
1
0
0
4
0
0
145,021
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/__init__.py
helpscout.HelpScout
class HelpScout(object): """This object is the primary point of interaction with HelpScout. Properties will be set on this ``HelpScout`` instance that will mirror the class names of APIs in the ``helpscout.api`` module. These API classes are naive of authentication, so the actual properties set will be using the ``AuthProxy`` class, which will transparently inject authentication into the API requests while still allowing for a naive API object. This allows for the ``HelpScout`` instance to act as a container for all of the authenticated API objects. Examples:: from helpscout import HelpScout hs = HelpScout('api_key') for customer in hs.Customers.list(): print(customer) Attributes: Conversations (helpscout.api.conversations.Conversations): Conversations API endpoint. Customers (helpscout.api.customers.Customers): Customers API endpoint. Mailboxes (helpscout.api.mailboxes.Mailboxes): Mailboxes API endpoint. Tags (helpscout.api.tags.Tags): Tags API endpoint. Teams (helpscout.api.teams.Teams): Teams API endpoint. Users (helpscout.api.users.Users): Users API endpoint. WebHook (helpscout.api.web_hook.WebHook): Web Hook API endpoint. __apis__ (dict): References to all available APIs, keyed by class name. """ __apis__ = {} def __init__(self, api_key): """Initialize a new HelpScout client. Args: api_key (str): The API key to use for this session. """ self.session = Session() self.session.auth = HTTPBasicAuth(api_key, 'NoPassBecauseKey!') self._load_apis() def _load_apis(self): """Find available APIs and set instances property auth proxies.""" helpscout = __import__('helpscout.apis') for class_name in helpscout.apis.__all__: if not class_name.startswith('_'): cls = getattr(helpscout.apis, class_name) api = AuthProxy(self.session, cls) setattr(self, class_name, api) self.__apis__[class_name] = api
class HelpScout(object): '''This object is the primary point of interaction with HelpScout. Properties will be set on this ``HelpScout`` instance that will mirror the class names of APIs in the ``helpscout.api`` module. These API classes are naive of authentication, so the actual properties set will be using the ``AuthProxy`` class, which will transparently inject authentication into the API requests while still allowing for a naive API object. This allows for the ``HelpScout`` instance to act as a container for all of the authenticated API objects. Examples:: from helpscout import HelpScout hs = HelpScout('api_key') for customer in hs.Customers.list(): print(customer) Attributes: Conversations (helpscout.api.conversations.Conversations): Conversations API endpoint. Customers (helpscout.api.customers.Customers): Customers API endpoint. Mailboxes (helpscout.api.mailboxes.Mailboxes): Mailboxes API endpoint. Tags (helpscout.api.tags.Tags): Tags API endpoint. Teams (helpscout.api.teams.Teams): Teams API endpoint. Users (helpscout.api.users.Users): Users API endpoint. WebHook (helpscout.api.web_hook.WebHook): Web Hook API endpoint. __apis__ (dict): References to all available APIs, keyed by class name. ''' def __init__(self, api_key): '''Initialize a new HelpScout client. Args: api_key (str): The API key to use for this session. ''' pass def _load_apis(self): '''Find available APIs and set instances property auth proxies.''' pass
3
3
9
1
6
3
2
2.29
1
3
1
0
2
1
2
2
56
10
14
9
11
32
14
9
11
3
1
2
4
145,022
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/apis/conversations.py
helpscout.apis.conversations.Conversations
class Conversations(BaseApi): """This represents the ``Conversations`` Endpoint. The following aspects are implemented: * `List Conversations <http://developer.helpscout.net/help-desk-api/conversations/list/>`_ (:func:`helpscout.apis.conversations.Conversations.list`) * `Search Conversations <http://developer.helpscout.net/help-desk-api/search/conversations/>`_ (:func:`helpscout.apis.conversations.Conversations.search`) * `Get Conversation <http://developer.helpscout.net/help-desk-api/conversations/get/>`_ (:func:`helpscout.apis.conversations.Conversations.get`) * `Create Conversation <http://developer.helpscout.net/help-desk-api/conversations/create/>`_ (:func:`helpscout.apis.conversations.Conversations.create`) * `Update Conversation <http://developer.helpscout.net/help-desk-api/conversations/update/>`_ (:func:`helpscout.apis.conversations.Conversations.update`) * `Delete Conversation <http://developer.helpscout.net/help-desk-api/conversations/delete/>`_ (:func:`helpscout.apis.conversations.Conversations.delete`) * `Create Thread <http://developer.helpscout.net/help-desk-api/conversations/ create-thread/>`_ (:func:`helpscout.apis.conversations.Conversations.create_thread`) * `Update Thread <http://developer.helpscout.net/help-desk-api/conversations/ update-thread/>`_ (:func:`helpscout.apis.conversations.Conversations.update_thread`) * `Get Attachment Data <http://developer.helpscout.com/help-desk-api/conversations/attachment-data/>`_ (:func:`helpscout.apis.conversations.Conversations.get_attachment_data`) * `Create Attachment <http://developer.helpscout.com/help-desk-api/conversations/create-attachment/>`_ (:func:`helpscout.apis.conversations.Conversations.create_attachment`) * `Delete Attachment <http://developer.helpscout.com/help-desk-api/conversations/delete-attachment/>`_ (:func:`helpscout.apis.conversations.Conversations.delete_attachment`) """ __object__ = Conversation __endpoint__ = 'conversations' @classmethod def create(cls, session, record, imported=False, auto_reply=False): """Create a conversation. Please note that conversation cannot be created with more than 100 threads, if attempted the API will respond with HTTP 412. Args: session (requests.sessions.Session): Authenticated session. record (helpscout.models.Conversation): The conversation to be created. imported (bool, optional): The ``imported`` request parameter enables conversations to be created for historical purposes (i.e. if moving from a different platform, you can import your history). When ``imported`` is set to ``True``, no outgoing emails or notifications will be generated. auto_reply (bool): The ``auto_reply`` request parameter enables auto replies to be sent when a conversation is created via the API. When ``auto_reply`` is set to ``True``, an auto reply will be sent as long as there is at least one ``customer`` thread in the conversation. Returns: helpscout.models.Conversation: Newly created conversation. """ return super(Conversations, cls).create( session, record, imported=imported, auto_reply=auto_reply, ) @classmethod def create_attachment(cls, session, attachment): """Create an attachment. An attachment must be sent to the API before it can be used in a thread. Use this method to create the attachment, then use the resulting hash when creating a thread. Note that HelpScout only supports attachments of 10MB or lower. Args: session (requests.sessions.Session): Authenticated session. attachment (helpscout.models.Attachment): The attachment to be created. Returns: helpscout.models.Attachment: The newly created attachment (hash property only). Use this hash when associating the attachment with a new thread. """ return super(Conversations, cls).create( session, attachment, endpoint_override='/attachments.json', out_type=Attachment, ) @classmethod def create_thread(cls, session, conversation, thread, imported=False): """Create a conversation thread. Please note that threads cannot be added to conversations with 100 threads (or more), if attempted the API will respond with HTTP 412. Args: conversation (helpscout.models.Conversation): The conversation that the thread is being added to. session (requests.sessions.Session): Authenticated session. thread (helpscout.models.Thread): The thread to be created. imported (bool, optional): The ``imported`` request parameter enables conversations to be created for historical purposes (i.e. if moving from a different platform, you can import your history). When ``imported`` is set to ``True``, no outgoing emails or notifications will be generated. Returns: helpscout.models.Conversation: Conversation including newly created thread. """ return super(Conversations, cls).create( session, thread, endpoint_override='/conversations/%s.json' % conversation.id, imported=imported, ) @classmethod def delete_attachment(cls, session, attachment): """Delete an attachment. Args: session (requests.sessions.Session): Authenticated session. attachment (helpscout.models.Attachment): The attachment to be deleted. Returns: NoneType: Nothing. """ return super(Conversations, cls).delete( session, attachment, endpoint_override='/attachments/%s.json' % attachment.id, out_type=Attachment, ) @classmethod def find_customer(cls, session, mailbox, customer): """Return conversations for a specific customer in a mailbox. Args: session (requests.sessions.Session): Authenticated session. mailbox (helpscout.models.Mailbox): Mailbox to search. customer (helpscout.models.Customer): Customer to search for. Returns: RequestPaginator(output_type=helpscout.models.Conversation): Conversations iterator. """ return cls( '/mailboxes/%d/customers/%s/conversations.json' % ( mailbox.id, customer.id, ), session=session, ) @classmethod def find_user(cls, session, mailbox, user): """Return conversations for a specific user in a mailbox. Args: session (requests.sessions.Session): Authenticated session. mailbox (helpscout.models.Mailbox): Mailbox to search. user (helpscout.models.User): User to search for. Returns: RequestPaginator(output_type=helpscout.models.Conversation): Conversations iterator. """ return cls( '/mailboxes/%d/users/%s/conversations.json' % ( mailbox.id, user.id, ), session=session, ) @classmethod def get_attachment_data(cls, session, attachment_id): """Return a specific attachment's data. Args: session (requests.sessions.Session): Authenticated session. attachment_id (int): The ID of the attachment from which to get data. Returns: helpscout.models.AttachmentData: An attachment data singleton, if existing. Otherwise ``None``. """ return cls( '/attachments/%d/data.json' % attachment_id, singleton=True, session=session, out_type=AttachmentData, ) @classmethod def list(cls, session, mailbox): """Return conversations in a mailbox. Args: session (requests.sessions.Session): Authenticated session. mailbox (helpscout.models.Mailbox): Mailbox to list. Returns: RequestPaginator(output_type=helpscout.models.Conversation): Conversations iterator. """ endpoint = '/mailboxes/%d/conversations.json' % mailbox.id return super(Conversations, cls).list(session, endpoint) @classmethod def list_folder(cls, session, mailbox, folder): """Return conversations in a specific folder of a mailbox. Args: session (requests.sessions.Session): Authenticated session. mailbox (helpscout.models.Mailbox): Mailbox that folder is in. folder (helpscout.models.Folder): Folder to list. Returns: RequestPaginator(output_type=helpscout.models.Conversation): Conversations iterator. """ return cls( '/mailboxes/%d/folders/%s/conversations.json' % ( mailbox.id, folder.id, ), session=session, ) @classmethod def search(cls, session, queries): """Search for a conversation given a domain. Args: session (requests.sessions.Session): Authenticated session. queries (helpscout.models.Domain or iter): The queries for the domain. If a ``Domain`` object is provided, it will simply be returned. Otherwise, a ``Domain`` object will be generated from the complex queries. In this case, the queries should conform to the interface in :func:`helpscout.domain.Domain.from_tuple`. Returns: RequestPaginator(output_type=helpscout.models.SearchCustomer): SearchCustomer iterator. """ return super(Conversations, cls).search( session, queries, SearchConversation, ) @classmethod def update_thread(cls, session, conversation, thread): """Update a thread. Args: session (requests.sessions.Session): Authenticated session. conversation (helpscout.models.Conversation): The conversation that the thread belongs to. thread (helpscout.models.Thread): The thread to be updated. Returns: helpscout.models.Conversation: Conversation including freshly updated thread. """ data = thread.to_api() data['reload'] = True return cls( '/conversations/%s/threads/%d.json' % ( conversation.id, thread.id, ), data=data, request_type=RequestPaginator.PUT, singleton=True, session=session, )
class Conversations(BaseApi): '''This represents the ``Conversations`` Endpoint. The following aspects are implemented: * `List Conversations <http://developer.helpscout.net/help-desk-api/conversations/list/>`_ (:func:`helpscout.apis.conversations.Conversations.list`) * `Search Conversations <http://developer.helpscout.net/help-desk-api/search/conversations/>`_ (:func:`helpscout.apis.conversations.Conversations.search`) * `Get Conversation <http://developer.helpscout.net/help-desk-api/conversations/get/>`_ (:func:`helpscout.apis.conversations.Conversations.get`) * `Create Conversation <http://developer.helpscout.net/help-desk-api/conversations/create/>`_ (:func:`helpscout.apis.conversations.Conversations.create`) * `Update Conversation <http://developer.helpscout.net/help-desk-api/conversations/update/>`_ (:func:`helpscout.apis.conversations.Conversations.update`) * `Delete Conversation <http://developer.helpscout.net/help-desk-api/conversations/delete/>`_ (:func:`helpscout.apis.conversations.Conversations.delete`) * `Create Thread <http://developer.helpscout.net/help-desk-api/conversations/ create-thread/>`_ (:func:`helpscout.apis.conversations.Conversations.create_thread`) * `Update Thread <http://developer.helpscout.net/help-desk-api/conversations/ update-thread/>`_ (:func:`helpscout.apis.conversations.Conversations.update_thread`) * `Get Attachment Data <http://developer.helpscout.com/help-desk-api/conversations/attachment-data/>`_ (:func:`helpscout.apis.conversations.Conversations.get_attachment_data`) * `Create Attachment <http://developer.helpscout.com/help-desk-api/conversations/create-attachment/>`_ (:func:`helpscout.apis.conversations.Conversations.create_attachment`) * `Delete Attachment <http://developer.helpscout.com/help-desk-api/conversations/delete-attachment/>`_ (:func:`helpscout.apis.conversations.Conversations.delete_attachment`) ''' @classmethod def create(cls, session, record, imported=False, auto_reply=False): '''Create a conversation. Please note that conversation cannot be created with more than 100 threads, if attempted the API will respond with HTTP 412. Args: session (requests.sessions.Session): Authenticated session. record (helpscout.models.Conversation): The conversation to be created. imported (bool, optional): The ``imported`` request parameter enables conversations to be created for historical purposes (i.e. if moving from a different platform, you can import your history). When ``imported`` is set to ``True``, no outgoing emails or notifications will be generated. auto_reply (bool): The ``auto_reply`` request parameter enables auto replies to be sent when a conversation is created via the API. When ``auto_reply`` is set to ``True``, an auto reply will be sent as long as there is at least one ``customer`` thread in the conversation. Returns: helpscout.models.Conversation: Newly created conversation. ''' pass @classmethod def create_attachment(cls, session, attachment): '''Create an attachment. An attachment must be sent to the API before it can be used in a thread. Use this method to create the attachment, then use the resulting hash when creating a thread. Note that HelpScout only supports attachments of 10MB or lower. Args: session (requests.sessions.Session): Authenticated session. attachment (helpscout.models.Attachment): The attachment to be created. Returns: helpscout.models.Attachment: The newly created attachment (hash property only). Use this hash when associating the attachment with a new thread. ''' pass @classmethod def create_thread(cls, session, conversation, thread, imported=False): '''Create a conversation thread. Please note that threads cannot be added to conversations with 100 threads (or more), if attempted the API will respond with HTTP 412. Args: conversation (helpscout.models.Conversation): The conversation that the thread is being added to. session (requests.sessions.Session): Authenticated session. thread (helpscout.models.Thread): The thread to be created. imported (bool, optional): The ``imported`` request parameter enables conversations to be created for historical purposes (i.e. if moving from a different platform, you can import your history). When ``imported`` is set to ``True``, no outgoing emails or notifications will be generated. Returns: helpscout.models.Conversation: Conversation including newly created thread. ''' pass @classmethod def delete_attachment(cls, session, attachment): '''Delete an attachment. Args: session (requests.sessions.Session): Authenticated session. attachment (helpscout.models.Attachment): The attachment to be deleted. Returns: NoneType: Nothing. ''' pass @classmethod def find_customer(cls, session, mailbox, customer): '''Return conversations for a specific customer in a mailbox. Args: session (requests.sessions.Session): Authenticated session. mailbox (helpscout.models.Mailbox): Mailbox to search. customer (helpscout.models.Customer): Customer to search for. Returns: RequestPaginator(output_type=helpscout.models.Conversation): Conversations iterator. ''' pass @classmethod def find_user(cls, session, mailbox, user): '''Return conversations for a specific user in a mailbox. Args: session (requests.sessions.Session): Authenticated session. mailbox (helpscout.models.Mailbox): Mailbox to search. user (helpscout.models.User): User to search for. Returns: RequestPaginator(output_type=helpscout.models.Conversation): Conversations iterator. ''' pass @classmethod def get_attachment_data(cls, session, attachment_id): '''Return a specific attachment's data. Args: session (requests.sessions.Session): Authenticated session. attachment_id (int): The ID of the attachment from which to get data. Returns: helpscout.models.AttachmentData: An attachment data singleton, if existing. Otherwise ``None``. ''' pass @classmethod def list(cls, session, mailbox): '''Return conversations in a mailbox. Args: session (requests.sessions.Session): Authenticated session. mailbox (helpscout.models.Mailbox): Mailbox to list. Returns: RequestPaginator(output_type=helpscout.models.Conversation): Conversations iterator. ''' pass @classmethod def list_folder(cls, session, mailbox, folder): '''Return conversations in a specific folder of a mailbox. Args: session (requests.sessions.Session): Authenticated session. mailbox (helpscout.models.Mailbox): Mailbox that folder is in. folder (helpscout.models.Folder): Folder to list. Returns: RequestPaginator(output_type=helpscout.models.Conversation): Conversations iterator. ''' pass @classmethod def search(cls, session, queries): '''Search for a conversation given a domain. Args: session (requests.sessions.Session): Authenticated session. queries (helpscout.models.Domain or iter): The queries for the domain. If a ``Domain`` object is provided, it will simply be returned. Otherwise, a ``Domain`` object will be generated from the complex queries. In this case, the queries should conform to the interface in :func:`helpscout.domain.Domain.from_tuple`. Returns: RequestPaginator(output_type=helpscout.models.SearchCustomer): SearchCustomer iterator. ''' pass @classmethod def update_thread(cls, session, conversation, thread): '''Update a thread. Args: session (requests.sessions.Session): Authenticated session. conversation (helpscout.models.Conversation): The conversation that the thread belongs to. thread (helpscout.models.Thread): The thread to be updated. Returns: helpscout.models.Conversation: Conversation including freshly updated thread. ''' pass
23
12
21
2
7
11
1
1.84
1
5
4
0
0
0
11
22
293
40
89
27
66
164
28
16
16
1
2
0
11
145,023
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/apis/customers.py
helpscout.apis.customers.Customers
class Customers(BaseApi): """This represents the ``Customers`` Endpoint. The following aspects are implemented: * `List Customers <http://developer.helpscout.net/help-desk-api/customers/list/>`_ (:func:`helpscout.apis.customers.Customers.list`) * `Search Customers <http://developer.helpscout.net/help-desk-api/search/customers/>`_ (:func:`helpscout.apis.customers.Customers.search`) * `Get Customer <http://developer.helpscout.net/help-desk-api/customers/get/>`_ (:func:`helpscout.apis.customers.Customers.get`) * `Create Customer <http://developer.helpscout.net/help-desk-api/customers/create/>`_ (:func:`helpscout.apis.customers.Customers.create`) * `Update Customer <http://developer.helpscout.net/help-desk-api/customers/update/>`_ (:func:`helpscout.apis.customers.Customers.update`) """ __object__ = Customer __endpoint__ = 'customers' __implements__ = ['create', 'get', 'update', 'search', 'list'] @classmethod def list(cls, session, first_name=None, last_name=None, email=None, modified_since=None): """List the customers. Customers can be filtered on any combination of first name, last name, email, and modifiedSince. Args: session (requests.sessions.Session): Authenticated session. first_name (str, optional): First name of customer. last_name (str, optional): Last name of customer. email (str, optional): Email address of customer. modified_since (datetime.datetime, optional): If modified after this date. Returns: RequestPaginator(output_type=helpscout.models.Customer): Customers iterator. """ return super(Customers, cls).list( session, data=cls.__object__.get_non_empty_vals({ 'firstName': first_name, 'lastName': last_name, 'email': email, 'modifiedSince': modified_since, }) ) @classmethod def search(cls, session, queries): """Search for a customer given a domain. Args: session (requests.sessions.Session): Authenticated session. queries (helpscout.models.Domain or iter): The queries for the domain. If a ``Domain`` object is provided, it will simply be returned. Otherwise, a ``Domain`` object will be generated from the complex queries. In this case, the queries should conform to the interface in :func:`helpscout.domain.Domain.from_tuple`. Returns: RequestPaginator(output_type=helpscout.models.SearchCustomer): SearchCustomer iterator. """ return super(Customers, cls).search(session, queries, SearchCustomer)
class Customers(BaseApi): '''This represents the ``Customers`` Endpoint. The following aspects are implemented: * `List Customers <http://developer.helpscout.net/help-desk-api/customers/list/>`_ (:func:`helpscout.apis.customers.Customers.list`) * `Search Customers <http://developer.helpscout.net/help-desk-api/search/customers/>`_ (:func:`helpscout.apis.customers.Customers.search`) * `Get Customer <http://developer.helpscout.net/help-desk-api/customers/get/>`_ (:func:`helpscout.apis.customers.Customers.get`) * `Create Customer <http://developer.helpscout.net/help-desk-api/customers/create/>`_ (:func:`helpscout.apis.customers.Customers.create`) * `Update Customer <http://developer.helpscout.net/help-desk-api/customers/update/>`_ (:func:`helpscout.apis.customers.Customers.update`) ''' @classmethod def list(cls, session, first_name=None, last_name=None, email=None, modified_since=None): '''List the customers. Customers can be filtered on any combination of first name, last name, email, and modifiedSince. Args: session (requests.sessions.Session): Authenticated session. first_name (str, optional): First name of customer. last_name (str, optional): Last name of customer. email (str, optional): Email address of customer. modified_since (datetime.datetime, optional): If modified after this date. Returns: RequestPaginator(output_type=helpscout.models.Customer): Customers iterator. ''' pass @classmethod def search(cls, session, queries): '''Search for a customer given a domain. Args: session (requests.sessions.Session): Authenticated session. queries (helpscout.models.Domain or iter): The queries for the domain. If a ``Domain`` object is provided, it will simply be returned. Otherwise, a ``Domain`` object will be generated from the complex queries. In this case, the queries should conform to the interface in :func:`helpscout.domain.Domain.from_tuple`. Returns: RequestPaginator(output_type=helpscout.models.SearchCustomer): SearchCustomer iterator. ''' pass
5
3
23
3
7
14
1
2.37
1
2
1
0
0
0
2
13
74
10
19
9
13
45
8
6
5
1
2
0
2
145,024
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/apis/mailboxes.py
helpscout.apis.mailboxes.Mailboxes
class Mailboxes(BaseApi): """This represents the ``Mailboxes`` Endpoint. The following aspects are implemented: * `List Mailboxes <http://developer.helpscout.net/help-desk-api/mailboxes/list/>`_ (:func:`helpscout.apis.mailboxes.Mailboxes.list`) * `Get Mailboxes <http://developer.helpscout.net/help-desk-api/mailboxes/get/>`_ (:func:`helpscout.apis.mailboxes.Mailboxes.get`) * `Get Folders <http://developer.helpscout.net/help-desk-api/mailboxes/folders/>`_ (:func:`helpscout.apis.mailboxes.Mailboxes.get_folders`) """ __object__ = Mailbox __endpoint__ = 'mailboxes' __implements__ = ['get', 'list'] @classmethod def list(cls, session): """List the mailboxes. Args: session (requests.sessions.Session): Authenticated session. Returns: RequestPaginator(output_type=helpscout.models.Mailbox): Mailboxes iterator. """ return cls('/mailboxes.json', session=session) @classmethod def get_folders(cls, session, mailbox_or_id): """List the folders for the mailbox. Args: mailbox_or_id (helpscout.models.Mailbox or int): Mailbox or the ID of the mailbox to get the folders for. Returns: RequestPaginator(output_type=helpscout.models.Folder): Folders iterator. """ if isinstance(mailbox_or_id, Mailbox): mailbox_or_id = mailbox_or_id.id return cls( '/mailboxes/%d/folders.json' % mailbox_or_id, session=session, out_type=Folder, )
class Mailboxes(BaseApi): '''This represents the ``Mailboxes`` Endpoint. The following aspects are implemented: * `List Mailboxes <http://developer.helpscout.net/help-desk-api/mailboxes/list/>`_ (:func:`helpscout.apis.mailboxes.Mailboxes.list`) * `Get Mailboxes <http://developer.helpscout.net/help-desk-api/mailboxes/get/>`_ (:func:`helpscout.apis.mailboxes.Mailboxes.get`) * `Get Folders <http://developer.helpscout.net/help-desk-api/mailboxes/folders/>`_ (:func:`helpscout.apis.mailboxes.Mailboxes.get_folders`) ''' @classmethod def list(cls, session): '''List the mailboxes. Args: session (requests.sessions.Session): Authenticated session. Returns: RequestPaginator(output_type=helpscout.models.Mailbox): Mailboxes iterator. ''' pass @classmethod def get_folders(cls, session, mailbox_or_id): '''List the folders for the mailbox. Args: mailbox_or_id (helpscout.models.Mailbox or int): Mailbox or the ID of the mailbox to get the folders for. Returns: RequestPaginator(output_type=helpscout.models.Folder): Folders iterator. ''' pass
5
3
15
2
5
8
2
1.69
1
2
2
0
0
0
2
13
52
9
16
8
11
27
10
6
7
2
2
1
3
145,025
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/apis/tags.py
helpscout.apis.tags.Tags
class Tags(BaseApi): """This represents the ``Tags`` Endpoint. The following aspects are implemented: * `List Tags <http://developer.helpscout.net/help-desk-api/tags/list/>`_ (:func:`helpscout.apis.tags.Tags.list`) """ __object__ = Tag __endpoint__ = 'tags' __implements__ = ['list']
class Tags(BaseApi): '''This represents the ``Tags`` Endpoint. The following aspects are implemented: * `List Tags <http://developer.helpscout.net/help-desk-api/tags/list/>`_ (:func:`helpscout.apis.tags.Tags.list`) ''' pass
1
1
0
0
0
0
0
1.5
1
0
0
0
0
0
0
11
13
3
4
4
3
6
4
4
3
0
2
0
0
145,026
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/apis/teams.py
helpscout.apis.teams.Teams
class Teams(BaseApi): """This represents the ``Teams`` Endpoint. The following aspects are implemented: * `List Teams <http://developer.helpscout.net/help-desk-api/teams/list/>`_ (:func:`helpscout.apis.teams.Teams.list`) * `Get Teams <http://developer.helpscout.net/help-desk-api/teams/get/>`_ (:func:`helpscout.apis.teams.Teams.get`) * `Get Team Members <http://developer.helpscout.net/help-desk-api/teams/team-members/>`_ (:func:`helpscout.apis.teams.Teams.get_members`) """ __object__ = Person __implements__ = ['get', 'list'] @classmethod def get(cls, session, team_id): """Return a specific team. Args: session (requests.sessions.Session): Authenticated session. team_id (int): The ID of the team to get. Returns: helpscout.models.Person: A person singleton representing the team, if existing. Otherwise ``None``. """ return cls( '/teams/%d.json' % team_id, singleton=True, session=session, ) @classmethod def list(cls, session): """List the teams. Args: session (requests.sessions.Session): Authenticated session. Returns: RequestPaginator(output_type=helpscout.models.Person): Person iterator representing the teams. """ return cls('/teams.json', session=session) @classmethod def get_members(cls, session, team_or_id): """List the members for the team. Args: team_or_id (helpscout.models.Person or int): Team or the ID of the team to get the folders for. Returns: RequestPaginator(output_type=helpscout.models.Users): Users iterator. """ if isinstance(team_or_id, Person): team_or_id = team_or_id.id return cls( '/teams/%d/members.json' % team_or_id, session=session, out_type=User, )
class Teams(BaseApi): '''This represents the ``Teams`` Endpoint. The following aspects are implemented: * `List Teams <http://developer.helpscout.net/help-desk-api/teams/list/>`_ (:func:`helpscout.apis.teams.Teams.list`) * `Get Teams <http://developer.helpscout.net/help-desk-api/teams/get/>`_ (:func:`helpscout.apis.teams.Teams.get`) * `Get Team Members <http://developer.helpscout.net/help-desk-api/teams/team-members/>`_ (:func:`helpscout.apis.teams.Teams.get_members`) ''' @classmethod def get(cls, session, team_id): '''Return a specific team. Args: session (requests.sessions.Session): Authenticated session. team_id (int): The ID of the team to get. Returns: helpscout.models.Person: A person singleton representing the team, if existing. Otherwise ``None``. ''' pass @classmethod def list(cls, session): '''List the teams. Args: session (requests.sessions.Session): Authenticated session. Returns: RequestPaginator(output_type=helpscout.models.Person): Person iterator representing the teams. ''' pass @classmethod def get_members(cls, session, team_or_id): '''List the members for the team. Args: team_or_id (helpscout.models.Person or int): Team or the ID of the team to get the folders for. Returns: RequestPaginator(output_type=helpscout.models.Users): Users iterator. ''' pass
7
4
15
2
5
8
1
1.59
1
2
2
0
0
0
3
14
69
12
22
9
15
35
11
6
7
2
2
1
4
145,027
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/apis/users.py
helpscout.apis.users.Users
class Users(BaseApi): """This represents the ``Users`` Endpoint. The following aspects are implemented: * `List Users <http://developer.helpscout.net/help-desk-api/users/list/>`_ (:func:`helpscout.apis.users.Users.list`) * `Get Users <http://developer.helpscout.net/help-desk-api/users/get/>`_ (:func:`helpscout.apis.users.Users.get`) * `Get Current User <http://developer.helpscout.net/help-desk-api/users/get/>`_ (:func:`helpscout.apis.users.Users.get_me`) * `List Users By Mailbox <http://developer.helpscout.net/help-desk-api/users/mailbox-users/>`_ (:func:`helpscout.apis.users.Users.find_in_mailbox`) """ __object__ = User __endpoint__ = 'users' __implements__ = ['get', 'list'] @classmethod def get_me(cls, session): """Return the current user. Args: session (requests.sessions.Session): Authenticated session. Returns: helpscout.models.User: A user singleton """ return cls( '/users/me.json', singleton=True, session=session, ) @classmethod def find_in_mailbox(cls, session, mailbox_or_id): """Get the users that are associated to a Mailbox. Args: session (requests.sessions.Session): Authenticated session. mailbox_or_id (MailboxRef or int): Mailbox of the ID of the mailbox to get the folders for. Returns: RequestPaginator(output_type=helpscout.models.User): Users iterator. """ if hasattr(mailbox_or_id, 'id'): mailbox_or_id = mailbox_or_id.id return cls( '/mailboxes/%d/users.json' % mailbox_or_id, session=session, )
class Users(BaseApi): '''This represents the ``Users`` Endpoint. The following aspects are implemented: * `List Users <http://developer.helpscout.net/help-desk-api/users/list/>`_ (:func:`helpscout.apis.users.Users.list`) * `Get Users <http://developer.helpscout.net/help-desk-api/users/get/>`_ (:func:`helpscout.apis.users.Users.get`) * `Get Current User <http://developer.helpscout.net/help-desk-api/users/get/>`_ (:func:`helpscout.apis.users.Users.get_me`) * `List Users By Mailbox <http://developer.helpscout.net/help-desk-api/users/mailbox-users/>`_ (:func:`helpscout.apis.users.Users.find_in_mailbox`) ''' @classmethod def get_me(cls, session): '''Return the current user. Args: session (requests.sessions.Session): Authenticated session. Returns: helpscout.models.User: A user singleton ''' pass @classmethod def find_in_mailbox(cls, session, mailbox_or_id): '''Get the users that are associated to a Mailbox. Args: session (requests.sessions.Session): Authenticated session. mailbox_or_id (MailboxRef or int): Mailbox of the ID of the mailbox to get the folders for. Returns: RequestPaginator(output_type=helpscout.models.User): Users iterator. ''' pass
5
3
16
2
7
8
2
1.58
1
0
0
0
0
0
2
13
58
9
19
8
14
30
10
6
7
2
2
1
3
145,028
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/apis/web_hook.py
helpscout.apis.web_hook.WebHook
class WebHook(BaseApi): """This represents the ``WebHook`` Endpoint. The following aspects are implemented: * `Create Web Hook <http://developer.helpscout.net/help-desk-api/hooks/create/>`_ (:func:`helpscout.apis.web_hook.WebHook.create`) """ __object__ = WebHook @classmethod def create(cls, session, web_hook): """Create a web hook. Note that creating a new web hook will overwrite the web hook that is already configured for this company. There is also no way to programmatically determine if a web hook already exists for the company. This is a limitation of the HelpScout API and cannot be circumvented. Args: session (requests.sessions.Session): Authenticated session. web_hook (helpscout.models.WebHook): The web hook to be created. Returns: bool: ``True`` if the creation was a success. Errors otherwise. """ cls( '/hooks.json', data=web_hook.to_api(), request_type=RequestPaginator.POST, session=session, ) return True
class WebHook(BaseApi): '''This represents the ``WebHook`` Endpoint. The following aspects are implemented: * `Create Web Hook <http://developer.helpscout.net/help-desk-api/hooks/create/>`_ (:func:`helpscout.apis.web_hook.WebHook.create`) ''' @classmethod def create(cls, session, web_hook): '''Create a web hook. Note that creating a new web hook will overwrite the web hook that is already configured for this company. There is also no way to programmatically determine if a web hook already exists for the company. This is a limitation of the HelpScout API and cannot be circumvented. Args: session (requests.sessions.Session): Authenticated session. web_hook (helpscout.models.WebHook): The web hook to be created. Returns: bool: ``True`` if the creation was a success. Errors otherwise. ''' pass
3
2
23
3
8
12
1
1.64
1
1
1
0
0
0
1
12
36
7
11
4
8
18
5
3
3
1
2
0
1
145,029
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/auth_proxy.py
helpscout.auth_proxy.AuthProxy
class AuthProxy(object): """This object acts as a transparent authentication proxy for the API. This is required because the API objects are naive of the authentication that is setup in ``HelpScout``, and all of the API interface methods are ``classmethods`` because they are instantiating. """ # These methods will not pass through to ``proxy_class``. METHOD_NO_PROXY = [ 'auth_proxy', ] def __init__(self, session, proxy_class): """Instantiate an API Authentication Proxy. Args: auth (requests.Session): Authenticated requests Session. proxy_class (type): A class implementing the ``BaseApi`` interface. """ assert isinstance(proxy_class, type) self.session = session self.proxy_class = proxy_class def __getattr__(self, item): """Override attribute getter to act as a proxy for``proxy_class``. If ``item`` is contained in ``METHOD_NO_PROXY``, it will not be proxied to the ``proxy_class`` and will instead return the attribute on this object. Args: item (str): Name of attribute to get. """ if item in self.METHOD_NO_PROXY: return super(AuthProxy, self).__getattr__(item) attr = getattr(self.proxy_class, item) if callable(attr): return self.auth_proxy(attr) def auth_proxy(self, method): """Authentication proxy for API requests. This is required because the API objects are naive of ``HelpScout``, so they would otherwise be unauthenticated. Args: method (callable): A method call that should be authenticated. It should accept a ``requests.Session`` as its first parameter, which should be used for the actual API call. Returns: mixed: The results of the authenticated callable. """ def _proxy(*args, **kwargs): """The actual proxy, which instantiates and authenticates the API. Args: *args (mixed): Args to send to class instantiation. **kwargs (mixed): Kwargs to send to class instantiation. Returns: mixed: The result of the authenticated callable. """ return method(self.session, *args, **kwargs) return _proxy
class AuthProxy(object): '''This object acts as a transparent authentication proxy for the API. This is required because the API objects are naive of the authentication that is setup in ``HelpScout``, and all of the API interface methods are ``classmethods`` because they are instantiating. ''' def __init__(self, session, proxy_class): '''Instantiate an API Authentication Proxy. Args: auth (requests.Session): Authenticated requests Session. proxy_class (type): A class implementing the ``BaseApi`` interface. ''' pass def __getattr__(self, item): '''Override attribute getter to act as a proxy for``proxy_class``. If ``item`` is contained in ``METHOD_NO_PROXY``, it will not be proxied to the ``proxy_class`` and will instead return the attribute on this object. Args: item (str): Name of attribute to get. ''' pass def auth_proxy(self, method): '''Authentication proxy for API requests. This is required because the API objects are naive of ``HelpScout``, so they would otherwise be unauthenticated. Args: method (callable): A method call that should be authenticated. It should accept a ``requests.Session`` as its first parameter, which should be used for the actual API call. Returns: mixed: The results of the authenticated callable. ''' pass def _proxy(*args, **kwargs): '''The actual proxy, which instantiates and authenticates the API. Args: *args (mixed): Args to send to class instantiation. **kwargs (mixed): Kwargs to send to class instantiation. Returns: mixed: The result of the authenticated callable. ''' pass
5
5
16
3
4
9
2
2
1
2
0
0
3
2
3
3
68
14
18
9
13
36
16
9
11
3
1
1
6
145,030
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/base_model.py
helpscout.base_model.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', ) @classmethod def from_api(cls, **kwargs): """Create a new instance from API arguments. This will switch camelCase keys into snake_case for instantiation. It will also identify any ``Instance`` or ``List`` properties, and instantiate the proper objects using the values. The end result being a fully Objectified and Pythonified API response. Returns: BaseModel: Instantiated model using the API values. """ vals = cls.get_non_empty_vals({ cls._to_snake_case(k): v for k, v in kwargs.items() }) remove = [] for attr, val in vals.items(): try: vals[attr] = cls._parse_property(attr, val) except HelpScoutValidationException: remove.append(attr) logger.info( 'Unexpected property received in API response', exc_info=True, ) for attr in remove: del vals[attr] return cls(**cls.get_non_empty_vals(vals)) def get(self, key, default=None): """Return the field indicated by the key, if present.""" try: return self.__getitem__(key) except KeyError: return default def to_api(self): """Return a dictionary to send to the API. Returns: dict: Mapping representing this object that can be sent to the API. """ vals = {} for attribute, attribute_type in self._props.items(): prop = getattr(self, attribute) vals[self._to_camel_case(attribute)] = self._to_api_value( attribute_type, prop, ) return vals def _to_api_value(self, attribute_type, value): """Return a parsed value for the API.""" if not value: return None if isinstance(attribute_type, properties.Instance): return value.to_api() if isinstance(attribute_type, properties.List): return self._parse_api_value_list(value) return attribute_type.serialize(value) def _parse_api_value_list(self, values): """Return a list field compatible with the API.""" try: return [v.to_api() for v in values] # Not models except AttributeError: return list(values) @staticmethod def get_non_empty_vals(mapping): """Return the mapping without any ``None`` values.""" return { k: v for k, v in mapping.items() if v is not None } @classmethod def _parse_property(cls, name, value): """Parse a property received from the API into an internal object. Args: name (str): Name of the property on the object. value (mixed): The unparsed API value. Raises: HelpScoutValidationException: In the event that the property name is not found. Returns: mixed: A value compatible with the internal models. """ prop = cls._props.get(name) return_value = value if not prop: logger.debug( '"%s" with value "%s" is not a valid property for "%s".' % ( name, value, cls, ), ) return_value = None elif isinstance(prop, properties.Instance): return_value = prop.instance_class.from_api(**value) elif isinstance(prop, properties.List): return_value = cls._parse_property_list(prop, value) elif isinstance(prop, properties.Color): return_value = cls._parse_property_color(value) return return_value @staticmethod def _parse_property_color(value): """Parse a color property and return a valid value.""" if value == 'none': return 'lightgrey' return value @staticmethod def _parse_property_list(prop, value): """Parse a list property and return a list of the results.""" attributes = [] for v in value: try: attributes.append( prop.prop.instance_class.from_api(**v), ) except AttributeError: attributes.append(v) return attributes @staticmethod def _to_snake_case(string): """Return a snake cased version of the input string. Args: string (str): A camel cased string. Returns: str: A snake cased string. """ sub_string = r'\1_\2' string = REGEX_CAMEL_FIRST.sub(sub_string, string) return REGEX_CAMEL_SECOND.sub(sub_string, string).lower() @staticmethod def _to_camel_case(string): """Return a camel cased version of the input string. Args: string (str): A snake cased string. Returns: str: A camel cased string. """ components = string.split('_') return '%s%s' % ( components[0], ''.join(c.title() for c in components[1:]), ) def __getitem__(self, item): """Return the field indicated by the key, if present. This is better than using ``getattr`` because it will not expose any properties that are not meant to be fields for the object. Raises: KeyError: In the event that the field doesn't exist. """ self.__check_field(item) return getattr(self, item) def __setitem__(self, key, value): """Return the field indicated by the key, if present. This is better than using ``getattr`` because it will not expose any properties that are not meant to be fields for the object. Raises: KeyError: In the event that the field doesn't exist. """ self.__check_field(key) return setattr(self, key, value) def __check_field(self, key): """Raises a KeyError if the field doesn't exist.""" if not self._props.get(key): raise KeyError( 'The field "%s" does not exist on "%s"' % ( key, self.__class__.__name__, ), )
class BaseModel(properties.HasProperties): '''This is the model that all other models inherit from. It provides some convenience functions, and the standard ``id`` property. ''' @classmethod def from_api(cls, **kwargs): '''Create a new instance from API arguments. This will switch camelCase keys into snake_case for instantiation. It will also identify any ``Instance`` or ``List`` properties, and instantiate the proper objects using the values. The end result being a fully Objectified and Pythonified API response. Returns: BaseModel: Instantiated model using the API values. ''' pass def get(self, key, default=None): '''Return the field indicated by the key, if present.''' pass def to_api(self): '''Return a dictionary to send to the API. Returns: dict: Mapping representing this object that can be sent to the API. ''' pass def _to_api_value(self, attribute_type, value): '''Return a parsed value for the API.''' pass def _parse_api_value_list(self, values): '''Return a list field compatible with the API.''' pass @staticmethod def get_non_empty_vals(mapping): '''Return the mapping without any ``None`` values.''' pass @classmethod def _parse_property(cls, name, value): '''Parse a property received from the API into an internal object. Args: name (str): Name of the property on the object. value (mixed): The unparsed API value. Raises: HelpScoutValidationException: In the event that the property name is not found. Returns: mixed: A value compatible with the internal models. ''' pass @staticmethod def _parse_property_color(value): '''Parse a color property and return a valid value.''' pass @staticmethod def _parse_property_list(prop, value): '''Parse a list property and return a list of the results.''' pass @staticmethod def _to_snake_case(string): '''Return a snake cased version of the input string. Args: string (str): A camel cased string. Returns: str: A snake cased string. ''' pass @staticmethod def _to_camel_case(string): '''Return a camel cased version of the input string. Args: string (str): A snake cased string. Returns: str: A camel cased string. ''' pass def __getitem__(self, item): '''Return the field indicated by the key, if present. This is better than using ``getattr`` because it will not expose any properties that are not meant to be fields for the object. Raises: KeyError: In the event that the field doesn't exist. ''' pass def __setitem__(self, key, value): '''Return the field indicated by the key, if present. This is better than using ``getattr`` because it will not expose any properties that are not meant to be fields for the object. Raises: KeyError: In the event that the field doesn't exist. ''' pass def __check_field(self, key): '''Raises a KeyError if the field doesn't exist.''' pass
22
15
13
2
7
4
2
0.52
1
4
1
23
7
0
14
14
212
42
112
34
90
58
78
27
63
5
1
2
31
145,031
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/models/search_conversation.py
helpscout.models.search_conversation.SearchConversation
class SearchConversation(BaseConversation): """This represents a conversation as returned by search results.""" mailbox_id = properties.Integer( 'The ID of the mailbox this conversation is in.', required=True, ) customer_name = properties.String( 'Name of the customer this conversation is regarding.', required=True, ) customer_email = properties.String( 'Email address of the customer', required=True, ) has_attachments = properties.Bool( '``True`` when the conversation has at least one attachment.', )
class SearchConversation(BaseConversation): '''This represents a conversation as returned by search results.''' pass
1
1
0
0
0
0
0
0.06
1
0
0
0
0
0
0
14
18
1
16
5
15
1
5
5
4
0
3
0
0
145,032
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/domain/__init__.py
helpscout.domain.DomainCondition
class DomainCondition(properties.HasProperties): """This represents one condition of a domain query.""" field = properties.String( 'Field to search on', required=True, ) value = properties.String( 'String Value', required=True, ) @property def field_name(self): """Return the name of the API field.""" return BaseModel._to_camel_case(self.field) def __init__(self, field, value, **kwargs): """Initialize a new generic query condition. Args: field (str): Field name to search on. This should be the Pythonified name as in the internal models, not the name as provided in the API e.g. ``first_name`` for the Customer's first name instead of ``firstName``. value (mixed): The value of the field. """ return super(DomainCondition, self).__init__( field=field, value=value, **kwargs ) @classmethod def from_tuple(cls, query): """Create a condition from a query tuple. Args: query (tuple or list): Tuple or list that contains a query domain in the format of ``(field_name, field_value, field_value_to)``. ``field_value_to`` is only applicable in the case of a date search. Returns: DomainCondition: An instance of a domain condition. The specific type will depend on the data type of the first value provided in ``query``. """ field, query = query[0], query[1:] try: cls = TYPES[type(query[0])] except KeyError: # We just fallback to the base class if unknown type. pass return cls(field, *query) def __str__(self): """Return a string usable as a query part in an API request.""" return '%s:"%s"' % (self.field_name, self.value)
class DomainCondition(properties.HasProperties): '''This represents one condition of a domain query.''' @property def field_name(self): '''Return the name of the API field.''' pass def __init__(self, field, value, **kwargs): '''Initialize a new generic query condition. Args: field (str): Field name to search on. This should be the Pythonified name as in the internal models, not the name as provided in the API e.g. ``first_name`` for the Customer's first name instead of ``firstName``. value (mixed): The value of the field. ''' pass @classmethod def from_tuple(cls, query): '''Create a condition from a query tuple. Args: query (tuple or list): Tuple or list that contains a query domain in the format of ``(field_name, field_value, field_value_to)``. ``field_value_to`` is only applicable in the case of a date search. Returns: DomainCondition: An instance of a domain condition. The specific type will depend on the data type of the first value provided in ``query``. ''' pass def __str__(self): '''Return a string usable as a query part in an API request.''' pass
7
5
11
2
4
6
1
0.88
1
4
1
3
3
0
4
4
60
11
26
10
19
23
16
8
11
2
1
1
5
145,033
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/domain/__init__.py
helpscout.domain.DomainConditionBoolean
class DomainConditionBoolean(DomainCondition): """This represents an integer query.""" value = properties.Bool( 'Boolean Value', required=True, ) def __str__(self): """Return a string usable as a query part in an API request.""" value = 'true' if self.value else 'false' return '%s:%s' % (self.field_name, value)
class DomainConditionBoolean(DomainCondition): '''This represents an integer query.''' def __str__(self): '''Return a string usable as a query part in an API request.''' pass
2
2
4
0
3
1
2
0.25
1
0
0
0
1
0
1
5
12
2
8
4
6
2
5
4
3
2
2
0
2
145,034
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/domain/__init__.py
helpscout.domain.DomainConditionDateTime
class DomainConditionDateTime(DomainCondition): """This represents a date time query.""" value = properties.DateTime( 'Date From', required=True, ) value_to = properties.DateTime( 'Date To', ) def __init__(self, field, value_from, value_to=None): """Initialize a new datetime query condition. Args: field (str): Field name to search on. This should be the Pythonified name as in the internal models, not the name as provided in the API e.g. ``first_name`` for the Customer's first name instead of ``firstName``. value_from (date or datetime): The start value of the field. value_to (date or datetime, optional): The ending value for the field. If omitted, will search to now. """ return super(DomainConditionDateTime, self).__init__( field=field, value=value_from, value_to=value_to, ) def __str__(self): """Return a string usable as a query part in an API request.""" value_to = self.value_to.isoformat() if self.value_to else '*' return '%s:[%sZ TO %sZ]' % ( self.field_name, self.value.isoformat(), value_to, )
class DomainConditionDateTime(DomainCondition): '''This represents a date time query.''' def __init__(self, field, value_from, value_to=None): '''Initialize a new datetime query condition. Args: field (str): Field name to search on. This should be the Pythonified name as in the internal models, not the name as provided in the API e.g. ``first_name`` for the Customer's first name instead of ``firstName``. value_from (date or datetime): The start value of the field. value_to (date or datetime, optional): The ending value for the field. If omitted, will search to now. ''' pass def __str__(self): '''Return a string usable as a query part in an API request.''' pass
3
3
12
1
6
6
2
0.63
1
1
0
0
2
0
2
6
35
4
19
6
16
12
8
6
5
2
2
0
3
145,035
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/domain/__init__.py
helpscout.domain.DomainConditionInteger
class DomainConditionInteger(DomainCondition): """This represents an integer query.""" value = properties.Integer( 'Integer Value', required=True, ) def __str__(self): """Return a string usable as a query part in an API request.""" return '%s:%d' % (self.field_name, self.value)
class DomainConditionInteger(DomainCondition): '''This represents an integer query.''' def __str__(self): '''Return a string usable as a query part in an API request.''' pass
2
2
3
0
2
1
1
0.29
1
0
0
0
1
0
1
5
11
2
7
3
5
2
4
3
2
1
2
0
1
145,036
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/tests/test_model_person.py
helpscout.tests.test_model_person.TestPerson
class TestPerson(unittest.TestCase): def new_record(self, type): test_values = { 'firstName': 'Boo', 'lastName': 'Radley', 'type': type, } return Person.from_api(**test_values) def _setter_tester(self, customer_person_type, expected): person = self.new_record('customer') person.customer_person_type = customer_person_type self.assertEqual(person.type, expected) def test_customer_person_type_customer(self): """It should properly set customer_person_type to True when person type is 'customer'""" self.assertTrue(self.new_record('customer').customer_person_type) def test_customer_person_type_user(self): """It should properly set customer_person_type to False when person type is not 'customer'""" self.assertFalse(self.new_record('user').customer_person_type) def test_customer_person_type_setter_true(self): """It should properly set type to 'customer' when customer_person_type is set as True""" self._setter_tester(True, 'customer') def test_customer_person_type_setter_false(self): """It should properly set type to 'user' when customer_person_type is set as False""" self._setter_tester(False, 'user')
class TestPerson(unittest.TestCase): def new_record(self, type): pass def _setter_tester(self, customer_person_type, expected): pass def test_customer_person_type_customer(self): '''It should properly set customer_person_type to True when person type is 'customer'''' pass def test_customer_person_type_user(self): '''It should properly set customer_person_type to False when person type is not 'customer'''' pass def test_customer_person_type_setter_true(self): '''It should properly set type to 'customer' when customer_person_type is set as True''' pass def test_customer_person_type_setter_false(self): '''It should properly set type to 'user' when customer_person_type is set as False''' pass
7
4
5
0
3
1
1
0.4
1
1
1
0
6
0
6
78
34
6
20
9
13
8
16
9
9
1
2
0
6
145,037
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/tests/test_helpscout_web_hook_event.py
helpscout.tests.test_helpscout_web_hook_event.TestHelpScoutWebHookEvent
class TestHelpScoutWebHookEvent(unittest.TestCase): def setUp(self): super(TestHelpScoutWebHookEvent, self).setUp() self.event_type = 'customer.created' self.data = { 'gender': 'male', 'first_name': 'Test', 'last_name': 'Dude', 'type': 'customer', } self.api_data = { 'gender': self.data['gender'], 'firstName': self.data['first_name'], 'lastName': self.data['last_name'], 'type': self.data['type'], } def _validate_record(self, record): self.assertIsInstance(record.record, Customer) for key, val in self.data.items(): self.assertEqual(getattr(record.record, key), val) def test_record_from_data(self): """It should create a correct record from the API data.""" self._validate_record( HelpScoutWebHookEvent( event_type=self.event_type, record=self.api_data, ), ) def test_record_from_record(self): """It should pass through a pre-existing record.""" record = Customer(**self.data) self._validate_record( HelpScoutWebHookEvent( event_type=self.event_type, record=record, ), )
class TestHelpScoutWebHookEvent(unittest.TestCase): def setUp(self): pass def _validate_record(self, record): pass def test_record_from_data(self): '''It should create a correct record from the API data.''' pass def test_record_from_record(self): '''It should pass through a pre-existing record.''' pass
5
2
9
0
8
1
1
0.06
1
2
1
0
4
3
4
76
39
4
33
10
28
2
15
10
10
2
2
1
5
145,038
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/tests/test_helpscout_web_hook.py
helpscout.tests.test_helpscout_web_hook.TestHelpScoutWebHook
class TestHelpScoutWebHook(unittest.TestCase): def setUp(self): super(TestHelpScoutWebHook, self).setUp() self.data_str = '{"firstName":"Jackie","lastName":"Chan",' \ '"email":"jackie.chan@somewhere.com",' \ '"gender":"male"}' self.data = json.loads(self.data_str) self.signature = '\n2iFmnzC8SCNVF/iNiMnSe19yceU=\n' self.bad_signature = '4+kjl2zB5OwZZjHznSTkD1/J208=' self.hook = HelpScoutWebHook(secret_key='your secret key') def test_validate_signature_valid(self): """It should return True for valid signature.""" self.assertTrue( self.hook.validate_signature(self.signature, self.data_str), ) def test_validate_signature_invalid(self): """It should return False for invalid signature.""" self.assertFalse( self.hook.validate_signature(self.bad_signature, self.data_str), ) def test_receive_str_invalid(self): """It should raise on invalid signature from data string.""" with self.assertRaises(HelpScoutSecurityException): self.hook.receive(None, self.signature, '{"nope": "1"}') def test_receive_returns_event(self): """Valid receive should return instantiated web hook event.""" self.assertIsInstance( self.hook.receive( 'customer.created', self.signature, self.data_str, ), HelpScoutWebHookEvent, ) def test_create(self): """It should pass self through to the WebHook endpoint create.""" helpscout = mock.MagicMock() self.hook.helpscout = helpscout res = self.hook.create() helpscout.WebHook.create.assert_called_once_with(self.hook) self.assertEqual(res, helpscout.WebHook.create())
class TestHelpScoutWebHook(unittest.TestCase): def setUp(self): pass def test_validate_signature_valid(self): '''It should return True for valid signature.''' pass def test_validate_signature_invalid(self): '''It should return False for invalid signature.''' pass def test_receive_str_invalid(self): '''It should raise on invalid signature from data string.''' pass def test_receive_returns_event(self): '''Valid receive should return instantiated web hook event.''' pass def test_create(self): '''It should pass self through to the WebHook endpoint create.''' pass
7
5
6
0
5
1
1
0.15
1
4
3
0
6
5
6
78
45
7
33
14
26
5
23
14
16
1
2
1
6
145,039
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/tests/test_helpscout.py
helpscout.tests.test_helpscout.TestHelpScout
class TestHelpScout(unittest.TestCase): API_KEY = 'test key' def setUp(self): super(TestHelpScout, self).setUp() self.hs = HelpScout(self.API_KEY) def test_init_session(self): """It should build a session with the proper authentication.""" self.assertEqual(self.hs.session.auth.username, self.API_KEY) def test_load_apis(self): """It should load all available APIs.""" self.assertEqual(len(self.hs.__apis__), len(all_apis)) def test_api_instance_attributes(self): """It should properly set all of the API instance attributes.""" for api_name, api in self.hs.__apis__.items(): self.assertEqual(getattr(self.hs, api_name), api) def test_api_auth_proxy(self): """It should wrap the APIs in an AuthProxy.""" for api in self.hs.__apis__.values(): self.assertIsInstance(api, AuthProxy)
class TestHelpScout(unittest.TestCase): def setUp(self): pass def test_init_session(self): '''It should build a session with the proper authentication.''' pass def test_load_apis(self): '''It should load all available APIs.''' pass def test_api_instance_attributes(self): '''It should properly set all of the API instance attributes.''' pass def test_api_auth_proxy(self): '''It should wrap the APIs in an AuthProxy.''' pass
6
4
3
0
3
1
1
0.27
1
3
2
0
5
1
5
77
25
6
15
10
9
4
15
10
9
2
2
1
7
145,040
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/models/search_customer.py
helpscout.models.search_customer.SearchCustomer
class SearchCustomer(Person): """This represents a customer as returned by a search.""" photo_type = properties.StringChoice( 'Type of photo.', choices=['unknown', 'gravatar', 'twitter', 'facebook', 'googleprofile', 'googleplus', 'linkedin', ], ) gender = properties.StringChoice( 'Gender of this customer.', choices=['female', 'male', 'unknown'], default='unknown', required=True, ) age = properties.String( 'Age (or age range) of this customer.', ) organization = properties.String( 'Company/Organization the customer identifies with.', ) job_title = properties.String( 'Job title at company/organization.', ) location = properties.String( 'Location', ) emails = properties.List( 'Email addresses for the customer.', prop=properties.String(''), )
class SearchCustomer(Person): '''This represents a customer as returned by a search.''' pass
1
1
0
0
0
0
0
0.03
1
0
0
2
0
0
0
17
36
1
34
8
33
1
8
8
7
0
3
0
0
145,041
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/models/social_profile.py
helpscout.models.social_profile.SocialProfile
class SocialProfile(BaseModel): value = properties.String( 'Username', required=True, ) type = properties.StringChoice( 'Type of social profile.', choices=['twitter', 'facebook', 'linkedin', 'aboutme', 'google', 'googleplus', 'tungleme', 'quora', 'foursquare', 'youtube', 'flickr', 'other', ], default='other', required=True, )
class SocialProfile(BaseModel): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
14
24
1
23
3
22
0
3
3
2
0
2
0
0
145,042
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/models/source.py
helpscout.models.source.Source
class Source(BaseModel): type = properties.StringChoice( 'The method from which this conversation (or thread) was created.', choices=['email', 'web', 'notification', 'emailfwd', 'api', 'chat'], default='api', required=True, ) via = properties.StringChoice( 'Indicates what type of entity this source represents (customer, ' 'user).', choices=['customer', 'user'], )
class Source(BaseModel): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
14
13
1
12
3
11
0
3
3
2
0
2
0
0
145,043
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/models/tag.py
helpscout.models.tag.Tag
class Tag(BaseModel): tag = properties.String( 'The tag value.', required=True, ) slug = properties.String( 'Slugified version of the tag value.', ) count = properties.Integer( 'The number of times the tag is used.', ) color = properties.Color( 'The tag color.', ) created_at = properties.DateTime( 'UTC time when this tag was created.', ) modified_at = properties.DateTime( 'UTC time when this tag was modified.', )
class Tag(BaseModel): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
14
21
1
20
7
19
0
7
7
6
0
2
0
0
145,044
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/models/thread.py
helpscout.models.thread.Thread
class Thread(BaseModel): assigned_to = properties.Instance( 'The Help Scout user assigned to this conversation.', instance_class=Person, ) status = properties.StringChoice( 'Status of the thread.', choices=['nochange', 'active', 'pending', 'closed', 'spam'], ) created_at = properties.DateTime( 'UTC time when this thread was created.', ) opened_at = properties.DateTime( 'UTC time when this thread was viewed by the customer. Only applies ' 'to threads with a ``type`` of message.', ) created_by = properties.Instance( 'The Person who created this thread. The ``type`` property will ' 'specify whether it was created by a ``user`` or a ``customer``.', instance_class=Person, ) source = properties.Instance( 'Origin of thread', instance_class=Source, ) action_type = properties.StringChoice( 'Describes an optional action associated with the line item.', choices=['movedFromMailbox', 'merged', 'imported', 'workflow', 'importedExternal', 'changedTicketCustomer', 'deletedTicket', 'restoredTicket', 'originalCreator', ], ) action_source_id = properties.Integer( 'Associated with the ``action_type`` property. \n\n' '* If ``action_type`` is ``movedFromMailbox``, this will be the id ' ' of the mailbox the conversation was moved from. \n' '* If ``action_type`` is ``merged``, this will be the id of the ' ' original conversation. \n' '* If ``action_type`` is ``imported``, this will be null. \n' '* If ``action_type`` is ``workflow``, this will be the id of the ' ' workflow that was run. \n', ) from_mailbox = properties.Instance( 'If the conversation was moved, this represents the MailboxRef from ' 'which it was moved.', instance_class=MailboxRef, ) type = properties.StringChoice( 'The type of thread. \n' 'A ``lineitem`` represents a change of state on the conversation. ' 'This could include, but not limited to, the conversation was ' 'assigned, the status changed, the conversation was moved from one ' 'mailbox to another, etc. A line item won\'t have a body, to/cc/bcc ' 'lists, or attachments. \n' 'When a conversation is forwarded, a new conversation is created to ' 'represent the forwarded conversation. \n' '``forwardparent ``is the type set on the thread of the original ' 'conversation that initiated the forward event. \n' '``forwardchild`` is the type set on the first thread of the new ' 'forwarded conversation.', choices=['lineitem', 'note', 'message', 'chat', 'customer', 'forwardparent', 'forwardchild', 'phone', ], ) state = properties.StringChoice( 'The state of the thread. \n' 'A state of ``underreview`` means the thread has been stopped by ' 'Traffic Cop and is waiting to be confirmed (or discarded) by the ' 'person that created the thread. \n' 'A state of ``hidden`` means the thread was hidden (or removed) from ' 'customer-facing emails.', choices=['published', 'draft', 'underreview', 'hidden'], ) customer = properties.Instance( 'If thread type is ``message``, this is the customer associated with ' 'the conversation. \n' 'If thread type is ``customer``, this is the the customer who ' 'initiated the thread.', instance_class=Person, ) body = properties.String( 'Body text', ) to = properties.List( 'Email to', prop=properties.String( 'Email Address', ), ) cc = properties.List( 'CC to', prop=properties.String( 'Email Address', ), ) bcc = properties.List( 'BCC to', prop=properties.String( 'Email Address', ), ) attachments = properties.List( 'Attachments', prop=Attachment, ) saved_reply_id = properties.Integer( 'ID of Saved reply that was used to create this Thread.', ) created_by_customer = properties.Bool( 'Equivalent to ``created_by.type == "customer"``.', )
class Thread(BaseModel): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
14
124
1
123
20
122
0
20
20
19
0
2
0
0
145,045
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/models/user.py
helpscout.models.user.User
class User(Person): role = properties.StringChoice( 'Role of this user.', choices=['owner', 'admin', 'user'], required=True, ) timezone = properties.String( 'Name of the user\'s time zone.', ) type = properties.StringChoice( 'The type of user.', choices=['user', 'team'], required=True, )
class User(Person): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
17
15
1
14
4
13
0
4
4
3
0
3
0
0
145,046
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/models/web_hook.py
helpscout.models.web_hook.WebHook
class WebHook(BaseModel): url = properties.String( 'The callback URL where Help Scout will post your webhook events. ' 'This is the script or location where you\'ll handle the data ' 'received from Help Scout.', required=True, ) secret_key = properties.String( 'A randomly-generated (by you) string of 40 characters or less used ' 'to create signatures for each webhook method. Help Scout uses this ' 'secret key to generate a signature for each webhook message. When ' 'the message is received at your callback URL, you can calculate a ' 'signature and compare to the one Help Scout sends. If the ' 'signatures match, you know it\'s from Help Scout.', required=True, ) events = properties.List( 'The events to subscribe to.', prop=event_type, )
class WebHook(BaseModel): pass
1
0
0
0
0
0
0
0
1
0
0
1
0
0
0
14
21
1
20
4
19
0
4
4
3
0
2
0
0
145,047
LasLabs/python-helpscout
LasLabs_python-helpscout/helpscout/models/web_hook_event.py
helpscout.models.web_hook_event.WebHookEvent
class WebHookEvent(BaseModel): event_type = event_type record = properties.Instance( 'The parsed data record that was received in the request.', instance_class=BaseModel, required=True, )
class WebHookEvent(BaseModel): pass
1
0
0
0
0
0
0
0
1
0
0
1
0
0
0
14
8
1
7
3
6
0
3
3
2
0
2
0
0