From 40ea12a22f8ad9cd441e1ae841e156e1e6460ba0 Mon Sep 17 00:00:00 2001 From: hugovk Date: Mon, 3 Mar 2014 14:57:15 +0200 Subject: [PATCH] Improve rate limiting and tests, for #80 --- pylast.py | 6 ++++-- test_pylast.py | 13 +++++++++++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/pylast.py b/pylast.py index 5677e51..ee0c760 100644 --- a/pylast.py +++ b/pylast.py @@ -302,8 +302,10 @@ class _Network(object): DELAY_TIME = 0.2 now = time.time() - if (now - self.last_call_time) < DELAY_TIME: - time.sleep(now - self.last_call_time - DELAY_TIME) + time_since_last = now - self.last_call_time + + if time_since_last < DELAY_TIME: + time.sleep(DELAY_TIME - time_since_last) self.last_call_time = now diff --git a/test_pylast.py b/test_pylast.py index 6cdb5b4..188680f 100755 --- a/test_pylast.py +++ b/test_pylast.py @@ -541,9 +541,16 @@ class TestPyLast(unittest.TestCase): # Act self.network.enable_rate_limit() + then = time.time() + # Make some network call, limit not applied first time + self.network.get_user(self.username) + # Make a second network call, limiting should be applied + self.network.get_top_artists() + now = time.time() # Assert self.assertTrue(self.network.is_rate_limited()) + self.assertGreaterEqual(now - then, 0.2) def test_disable_rate_limiting(self): @@ -553,6 +560,12 @@ class TestPyLast(unittest.TestCase): # Act self.network.disable_rate_limit() + then = time.time() + # Make some network call, limit not applied first time + self.network.get_user(self.username) + # Make a second network call, limiting should be applied + self.network.get_top_artists() + now = time.time() # Assert self.assertFalse(self.network.is_rate_limited())