Merge branch '4759-timestamp-precision-TC' closes #4759
[arvados.git] / sdk / python / tests / arvados_testutil.py
1 #!/usr/bin/env python
2
3 import arvados
4 import errno
5 import hashlib
6 import httplib
7 import httplib2
8 import io
9 import mock
10 import os
11 import Queue
12 import requests
13 import shutil
14 import tempfile
15 import unittest
16
17 # Use this hostname when you want to make sure the traffic will be
18 # instantly refused.  100::/64 is a dedicated black hole.
19 TEST_HOST = '100::'
20
21 skip_sleep = mock.patch('time.sleep', lambda n: None)  # clown'll eat me
22
23 def queue_with(items):
24     """Return a thread-safe iterator that yields the given items.
25
26     +items+ can be given as an array or an iterator. If an iterator is
27     given, it will be consumed to fill the queue before queue_with()
28     returns.
29     """
30     queue = Queue.Queue()
31     for val in items:
32         queue.put(val)
33     return lambda *args, **kwargs: queue.get(block=False)
34
35 # fake_httplib2_response and mock_responses
36 # mock calls to httplib2.Http.request()
37 def fake_httplib2_response(code, **headers):
38     headers.update(status=str(code),
39                    reason=httplib.responses.get(code, "Unknown Response"))
40     return httplib2.Response(headers)
41
42 def mock_responses(body, *codes, **headers):
43     return mock.patch('httplib2.Http.request', side_effect=queue_with((
44         (fake_httplib2_response(code, **headers), body) for code in codes)))
45
46 # fake_requests_response, mock_get_responses and mock_put_responses
47 # mock calls to requests.get() and requests.put()
48 def fake_requests_response(code, body, **headers):
49     r = requests.Response()
50     r.status_code = code
51     r.reason = httplib.responses.get(code, "Unknown Response")
52     r.headers = headers
53     r.raw = io.BytesIO(body)
54     return r
55
56 def mock_get_responses(body, *codes, **headers):
57     return mock.patch('requests.get', side_effect=queue_with((
58         fake_requests_response(code, body, **headers) for code in codes)))
59
60 def mock_put_responses(body, *codes, **headers):
61     return mock.patch('requests.put', side_effect=queue_with((
62         fake_requests_response(code, body, **headers) for code in codes)))
63
64 def mock_requestslib_responses(method, body, *codes, **headers):
65     return mock.patch(method, side_effect=queue_with((
66         fake_requests_response(code, body, **headers) for code in codes)))
67
68 class MockStreamReader(object):
69     def __init__(self, name='.', *data):
70         self._name = name
71         self._data = ''.join(data)
72         self._data_locators = ['{}+{}'.format(hashlib.md5(d).hexdigest(),
73                                               len(d)) for d in data]
74         self.num_retries = 0
75
76     def name(self):
77         return self._name
78
79     def readfrom(self, start, size, num_retries=None):
80         return self._data[start:start + size]
81
82
83 class ApiClientMock(object):
84     def api_client_mock(self):
85         return mock.MagicMock(name='api_client_mock')
86
87     def mock_keep_services(self, api_mock=None, status=200, count=12,
88                            service_type='disk',
89                            service_host=None,
90                            service_port=None,
91                            service_ssl_flag=False):
92         if api_mock is None:
93             api_mock = self.api_client_mock()
94         body = {
95             'items_available': count,
96             'items': [{
97                 'uuid': 'zzzzz-bi6l4-{:015x}'.format(i),
98                 'owner_uuid': 'zzzzz-tpzed-000000000000000',
99                 'service_host': service_host or 'keep0x{:x}'.format(i),
100                 'service_port': service_port or 65535-i,
101                 'service_ssl_flag': service_ssl_flag,
102                 'service_type': service_type,
103             } for i in range(0, count)]
104         }
105         self._mock_api_call(api_mock.keep_services().accessible, status, body)
106         return api_mock
107
108     def _mock_api_call(self, mock_method, code, body):
109         mock_method = mock_method().execute
110         if code == 200:
111             mock_method.return_value = body
112         else:
113             mock_method.side_effect = arvados.errors.ApiError(
114                 fake_httplib2_response(code), "{}")
115
116
117 class ArvadosBaseTestCase(unittest.TestCase):
118     # This class provides common utility functions for our tests.
119
120     def setUp(self):
121         self._tempdirs = []
122
123     def tearDown(self):
124         for workdir in self._tempdirs:
125             shutil.rmtree(workdir, ignore_errors=True)
126
127     def make_tmpdir(self):
128         self._tempdirs.append(tempfile.mkdtemp())
129         return self._tempdirs[-1]
130
131     def data_file(self, filename):
132         try:
133             basedir = os.path.dirname(__file__)
134         except NameError:
135             basedir = '.'
136         return open(os.path.join(basedir, 'data', filename))
137
138     def build_directory_tree(self, tree):
139         tree_root = self.make_tmpdir()
140         for leaf in tree:
141             path = os.path.join(tree_root, leaf)
142             try:
143                 os.makedirs(os.path.dirname(path))
144             except OSError as error:
145                 if error.errno != errno.EEXIST:
146                     raise
147             with open(path, 'w') as tmpfile:
148                 tmpfile.write(leaf)
149         return tree_root
150
151     def make_test_file(self, text="test"):
152         testfile = tempfile.NamedTemporaryFile()
153         testfile.write(text)
154         testfile.flush()
155         return testfile