Exemplo n.º 1
0
 def test_rate_limitingcheck_isTrue_NonIndexError(self):
     api = Api()
     api.__xrls__ = 50
     nsinstance = api.get_world(shard=["TEST"], auto_load=False)
     ct = time()
     nsinstance.rltime = [(ct-(x)) for x in range(50)]
     self.assertTrue(nsinstance.ratelimitcheck(xrls=50))
Exemplo n.º 2
0
 def test_ratelimit_check_indexerror_returns_True(self):
     api = Api()
     api.__xrls__ = 50
     nsinstance = api.get_world(shard=["TEST"], auto_load=False)
     ct = time()
     nsinstance.rltime = [(ct-(x+31)) for x in range(50)]
     self.assertTrue(nsinstance.ratelimitcheck(xrls=50))
Exemplo n.º 3
0
    def test_ratelimiting_clear_raises_not_implmented(self):
        api = Api("AUTOMATED TESTING BY PYNATIONSTATES")

        ct = time()
        api.__rltime__ = [(ct+x) for x in range(55)]
        api.clear_ratelimit()
        self.assertEqual(len(api.__rltime__), 0)
Exemplo n.º 4
0
 def test_rate_limiting_check_Sleeps(self):
     api = Api()
     nsinstance = api.get_world(shard=["TEST"], auto_load=False)
     api.__xrls__ = 50
     ct = time()
     nsinstance.rltime = [(ct+x) for x in range(0)]
     # This is to assert that the RateLimitCatch isn't meaningless
     self.assertFalse(nsinstance.ratelimitcheck(xrls=50))
     # Tests that numattempts will raise this exception at zero
     nsinstance._load(numattempt=0, retry_after=0, sleep_for=0)
     # To assure that data was not requested, so the rate-limit will not be
     # broken
     self.assertTrue(nsinstance.has_data)
Exemplo n.º 5
0
 def test_rate_limiting_check_RaisesCatch_use_error_rl(self):
     api = Api()
     api.__xrls__ = 50
     nsinstance = api.get_world(shard=["TEST"], auto_load=False)
     nsinstance.__use_error_rl__ = True
     ct = time()
     nsinstance.rltime = [(ct+x) for x in range(0)]
     # This is to assert that the RateLimitCatch isn't meaningless
     self.assertFalse(nsinstance.ratelimitcheck(xrls=50))
     # Tests that numattempts will raise this exception at zero
     self.assertRaises(
         nationstates.core.exceptions.RateLimitCatch, nsinstance._load, numattempt=0, retry_after=0)
     # To assure that data was not requested, so the rate-limit will not be
     # broken
     self.assertFalse(nsinstance.has_data)
Exemplo n.º 6
0
class SessionWrapper():

    """
    This Class Wraps around Nationstates.Api
    """

    def __init__(self, user_agent):
        self.session = NSApi(user_agent=user_agent)

    def get(self, api, value, shard):
        return self.session.request(api, value=value, shard=list(shard) if shard else None, auto_load=False)
Exemplo n.º 7
0
 def __init__(self, bot):
     self.bot = bot
     self.settings = dataIO.load_json("data/nsapi/settings.json")
     self._api = Api()
Exemplo n.º 8
0
class NSApi:
    def __init__(self, bot):
        self.bot = bot
        self.settings = dataIO.load_json("data/nsapi/settings.json")
        self._api = Api()

    @commands.command(pass_context=True)
    @checks.is_owner()
    # API requests: 0; non-API requests: 0
    async def agent(self, ctx, *, agent=None):
        """Gets or sets the user agent for use with the NationStates API

        Use an informative agent, like an email address, nation name, or both.
        Contact the cog creator (and unload this cog) if you get any relevant
        emails or telegrams."""
        if not agent:
            await self.bot.whisper("```User agent: {}```".format(
                self.settings["AGENT"]))
            await send_cmd_help(ctx)
        else:
            self.settings["AGENT"] = agent
            dataIO.save_json("data/nsapi/settings.json", self.settings)
            await self.bot.say("```New user agent: {}```".format(
                self.settings["AGENT"]))

    def check_agent(self):
        if not self.settings["AGENT"]:
            raise RuntimeError(
                "User agent is not yet set! Set it with \"[p]agent\" first.")

    def shard(self, shard: str, **kwargs):
        return Shard(shard, **kwargs)

    async def api(self, *shards, **kwargs):
        self.check_agent()
        args = {
            "shard": list(shards),
            "user_agent": self.settings["AGENT"],
            "auto_load": True,
            "version": "9",
            "use_error_xrls": True,
            "use_error_rl": True
        }
        try:
            if not kwargs:
                args["api"] = "world"
            elif len(kwargs) != 1:
                raise TypeError("Multiple **kwargs: {}".format(kwargs))
            else:
                nation = kwargs.pop("nation", None)
                region = kwargs.pop("region", None)
                council = kwargs.pop("council", None)
                if kwargs:
                    raise TypeError("Unexpected **kwargs: {}".format(kwargs))
                if nation:
                    args.update(api="nation", value=nation)
                if region:
                    args.update(api="region", value=region)
                if council:
                    args.update(api="wa", value=council)
            part = partial(self._api.request, **args)
            try:
                ret = await wait_for(self.bot.loop.run_in_executor(None, part),
                                     timeout=10)
                return ret.collect()
            except TimeoutError:
                await self.bot.say("Error: Request timed out.")
                raise
        except NotFound as e:
            raise ValueError(*e.args) from e
        except RateLimitCatch as e:
            await self.bot.say(" ".join(e.args))
            retry_after = 30. - (time() - min(self._api.get_ratelimit()))
            raise commands.CommandOnCooldown(30, retry_after)
Exemplo n.º 9
0
 def test_ratelimiting_get(self):
     api = Api("AUTOMATED TESTING BY PYNATIONSTATES")
     ct = time()
     api.__rltime__ = [(ct+x) for x in range(55)]
     self.assertEqual(
         api.get_ratelimit(), api.__rltime__)
Exemplo n.º 10
0
 def test_rate_limiter_handles_error_prone_zone(self):
     api = Api("AUTOMATED TESTING BY PYNATIONSTATES")
     nsinstance = api.get_world(shard=["TEST"], auto_load=False)
     nsinstance.ratelimitcheck = ratelimitcheck
     nsinstance._load()
     self.assertTrue(nsinstance.has_data)
Exemplo n.º 11
0
 def __init__(self, user_agent):
     self.session = NSApi(user_agent=user_agent)