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,
108 additional_services=[]):
110 api_mock = self.api_client_mock()
112 'items_available': count,
114 'uuid': 'zzzzz-bi6l4-{:015x}'.format(i),
115 'owner_uuid': 'zzzzz-tpzed-000000000000000',
116 'service_host': service_host or 'keep0x{:x}'.format(i),
117 'service_port': service_port or 65535-i,
118 'service_ssl_flag': service_ssl_flag,
119 'service_type': service_type,
120 } for i in range(0, count)] + additional_services
122 self._mock_api_call(api_mock.keep_services().accessible, status, body)
125 def _mock_api_call(self, mock_method, code, body):
126 mock_method = mock_method().execute
128 mock_method.return_value = body
130 mock_method.side_effect = arvados.errors.ApiError(
131 fake_httplib2_response(code), "{}")
134 class ArvadosBaseTestCase(unittest.TestCase):
135 # This class provides common utility functions for our tests.
141 for workdir in self._tempdirs:
142 shutil.rmtree(workdir, ignore_errors=True)
144 def make_tmpdir(self):
145 self._tempdirs.append(tempfile.mkdtemp())
146 return self._tempdirs[-1]
148 def data_file(self, filename):
150 basedir = os.path.dirname(__file__)
153 return open(os.path.join(basedir, 'data', filename))
155 def build_directory_tree(self, tree):
156 tree_root = self.make_tmpdir()
158 path = os.path.join(tree_root, leaf)
160 os.makedirs(os.path.dirname(path))
161 except OSError as error:
162 if error.errno != errno.EEXIST:
164 with open(path, 'w') as tmpfile:
168 def make_test_file(self, text="test"):
169 testfile = tempfile.NamedTemporaryFile()