Merge branch '8087-arv-cli-request-body-from-file' of https://github.com/wtsi-hgi...
[arvados.git] / services / nodemanager / tests / testutil.py
1 #!/usr/bin/env python
2
3 from __future__ import absolute_import, print_function
4
5 import datetime
6 import threading
7 import time
8
9 import mock
10 import pykka
11
12 from . import pykka_timeout
13
14 no_sleep = mock.patch('time.sleep', lambda n: None)
15
16 def arvados_node_mock(node_num=99, job_uuid=None, age=-1, **kwargs):
17     mod_time = datetime.datetime.utcnow() - datetime.timedelta(seconds=age)
18     mod_time_s = mod_time.strftime('%Y-%m-%dT%H:%M:%S.%fZ')
19     if job_uuid is True:
20         job_uuid = 'zzzzz-jjjjj-jobjobjobjobjob'
21     crunch_worker_state = 'idle' if (job_uuid is None) else 'busy'
22     node = {'uuid': 'zzzzz-yyyyy-{:015x}'.format(node_num),
23             'created_at': '2014-01-01T01:02:03.04050607Z',
24             'modified_at': mod_time_s,
25             'first_ping_at': kwargs.pop('first_ping_at', mod_time_s),
26             'last_ping_at': mod_time_s,
27             'slot_number': node_num,
28             'hostname': 'compute{}'.format(node_num),
29             'domain': 'zzzzz.arvadosapi.com',
30             'ip_address': ip_address_mock(node_num),
31             'job_uuid': job_uuid,
32             'crunch_worker_state': crunch_worker_state,
33             'properties': {},
34             'info': {'ping_secret': 'defaulttestsecret', 'ec2_instance_id': str(node_num)}}
35     node.update(kwargs)
36     return node
37
38 def cloud_object_mock(name_id, **extra):
39     # A very generic mock, useful for stubbing libcloud objects we
40     # only search for and pass around, like locations, subnets, etc.
41     cloud_object = mock.NonCallableMagicMock(['id', 'name'],
42                                              name='cloud_object')
43     cloud_object.name = str(name_id)
44     cloud_object.id = 'id_' + cloud_object.name
45     cloud_object.extra = extra
46     return cloud_object
47
48
49 def cloud_node_fqdn(node):
50     # We intentionally put the FQDN somewhere goofy to make sure tested code is
51     # using this function for lookups.
52     return node.extra.get('testname', 'NoTestName')
53
54 def ip_address_mock(last_octet):
55     return '10.20.30.{}'.format(last_octet)
56
57 class MockShutdownTimer(object):
58     def _set_state(self, is_open, next_opening):
59         self.window_open = lambda: is_open
60         self.next_opening = lambda: next_opening
61
62
63 class MockSize(object):
64     def __init__(self, factor):
65         self.id = 'z{}.test'.format(factor)
66         self.name = self.id
67         self.ram = 128 * factor
68         self.disk = 100 * factor
69         self.bandwidth = 16 * factor
70         self.price = float(factor)
71         self.extra = {}
72
73     def __eq__(self, other):
74         return self.id == other.id
75
76
77 class MockTimer(object):
78     def __init__(self, deliver_immediately=True):
79         self.deliver_immediately = deliver_immediately
80         self.messages = []
81         self.lock = threading.Lock()
82
83     def deliver(self):
84         with self.lock:
85             to_deliver = self.messages
86             self.messages = []
87         for callback, args, kwargs in to_deliver:
88             try:
89                 callback(*args, **kwargs)
90             except pykka.ActorDeadError:
91                 pass
92
93     def schedule(self, want_time, callback, *args, **kwargs):
94         with self.lock:
95             self.messages.append((callback, args, kwargs))
96         if self.deliver_immediately:
97             self.deliver()
98
99
100 class ActorTestMixin(object):
101     FUTURE_CLASS = pykka.ThreadingFuture
102     TIMEOUT = pykka_timeout
103
104     def tearDown(self):
105         pykka.ActorRegistry.stop_all()
106
107     def stop_proxy(self, proxy):
108         return proxy.actor_ref.stop(timeout=self.TIMEOUT)
109
110     def wait_for_assignment(self, proxy, attr_name, unassigned=None,
111                             timeout=TIMEOUT):
112         deadline = time.time() + timeout
113         while True:
114             loop_timeout = deadline - time.time()
115             if loop_timeout <= 0:
116                 self.fail("actor did not assign {} in time".format(attr_name))
117             result = getattr(proxy, attr_name).get(loop_timeout)
118             if result is not unassigned:
119                 return result
120
121
122 class DriverTestMixin(object):
123     def setUp(self):
124         self.driver_mock = mock.MagicMock(name='driver_mock')
125         super(DriverTestMixin, self).setUp()
126
127     def new_driver(self, auth_kwargs={}, list_kwargs={}, create_kwargs={}):
128         create_kwargs.setdefault('ping_host', '100::')
129         return self.TEST_CLASS(
130             auth_kwargs, list_kwargs, create_kwargs,
131             driver_class=self.driver_mock)
132
133     def driver_method_args(self, method_name):
134         return getattr(self.driver_mock(), method_name).call_args
135
136     def test_driver_create_retry(self):
137         with mock.patch('time.sleep'):
138             driver_mock2 = mock.MagicMock(name='driver_mock2')
139             self.driver_mock.side_effect = (Exception("oops"), driver_mock2)
140             kwargs = {'user_id': 'foo'}
141             driver = self.new_driver(auth_kwargs=kwargs)
142             self.assertTrue(self.driver_mock.called)
143             self.assertIs(driver.real, driver_mock2)
144
145 class RemotePollLoopActorTestMixin(ActorTestMixin):
146     def build_monitor(self, *args, **kwargs):
147         self.timer = mock.MagicMock(name='timer_mock')
148         self.client = mock.MagicMock(name='client_mock')
149         self.subscriber = mock.Mock(name='subscriber_mock')
150         self.monitor = self.TEST_CLASS.start(
151             self.client, self.timer, *args, **kwargs).proxy()
152
153 def cloud_node_mock(node_num=99, size=MockSize(1), **extra):
154     node = mock.NonCallableMagicMock(
155         ['id', 'name', 'state', 'public_ips', 'private_ips', 'driver', 'size',
156          'image', 'extra'],
157         name='cloud_node')
158     node.id = str(node_num)
159     node.name = node.id
160     node.size = size
161     node.public_ips = []
162     node.private_ips = [ip_address_mock(node_num)]
163     node.extra = extra
164     return node