|
| 1 | +# -*- coding: utf-8 -*- # noqa |
| 2 | + |
| 3 | +import time |
| 4 | +import unittest |
| 5 | + |
| 6 | +from datetime import datetime |
| 7 | +from datetime import timedelta |
| 8 | +from intercom.client import Client |
| 9 | +from intercom.request import Request |
| 10 | +from mock import Mock |
| 11 | +from mock import patch |
| 12 | +from nose.tools import istest |
| 13 | +from pytz import utc |
| 14 | + |
| 15 | + |
| 16 | +class ClientTest(unittest.TestCase): # noqa |
| 17 | + |
| 18 | + def setUp(self): # noqa |
| 19 | + self.client = Client() |
| 20 | + now = datetime.utcnow().replace(tzinfo=utc) |
| 21 | + reset_at = now + timedelta(seconds=2) |
| 22 | + # set the reset to be in 2 seconds |
| 23 | + self.rate_limit_details = { |
| 24 | + 'remaining': 0, |
| 25 | + 'limit': 20, |
| 26 | + 'reset_at': reset_at |
| 27 | + } |
| 28 | + headers = { |
| 29 | + 'x-ratelimit-limit': 20, |
| 30 | + 'x-ratelimit-remaining': 0, |
| 31 | + 'x-ratelimit-reset': time.mktime(reset_at.timetuple()) |
| 32 | + } |
| 33 | + payload = """{ |
| 34 | + "user_id": "1224242", |
| 35 | + "update_last_request_at": true, |
| 36 | + "custom_attributes": {} |
| 37 | + }""" |
| 38 | + |
| 39 | + if not hasattr(payload, 'decode'): |
| 40 | + # python 3 |
| 41 | + payload = payload.encode('utf-8') |
| 42 | + |
| 43 | + self.response = Mock( |
| 44 | + content=payload, |
| 45 | + encoding='utf-8', |
| 46 | + headers=headers) |
| 47 | + self.started_at = now |
| 48 | + |
| 49 | + @istest |
| 50 | + def it_can_control_throttle_on_creation(self): # noqa |
| 51 | + client = Client() |
| 52 | + self.assertFalse(client.throttle) |
| 53 | + client = Client(throttle=True) |
| 54 | + self.assertTrue(client.throttle) |
| 55 | + |
| 56 | + @istest |
| 57 | + def it_will_sleep_if_throttle_is_on(self): # noqa |
| 58 | + client = Client(throttle=True) |
| 59 | + client.rate_limit_details = self.rate_limit_details |
| 60 | + with patch.object(Request, 'send_request_to_path', return_value=self.response): |
| 61 | + # this call should take approximately 2 seconds |
| 62 | + client.users.find(email="john@example.com") |
| 63 | + finished_at = datetime.utcnow().replace(tzinfo=utc) |
| 64 | + self.assertEqual(2, int((finished_at - self.started_at).seconds)) |
| 65 | + |
| 66 | + @istest |
| 67 | + def it_wont_sleep_if_throttle_is_off(self): # noqa |
| 68 | + client = Client() |
| 69 | + client.rate_limit_details = self.rate_limit_details |
| 70 | + with patch.object(Request, 'send_request_to_path', return_value=self.response): |
| 71 | + # this call should take approximately 2 seconds |
| 72 | + client.users.find(email="john@example.com") |
| 73 | + finished_at = datetime.utcnow().replace(tzinfo=utc) |
| 74 | + self.assertEqual(0, int((finished_at - self.started_at).seconds)) |
0 commit comments