def __init__(self, *, state, data, group: Group): self._state = state self._data = CaseInsensitiveDict({ "body": None, "poster": None, "created": None, "updated": None }) self.group = group self._update(data)
def __init__(self, *, state: Session, data, group): self._state = state self._data = CaseInsensitiveDict({ "id": None, "name": None, "description": None, "rank": None, "membercount": None, "permissions": None, }) self._update(data) self.group = group
def __init__(self, *, state: Session, data): self._state = state self._data = CaseInsensitiveDict({ "id": None, "name": None, "description": None, "owner": None, "shout": None, "membercount": None, "isbuildersclubonly": None, "publicentryallowed": None, "islocked": None }) self._update(data)
def __init__(self, *, state: Session, data): self._state = state self._data = CaseInsensitiveDict({ "username": None, "name": None, "id": None, "created": None, "description": None, "status": None, "isBanned": None }) self._update(data) if self._data["username"] is None and self._data["id"] is None: raise UserIdentificationError("Username or Id must be specified in user data")
def getDownloadLinks(self): self.ServersDownloadURLs = CaseInsensitiveDict() try: self.WebDriver.get(Constants.BASE_URL + self.EpisodeURL) self.Title = self.WebDriver.find_element_by_class_name( Constants.CLASS_DIV_TITLE).text self.Title = HelperFunctions.transformFileName(self.Title) download_div_master = self.WebDriver.find_element_by_class_name( Constants.CLASS_DIV_DOWNLOAD_ANIME) anchor_elem = HelperFunctions.findAnchorElementHref( download_div_master) self.ResolvedURL = anchor_elem[Constants.IDF_HREF].strip() self.WebDriver.get(self.ResolvedURL) download_div_links = self.WebDriver.find_elements_by_class_name( Constants.CLASS_DIV_DOWNLOAD_VIA_SERVER) for download_link in download_div_links: download_anchor = HelperFunctions.findAnchorElementHref( download_link) server = Constants.REGEX_REPLACE_DOWNLOAD.sub( '', download_anchor.text).strip().strip('\n').strip() if server not in self.ServersDownloadURLs: self.ServersDownloadURLs[server] = [] self.ServersDownloadURLs[server].append(download_link) except Exception, e: print e
def test_compare(self): self.assertTrue({ "a": 1, "B": 2 } == CaseInsensitiveDict({ "A": 1, "b": 2 }))
def test_multiple(self): self.assertEqual({ 'a': 1, 'b': 2 }, dict(CaseInsensitiveDict({ "A": 1, "B": 2 }).items()))
def test_nested(self): self.assertEqual({ 'a': { 'a': 2 }, 'b': 2 }, dict(CaseInsensitiveDict({ "A": { "A": 2 }, "B": 2 }).items()))
def __init__(self, *, state: Session, data): self._state = state self._data = CaseInsensitiveDict({ "name": None, "description": None, "id": None, "productid": None, "created": None, "updated": None, "price": None, "assettypeid": None, "sales": None, "isforsale": None, "ispublicdomain": None, "islimited": None, "islimitedunique": None, "remaining": None, "serialnumber": None, "creator": None }) self._update(data)
def __init__(self, *, state: Session, data): self._state = state self._data = CaseInsensitiveDict({ "name": None, "description": None, "id": None, "rootplaceid": None, "created": None, "updated": None, "price": None, "sales": None, "creator": None, "allowedgearcategories": None, "playing": None, "visits": None, "maxplayers": None, "studioaccesstoapisallowed": None, "createvipserversallowed": None, "universeavatartype": None, "genre": None }) self._update(data)
class TestLowercaseDict(unittest.TestCase): def setUp(self): self.cid = CaseInsensitiveDict({"A": {"A": {"A": 3}}, "B": 2}) def test_blank_init(self): self.assertEqual({}, dict(CaseInsensitiveDict().items())) def test_empty(self): self.assertEqual({}, dict(CaseInsensitiveDict({}).items())) def test_small(self): self.assertEqual({'a': 1}, dict(CaseInsensitiveDict({"a": 1}).items())) def test_multiple(self): self.assertEqual({ 'a': 1, 'b': 2 }, dict(CaseInsensitiveDict({ "A": 1, "B": 2 }).items())) def test_nested(self): self.assertEqual({ 'a': { 'a': 2 }, 'b': 2 }, dict(CaseInsensitiveDict({ "A": { "A": 2 }, "B": 2 }).items())) def test_multi_nested(self): self.assertEqual({ 'a': { 'a': { 'a': 3 } }, 'b': 2 }, dict(CaseInsensitiveDict({ "A": { "A": { "A": 3 } }, "B": 2 }).items())) def test_get(self): self.assertEqual({'a': {'a': 3}}, dict(self.cid["A"].items())) def test_nested_get(self): self.assertEqual(3, self.cid["A"]["A"]["A"]) def test_get_low(self): self.assertEqual(2, self.cid["b"]) def test_has_a(self): self.assertTrue("A" in self.cid) def test_has_c(self): self.assertFalse("C" in self.cid) def test_del(self): cid = CaseInsensitiveDict({"a": 1}) del cid["a"] self.assertFalse("a" in cid) def test_set(self): cid = CaseInsensitiveDict() cid["a"] = 1 self.assertEqual({'a': 1}, dict(cid.items())) def test_nested_set(self): cid = CaseInsensitiveDict() cid["a"] = {"B": 2} self.assertEqual({'a': {'b': 2}}, dict(cid.items())) def test_iteration(self): self.assertEqual(["a", "b"], sorted([k for k in self.cid])) def test_has_key_a(self): self.assertTrue(self.cid.has_key("A")) self.assertTrue("A" in self.cid) def test_has_key_c(self): self.assertFalse(self.cid.has_key("C")) self.assertFalse("C" in self.cid) def test_get_method(self): self.assertEqual(2, self.cid.get("b")) def test_get_method_default(self): self.assertEqual(2, self.cid.get("b", 1)) def test_get_method_default_used(self): self.assertEqual(1, self.cid.get("C", 1)) def test_items(self): self.assertEqual([('a', { 'a': { 'a': 3 } }), ('b', 2)], sorted(self.cid.items(), key=lambda x: x[0])) def test_keys(self): self.assertEqual(["a", "b"], sorted(self.cid.keys())) def test_vals(self): # or is used because various versions of python are not consistent in order of dict conversion self.assertTrue([{ 'a': { 'a': 3 } }, 2] == self.cid.values() or [2, { 'a': { 'a': 3 } }] == self.cid.values()) def test_compare(self): self.assertTrue({ "a": 1, "B": 2 } == CaseInsensitiveDict({ "A": 1, "b": 2 })) def test_update(self): cid = CaseInsensitiveDict({"A": 1, "b": 2}) cid.update({"A": 2}) self.assertEquals({'a': 2, 'b': 2}, dict(cid.items())) def test_update_nested(self): cid = CaseInsensitiveDict({"A": 1, "b": 2}) cid.update({"A": {"C": 3}}) self.assertEquals({'a': {'c': 3}, 'b': 2}, dict(cid.items()))
def test_nested_set(self): cid = CaseInsensitiveDict() cid["a"] = {"B": 2} self.assertEqual({'a': {'b': 2}}, dict(cid.items()))
class TestLowercaseDict(unittest.TestCase): def setUp(self): self.cid = CaseInsensitiveDict({"A": {"A": {"A": 3}}, "B": 2}) def test_blank_init(self): self.assertEqual({}, dict(CaseInsensitiveDict().items())) def test_empty(self): self.assertEqual({}, dict(CaseInsensitiveDict({}).items())) def test_small(self): self.assertEqual({'a': 1}, dict(CaseInsensitiveDict({"a": 1}).items())) def test_multiple(self): self.assertEqual({'a': 1, 'b': 2}, dict(CaseInsensitiveDict({"A": 1, "B": 2}).items())) def test_nested(self): self.assertEqual({'a': {'a': 2}, 'b': 2}, dict(CaseInsensitiveDict({"A": {"A": 2}, "B": 2}).items())) def test_multi_nested(self): self.assertEqual({'a': {'a': {'a': 3}}, 'b': 2}, dict(CaseInsensitiveDict({"A": {"A": {"A": 3}}, "B": 2}).items())) def test_get(self): self.assertEqual({'a': {'a': 3}}, dict(self.cid["A"].items())) def test_nested_get(self): self.assertEqual(3, self.cid["A"]["A"]["A"]) def test_get_low(self): self.assertEqual(2, self.cid["b"]) def test_has_a(self): self.assertTrue("A" in self.cid) def test_has_c(self): self.assertFalse("C" in self.cid) def test_del(self): cid = CaseInsensitiveDict({"a": 1}) del cid["a"] self.assertFalse("a" in cid) def test_set(self): cid = CaseInsensitiveDict() cid["a"] = 1 self.assertEqual({'a': 1}, dict(cid.items())) def test_nested_set(self): cid = CaseInsensitiveDict() cid["a"] = {"B": 2} self.assertEqual({'a': {'b': 2}}, dict(cid.items())) def test_iteration(self): self.assertEqual(["a", "b"], sorted([k for k in self.cid])) def test_has_key_a(self): self.assertTrue(self.cid.has_key("A")) self.assertTrue("A" in self.cid) def test_has_key_c(self): self.assertFalse(self.cid.has_key("C")) self.assertFalse("C" in self.cid) def test_get_method(self): self.assertEqual(2, self.cid.get("b")) def test_get_method_default(self): self.assertEqual(2, self.cid.get("b", 1)) def test_get_method_default_used(self): self.assertEqual(1, self.cid.get("C", 1)) def test_items(self): self.assertEqual([('a', {'a': {'a': 3}}), ('b', 2)], sorted(self.cid.items(), key=lambda x: x[0])) def test_keys(self): self.assertEqual(["a", "b"], sorted(self.cid.keys())) def test_vals(self): # or is used because various versions of python are not consistent in order of dict conversion self.assertTrue([{'a': {'a': 3}}, 2] == self.cid.values() or [2, {'a': {'a': 3}}] == self.cid.values()) def test_compare(self): self.assertTrue({"a": 1, "B": 2} == CaseInsensitiveDict({"A": 1, "b": 2})) def test_update(self): cid = CaseInsensitiveDict({"A": 1, "b": 2}) cid.update({"A": 2}) self.assertEquals({'a': 2, 'b': 2}, dict(cid.items())) def test_update_nested(self): cid = CaseInsensitiveDict({"A": 1, "b": 2}) cid.update({"A": {"C": 3}}) self.assertEquals({'a': {'c': 3}, 'b': 2}, dict(cid.items()))
class TestCloudomateController(unittest.TestCase): class Price(object): def __init__(self, me): self.price = me price = 0 def test_child_account(self): self.cloudomate_settings = Settings.__init__ self.cloudomate_read = Settings.read_settings self.os_is_join = os.path.join self.PlebNetConfig = PlebNetConfig.__init__ self.PlebNetConfig_get = PlebNetConfig.get os.path.join = MagicMock() Settings.read_settings = MagicMock() Settings.__init__ = MagicMock(return_value=None) PlebNetConfig.__init__ = MagicMock(return_value=None) PlebNetConfig.get = MagicMock(return_value="test") # Test child_account with index cloudomate.child_account("1") os.path.join.assert_called_once() Settings.read_settings.assert_called_once() Settings.__init__.assert_called_once() PlebNetConfig.get.assert_not_called() # Test child_account without index cloudomate.child_account() PlebNetConfig.get.assert_called_once() os.path.join = self.os_is_join Settings.read_settings = self.cloudomate_read Settings.__init__ = self.cloudomate_settings PlebNetConfig.__init__ = self.PlebNetConfig PlebNetConfig.get = self.PlebNetConfig_get def test_vps_providers(self): r = cloudomate.get_vps_providers() assert len(r) > 0 def test_status(self): self.child_account = cloudomate.child_account self.provider = blueAngel.BlueAngelHost.get_status cloudomate.child_account = MagicMock() blueAngel.BlueAngelHost.get_status = MagicMock() assert cloudomate.status(blueAngel.BlueAngelHost) cloudomate.child_account = self.child_account blueAngel.BlueAngelHost.get_status = self.provider def test_get_ip(self): self.clientarea = ClientArea.__init__ self.clientarea_service = ClientArea.get_services self.clientarea_ip = ClientArea.get_ip self.logger_log = Logger.log ClientArea.__init__ = MagicMock(return_value=None) Logger.log = MagicMock() ClientArea.get_services = MagicMock() ClientArea.get_ip = MagicMock() cloudomate.get_ip(blueAngel.BlueAngelHost, 'testaccount') ClientArea.get_ip.assert_called_once() ClientArea.__init__ = self.clientarea Logger.log = self.logger_log ClientArea.get_services = self.clientarea_service ClientArea.get_ip = self.clientarea_ip def test_options(self): self.provider = blueAngel.BlueAngelHost.get_options blueAngel.BlueAngelHost.get_options = MagicMock() cloudomate.options(blueAngel.BlueAngelHost) blueAngel.BlueAngelHost.get_options.assert_called_once() blueAngel.BlueAngelHost.get_options = self.provider def test_get_network_fee(self): self.wallet_util = wallet_util.get_network_fee wallet_util.get_network_fee = MagicMock() cloudomate.get_network_fee() wallet_util.get_network_fee.assert_called_once() wallet_util.get_network_fee = self.wallet_util @mock.patch('plebnet.controllers.cloudomate_controller.get_vps_providers', return_value=CaseInsensitiveDict( {'blueangelhost': blueAngel.BlueAngelHost})) def test_pick_providers(self, mock1): self.vps = cloudomate.get_vps_providers self.get_gateway = blueAngel.BlueAngelHost.get_gateway self.estimate_price = Coinbase.Coinbase.estimate_price self.get_price = wallet_util.get_price self.get_fee = wallet_util.get_network_fee # cloudomate.get_vps_providers = MagicMock( # return_value=CaseInsensitiveDict({'blueangelhost': blueAngel.BlueAngelHost})) random.expovariate = MagicMock(return_value=0.55) blueAngel.BlueAngelHost.get_gateway = MagicMock() Coinbase.Coinbase.estimate_price = MagicMock() cloudomate.pick_option = MagicMock(return_value=[1, 2, 3]) wallet_util.get_price = MagicMock() wallet_util.get_network_fee = MagicMock() cloudomate.pick_provider(cloudomate.get_vps_providers()) blueAngel.BlueAngelHost.get_gateway.assert_called_once() cloudomate.get_vps_providers = self.vps blueAngel.BlueAngelHost.get_gateway = self.get_gateway Coinbase.Coinbase.estimate_price = self.estimate_price wallet_util.get_price = self.get_price wallet_util.get_network_fee = self.get_fee def test_pick_options_zero(self): self.options = cloudomate.options self.providers = cloudomate_providers.__init__ cloudomate.options = MagicMock() cloudomate_providers.__init__ = MagicMock() cloudomate.pick_option('BlueAngelHost') cloudomate.options.assert_called_once() cloudomate.options = self.options cloudomate_providers.__init__ = self.providers def test_pick_options(self): self.options = cloudomate.options self.providers_true = cloudomate_providers.__init__ self.linevast = linevast.LineVast self.logger = Logger.log cloudomate.options = MagicMock( return_value=[self.Price( 2), self.Price(5), self.Price(1)]) cloudomate_providers.__init__ = MagicMock() Logger.log = MagicMock() cloudomate.pick_option('BlueAngelHost') Logger.log.assert_called_once() cloudomate_providers.__init__ = self.providers_true cloudomate.options = self.options linevast.LineVast = self.linevast Logger.log = self.logger def test_calculate_price(self): self.options = cloudomate.options self.logger = Logger.log self.providers = cloudomate_providers.__init__ cloudomate.get_vps_option = MagicMock() Logger.log = MagicMock() cloudomate_providers.__init__ = MagicMock() cloudomate.calculate_price('BlueAngelHost', 'option') cloudomate.get_vps_option.assert_called_once() self.options = cloudomate.options = self.options Logger.log = self.logger cloudomate_providers.__init__ = self.providers def test_calculate_price_vpn(self): self.options = cloudomate.options self.logger = Logger.log self.providers = cloudomate_providers.__init__ cloudomate.options = MagicMock() Logger.log = MagicMock() cloudomate_providers.__init__ = MagicMock() cloudomate.calculate_price_vpn('azirevpn') cloudomate.options.assert_called_once() self.options = cloudomate.options = self.options Logger.log = self.logger cloudomate_providers.__init__ = self.providers def test_purchase_choice_failure(self): self.config = PlebNetConfig.get self.triblerwallet = TriblerWallet.__init__ self.settings = plebnet_settings.Init.wallets_testnet_created self.purchase = blueAngel.BlueAngelHost.purchase self.logger = Logger.warning PlebNetConfig.get = MagicMock(side_effect=self.side_effect) plebnet_settings.Init.wallets_testnet_created = MagicMock( return_value=None) TriblerWallet.__init__ = MagicMock(return_value=None) blueAngel.BlueAngelHost.purchase = MagicMock( side_effect=Exception("Purchase failed")) Logger.warning = MagicMock() self.assertEquals(cloudomate.purchase_choice(PlebNetConfig()), plebnet_settings.FAILURE) PlebNetConfig.get = self.config TriblerWallet.__init__ = self.triblerwallet plebnet_settings.Init.wallets_testnet_created = self.settings blueAngel.BlueAngelHost.purchase = self.purchase Logger.warning = self.logger def test_purchase_choice(self): self.config = PlebNetConfig.get self.triblerwallet = TriblerWallet.__init__ self.settings = plebnet_settings.Init.wallets_testnet_created self.purchase = blueAngel.BlueAngelHost.purchase self.logger = Logger.warning PlebNetConfig.get = MagicMock(side_effect=self.side_effect) plebnet_settings.Init.wallets_testnet_created = MagicMock( return_value=None) TriblerWallet.__init__ = MagicMock(return_value=None) blueAngel.BlueAngelHost.purchase = MagicMock(return_value=('Hash', 0)) Logger.warning = MagicMock() self.assertEquals(cloudomate.purchase_choice(PlebNetConfig()), plebnet_settings.SUCCESS) PlebNetConfig.get = self.config TriblerWallet.__init__ = self.triblerwallet plebnet_settings.Init.wallets_testnet_created = self.settings blueAngel.BlueAngelHost.purchase = self.purchase Logger.warning = self.logger def test_purchase_choice_error(self): self.config = PlebNetConfig.get self.triblerwallet = TriblerWallet.__init__ self.settings = plebnet_settings.Init.wallets_testnet_created self.purchase = blueAngel.BlueAngelHost.purchase self.logger = Logger.warning self.error = Logger.error self.issue = git_issuer.handle_error PlebNetConfig.get = MagicMock(side_effect=self.side_effect) plebnet_settings.Init.wallets_testnet_created = MagicMock( return_value=None) TriblerWallet.__init__ = MagicMock(return_value=None) blueAngel.BlueAngelHost.purchase = MagicMock(side_effect=Exception) Logger.warning = MagicMock() Logger.error = MagicMock() git_issuer.handle_error = MagicMock() self.assertEquals(cloudomate.purchase_choice(PlebNetConfig()), plebnet_settings.FAILURE) PlebNetConfig.get = self.config TriblerWallet.__init__ = self.triblerwallet plebnet_settings.Init.wallets_testnet_created = self.settings blueAngel.BlueAngelHost.purchase = self.purchase Logger.warning = self.logger Logger.error = self.error git_issuer.handle_error = self.issue def test_purchase_choice_vpn(self): self.config = PlebNetConfig.get self.triblerwallet = TriblerWallet.__init__ self.settings = plebnet_settings.Init.wallets_testnet_created self.purchase = azirevpn.AzireVpn.purchase self.logger = Logger.warning self.host = plebnet_settings.Init.vpn_host PlebNetConfig.get = MagicMock(side_effect=self.side_effect) plebnet_settings.Init.wallets_testnet_created = MagicMock( return_value=None) TriblerWallet.__init__ = MagicMock(return_value=None) azirevpn.AzireVpn.purchase = MagicMock(return_value=('Hash', 0)) Logger.warning = MagicMock() plebnet_settings.Init.vpn_host = MagicMock(return_value='AzireVPN') self.assertEquals(cloudomate.purchase_choice_vpn(PlebNetConfig()), plebnet_settings.SUCCESS) PlebNetConfig.get = self.config TriblerWallet.__init__ = self.triblerwallet plebnet_settings.Init.wallets_testnet_created = self.settings azirevpn.AzireVpn.purchase = self.purchase Logger.warning = self.logger plebnet_settings.Init.vpn_host = self.host def side_effect(type, value): if value == 'child_index': return 2 else: return ['BlueAngelHost', 0, 'test']
def test_update_nested(self): cid = CaseInsensitiveDict({"A": 1, "b": 2}) cid.update({"A": {"C": 3}}) self.assertEquals({'a': {'c': 3}, 'b': 2}, dict(cid.items()))
def test_set(self): cid = CaseInsensitiveDict() cid["a"] = 1 self.assertEqual({'a': 1}, dict(cid.items()))
def test_blank_init(self): self.assertEqual({}, dict(CaseInsensitiveDict().items()))
def _map_providers_to_dict(provider_list): return CaseInsensitiveDict( dict((provider.get_metadata()[0], provider) for provider in provider_list)) types = ["vps", "vpn"] providers = CaseInsensitiveDict({ "vps": _map_providers_to_dict([ BlueAngelHost, CCIHosting, CrownCloud, LineVast, Pulseservers, UndergroundPrivate, ]), "vpn": _map_providers_to_dict([ AzireVpn, ]) }) def execute(cmd=sys.argv[1:]): parser = ArgumentParser(description="Cloudomate") subparsers = parser.add_subparsers(dest="type") add_vps_parsers(subparsers) add_vpn_parsers(subparsers)
def test_update(self): cid = CaseInsensitiveDict({"A": 1, "b": 2}) cid.update({"A": 2}) self.assertEquals({'a': 2, 'b': 2}, dict(cid.items()))
class Asset(_BaseAsset): """ Represents a Roblox Asset. """ __slots__ = ("_data", "_state") def __init__(self, *, state: Session, data): self._state = state self._data = CaseInsensitiveDict({ "name": None, "description": None, "id": None, "productid": None, "created": None, "updated": None, "price": None, "assettypeid": None, "sales": None, "isforsale": None, "ispublicdomain": None, "islimited": None, "islimitedunique": None, "remaining": None, "serialnumber": None, "creator": None }) self._update(data) def __repr__(self): return "Asset({!r})".format(self._data["name"] or self._data["id"]) def __hash__(self): return self._data["id"] or -2 def __eq__(self, other): if not isinstance(other, Asset): return False return self._data["id"] == other._data["id"] def _update(self, data: dict): for k in list(data.keys()): data[k.lower()] = data[k] data.setdefault("price", data.get("priceinrobux")) data.setdefault("id", data.get("assetid")) data.setdefault("name", data.get("assetname")) self._data.update(data) async def _get_product_info(self): data = await self._state.product_info(self._data["id"]) self._update(data) @async_property @p_info("name") async def name(self): """|asyncprop| The asset's name. :rtype: str """ pass @async_property @p_info("description") async def description(self): """|asyncprop| The asset's description. :rtype: str """ pass @async_property @p_info("id") async def id(self): """|asyncprop| The asset's ID. :rtype: int """ pass @async_property async def type(self): """|asyncprop| The asset's type. :rtype: :class:`.AssetType` """ if self._data["assettypeid"] is None: await self._get_product_info() return AssetType(self._data["assettypeid"]) @async_property async def url(self): """|asyncprop| URL to the asset's page. :rtype: str """ safe_name = urlify(await self.name) return "https://roblox.com/library/{}/{}".format(await self.id, safe_name) @async_property @p_info("productid") async def product_id(self): """|asyncprop| The asset's product ID. :rtype: int """ pass @async_property async def created_at(self): """|asyncprop| Time at which the asset was created. :rtype: :class:`datetime.datetime` """ if self._data["created"] is None: await self._get_product_info() try: return maya.parse(self._data["created"]).datetime() except OSError: return None @async_cached_property async def updated_at(self): """|asyncprop| Time at which the asset was last updated. :rtype: :class:`datetime.datetime` """ if self._data["updated"] is None: await self._get_product_info() try: return maya.parse(self._data["updated"]).datetime() except OSError: return None @async_property @p_info("price", nocache=True) async def price(self): """|asyncprop| The asset's purchase price. :rtype: int """ pass @async_property @p_info("sales", nocache=True) async def sales(self): """|asyncprop| Number of sales the asset has. :rtype: int """ pass @async_property async def for_sale(self): """|asyncprop| Whether the asset can be purchased/taken. :rtype: bool """ if self._data["isforsale"] is None and self._data["ispublicdomain"] is None: await self._get_product_info() return self._data["isforsale"] or self._data["ispublicdomain"] @async_property async def creator(self): """|asyncprop| The asset's creator. :rtype: :class:`.User` """ if self._data["creator"] is None: await self._get_product_info() creator = self._data["creator"] if creator.get("CreatorType") == "User": return await self._state.client.get_user(username=creator["Name"]) @async_property async def favorites(self): """|asyncprop| Number of favorites the asset has. :rtype: int """ return await self._state.favorites_count(await self.id) @async_property async def is_favorited(self): """|asyncprop| Whether the client has favorited the asset. :rtype: bool """ model = await self._state.favorite_model(await self._state.client.user.id, await self.id) return False if model is None else True async def favorite(self): """ Favorites the asset. """ return await self._state.create_favorite(await self._state.client.user.id, await self.id) async def unfavorite(self): """ Unfavorites the asset. """ return await self._state.delete_favorite(await self._state.client.user.id, await self.id) async def toggle_favorite(self): """ Toggles the asset's favorite. """ if await self.is_favorited: return await self.unfavorite() else: return await self.favorite() async def purchase(self, expected_price: int = None): """ Purchases the asset from the client user. Args: expected_price: Price to check the asset against before purchasing. Asset will not be purchased if the current price doesn't match the expected price. """ expected_price = expected_price or await self.price expected_seller = await (await self.creator).id return await self._state.purchase_product(await self.product_id, expected_price, expected_seller) async def delete(self): """ Deletes the asset from the client user's inventory. """ return await self._state.delete_from_inventory(await self.id) async def download(self, path): file = open(path, "wb") await self._state.download_asset(await self.id, file) file.close()
class TestQTable(unittest.TestCase): qtable = {} providers = {} option = {} @mock.patch('plebnet.controllers.cloudomate_controller.get_vps_providers', return_value=CaseInsensitiveDict( {'blueangelhost': blueAngel.BlueAngelHost})) @mock.patch('plebnet.controllers.cloudomate_controller.options', return_value=[ VpsOption(name='Advanced', storage=2, cores=2, memory=2, bandwidth="mock", connection="1", price=100.0, purchase_url="mock"), VpsOption(name='Basic Plan', storage=2, cores=2, memory=2, bandwidth="mock", connection="1", price=10.0, purchase_url="mock") ]) def setUp(self, mock1, mock2): self.qtable = QTable() self.providers = cloudomate_controller.get_vps_providers() def tearDown(self): del self.qtable del self.providers @mock.patch('plebnet.controllers.cloudomate_controller.get_vps_providers', return_value=CaseInsensitiveDict( {'blueangelhost': blueAngel.BlueAngelHost})) @mock.patch('plebnet.controllers.cloudomate_controller.options', return_value=[ VpsOption(name='Advanced', storage=2, cores=2, memory=2, bandwidth="mock", connection="1", price=100.0, purchase_url="mock"), VpsOption(name='Basic Plan', storage=2, cores=2, memory=2, bandwidth="mock", connection="1", price=10.0, purchase_url="mock") ]) def test_init_providers(self, mock1, mock2): assert (len(self.qtable.providers_offers) == 0) self.qtable.init_providers_offers(self.providers) assert (len(self.qtable.providers_offers) > 0) @mock.patch('plebnet.controllers.cloudomate_controller.get_vps_providers', return_value=CaseInsensitiveDict( {'blueangelhost': blueAngel.BlueAngelHost})) @mock.patch('plebnet.controllers.cloudomate_controller.options', return_value=[ VpsOption(name='Advanced', storage=2, cores=2, memory=2, bandwidth="mock", connection="1", price=100.0, purchase_url="mock"), VpsOption(name='Basic Plan', storage=2, cores=2, memory=2, bandwidth="mock", connection="1", price=10.0, purchase_url="mock") ]) def test_init_qtable_and_environment(self, mock1, mock2): assert (len(self.qtable.environment) == 0) self.qtable.init_qtable_and_environment(self.providers) assert (len(self.qtable.environment) > 0) assert (len(self.qtable.qtable) > 0) @mock.patch('plebnet.controllers.cloudomate_controller.get_vps_providers', return_value=CaseInsensitiveDict( {'blueangelhost': blueAngel.BlueAngelHost})) @mock.patch('plebnet.controllers.cloudomate_controller.options', return_value=[ VpsOption(name='Advanced', storage=2, cores=2, memory=2, bandwidth="mock", connection="1", price=100.0, purchase_url="mock"), VpsOption(name='Basic Plan', storage=2, cores=2, memory=2, bandwidth="mock", connection="1", price=10.0, purchase_url="mock") ]) def test_calculate_measure(self, mock1, mock2): provider_offer = ProviderOffer(provider_name="mock provider", name="mock name", bandwidth=3, price=5, memory=2) assert (self.qtable.calculate_measure(provider_offer) == 0.024) @mock.patch('plebnet.controllers.cloudomate_controller.get_vps_providers', return_value=CaseInsensitiveDict( {'blueangelhost': blueAngel.BlueAngelHost})) @mock.patch('plebnet.controllers.cloudomate_controller.options', return_value=[ VpsOption(name='Advanced', storage=2, cores=2, memory=2, bandwidth="mock", connection="1", price=100.0, purchase_url="mock"), VpsOption(name='Basic Plan', storage=2, cores=2, memory=2, bandwidth="mock", connection="1", price=10.0, purchase_url="mock") ]) def test_calculate_measure_unmetric_bandwidth(self, mock1, mock2): self.qtable.init_qtable_and_environment(self.providers) assert (self.qtable.calculate_measure( self.qtable.providers_offers[1]) == 0.01) @mock.patch('plebnet.controllers.cloudomate_controller.get_vps_providers', return_value=CaseInsensitiveDict( {'blueangelhost': blueAngel.BlueAngelHost})) @mock.patch('plebnet.controllers.cloudomate_controller.options', return_value=[ VpsOption(name='Advanced', storage=2, cores=2, memory=2, bandwidth="mock", connection="1", price=100.0, purchase_url="mock"), VpsOption(name='Basic Plan', storage=2, cores=2, memory=2, bandwidth="mock", connection="1", price=10.0, purchase_url="mock") ]) def test_update_environment_positive(self, mock1, mock2): blue_angel_offers = cloudomate_controller.options( self.providers["blueangelhost"]) self.qtable.self_state = VPSState("blueangelhost", blue_angel_offers[0].name) self.qtable.init_qtable_and_environment(self.providers) environment_copy = copy.deepcopy(self.qtable.environment) vps_options_list = cloudomate_controller.options(self.providers) vps_option = vps_options_list[0] provider_offer_ID = str(self.providers.keys()[0]).lower() + "_" + str( vps_option.name).lower() provider_offer_ID_other = str( self.providers.keys()[0]).lower() + "_" + str( vps_options_list[1].name).lower() self.qtable.update_environment(provider_offer_ID, True, 0) assert (environment_copy != self.qtable.environment) assert (environment_copy[provider_offer_ID_other] [provider_offer_ID_other] == self.qtable. environment[provider_offer_ID_other][provider_offer_ID_other]) assert (environment_copy[provider_offer_ID][provider_offer_ID] < self.qtable.environment[provider_offer_ID][provider_offer_ID]) assert (self.qtable.environment[provider_offer_ID][provider_offer_ID] == 0.4) @mock.patch('plebnet.controllers.cloudomate_controller.get_vps_providers', return_value=CaseInsensitiveDict( {'blueangelhost': blueAngel.BlueAngelHost})) @mock.patch('plebnet.controllers.cloudomate_controller.options', return_value=[ VpsOption(name='Advanced', storage=2, cores=2, memory=2, bandwidth="mock", connection="1", price=100.0, purchase_url="mock"), VpsOption(name='Basic Plan', storage=2, cores=2, memory=2, bandwidth="mock", connection="1", price=10.0, purchase_url="mock") ]) def test_update_environment_negative(self, mock1, mock2): blue_angel_offers = cloudomate_controller.options( self.providers["blueangelhost"]) self.qtable.self_state = VPSState("blueangelhost", blue_angel_offers[0].name) self.qtable.init_qtable_and_environment(self.providers) environment_copy = copy.deepcopy(self.qtable.environment) vps_options_list = cloudomate_controller.options(self.providers) vps_option = vps_options_list[0] provider_offer_ID = str(self.providers.keys()[0]).lower() + "_" + str( vps_option.name).lower() provider_offer_ID_other = str( self.providers.keys()[0]).lower() + "_" + str( vps_options_list[1].name).lower() self.qtable.update_environment(provider_offer_ID, False, 0) assert (environment_copy != self.qtable.environment) assert (environment_copy[provider_offer_ID][provider_offer_ID] > self.qtable.environment[provider_offer_ID][provider_offer_ID]) assert (environment_copy[provider_offer_ID][provider_offer_ID_other] == self.qtable.environment[provider_offer_ID] [provider_offer_ID_other]) assert (self.qtable.environment[provider_offer_ID][provider_offer_ID] == -0.4) @mock.patch('plebnet.controllers.cloudomate_controller.get_vps_providers', return_value=CaseInsensitiveDict( {'blueangelhost': blueAngel.BlueAngelHost})) @mock.patch('plebnet.controllers.cloudomate_controller.options', return_value=[ VpsOption(name='Advanced', storage=2, cores=2, memory=2, bandwidth="mock", connection="1", price=100.0, purchase_url="mock"), VpsOption(name='Basic Plan', storage=2, cores=2, memory=2, bandwidth="mock", connection="1", price=10.0, purchase_url="mock") ]) def test_update_values_positive(self, mock1, mock2): blue_angel_offers = cloudomate_controller.options( self.providers["blueangelhost"]) self.qtable.self_state = VPSState("blueangelhost", blue_angel_offers[0].name) self.qtable.init_qtable_and_environment(self.providers) self.qtable.init_alpha_and_beta() qtable_copy = copy.deepcopy(self.qtable.qtable) vps_options_list = cloudomate_controller.options(self.providers) vps_option = vps_options_list[0] provider_offer_ID = str(self.providers.keys()[0]).lower() + "_" + str( vps_option.name).lower() provider_offer_ID_other = str( self.providers.keys()[0]).lower() + "_" + str( vps_options_list[1].name).lower() self.qtable.update_qtable([], provider_offer_ID, True, 0) assert (qtable_copy != self.qtable.qtable) assert (qtable_copy[provider_offer_ID_other][provider_offer_ID] < self.qtable.qtable[provider_offer_ID_other][provider_offer_ID]) assert (round( self.qtable.qtable[provider_offer_ID_other][provider_offer_ID], 2) == 0.64) @mock.patch('plebnet.controllers.cloudomate_controller.get_vps_providers', return_value=CaseInsensitiveDict( {'blueangelhost': blueAngel.BlueAngelHost})) @mock.patch('plebnet.controllers.cloudomate_controller.options', return_value=[ VpsOption(name='Advanced', storage=2, cores=2, memory=2, bandwidth="mock", connection="1", price=100.0, purchase_url="mock"), VpsOption(name='Basic Plan', storage=2, cores=2, memory=2, bandwidth="mock", connection="1", price=10.0, purchase_url="mock") ]) def test_update_qtable_from_remote_qtable(self, mock1, mock2): blue_angel_offers = cloudomate_controller.options( self.providers["blueangelhost"]) self.qtable.self_state = VPSState("blueangelhost", blue_angel_offers[0].name) self.qtable.init_qtable_and_environment(self.providers) self.qtable.init_alpha_and_beta() qtable2 = QTable() qtable2.self_state = VPSState("blueangelhost", blue_angel_offers[1].name) qtable2.init_qtable_and_environment(self.providers) qtable2.init_alpha_and_beta() vps_options_list = cloudomate_controller.options(self.providers) vps_option = vps_options_list[0] provider_offer_ID = str(self.providers.keys()[0]).lower() + "_" + str( vps_option.name).lower() provider_offer_ID_other = str( self.providers.keys()[0]).lower() + "_" + str( vps_options_list[1].name).lower() self.qtable.update_qtable([], provider_offer_ID_other, True, 0.5) self.qtable.set_self_state( VPSState("blueangelhost", blue_angel_offers[1].name)) qtable2.update_qtable([], provider_offer_ID_other, True, 0.6) qtable2.set_self_state( VPSState("blueangelhost", blue_angel_offers[1].name)) self.qtable.update_qtable([qtable2.qtable], provider_offer_ID, True, 0.3) assert (qtable2.qtable != self.qtable.qtable) assert (qtable2.qtable[provider_offer_ID_other][provider_offer_ID] < self.qtable.qtable[provider_offer_ID_other][provider_offer_ID]) @mock.patch('plebnet.controllers.cloudomate_controller.get_vps_providers', return_value=CaseInsensitiveDict( {'blueangelhost': blueAngel.BlueAngelHost})) @mock.patch('plebnet.controllers.cloudomate_controller.options', return_value=[ VpsOption(name='Advanced', storage=2, cores=2, memory=2, bandwidth="mock", connection="1", price=100.0, purchase_url="mock"), VpsOption(name='Basic Plan', storage=2, cores=2, memory=2, bandwidth="mock", connection="1", price=10.0, purchase_url="mock") ]) def test_init_alphatable(self, mock1, mock2): blue_angel_offers = cloudomate_controller.options( self.providers["blueangelhost"]) self.qtable.self_state = VPSState("blueangelhost", blue_angel_offers[0].name) self.qtable.init_qtable_and_environment(self.providers) self.qtable.init_alpha_and_beta() vps_options_list = cloudomate_controller.options(self.providers) vps_option = vps_options_list[0] provider_offer_ID = str(self.providers.keys()[0]).lower() + "_" + str( vps_option.name).lower() provider_offer_ID_other = str( self.providers.keys()[0]).lower() + "_" + str( vps_options_list[1].name).lower() assert (self.qtable.alphatable[provider_offer_ID_other] [provider_offer_ID] == 0.8) assert (self.qtable.betatable[provider_offer_ID_other] [provider_offer_ID] == 0.2) assert (self.qtable.number_of_updates[provider_offer_ID_other] [provider_offer_ID] == 0) @mock.patch('plebnet.controllers.cloudomate_controller.get_vps_providers', return_value=CaseInsensitiveDict( {'blueangelhost': blueAngel.BlueAngelHost})) @mock.patch('plebnet.controllers.cloudomate_controller.options', return_value=[ VpsOption(name='Advanced', storage=2, cores=2, memory=2, bandwidth="mock", connection="1", price=100.0, purchase_url="mock"), VpsOption(name='Basic Plan', storage=2, cores=2, memory=2, bandwidth="mock", connection="1", price=10.0, purchase_url="mock") ]) def test_update_values_negative(self, mock1, mock2): blue_angel_offers = cloudomate_controller.options( self.providers["blueangelhost"]) self.qtable.self_state = VPSState("blueangelhost", blue_angel_offers[0].name) self.qtable.init_qtable_and_environment(self.providers) self.qtable.init_alpha_and_beta() qtable_copy = copy.deepcopy(self.qtable.qtable) vps_options_list = cloudomate_controller.options(self.providers) vps_option = vps_options_list[1] provider_offer_ID = str(self.providers.keys()[0]).lower() + "_" + str( vps_option.name).lower() provider_offer_ID_other = str( self.providers.keys()[0]).lower() + "_" + str( vps_options_list[1].name).lower() self.qtable.update_qtable([], provider_offer_ID_other, False) assert (qtable_copy != self.qtable.qtable) assert (qtable_copy[provider_offer_ID_other][provider_offer_ID_other] > self.qtable.qtable[provider_offer_ID_other] [provider_offer_ID_other]) assert (round( self.qtable.qtable[provider_offer_ID_other][provider_offer_ID], 2) == -0.32) @mock.patch('plebnet.controllers.cloudomate_controller.get_vps_providers', return_value=CaseInsensitiveDict( {'blueangelhost': blueAngel.BlueAngelHost})) @mock.patch('plebnet.controllers.cloudomate_controller.options', return_value=[ VpsOption(name='Advanced', storage=2, cores=2, memory=2, bandwidth="mock", connection="1", price=100.0, purchase_url="mock"), VpsOption(name='Basic Plan', storage=2, cores=2, memory=2, bandwidth="mock", connection="1", price=10.0, purchase_url="mock") ]) def test_find_provider(self, mock1, mock2): self.qtable.init_qtable_and_environment(self.providers) self.qtable.set_self_state(VPSState("blueangelhost", "Advanced")) provider_name = self.qtable.find_provider("blueangelhost_basic plan") assert (provider_name == "blueangelhost") @mock.patch('plebnet.controllers.cloudomate_controller.get_vps_providers', return_value=CaseInsensitiveDict( {'blueangelhost': blueAngel.BlueAngelHost})) @mock.patch('plebnet.controllers.cloudomate_controller.options', return_value=[ VpsOption(name='Advanced', storage=2, cores=2, memory=2, bandwidth="mock", connection="1", price=100.0, purchase_url="mock"), VpsOption(name='Basic Plan', storage=2, cores=2, memory=2, bandwidth="mock", connection="1", price=10.0, purchase_url="mock") ]) def test_kth_score(self, mock1, mock2): self.qtable.init_qtable_and_environment(self.providers) self.qtable.set_self_state(VPSState("blueangelhost", "Advanced")) self.qtable.init_alpha_and_beta() vps_options_list = cloudomate_controller.options(self.providers) vps_option = vps_options_list[0] provider_offer_ID = str(self.providers.keys()[0]).lower() + "_" + str( vps_option.name).lower() self.qtable.update_qtable([], provider_offer_ID, True, 0) assert (self.qtable.get_kth_score(self.providers, 1) == 0) @mock.patch('plebnet.controllers.cloudomate_controller.get_vps_providers', return_value=CaseInsensitiveDict( {'blueangelhost': blueAngel.BlueAngelHost})) @mock.patch('plebnet.controllers.cloudomate_controller.options', return_value=[ VpsOption(name='Advanced', storage=2, cores=2, memory=2, bandwidth="mock", connection="1", price=100.0, purchase_url="mock"), VpsOption(name='Basic Plan', storage=2, cores=2, memory=2, bandwidth="mock", connection="1", price=10.0, purchase_url="mock") ]) def test_choose_k_option(self, mock1, mock2): self.qtable.init_qtable_and_environment(self.providers) self.qtable.set_self_state(VPSState("blueangelhost", "Advanced")) self.qtable.init_alpha_and_beta() vps_options_list = cloudomate_controller.options(self.providers) vps_option = vps_options_list[0] provider_offer_ID = str(self.providers.keys()[0]).lower() + "_" + str( vps_option.name).lower() self.qtable.update_qtable([], provider_offer_ID, True, 0) option = self.qtable.choose_k_option(self.providers, 0) assert (option["option_name"] == "Advanced") assert (option["price"] == 100.0) @mock.patch('plebnet.settings.plebnet_settings.Init.irc_nick', return_value="plebbot1") @mock.patch('plebnet.controllers.cloudomate_controller.get_vps_providers', return_value=CaseInsensitiveDict( {'blueangelhost': blueAngel.BlueAngelHost})) @mock.patch('plebnet.controllers.cloudomate_controller.options', return_value=[ VpsOption(name='Advanced', storage=2, cores=2, memory=2, bandwidth="mock", connection="1", price=100.0, purchase_url="mock"), VpsOption(name='Basic Plan', storage=2, cores=2, memory=2, bandwidth="mock", connection="1", price=10.0, purchase_url="mock") ]) def test_choose_option(self, mock1, mock2, mock3): self.qtable.init_qtable_and_environment(self.providers) self.qtable.set_self_state(VPSState("blueangelhost", "Advanced")) random.expovariate = MagicMock(return_value=0.55) option = self.qtable.choose_option(self.providers) assert (option["option_name"] == "Basic Plan") assert (option["price"] == 10.0) @mock.patch('plebnet.settings.plebnet_settings.Init.irc_nick', return_value="plebbot1") def test_create_initial_tree(self, mock1): self.qtable.set_self_state(VPSState("blueangelhost", "Advanced")) self.qtable.create_initial_tree() assert (self.qtable.tree == "plebbot1") def test_get_no_replications(self): self.qtable.tree = "plebbot1.2.3" self.assertEqual(self.qtable.get_no_replications(), 3) def get_ID(self, provider_offer): return str(provider_offer.provider_name).lower() + "_" + str( provider_offer.name).lower()
bandwidth="mock", connection="1", price=10.5, purchase_url="mock"), VpsOption(name='Option 4', storage=2, cores=2, memory=2, bandwidth="mock", connection="1", price=11.0, purchase_url="mock") ] vps_providers = CaseInsensitiveDict({ 'blueangelhost': blueAngel.BlueAngelHost, 'linevast': lineVast.LineVast }) class ProviderOffer: UNLIMITED_BANDWIDTH = 10 def __init__(self, provider_name="", offer_name="", bandwidth="", price=0, memory=0): self.provider_name = provider_name
All implemented providers, those commented out are not working for now. CCIHosting's and Pulseserver's gateway changed to CoinPayments and this is not implemented. CrownCloud manually checks orders and do not accept multiple variations of the same email. """ providers = CaseInsensitiveDict({ "vps": _map_providers_to_dict([ BlueAngelHost, CCIHosting, # CrownCloud, HostSailor, LibertyVPS, LineVast, OrangeWebsite, # Pulseservers, QHoster, RouterHosting, UndergroundPrivate, TwoSync, ProxHost ]), "vpn": _map_providers_to_dict([ AzireVpn, MullVad, ]) }) def execute(cmd=sys.argv[1:]): parser = ArgumentParser(description="Cloudomate")
def setUp(self): self.cid = CaseInsensitiveDict({"A": {"A": {"A": 3}}, "B": 2})
def test_del(self): cid = CaseInsensitiveDict({"a": 1}) del cid["a"] self.assertFalse("a" in cid)
class TestCore(unittest.TestCase): def test_create_wallet_testnet(self): self.settings = plebnet_settings.Init.wallets_testnet self.logger = logger.log self.wallet = wallet_controller.create_wallet self.wallet_created = plebnet_settings.Init.wallets_testnet_created self.initiated = plebnet_settings.Init.wallets_initiate_once self.write = plebnet_settings.write plebnet_settings.Init.wallets_testnet = MagicMock(return_value=True) logger.log = MagicMock() wallet_controller.create_wallet = MagicMock(return_value=True) plebnet_settings.Init.wallets_testnet_created = MagicMock() plebnet_settings.Init.wallets_initiate_once = MagicMock() plebnet_settings.write = MagicMock() Core.create_wallet() self.assertEqual(os.environ.get('TESTNET'), '1') os.environ['TESTNET'] = '0' plebnet_settings.Init.wallets_testnet = self.settings logger.log = self.logger wallet_controller.create_wallet = self.wallet plebnet_settings.Init.wallets_testnet_created = self.wallet_created plebnet_settings.Init.wallets_initiate_once = self.initiated plebnet_settings.write = self.write def test_create_wallet_bitcoin(self): self.settings = plebnet_settings.Init.wallets_testnet self.logger = logger.log self.wallet = wallet_controller.create_wallet self.initiated = plebnet_settings.Init.wallets_initiate_once self.write = plebnet_settings.setting.Settings.write plebnet_settings.Init.wallets_testnet = MagicMock(return_value=False) logger.log = MagicMock() wallet_controller.create_wallet = MagicMock(return_value=True) plebnet_settings.Init.wallets_initiate_once = MagicMock() plebnet_settings.setting.Settings.write = MagicMock() Core.create_wallet() plebnet_settings.Init.wallets_initiate_once.assert_called_once() plebnet_settings.setting.Settings.write.assert_called_once() plebnet_settings.Init.wallets_testnet = self.settings logger.log = self.logger wallet_controller.create_wallet = self.wallet plebnet_settings.Init.wallets_initiate_once = self.initiated plebnet_settings.setting.Settings.write = self.write def test_check_tribler_true(self): self.running = tribler_controller.running self.logger = logger.log tribler_controller.running = MagicMock(return_value=True) logger.log = MagicMock() assert Core.check_tribler() tribler_controller.running = self.running logger.log = self.logger def test_check_tribler_false(self): self.running = tribler_controller.running self.start = tribler_controller.start self.logger = logger.log tribler_controller.start = MagicMock() tribler_controller.running = MagicMock(return_value=False) logger.log = MagicMock() self.assertFalse(Core.check_tribler()) tribler_controller.running = self.running logger.log = self.logger tribler_controller.start = self.start def test_setup(self): self.logger = logger.log self.provider = cloudomate_controller.get_vps_providers self.settings = plebnet_settings.Init.wallets_testnet self.fake = fake_generator.generate_child_account self.irc_nic = plebnet_settings.Init.irc_nick self.irc_def = plebnet_settings.Init.irc_nick_def self.save = PlebNetConfig.save self.init_client = irc_handler.init_irc_client self.start_client = irc_handler.start_irc_client self.success = logger.success self.load = PlebNetConfig.load self.exit = plebnet_settings.Init.tribler_exitnode args = MagicMock() args.testnet = True logger.log = MagicMock() fake_generator.generate_child_account = MagicMock() plebnet_settings.Init.wallets_testnet = MagicMock() cloudomate_controller.get_vps_providers = MagicMock() plebnet_settings.Init.irc_nick = MagicMock() plebnet_settings.Init.irc_nick_def = MagicMock() PlebNetConfig.save = MagicMock() PlebNetConfig.load = MagicMock() irc_handler.init_irc_client = MagicMock() irc_handler.start_irc_client = MagicMock() logger.success = MagicMock() plebnet_settings.Init.tribler_exitnode = MagicMock() Core.setup(args) logger.success.assert_called_once() logger.log = self.logger cloudomate_controller.get_vps_providers = self.provider plebnet_settings.Init.wallets_testnet = self.settings fake_generator.generate_child_account = self.fake plebnet_settings.Init.irc_nick = self.irc_nic plebnet_settings.Init.irc_nick_def = self.irc_def PlebNetConfig.save = self.save PlebNetConfig.load = self.load irc_handler.init_irc_client = self.init_client irc_handler.start_irc_client = self.start_client logger.success = self.success plebnet_settings.Init.tribler_exitnode = self.exit @mock.patch('plebnet.agent.core.attempt_purchase') @mock.patch('plebnet.settings.plebnet_settings.Init.wallets_initiate_once', return_value=False) @mock.patch( 'plebnet.settings.plebnet_settings.Init.wallets_testnet_created', return_value=True) @mock.patch('plebnet.agent.core.check_tribler', return_value=False) @mock.patch('plebnet.agent.core.vpn_is_running', return_value=True) @mock.patch('plebnet.agent.core.create_wallet') @mock.patch('plebnet.agent.core.select_provider') @mock.patch('plebnet.agent.core.strategies') @mock.patch('plebnet.agent.core.install_vps') @mock.patch('plebnet.controllers.market_controller.has_matchmakers', return_value=True) @mock.patch('plebnet.agent.config.PlebNetConfig.load', return_value=False) def test_check(self, mock1, mock2, mock3, mock4, mock5, mock6, mock7, mock8, mock9, mock10, mock11): self.logger = logger.log logger.log = MagicMock() Core.strategies['test']().apply = MagicMock() Core.check() os.environ['TESTNET'] = '0' plebnet_settings.Init.wallets_testnet_created = MagicMock( return_value=False) Core.check_tribler = MagicMock(return_value=True) Core.check() Core.install_vps.assert_called_once() Core.strategies['test']().apply.assert_called_once() Core.create_wallet.assert_called_once() logger.log = self.logger @mock.patch('plebnet.controllers.cloudomate_controller.get_vps_providers', return_value=CaseInsensitiveDict( {'blueangelhost': blueAngel.BlueAngelHost})) @mock.patch('plebnet.controllers.cloudomate_controller.options', return_value=[ VpsOption(name='Advanced', storage=2, cores=2, memory=2, bandwidth="4.0", connection="1", price=100.0, purchase_url="mock"), VpsOption(name='Basic Plan', storage=2, cores=2, memory=2, bandwidth="1.0", connection="1", price=10.0, purchase_url="mock") ]) def test_attempt_purchase(self, mock1, mock2): self.log = logger.log self.testnet = plebnet_settings.Init.wallets_testnet self.get = PlebNetConfig.get self.get_balance = market_controller.get_balance self.calculate_price = cloudomate_controller.calculate_price self.purchase_choice = cloudomate_controller.purchase_choice self.set = PlebNetConfig.set self.save = PlebNetConfig.save self.vpn = Core.attempt_purchase_vpn self.new = PlebNetConfig.increment_child_index self.provider = cloudomate_controller.get_vps_providers self.fg = fake_generator.generate_child_account self.qtable = QTable() self.providers = cloudomate_controller.get_vps_providers() providers = cloudomate_controller.get_vps_providers() self.qtable.init_qtable_and_environment(providers) self.qtable.set_self_state(VPSState("blueangelhost", "Basic Plan")) logger.log = MagicMock() plebnet_settings.Init.wallets_testnet = MagicMock(return_value=False) PlebNetConfig.get = MagicMock( return_value=['blueangelhost', 'Basic Plan', 0]) market_controller.get_balance = MagicMock(return_value=100000000) Core.qtable = self.qtable Core.attempt_purchase_vpn = MagicMock(return_value=False) cloudomate_controller.calculate_price = MagicMock(return_value=0.01) cloudomate_controller.purchase_choice = MagicMock( return_value=plebnet_settings.SUCCESS) PlebNetConfig.set = MagicMock() PlebNetConfig.save = MagicMock() PlebNetConfig.increment_child_index = MagicMock() cloudomate_controller.get_vps_providers = MagicMock() fake_generator.generate_child_account = MagicMock() Core.config = PlebNetConfig qtable_copy = copy.deepcopy(Core.qtable.qtable) Core.attempt_purchase() self.assertLess( qtable_copy['blueangelhost_basic plan'] ['blueangelhost_basic plan'], Core.qtable.qtable['blueangelhost_basic plan'] ['blueangelhost_basic plan']) qtable_copy = copy.deepcopy(Core.qtable.qtable) cloudomate_controller.purchase_choice = MagicMock( return_value=plebnet_settings.FAILURE) Core.attempt_purchase() self.assertGreater( qtable_copy['blueangelhost_basic plan'] ['blueangelhost_basic plan'], Core.qtable.qtable['blueangelhost_basic plan'] ['blueangelhost_basic plan']) logger.log = self.log plebnet_settings.Init.wallets_testnet = self.testnet PlebNetConfig.get = self.get market_controller.get_balance = self.get_balance cloudomate_controller.calculate_price = self.calculate_price cloudomate_controller.purchase_choice = self.purchase_choice Core.attempt_purchase_vpn = self.vpn PlebNetConfig.set = self.set PlebNetConfig.save = self.save PlebNetConfig.increment_child_index = self.new cloudomate_controller.get_vps_providers = self.provider fake_generator.generate_child_account = self.fg def test_install_vps(self): self.ias = server_installer.install_available_servers server_installer.install_available_servers = MagicMock() Core.install_vps() server_installer.install_available_servers.assert_called_once() server_installer.install_available_servers = self.ias def test_attempt_purchase_vpn(self): self.vpnset = plebnet_settings.Init.vpn_host self.vpnpro = cloudomate_controller.get_vpn_providers self.wall = plebnet_settings.Init.wallets_testnet self.bal = market_controller.get_balance self.price = cloudomate_controller.calculate_price_vpn self.pur = cloudomate_controller.purchase_choice_vpn self.suc = logger.success self.log = logger.log self.err = logger.error cloudomate_controller.purchase_choice_vpn = MagicMock( return_value=plebnet_settings.SUCCESS) plebnet_settings.Init.vpn_host = MagicMock() cloudomate_controller.get_vpn_providers = MagicMock( return_value='String') plebnet_settings.Init.wallets_testnet = MagicMock(return_value=True) market_controller.get_balance = MagicMock(return_value=1100000) cloudomate_controller.calculate_price_vpn = MagicMock( return_value=0.01) logger.success = MagicMock() logger.log = MagicMock() logger.error = MagicMock() Core.attempt_purchase_vpn() logger.success.assert_called_once() cloudomate_controller.purchase_choice_vpn = MagicMock( return_value=plebnet_settings.FAILURE) plebnet_settings.Init.wallets_testnet = MagicMock(return_value=False) Core.attempt_purchase_vpn() logger.error.assert_called_once() plebnet_settings.Init.vpn_host = self.vpnset cloudomate_controller.get_vpn_providers = self.vpnpro plebnet_settings.Init.wallets_testnet = self.wall market_controller.get_balance = self.bal cloudomate_controller.calculate_price_vpn = self.price cloudomate_controller.purchase_choice_vpn = self.pur logger.success = self.suc logger.log = self.log logger.error = self.err def test_vpn_is_running(self): self.pid = plebnet_settings.Init.vpn_pid self.run = plebnet_settings.Init.vpn_running self.call = subprocess.call plebnet_settings.Init.vpn_pid = MagicMock(return_value='String') plebnet_settings.Init.vpn_running = MagicMock() subprocess.call = MagicMock(return_value=0) assert Core.vpn_is_running() subprocess.call = MagicMock(return_value=1) self.assertFalse(Core.vpn_is_running()) plebnet_settings.Init.vpn_pid = self.pid plebnet_settings.Init.vpn_running = self.run subprocess.call = self.call def test_check_vpn_install(self): self.vpn_installed = plebnet_settings.Init.vpn_installed self.log = logger.log self.ospath = os.path.join self.path = plebnet_settings.Init.vpn_config_path self.pre = plebnet_settings.Init.vpn_own_prefix self.cre = plebnet_settings.Init.vpn_credentials_name self.nam = plebnet_settings.Init.vpn_config_name self.lis = os.listdir self.isf = os.path.isfile self.civ = Core.install_vpn self.cpr = plebnet_settings.Init.vpn_child_prefix self.usr = os.path.expanduser self.vpn_running = Core.vpn_is_running plebnet_settings.Init.vpn_installed = MagicMock(return_value=True) logger.log = MagicMock() os.path.join = MagicMock(return_value='String') Core.vpn_is_running = MagicMock(return_value=True) plebnet_settings.Init.vpn_config_path = MagicMock() plebnet_settings.Init.vpn_own_prefix = MagicMock() plebnet_settings.Init.vpn_credentials_name = MagicMock( return_value='cred_name') plebnet_settings.Init.vpn_config_name = MagicMock( return_value='config_name') os.listdir = MagicMock(return_value=[]) os.path.isfile = MagicMock(return_value=False) os.path.expanduser = MagicMock() assert Core.check_vpn_install() Core.vpn_is_running = MagicMock(return_value=False) os.path.isfile = MagicMock(return_value=True) Core.install_vpn = MagicMock(return_value=False) plebnet_settings.Init.vpn_installed = MagicMock(return_value=False) self.assertFalse(Core.check_vpn_install()) Core.install_vpn = MagicMock(return_value=True) assert Core.check_vpn_install() os.listdir = MagicMock( return_value=['child_pre0config_name', 'child_pre0cred_name']) plebnet_settings.Init.vpn_child_prefix = MagicMock( return_value='child_pre') os.path.isfile = MagicMock(return_value=False) self.assertFalse(Core.check_vpn_install()) plebnet_settings.Init.vpn_installed = self.vpn_installed logger.log = self.log os.path.join = self.ospath plebnet_settings.Init.vpn_config_path = self.path plebnet_settings.Init.vpn_own_prefix = self.pre plebnet_settings.Init.vpn_credentials_name = self.cre plebnet_settings.Init.vpn_config_name = self.nam os.listdir = self.lis os.path.isfile = self.isf Core.install_vpn = self.civ plebnet_settings.Init.vpn_child_prefix = self.cpr os.path.expanduser = self.usr Core.vpn_is_running = self.vpn_running
def test_small(self): self.assertEqual({'a': 1}, dict(CaseInsensitiveDict({"a": 1}).items()))
class PgEnvironment(object): _environments: Dict[str, 'PgEnvironment'] = CaseInsensitiveDict() def __init__(self, host: str = 'localhost', port: int = 5432, database: str = None, user: str = None, password: str = None): self._host = host self._port = port self._database = database self._user = user self._password = password @property def host(self) -> str: return self._user @property def port(self) -> int: return self._port @property def database(self) -> str: return self._database @property def user(self) -> str: return self._user @property def password(self) -> str: return self._password @staticmethod def initialize(key: str = 'default', host: str = 'localhost', port: int = 5432, database: str = None, user: str = None, password: str = None) -> 'PgEnvironment': if key in PgEnvironment._environments: raise KeyError( "The {key} environment has already been initialized.".format( key=key)) else: # Initialize the environment. env = PgEnvironment(host=host, port=port, database=database, user=user, password=password) # Update the dictionary. PgEnvironment._environments[env] = env # Return the new environment to the caller. return env @staticmethod def instance(key: str = 'default') -> 'PgEnvironment': """ Get the current environment instance. :return: the current environment instance """ return PgEnvironment._environments[key]
class BaseUser(_BaseUser): # _BaseUser): __slots__ = ("_data", "_state") def __init__(self, *, state: Session, data): self._state = state self._data = CaseInsensitiveDict({ "username": None, "name": None, "id": None, "created": None, "description": None, "status": None, "isBanned": None }) self._update(data) if self._data["username"] is None and self._data["id"] is None: raise UserIdentificationError("Username or Id must be specified in user data") # def __str__(self): # return self._data["username"] or str(self._data["id"] or "") def __repr__(self): return "User({!r})".format(self._data["username"] or self._data["id"]) def __hash__(self): return self._data["id"] or -2 def __eq__(self, other): if not isinstance(other, BaseUser): return False if self._data["id"] == other._data["id"] and self._data["id"] is not None: return True elif (self._data["username"] is not None) and (other._data["username"] is not None): return self._data["username"].lower() == other._data["username"].lower() else: return False def _update(self, data): data["username"] = data.get("username", data.get("name", data.get("displayname", data.get("displayName")))) data["id"] = data.get("id", data.get("userid", data.get("userId"))) self._data.update(data) async def _get_profile_data(self): new = await self._state.get_user_data(await self.id) self._update(new) @async_cached_property async def id(self): """|asyncprop| The user's ID. :rtype: int """ if self._data["id"] is None: new = await self._state.get_by_username(self._data["username"]) self._update(new) return self._data["id"] @async_cached_property async def username(self): """|asyncprop| The user's username. :rtype: str """ if self._data["username"] is None: await self._get_profile_data() return self._data["username"] or self._data["name"] @async_cached_property async def url(self): """|asyncprop| The user's profile URL. :rtype: str """ return "https://www.roblox.com/users/{}/profile".format(await self.id) @async_property async def description(self): """|asyncprop| The user's profile description. :rtype: str """ if self._data["description"] is None: await self._get_profile_data() return self._data["description"] async def status(self): """|coro| The user's current status message. :rtype: str """ self._update(await self._state.user_status(await self.id)) return self._data["status"] @async_cached_property async def created_at(self): """|asyncprop| :class:`datetime.datetime` at which the user was created. """ if self._data["created"] is None: await self._get_profile_data() try: return maya.parse(self._data["created"]).datetime() except OSError: return None @async_property async def is_banned(self): """|asyncprop| Whether the user is currently banned. :rtype: bool """ if self._data["isBanned"] is None: await self._get_profile_data() return self._data["isBanned"] @async_property async def is_premium(self): """|asyncprop| Whether the user is currently a premium member. :rtype: bool """ return await self._state.is_premium(await self.id) async def _friends_iter(self): data = await self._state.get_user_friends(await self.id) return [User(state=self._state, data=friend) for friend in data] @property def friends(self): """ :class:`.AsyncIterator` for this user's friends. Yields: :class:`User` """ async def gen(): for friend in await self._friends_iter(): yield friend return AsyncIterator(gen=gen(), state=self._state) async def is_friends(self, other: User = None): """|coro| Checks whether this user is friends with another user or the client user. Args: other: User to check friendship with. If not specified, this will be the client user. """ if self == other or not isinstance(other, BaseUser): return False if other: # can't use API endpoint on user other than client await other._get_profile_data() return other in await self._friends_iter() other = other or self._state.client.user statuses = await self._state.check_status(await other.id, await self.id) return statuses[0]["status"] == "Friends" @property def followers(self): """ :class:`.AsyncIterator` for user's followers. Yields: :class:`.User` """ return FollowerList(state=self._state, opts={"user": self}) @property def followings(self): """ :class:`.AsyncIterator` for user's followings. Yields: :class:`.User` """ return FollowingList(state=self._state, opts={"user": self}) following = followings @cached_property def inventory(self): """ :class:`.Inventory` for this user. """ return Inventory(state=self._state, opts={"user": self}) @property def games(self): """ :class:`.AsyncIterator` for this user's games. Yields: :class:`.Universe` """ access_filter = None async def gen(): async for data in self._state.get_user_games(await self.id, access_filter=str(access_filter) if access_filter else None): yield await self._state.client.get_universe(data["id"], data=data) return AsyncIterator(gen=gen())
def _map_providers_to_dict(provider_list): return CaseInsensitiveDict( dict((provider.get_metadata()[0], provider) for provider in provider_list))
def test_empty(self): self.assertEqual({}, dict(CaseInsensitiveDict({}).items()))