|
| 1 | +import functools |
| 2 | +import json |
| 3 | +import threading |
| 4 | +import unittest |
| 5 | + |
| 6 | +from securenative import Event, event_types |
| 7 | +from securenative.event_manager import EventManager |
| 8 | +from securenative.event_options import User, CustomParam |
| 9 | + |
| 10 | + |
| 11 | +class EventManagerTests(unittest.TestCase): |
| 12 | + |
| 13 | + def build_event(self): |
| 14 | + return Event( event_type=event_types. login, user=User( user_id='1', user_email='[email protected]', user_name='1 2'), |
| 15 | + params=[CustomParam('key', 'val')]) |
| 16 | + |
| 17 | + def test_send_sync(self): |
| 18 | + api_key = 'key' |
| 19 | + resource = 'my/custom/resource' |
| 20 | + client = HttpClientMock(None) |
| 21 | + event = self.build_event() |
| 22 | + manager = EventManager(api_key=api_key, http_client=client) |
| 23 | + url, key, body = manager.send_sync(event, resource) |
| 24 | + |
| 25 | + self.assertEqual(url, 'https://api.securenative.com/' + resource) |
| 26 | + self.assertEqual(key, api_key) |
| 27 | + self.assertEqual(body, json.dumps(event.as_dict())) |
| 28 | + |
| 29 | + def test_send_async(self): |
| 30 | + wg = threading.Event() |
| 31 | + api_key = 'key' |
| 32 | + resource = 'my/custom/resource' |
| 33 | + event = self.build_event() |
| 34 | + client = HttpClientMock(functools.partial(self.assert_cb, wg, event)) |
| 35 | + |
| 36 | + manager = EventManager(api_key=api_key, http_client=client) |
| 37 | + manager.send_async(event, resource) |
| 38 | + self.assertTrue(wg.wait(manager.options.interval//1000 * 2)) |
| 39 | + |
| 40 | + def assert_cb(self, wg, event, url, key, body): |
| 41 | + self.assertEqual(url, 'https://api.securenative.com/my/custom/resource') |
| 42 | + self.assertEqual(key, 'key') |
| 43 | + self.assertEqual(body, json.dumps(event.as_dict())) |
| 44 | + wg.set() |
| 45 | + |
| 46 | + |
| 47 | +class HttpClientMock(object): |
| 48 | + def __init__(self, cb): |
| 49 | + self.cb = cb |
| 50 | + |
| 51 | + def post(self, url, api_key, body): |
| 52 | + if self.cb is not None: |
| 53 | + self.cb(url, api_key, body) |
| 54 | + return url, api_key, body |
0 commit comments