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 def mock_api_responses(api_client, body, codes, headers={}):
47 return mock.patch.object(api_client._http, 'request', side_effect=queue_with((
48 (fake_httplib2_response(code, **headers), body) for code in codes)))
50 def str_keep_locator(s):
51 return '{}+{}'.format(hashlib.md5(s).hexdigest(), len(s))
55 def make(cls, code, body='', headers={}):
56 return mock.Mock(spec=cls, wraps=cls(code, body, headers))
58 def __init__(self, code=200, body='', headers={}):
62 self._headerfunction = None
63 self._resp_code = code
64 self._resp_body = body
65 self._resp_headers = headers
67 def getopt(self, opt):
68 return self._opt.get(str(opt), None)
70 def setopt(self, opt, val):
71 self._opt[str(opt)] = val
72 if opt == pycurl.WRITEFUNCTION:
74 elif opt == pycurl.HEADERFUNCTION:
75 self._headerfunction = val
78 if not isinstance(self._resp_code, int):
80 if self.getopt(pycurl.URL) is None:
82 if self._writer is None:
84 if self._headerfunction:
85 self._headerfunction("HTTP/1.1 {} Status".format(self._resp_code))
86 for k, v in self._resp_headers.iteritems():
87 self._headerfunction(k + ': ' + str(v))
88 self._writer(self._resp_body)
94 """Prevent fake UAs from going back into the user agent pool."""
97 def getinfo(self, opt):
98 if opt == pycurl.RESPONSE_CODE:
99 return self._resp_code
102 def mock_keep_responses(body, *codes, **headers):
103 """Patch pycurl to return fake responses and raise exceptions.
105 body can be a string to return as the response body; an exception
106 to raise when perform() is called; or an iterable that returns a
107 sequence of such values.
109 cm = mock.MagicMock()
110 if isinstance(body, tuple):
112 codes.insert(0, body)
114 FakeCurl.make(code=code, body=b, headers=headers)
119 FakeCurl.make(code=code, body=body, headers=headers)
122 cm.side_effect = queue_with(responses)
123 cm.responses = responses
124 return mock.patch('pycurl.Curl', cm)
127 class MockStreamReader(object):
128 def __init__(self, name='.', *data):
130 self._data = ''.join(data)
131 self._data_locators = [str_keep_locator(d) for d in data]
137 def readfrom(self, start, size, num_retries=None):
138 return self._data[start:start + size]
140 class ApiClientMock(object):
141 def api_client_mock(self):
142 return mock.MagicMock(name='api_client_mock')
144 def mock_keep_services(self, api_mock=None, status=200, count=12,
148 service_ssl_flag=False,
149 additional_services=[],
152 api_mock = self.api_client_mock()
154 'items_available': count,
156 'uuid': 'zzzzz-bi6l4-{:015x}'.format(i),
157 'owner_uuid': 'zzzzz-tpzed-000000000000000',
158 'service_host': service_host or 'keep0x{:x}'.format(i),
159 'service_port': service_port or 65535-i,
160 'service_ssl_flag': service_ssl_flag,
161 'service_type': service_type,
162 'read_only': read_only,
163 } for i in range(0, count)] + additional_services
165 self._mock_api_call(api_mock.keep_services().accessible, status, body)
168 def _mock_api_call(self, mock_method, code, body):
169 mock_method = mock_method().execute
171 mock_method.return_value = body
173 mock_method.side_effect = arvados.errors.ApiError(
174 fake_httplib2_response(code), "{}")
177 class ArvadosBaseTestCase(unittest.TestCase):
178 # This class provides common utility functions for our tests.
184 for workdir in self._tempdirs:
185 shutil.rmtree(workdir, ignore_errors=True)
187 def make_tmpdir(self):
188 self._tempdirs.append(tempfile.mkdtemp())
189 return self._tempdirs[-1]
191 def data_file(self, filename):
193 basedir = os.path.dirname(__file__)
196 return open(os.path.join(basedir, 'data', filename))
198 def build_directory_tree(self, tree):
199 tree_root = self.make_tmpdir()
201 path = os.path.join(tree_root, leaf)
203 os.makedirs(os.path.dirname(path))
204 except OSError as error:
205 if error.errno != errno.EEXIST:
207 with open(path, 'w') as tmpfile:
211 def make_test_file(self, text="test"):
212 testfile = tempfile.NamedTemporaryFile()