Merge branch 'master' into 6827-no-passwords-in-logs
[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 pycurl
12 import Queue
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
47 class FakeCurl:
48     @classmethod
49     def make(cls, code, body='', headers={}):
50         return mock.Mock(spec=cls, wraps=cls(code, body, headers))
51
52     def __init__(self, code=200, body='', headers={}):
53         self._opt = {}
54         self._got_url = None
55         self._writer = None
56         self._headerfunction = None
57         self._resp_code = code
58         self._resp_body = body
59         self._resp_headers = headers
60
61     def getopt(self, opt):
62         return self._opt.get(str(opt), None)
63
64     def setopt(self, opt, val):
65         self._opt[str(opt)] = val
66         if opt == pycurl.WRITEFUNCTION:
67             self._writer = val
68         elif opt == pycurl.HEADERFUNCTION:
69             self._headerfunction = val
70
71     def perform(self):
72         if not isinstance(self._resp_code, int):
73             raise self._resp_code
74         if self.getopt(pycurl.URL) is None:
75             raise ValueError
76         if self._writer is None:
77             raise ValueError
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)
83
84     def close(self):
85         pass
86
87     def reset(self):
88         """Prevent fake UAs from going back into the user agent pool."""
89         raise Exception
90
91     def getinfo(self, opt):
92         if opt == pycurl.RESPONSE_CODE:
93             return self._resp_code
94         raise Exception
95
96 def mock_keep_responses(body, *codes, **headers):
97     """Patch pycurl to return fake responses and raise exceptions.
98
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.
102     """
103     cm = mock.MagicMock()
104     if isinstance(body, tuple):
105         codes = list(codes)
106         codes.insert(0, body)
107         responses = [
108             FakeCurl.make(code=code, body=b, headers=headers)
109             for b, code in codes
110         ]
111     else:
112         responses = [
113             FakeCurl.make(code=code, body=body, headers=headers)
114             for code in codes
115         ]
116     cm.side_effect = queue_with(responses)
117     cm.responses = responses
118     return mock.patch('pycurl.Curl', cm)
119
120
121 class MockStreamReader(object):
122     def __init__(self, name='.', *data):
123         self._name = name
124         self._data = ''.join(data)
125         self._data_locators = ['{}+{}'.format(hashlib.md5(d).hexdigest(),
126                                               len(d)) for d in data]
127         self.num_retries = 0
128
129     def name(self):
130         return self._name
131
132     def readfrom(self, start, size, num_retries=None):
133         return self._data[start:start + size]
134
135 class ApiClientMock(object):
136     def api_client_mock(self):
137         return mock.MagicMock(name='api_client_mock')
138
139     def mock_keep_services(self, api_mock=None, status=200, count=12,
140                            service_type='disk',
141                            service_host=None,
142                            service_port=None,
143                            service_ssl_flag=False,
144                            additional_services=[],
145                            read_only=False):
146         if api_mock is None:
147             api_mock = self.api_client_mock()
148         body = {
149             'items_available': count,
150             'items': [{
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
159         }
160         self._mock_api_call(api_mock.keep_services().accessible, status, body)
161         return api_mock
162
163     def _mock_api_call(self, mock_method, code, body):
164         mock_method = mock_method().execute
165         if code == 200:
166             mock_method.return_value = body
167         else:
168             mock_method.side_effect = arvados.errors.ApiError(
169                 fake_httplib2_response(code), "{}")
170
171
172 class ArvadosBaseTestCase(unittest.TestCase):
173     # This class provides common utility functions for our tests.
174
175     def setUp(self):
176         self._tempdirs = []
177
178     def tearDown(self):
179         for workdir in self._tempdirs:
180             shutil.rmtree(workdir, ignore_errors=True)
181
182     def make_tmpdir(self):
183         self._tempdirs.append(tempfile.mkdtemp())
184         return self._tempdirs[-1]
185
186     def data_file(self, filename):
187         try:
188             basedir = os.path.dirname(__file__)
189         except NameError:
190             basedir = '.'
191         return open(os.path.join(basedir, 'data', filename))
192
193     def build_directory_tree(self, tree):
194         tree_root = self.make_tmpdir()
195         for leaf in tree:
196             path = os.path.join(tree_root, leaf)
197             try:
198                 os.makedirs(os.path.dirname(path))
199             except OSError as error:
200                 if error.errno != errno.EEXIST:
201                     raise
202             with open(path, 'w') as tmpfile:
203                 tmpfile.write(leaf)
204         return tree_root
205
206     def make_test_file(self, text="test"):
207         testfile = tempfile.NamedTemporaryFile()
208         testfile.write(text)
209         testfile.flush()
210         return testfile