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)))
49 def make(cls, code, body='', headers={}):
50 return mock.Mock(spec=cls, wraps=cls(code, body, headers))
52 def __init__(self, code=200, body='', headers={}):
56 self._headerfunction = None
57 self._resp_code = code
58 self._resp_body = body
59 self._resp_headers = headers
61 def getopt(self, opt):
62 return self._opt.get(str(opt), None)
64 def setopt(self, opt, val):
65 self._opt[str(opt)] = val
66 if opt == pycurl.WRITEFUNCTION:
68 elif opt == pycurl.HEADERFUNCTION:
69 self._headerfunction = val
72 if not isinstance(self._resp_code, int):
74 if self.getopt(pycurl.URL) is None:
76 if self._writer is None:
78 if self._headerfunction:
79 self._headerfunction("HTTP/1.1 {} Status".format(self._resp_code))
80 for k, v in self._resp_headers.iteritems():
81 self._headerfunction(k + ': ' + str(v))
82 self._writer(self._resp_body)
88 """Prevent fake UAs from going back into the user agent pool."""
91 def getinfo(self, opt):
92 if opt == pycurl.RESPONSE_CODE:
93 return self._resp_code
96 def mock_keep_responses(body, *codes, **headers):
97 """Patch pycurl to return fake responses and raise exceptions.
99 body can be a string to return as the response body; an exception
100 to raise when perform() is called; or an iterable that returns a
101 sequence of such values.
103 cm = mock.MagicMock()
104 if isinstance(body, tuple):
106 codes.insert(0, body)
108 FakeCurl.make(code=code, body=b, headers=headers)
113 FakeCurl.make(code=code, body=body, headers=headers)
116 cm.side_effect = queue_with(responses)
117 cm.responses = responses
118 return mock.patch('pycurl.Curl', cm)
121 class MockStreamReader(object):
122 def __init__(self, name='.', *data):
124 self._data = ''.join(data)
125 self._data_locators = ['{}+{}'.format(hashlib.md5(d).hexdigest(),
126 len(d)) for d in data]
132 def readfrom(self, start, size, num_retries=None):
133 return self._data[start:start + size]
135 class ApiClientMock(object):
136 def api_client_mock(self):
137 return mock.MagicMock(name='api_client_mock')
139 def mock_keep_services(self, api_mock=None, status=200, count=12,
143 service_ssl_flag=False,
144 additional_services=[],
147 api_mock = self.api_client_mock()
149 'items_available': count,
151 'uuid': 'zzzzz-bi6l4-{:015x}'.format(i),
152 'owner_uuid': 'zzzzz-tpzed-000000000000000',
153 'service_host': service_host or 'keep0x{:x}'.format(i),
154 'service_port': service_port or 65535-i,
155 'service_ssl_flag': service_ssl_flag,
156 'service_type': service_type,
157 'read_only': read_only,
158 } for i in range(0, count)] + additional_services
160 self._mock_api_call(api_mock.keep_services().accessible, status, body)
163 def _mock_api_call(self, mock_method, code, body):
164 mock_method = mock_method().execute
166 mock_method.return_value = body
168 mock_method.side_effect = arvados.errors.ApiError(
169 fake_httplib2_response(code), "{}")
172 class ArvadosBaseTestCase(unittest.TestCase):
173 # This class provides common utility functions for our tests.
179 for workdir in self._tempdirs:
180 shutil.rmtree(workdir, ignore_errors=True)
182 def make_tmpdir(self):
183 self._tempdirs.append(tempfile.mkdtemp())
184 return self._tempdirs[-1]
186 def data_file(self, filename):
188 basedir = os.path.dirname(__file__)
191 return open(os.path.join(basedir, 'data', filename))
193 def build_directory_tree(self, tree):
194 tree_root = self.make_tmpdir()
196 path = os.path.join(tree_root, leaf)
198 os.makedirs(os.path.dirname(path))
199 except OSError as error:
200 if error.errno != errno.EEXIST:
202 with open(path, 'w') as tmpfile:
206 def make_test_file(self, text="test"):
207 testfile = tempfile.NamedTemporaryFile()