| 1 |
from unittest.mock import MagicMock, Mock, sentinel |
| 2 |
from urllib.parse import urlparse |
| 3 |
|
| 4 |
import pytest |
| 5 |
from kombu.utils.encoding import str_to_bytes |
| 6 |
|
| 7 |
from celery import states, uuid |
| 8 |
from celery.app import backends |
| 9 |
from celery.backends import couchdb as module |
| 10 |
from celery.backends.couchdb import CouchBackend |
| 11 |
from celery.exceptions import ImproperlyConfigured |
| 12 |
|
| 13 |
try: |
| 14 |
import pycouchdb |
| 15 |
except ImportError: |
| 16 |
pycouchdb = None |
| 17 |
|
| 18 |
COUCHDB_CONTAINER = 'celery_container' |
| 19 |
|
| 20 |
pytest.importorskip('pycouchdb') |
| 21 |
|
| 22 |
|
| 23 |
class test_CouchBackend: |
| 24 |
|
| 25 |
def setup_method(self): |
| 26 |
self.Server = self.patching('pycouchdb.Server') |
| 27 |
self.backend = CouchBackend(app=self.app) |
| 28 |
|
| 29 |
def test_init_no_pycouchdb(self): |
| 30 |
"""test init no pycouchdb raises""" |
| 31 |
prev, module.pycouchdb = module.pycouchdb, None |
| 32 |
try: |
| 33 |
with pytest.raises(ImproperlyConfigured): |
| 34 |
CouchBackend(app=self.app) |
| 35 |
finally: |
| 36 |
module.pycouchdb = prev |
| 37 |
|
| 38 |
def test_get_container_exists(self): |
| 39 |
self.backend._connection = sentinel._connection |
| 40 |
connection = self.backend.connection |
| 41 |
assert connection is sentinel._connection |
| 42 |
self.Server.assert_not_called() |
| 43 |
|
| 44 |
def test_get(self): |
| 45 |
"""test_get |
| 46 |
|
| 47 |
CouchBackend.get should return and take two params |
| 48 |
db conn to couchdb is mocked. |
| 49 |
""" |
| 50 |
x = CouchBackend(app=self.app) |
| 51 |
x._connection = Mock() |
| 52 |
get = x._connection.get = MagicMock() |
| 53 |
assert x.get('1f3fab') == get.return_value['value'] |
| 54 |
x._connection.get.assert_called_once_with('1f3fab') |
| 55 |
|
| 56 |
def test_get_non_existent_key(self): |
| 57 |
x = CouchBackend(app=self.app) |
| 58 |
x._connection = Mock() |
| 59 |
get = x._connection.get = MagicMock() |
| 60 |
get.side_effect = pycouchdb.exceptions.NotFound |
| 61 |
assert x.get('1f3fab') is None |
| 62 |
x._connection.get.assert_called_once_with('1f3fab') |
| 63 |
|
| 64 |
@pytest.mark.parametrize("key", ['1f3fab', b'1f3fab']) |
| 65 |
def test_set(self, key): |
| 66 |
x = CouchBackend(app=self.app) |
| 67 |
x._connection = Mock() |
| 68 |
|
| 69 |
x._set_with_state(key, 'value', states.SUCCESS) |
| 70 |
|
| 71 |
x._connection.save.assert_called_once_with({'_id': '1f3fab', |
| 72 |
'value': 'value'}) |
| 73 |
|
| 74 |
@pytest.mark.parametrize("key", ['1f3fab', b'1f3fab']) |
| 75 |
def test_set_with_conflict(self, key): |
| 76 |
x = CouchBackend(app=self.app) |
| 77 |
x._connection = Mock() |
| 78 |
x._connection.save.side_effect = (pycouchdb.exceptions.Conflict, None) |
| 79 |
get = x._connection.get = MagicMock() |
| 80 |
|
| 81 |
x._set_with_state(key, 'value', states.SUCCESS) |
| 82 |
|
| 83 |
x._connection.get.assert_called_once_with('1f3fab') |
| 84 |
x._connection.get('1f3fab').__setitem__.assert_called_once_with( |
| 85 |
'value', 'value') |
| 86 |
x._connection.save.assert_called_with(get('1f3fab')) |
| 87 |
assert x._connection.save.call_count == 2 |
| 88 |
|
| 89 |
def test_delete(self): |
| 90 |
"""test_delete |
| 91 |
|
| 92 |
CouchBackend.delete should return and take two params |
| 93 |
db conn to pycouchdb is mocked. |
| 94 |
TODO Should test on key not exists |
| 95 |
|
| 96 |
""" |
| 97 |
x = CouchBackend(app=self.app) |
| 98 |
x._connection = Mock() |
| 99 |
mocked_delete = x._connection.delete = Mock() |
| 100 |
mocked_delete.return_value = None |
| 101 |
# should return None |
| 102 |
assert x.delete('1f3fab') is None |
| 103 |
x._connection.delete.assert_called_once_with('1f3fab') |
| 104 |
|
| 105 |
def test_backend_by_url(self, url='couchdb://myhost/mycoolcontainer'): |
| 106 |
from celery.backends.couchdb import CouchBackend |
| 107 |
backend, url_ = backends.by_url(url, self.app.loader) |
| 108 |
assert backend is CouchBackend |
| 109 |
assert url_ == url |
| 110 |
|
| 111 |
def test_backend_params_by_url(self): |
| 112 |
url = 'couchdb://johndoe:mysecret@myhost:123/mycoolcontainer' |
| 113 |
with self.Celery(backend=url) as app: |
| 114 |
x = app.backend |
| 115 |
assert x.container == 'mycoolcontainer' |
| 116 |
assert x.host == 'myhost' |
| 117 |
assert x.username == 'johndoe' |
| 118 |
assert x.password == 'mysecret' |
| 119 |
assert x.port == 123 |
| 120 |
|
| 121 |
|
| 122 |
class CouchSessionMock: |
| 123 |
""" |
| 124 |
Mock for `requests.session` that emulates couchdb storage. |
| 125 |
""" |
| 126 |
|
| 127 |
_store = {} |
| 128 |
|
| 129 |
def request(self, method, url, stream=False, data=None, params=None, |
| 130 |
headers=None, **kw): |
| 131 |
tid = urlparse(url).path.split("/")[-1] |
| 132 |
|
| 133 |
response = Mock() |
| 134 |
response.headers = {"content-type": "application/json"} |
| 135 |
response.status_code = 200 |
| 136 |
response.content = b'' |
| 137 |
|
| 138 |
if method == "GET": |
| 139 |
if tid not in self._store: |
| 140 |
return self._not_found_response() |
| 141 |
response.content = self._store.get(tid) |
| 142 |
elif method == "PUT": |
| 143 |
self._store[tid] = data |
| 144 |
response.content = str_to_bytes(f'{{"ok":true,"id":"{tid}","rev":"1-revid"}}') |
| 145 |
elif method == "HEAD": |
| 146 |
if tid not in self._store: |
| 147 |
return self._not_found_response() |
| 148 |
response.headers.update({"etag": "1-revid"}) |
| 149 |
elif method == "DELETE": |
| 150 |
if tid not in self._store: |
| 151 |
return self._not_found_response() |
| 152 |
del self._store[tid] |
| 153 |
response.content = str_to_bytes(f'{{"ok":true,"id":"{tid}","rev":"1-revid"}}') |
| 154 |
else: |
| 155 |
raise NotImplementedError(f"CouchSessionMock.request() does not handle {method} method") |
| 156 |
|
| 157 |
return response |
| 158 |
|
| 159 |
def _not_found_response(self): |
| 160 |
response = Mock() |
| 161 |
response.headers = {"content-type": "application/json"} |
| 162 |
response.status_code = 404 |
| 163 |
response.content = str_to_bytes('{"error":"not_found","reason":"missing"}') |
| 164 |
return response |
| 165 |
|
| 166 |
|
| 167 |
class test_CouchBackend_result: |
| 168 |
def setup_method(self): |
| 169 |
self.backend = CouchBackend(app=self.app) |
| 170 |
resource = pycouchdb.resource.Resource("resource-url", session=CouchSessionMock()) |
| 171 |
self.backend._connection = pycouchdb.client.Database(resource, "container") |
| 172 |
|
| 173 |
def test_get_set_forget(self): |
| 174 |
tid = uuid() |
| 175 |
self.backend.store_result(tid, "successful-result", states.SUCCESS) |
| 176 |
assert self.backend.get_state(tid) == states.SUCCESS |
| 177 |
assert self.backend.get_result(tid) == "successful-result" |
| 178 |
self.backend.forget(tid) |
| 179 |
assert self.backend.get_state(tid) == states.PENDING |
| 180 |
|
| 181 |
def test_mark_as_started(self): |
| 182 |
tid = uuid() |
| 183 |
self.backend.mark_as_started(tid) |
| 184 |
assert self.backend.get_state(tid) == states.STARTED |
| 185 |
|
| 186 |
def test_mark_as_revoked(self): |
| 187 |
tid = uuid() |
| 188 |
self.backend.mark_as_revoked(tid) |
| 189 |
assert self.backend.get_state(tid) == states.REVOKED |
| 190 |
|
| 191 |
def test_mark_as_retry(self): |
| 192 |
tid = uuid() |
| 193 |
try: |
| 194 |
raise KeyError('foo') |
| 195 |
except KeyError as exception: |
| 196 |
import traceback |
| 197 |
trace = '\n'.join(traceback.format_stack()) |
| 198 |
self.backend.mark_as_retry(tid, exception, traceback=trace) |
| 199 |
assert self.backend.get_state(tid) == states.RETRY |
| 200 |
assert isinstance(self.backend.get_result(tid), KeyError) |
| 201 |
assert self.backend.get_traceback(tid) == trace |
| 202 |
|
| 203 |
def test_mark_as_failure(self): |
| 204 |
tid = uuid() |
| 205 |
try: |
| 206 |
raise KeyError('foo') |
| 207 |
except KeyError as exception: |
| 208 |
import traceback |
| 209 |
trace = '\n'.join(traceback.format_stack()) |
| 210 |
self.backend.mark_as_failure(tid, exception, traceback=trace) |
| 211 |
assert self.backend.get_state(tid) == states.FAILURE |
| 212 |
assert isinstance(self.backend.get_result(tid), KeyError) |
| 213 |
assert self.backend.get_traceback(tid) == trace |