OLD | NEW |
(Empty) | |
| 1 #!/usr/bin/env python |
| 2 # Copyright 2016 The LUCI Authors. All rights reserved. |
| 3 # Use of this source code is governed under the Apache License, Version 2.0 |
| 4 # that can be found in the LICENSE file. |
| 5 |
| 6 import logging |
| 7 import sys |
| 8 import threading |
| 9 import time |
| 10 import unittest |
| 11 |
| 12 import test_env_bot_code |
| 13 test_env_bot_code.setup_test_env() |
| 14 |
| 15 from depot_tools import auto_stub |
| 16 |
| 17 import remote_client |
| 18 |
| 19 |
| 20 class TestRemoteClient(auto_stub.TestCase): |
| 21 def setUp(self): |
| 22 super(TestRemoteClient, self).setUp() |
| 23 self.slept = 0 |
| 24 def sleep_mock(t): |
| 25 self.slept += t |
| 26 self.mock(time, 'sleep', sleep_mock) |
| 27 |
| 28 def test_initialize_success(self): |
| 29 headers = {'A': 'a'} |
| 30 exp_ts = time.time() + 3600 |
| 31 c = remote_client.RemoteClient( |
| 32 'http://localhost:1', lambda: (headers, exp_ts)) |
| 33 c.initialize(threading.Event()) |
| 34 self.assertEqual(0, self.slept) |
| 35 self.assertTrue(c.uses_auth) |
| 36 self.assertEqual(headers, c.get_authentication_headers()) |
| 37 |
| 38 def test_initialize_retries(self): |
| 39 headers = {'A': 'a'} |
| 40 exp_ts = time.time() + 3600 |
| 41 attempt = [0] |
| 42 def callback(): |
| 43 attempt[0] += 1 |
| 44 if attempt[0] == 10: |
| 45 return headers, exp_ts |
| 46 raise Exception('fail') |
| 47 c = remote_client.RemoteClient('http://localhost:1', callback) |
| 48 c.initialize(threading.Event()) |
| 49 self.assertEqual(9*2, self.slept) |
| 50 self.assertTrue(c.uses_auth) |
| 51 self.assertEqual(headers, c.get_authentication_headers()) |
| 52 |
| 53 def test_initialize_gives_up(self): |
| 54 def callback(): |
| 55 raise Exception('fail') |
| 56 c = remote_client.RemoteClient('http://localhost:1', callback) |
| 57 with self.assertRaises(remote_client.InitializationError): |
| 58 c.initialize(threading.Event()) |
| 59 self.assertEqual(29*2, self.slept) |
| 60 self.assertFalse(c.uses_auth) |
| 61 self.assertEqual({}, c.get_authentication_headers()) |
| 62 |
| 63 def test_get_authentication_headers(self): |
| 64 self.mock(time, 'time', lambda: 100000) |
| 65 c = remote_client.RemoteClient( |
| 66 'http://localhost:1', |
| 67 lambda: ({'Now': str(time.time())}, time.time() + 3600)) |
| 68 |
| 69 # Grab initial headers. |
| 70 self.assertEqual({'Now': '100000'}, c.get_authentication_headers()) |
| 71 |
| 72 # A bit later still using same cached headers. |
| 73 self.mock(time, 'time', lambda: 102000) |
| 74 self.assertEqual({'Now': '100000'}, c.get_authentication_headers()) |
| 75 |
| 76 # Close to expiration => refreshed. |
| 77 self.mock(time, 'time', lambda: 103500) |
| 78 self.assertEqual({'Now': '103500'}, c.get_authentication_headers()) |
| 79 |
| 80 |
| 81 if __name__ == '__main__': |
| 82 logging.basicConfig( |
| 83 level=logging.DEBUG if '-v' in sys.argv else logging.CRITICAL) |
| 84 unittest.main() |
OLD | NEW |