17 # Use this hostname when you want to make sure the traffic will be
18 # instantly refused. 100::/64 is a dedicated black hole.
21 skip_sleep = mock.patch('time.sleep', lambda n: None) # clown'll eat me
23 def queue_with(items):
24 """Return a thread-safe iterator that yields the given items.
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()
33 return lambda *args, **kwargs: queue.get(block=False)
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)
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)))
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()
51 r.reason = httplib.responses.get(code, "Unknown Response")
53 r.raw = io.BytesIO(body)
56 # The following methods patch requests.Session(), where return_value is a mock
57 # Session object. The put/get attributes are set on mock Session, and the
58 # desired put/get behavior is set on the put/get mocks.
60 def mock_put_responses(body, *codes, **headers):
62 if isinstance(body, tuple):
65 m.return_value.put.side_effect = queue_with((fake_requests_response(code, b, **headers) for b, code in codes))
67 m.return_value.put.side_effect = queue_with((fake_requests_response(code, body, **headers) for code in codes))
68 return mock.patch('requests.Session', m)
70 def mock_get_responses(body, *codes, **headers):
72 m.return_value.get.side_effect = queue_with((fake_requests_response(code, body, **headers) for code in codes))
73 return mock.patch('requests.Session', m)
75 def mock_get(side_effect):
77 m.return_value.get.side_effect = side_effect
78 return mock.patch('requests.Session', m)
80 def mock_put(side_effect):
82 m.return_value.put.side_effect = side_effect
83 return mock.patch('requests.Session', m)
85 class MockStreamReader(object):
86 def __init__(self, name='.', *data):
88 self._data = ''.join(data)
89 self._data_locators = ['{}+{}'.format(hashlib.md5(d).hexdigest(),
90 len(d)) for d in data]
96 def readfrom(self, start, size, num_retries=None):
97 return self._data[start:start + size]
99 class ApiClientMock(object):
100 def api_client_mock(self):
101 return mock.MagicMock(name='api_client_mock')
103 def mock_keep_services(self, api_mock=None, status=200, count=12,
107 service_ssl_flag=False):
109 api_mock = self.api_client_mock()
111 'items_available': count,
113 'uuid': 'zzzzz-bi6l4-{:015x}'.format(i),
114 'owner_uuid': 'zzzzz-tpzed-000000000000000',
115 'service_host': service_host or 'keep0x{:x}'.format(i),
116 'service_port': service_port or 65535-i,
117 'service_ssl_flag': service_ssl_flag,
118 'service_type': service_type,
119 } for i in range(0, count)]
121 self._mock_api_call(api_mock.keep_services().accessible, status, body)
124 def _mock_api_call(self, mock_method, code, body):
125 mock_method = mock_method().execute
127 mock_method.return_value = body
129 mock_method.side_effect = arvados.errors.ApiError(
130 fake_httplib2_response(code), "{}")
133 class ArvadosBaseTestCase(unittest.TestCase):
134 # This class provides common utility functions for our tests.
140 for workdir in self._tempdirs:
141 shutil.rmtree(workdir, ignore_errors=True)
143 def make_tmpdir(self):
144 self._tempdirs.append(tempfile.mkdtemp())
145 return self._tempdirs[-1]
147 def data_file(self, filename):
149 basedir = os.path.dirname(__file__)
152 return open(os.path.join(basedir, 'data', filename))
154 def build_directory_tree(self, tree):
155 tree_root = self.make_tmpdir()
157 path = os.path.join(tree_root, leaf)
159 os.makedirs(os.path.dirname(path))
160 except OSError as error:
161 if error.errno != errno.EEXIST:
163 with open(path, 'w') as tmpfile:
167 def make_test_file(self, text="test"):
168 testfile = tempfile.NamedTemporaryFile()