| 1 |
import datetime |
| 2 |
from pickle import dumps, loads |
| 3 |
from unittest.mock import ANY, MagicMock, Mock, patch, sentinel |
| 4 |
|
| 5 |
import dns.version |
| 6 |
import pymongo |
| 7 |
import pytest |
| 8 |
from kombu.exceptions import EncodeError |
| 9 |
|
| 10 |
try: |
| 11 |
from pymongo.errors import ConfigurationError |
| 12 |
except ImportError: |
| 13 |
ConfigurationError = None |
| 14 |
|
| 15 |
|
| 16 |
import sys |
| 17 |
|
| 18 |
if sys.version_info >= (3, 9): |
| 19 |
from zoneinfo import ZoneInfo |
| 20 |
else: |
| 21 |
from backports.zoneinfo import ZoneInfo |
| 22 |
|
| 23 |
from celery import states, uuid |
| 24 |
from celery.backends.mongodb import Binary, InvalidDocument, MongoBackend |
| 25 |
from celery.exceptions import ImproperlyConfigured |
| 26 |
from t.unit import conftest |
| 27 |
|
| 28 |
COLLECTION = 'taskmeta_celery' |
| 29 |
TASK_ID = uuid() |
| 30 |
MONGODB_HOST = 'localhost' |
| 31 |
MONGODB_PORT = 27017 |
| 32 |
MONGODB_USER = 'mongo' |
| 33 |
MONGODB_PASSWORD = '1234' |
| 34 |
MONGODB_DATABASE = 'testing' |
| 35 |
MONGODB_COLLECTION = 'collection1' |
| 36 |
MONGODB_GROUP_COLLECTION = 'group_collection1' |
| 37 |
# uri with user, password, database name, replica set, DNS seedlist format |
| 38 |
MONGODB_SEEDLIST_URI = ('srv://' |
| 39 |
'celeryuser:celerypassword@' |
| 40 |
'dns-seedlist-host.example.com/' |
| 41 |
'celerydatabase') |
| 42 |
MONGODB_BACKEND_HOST = [ |
| 43 |
'mongo1.example.com:27017', |
| 44 |
'mongo2.example.com:27017', |
| 45 |
'mongo3.example.com:27017', |
| 46 |
] |
| 47 |
CELERY_USER = 'celeryuser' |
| 48 |
CELERY_PASSWORD = 'celerypassword' |
| 49 |
CELERY_DATABASE = 'celerydatabase' |
| 50 |
|
| 51 |
pytest.importorskip('pymongo') |
| 52 |
|
| 53 |
|
| 54 |
def fake_resolver_dnspython(): |
| 55 |
TXT = pytest.importorskip('dns.rdtypes.ANY.TXT').TXT |
| 56 |
SRV = pytest.importorskip('dns.rdtypes.IN.SRV').SRV |
| 57 |
|
| 58 |
def mock_resolver(_, rdtype, rdclass=None, lifetime=None, **kwargs): |
| 59 |
|
| 60 |
if rdtype == 'SRV': |
| 61 |
return [ |
| 62 |
SRV(0, 0, 0, 0, 27017, hostname) |
| 63 |
for hostname in [ |
| 64 |
'mongo1.example.com', |
| 65 |
'mongo2.example.com', |
| 66 |
'mongo3.example.com' |
| 67 |
] |
| 68 |
] |
| 69 |
elif rdtype == 'TXT': |
| 70 |
return [TXT(0, 0, [b'replicaSet=rs0'])] |
| 71 |
|
| 72 |
return mock_resolver |
| 73 |
|
| 74 |
|
| 75 |
class test_MongoBackend: |
| 76 |
default_url = 'mongodb://uuuu:[email protected]/database' |
| 77 |
replica_set_url = ( |
| 78 |
'mongodb://uuuu:[email protected],' |
| 79 |
'hostname.dom/database?replicaSet=rs' |
| 80 |
) |
| 81 |
sanitized_default_url = 'mongodb://uuuu:**@hostname.dom/database' |
| 82 |
sanitized_replica_set_url = ( |
| 83 |
'mongodb://uuuu:**@hostname.dom/,' |
| 84 |
'hostname.dom/database?replicaSet=rs' |
| 85 |
) |
| 86 |
|
| 87 |
def setup_method(self): |
| 88 |
self.patching('celery.backends.mongodb.MongoBackend.encode') |
| 89 |
self.patching('celery.backends.mongodb.MongoBackend.decode') |
| 90 |
self.patching('celery.backends.mongodb.Binary') |
| 91 |
self.backend = MongoBackend(app=self.app, url=self.default_url) |
| 92 |
|
| 93 |
def test_init_no_mongodb(self, patching): |
| 94 |
patching('celery.backends.mongodb.pymongo', None) |
| 95 |
with pytest.raises(ImproperlyConfigured): |
| 96 |
MongoBackend(app=self.app) |
| 97 |
|
| 98 |
def test_init_no_settings(self): |
| 99 |
self.app.conf.mongodb_backend_settings = [] |
| 100 |
with pytest.raises(ImproperlyConfigured): |
| 101 |
MongoBackend(app=self.app) |
| 102 |
|
| 103 |
def test_init_settings_is_None(self): |
| 104 |
self.app.conf.mongodb_backend_settings = None |
| 105 |
MongoBackend(app=self.app) |
| 106 |
|
| 107 |
def test_init_with_settings(self): |
| 108 |
self.app.conf.mongodb_backend_settings = None |
| 109 |
# empty settings |
| 110 |
mb = MongoBackend(app=self.app) |
| 111 |
|
| 112 |
# uri |
| 113 |
uri = 'mongodb://localhost:27017' |
| 114 |
mb = MongoBackend(app=self.app, url=uri) |
| 115 |
assert mb.mongo_host == ['localhost:27017'] |
| 116 |
assert mb.options == mb._prepare_client_options() |
| 117 |
assert mb.database_name == 'celery' |
| 118 |
|
| 119 |
# uri with database name |
| 120 |
uri = 'mongodb://localhost:27017/celerydb' |
| 121 |
mb = MongoBackend(app=self.app, url=uri) |
| 122 |
assert mb.database_name == 'celerydb' |
| 123 |
|
| 124 |
# uri with user, password, database name, replica set |
| 125 |
uri = ('mongodb://' |
| 126 |
'celeryuser:celerypassword@' |
| 127 |
'mongo1.example.com:27017,' |
| 128 |
'mongo2.example.com:27017,' |
| 129 |
'mongo3.example.com:27017/' |
| 130 |
'celerydatabase?replicaSet=rs0') |
| 131 |
mb = MongoBackend(app=self.app, url=uri) |
| 132 |
assert mb.mongo_host == MONGODB_BACKEND_HOST |
| 133 |
if 'replicaSet' in mb.options: # pragma: no cover # pymongo >= 4.14 |
| 134 |
replicaset_option = 'replicaSet' |
| 135 |
else: # pragma: no cover # pymongo < 4.14 |
| 136 |
replicaset_option = 'replicaset' |
| 137 |
assert mb.options == { |
| 138 |
**mb._prepare_client_options(), |
| 139 |
replicaset_option: 'rs0', |
| 140 |
} |
| 141 |
assert mb.user == CELERY_USER |
| 142 |
assert mb.password == CELERY_PASSWORD |
| 143 |
assert mb.database_name == CELERY_DATABASE |
| 144 |
|
| 145 |
# same uri, change some parameters in backend settings |
| 146 |
self.app.conf.mongodb_backend_settings = { |
| 147 |
replicaset_option: 'rs1', |
| 148 |
'user': 'backenduser', |
| 149 |
'database': 'another_db', |
| 150 |
'options': { |
| 151 |
'socketKeepAlive': True, |
| 152 |
}, |
| 153 |
} |
| 154 |
mb = MongoBackend(app=self.app, url=uri) |
| 155 |
assert mb.mongo_host == MONGODB_BACKEND_HOST |
| 156 |
assert mb.options == { |
| 157 |
**mb._prepare_client_options(), |
| 158 |
replicaset_option: 'rs1', |
| 159 |
'socketKeepAlive': True, |
| 160 |
} |
| 161 |
assert mb.user == 'backenduser' |
| 162 |
assert mb.password == CELERY_PASSWORD |
| 163 |
assert mb.database_name == 'another_db' |
| 164 |
|
| 165 |
mb = MongoBackend(app=self.app, url='mongodb://') |
| 166 |
|
| 167 |
@pytest.mark.skipif(dns.version.MAJOR > 1, |
| 168 |
reason="For dnspython version > 1, pymongo's" |
| 169 |
"srv_resolver calls resolver.resolve") |
| 170 |
@pytest.mark.skipif(pymongo.version_tuple[0] > 3, |
| 171 |
reason="For pymongo version > 3, options returns ssl") |
| 172 |
def test_init_mongodb_dnspython1_pymongo3_seedlist(self): |
| 173 |
resolver = fake_resolver_dnspython() |
| 174 |
self.app.conf.mongodb_backend_settings = None |
| 175 |
|
| 176 |
with patch('dns.resolver.query', side_effect=resolver): |
| 177 |
mb = self.perform_seedlist_assertions() |
| 178 |
assert mb.options == dict( |
| 179 |
mb._prepare_client_options(), |
| 180 |
replicaset='rs0', |
| 181 |
ssl=True |
| 182 |
) |
| 183 |
|
| 184 |
@pytest.mark.skipif(dns.version.MAJOR <= 1, |
| 185 |
reason="For dnspython versions 1.X, pymongo's" |
| 186 |
"srv_resolver calls resolver.query") |
| 187 |
@pytest.mark.skipif(pymongo.version_tuple[0] > 3, |
| 188 |
reason="For pymongo version > 3, options returns ssl") |
| 189 |
def test_init_mongodb_dnspython2_pymongo3_seedlist(self): |
| 190 |
resolver = fake_resolver_dnspython() |
| 191 |
self.app.conf.mongodb_backend_settings = None |
| 192 |
|
| 193 |
with patch('dns.resolver.resolve', side_effect=resolver): |
| 194 |
mb = self.perform_seedlist_assertions() |
| 195 |
assert mb.options == dict( |
| 196 |
mb._prepare_client_options(), |
| 197 |
replicaset='rs0', |
| 198 |
ssl=True |
| 199 |
) |
| 200 |
|
| 201 |
@pytest.mark.skipif(dns.version.MAJOR > 1, |
| 202 |
reason="For dnspython version >= 2, pymongo's" |
| 203 |
"srv_resolver calls resolver.resolve") |
| 204 |
@pytest.mark.skipif(pymongo.version_tuple[0] <= 3, |
| 205 |
reason="For pymongo version > 3, options returns tls") |
| 206 |
def test_init_mongodb_dnspython1_pymongo4_seedlist(self): |
| 207 |
resolver = fake_resolver_dnspython() |
| 208 |
self.app.conf.mongodb_backend_settings = None |
| 209 |
|
| 210 |
with patch('dns.resolver.query', side_effect=resolver): |
| 211 |
mb = self.perform_seedlist_assertions() |
| 212 |
assert mb.options == dict( |
| 213 |
mb._prepare_client_options(), |
| 214 |
replicaset='rs0', |
| 215 |
tls=True |
| 216 |
) |
| 217 |
|
| 218 |
@pytest.mark.skipif(dns.version.MAJOR <= 1, |
| 219 |
reason="For dnspython versions 1.X, pymongo's" |
| 220 |
"srv_resolver calls resolver.query") |
| 221 |
@pytest.mark.skipif(pymongo.version_tuple[0] <= 3, |
| 222 |
reason="For pymongo version > 3, options returns tls") |
| 223 |
def test_init_mongodb_dnspython2_pymongo4_seedlist(self): |
| 224 |
resolver = fake_resolver_dnspython() |
| 225 |
self.app.conf.mongodb_backend_settings = None |
| 226 |
|
| 227 |
with patch('dns.resolver.resolve', side_effect=resolver): |
| 228 |
mb = self.perform_seedlist_assertions() |
| 229 |
if 'replicaSet' in mb.options: # pragma: no cover # pymongo >= 4.14 |
| 230 |
replicaset_option = 'replicaSet' |
| 231 |
else: # pragma: no cover # pymongo < 4.14 |
| 232 |
replicaset_option = 'replicaset' |
| 233 |
assert mb.options == { |
| 234 |
**mb._prepare_client_options(), |
| 235 |
replicaset_option: 'rs0', |
| 236 |
'tls': True, |
| 237 |
} |
| 238 |
|
| 239 |
def perform_seedlist_assertions(self): |
| 240 |
mb = MongoBackend(app=self.app, url=MONGODB_SEEDLIST_URI) |
| 241 |
assert mb.mongo_host == MONGODB_BACKEND_HOST |
| 242 |
assert mb.user == CELERY_USER |
| 243 |
assert mb.password == CELERY_PASSWORD |
| 244 |
assert mb.database_name == CELERY_DATABASE |
| 245 |
return mb |
| 246 |
|
| 247 |
def test_ensure_mongodb_uri_compliance(self): |
| 248 |
mb = MongoBackend(app=self.app, url=None) |
| 249 |
compliant_uri = mb._ensure_mongodb_uri_compliance |
| 250 |
|
| 251 |
assert compliant_uri('mongodb://') == 'mongodb://localhost' |
| 252 |
|
| 253 |
assert compliant_uri('mongodb+something://host') == \ |
| 254 |
'mongodb+something://host' |
| 255 |
|
| 256 |
assert compliant_uri('something://host') == 'mongodb+something://host' |
| 257 |
|
| 258 |
@pytest.mark.usefixtures('depends_on_current_app') |
| 259 |
def test_reduce(self): |
| 260 |
x = MongoBackend(app=self.app) |
| 261 |
assert loads(dumps(x)) |
| 262 |
|
| 263 |
def test_get_connection_connection_exists(self): |
| 264 |
with patch('pymongo.MongoClient') as mock_Connection: |
| 265 |
self.backend._connection = sentinel._connection |
| 266 |
|
| 267 |
connection = self.backend._get_connection() |
| 268 |
|
| 269 |
assert sentinel._connection == connection |
| 270 |
mock_Connection.assert_not_called() |
| 271 |
|
| 272 |
def test_get_connection_no_connection_host(self): |
| 273 |
with patch('pymongo.MongoClient') as mock_Connection: |
| 274 |
self.backend._connection = None |
| 275 |
self.backend.host = MONGODB_HOST |
| 276 |
self.backend.port = MONGODB_PORT |
| 277 |
mock_Connection.return_value = sentinel.connection |
| 278 |
|
| 279 |
connection = self.backend._get_connection() |
| 280 |
mock_Connection.assert_called_once_with( |
| 281 |
host='mongodb://localhost:27017', |
| 282 |
**self.backend._prepare_client_options() |
| 283 |
) |
| 284 |
assert sentinel.connection == connection |
| 285 |
|
| 286 |
def test_get_connection_no_connection_mongodb_uri(self): |
| 287 |
with patch('pymongo.MongoClient') as mock_Connection: |
| 288 |
mongodb_uri = 'mongodb://%s:%d' % (MONGODB_HOST, MONGODB_PORT) |
| 289 |
self.backend._connection = None |
| 290 |
self.backend.host = mongodb_uri |
| 291 |
|
| 292 |
mock_Connection.return_value = sentinel.connection |
| 293 |
|
| 294 |
connection = self.backend._get_connection() |
| 295 |
mock_Connection.assert_called_once_with( |
| 296 |
host=mongodb_uri, **self.backend._prepare_client_options() |
| 297 |
) |
| 298 |
assert sentinel.connection == connection |
| 299 |
|
| 300 |
def test_get_connection_with_authmechanism(self): |
| 301 |
with patch('pymongo.MongoClient') as mock_Connection: |
| 302 |
self.app.conf.mongodb_backend_settings = None |
| 303 |
uri = ('mongodb://' |
| 304 |
'celeryuser:celerypassword@' |
| 305 |
'localhost:27017/' |
| 306 |
'celerydatabase?authMechanism=SCRAM-SHA-256') |
| 307 |
mb = MongoBackend(app=self.app, url=uri) |
| 308 |
mock_Connection.return_value = sentinel.connection |
| 309 |
connection = mb._get_connection() |
| 310 |
if 'authMechanism' in mb.options: # pragma: no cover # pymongo >= 4.14 |
| 311 |
authmechanism_option = 'authMechanism' |
| 312 |
else: # pragma: no cover # pymongo < 4.14 |
| 313 |
authmechanism_option = 'authmechanism' |
| 314 |
mock_Connection.assert_called_once_with( |
| 315 |
host=['localhost:27017'], |
| 316 |
username=CELERY_USER, |
| 317 |
password=CELERY_PASSWORD, |
| 318 |
**{**mb._prepare_client_options(), authmechanism_option: 'SCRAM-SHA-256'} |
| 319 |
) |
| 320 |
assert sentinel.connection == connection |
| 321 |
|
| 322 |
def test_get_connection_with_authmechanism_no_username(self): |
| 323 |
with patch('pymongo.MongoClient') as mock_Connection: |
| 324 |
self.app.conf.mongodb_backend_settings = None |
| 325 |
uri = ('mongodb://' |
| 326 |
'localhost:27017/' |
| 327 |
'celerydatabase?authMechanism=SCRAM-SHA-256') |
| 328 |
mb = MongoBackend(app=self.app, url=uri) |
| 329 |
mock_Connection.side_effect = ConfigurationError( |
| 330 |
'SCRAM-SHA-256 requires a username.') |
| 331 |
with pytest.raises(ConfigurationError): |
| 332 |
mb._get_connection() |
| 333 |
if 'authMechanism' in mb.options: # pragma: no cover # pymongo >= 4.14 |
| 334 |
authmechanism_option = 'authMechanism' |
| 335 |
else: # pragma: no cover # pymongo < 4.14 |
| 336 |
authmechanism_option = 'authmechanism' |
| 337 |
mock_Connection.assert_called_once_with( |
| 338 |
host=['localhost:27017'], |
| 339 |
**{**mb._prepare_client_options(), authmechanism_option: 'SCRAM-SHA-256'} |
| 340 |
) |
| 341 |
|
| 342 |
@patch('celery.backends.mongodb.MongoBackend._get_connection') |
| 343 |
def test_get_database_no_existing(self, mock_get_connection): |
| 344 |
# Should really check for combinations of these two, to be complete. |
| 345 |
self.backend.user = MONGODB_USER |
| 346 |
self.backend.password = MONGODB_PASSWORD |
| 347 |
|
| 348 |
mock_database = Mock() |
| 349 |
mock_connection = MagicMock(spec=['__getitem__']) |
| 350 |
mock_connection.__getitem__.return_value = mock_database |
| 351 |
mock_get_connection.return_value = mock_connection |
| 352 |
|
| 353 |
database = self.backend.database |
| 354 |
|
| 355 |
assert database is mock_database |
| 356 |
assert self.backend.__dict__['database'] is mock_database |
| 357 |
|
| 358 |
@patch('celery.backends.mongodb.MongoBackend._get_connection') |
| 359 |
def test_get_database_no_existing_no_auth(self, mock_get_connection): |
| 360 |
# Should really check for combinations of these two, to be complete. |
| 361 |
self.backend.user = None |
| 362 |
self.backend.password = None |
| 363 |
|
| 364 |
mock_database = Mock() |
| 365 |
mock_connection = MagicMock(spec=['__getitem__']) |
| 366 |
mock_connection.__getitem__.return_value = mock_database |
| 367 |
mock_get_connection.return_value = mock_connection |
| 368 |
|
| 369 |
database = self.backend.database |
| 370 |
|
| 371 |
assert database is mock_database |
| 372 |
assert self.backend.__dict__['database'] is mock_database |
| 373 |
|
| 374 |
@patch('celery.backends.mongodb.MongoBackend._get_database') |
| 375 |
def test_store_result(self, mock_get_database): |
| 376 |
self.backend.taskmeta_collection = MONGODB_COLLECTION |
| 377 |
|
| 378 |
mock_database = MagicMock(spec=['__getitem__', '__setitem__']) |
| 379 |
mock_collection = Mock() |
| 380 |
|
| 381 |
mock_get_database.return_value = mock_database |
| 382 |
mock_database.__getitem__.return_value = mock_collection |
| 383 |
|
| 384 |
ret_val = self.backend._store_result( |
| 385 |
sentinel.task_id, sentinel.result, sentinel.status) |
| 386 |
|
| 387 |
mock_get_database.assert_called_once_with() |
| 388 |
mock_database.__getitem__.assert_called_once_with(MONGODB_COLLECTION) |
| 389 |
mock_collection.replace_one.assert_called_once_with(ANY, ANY, |
| 390 |
upsert=True) |
| 391 |
assert sentinel.result == ret_val |
| 392 |
|
| 393 |
mock_collection.replace_one.side_effect = InvalidDocument("bad") |
| 394 |
with pytest.raises(EncodeError): |
| 395 |
self.backend._store_result( |
| 396 |
sentinel.task_id, sentinel.result, sentinel.status) |
| 397 |
|
| 398 |
@patch('celery.backends.mongodb.MongoBackend._get_database') |
| 399 |
def test_store_result_with_request(self, mock_get_database): |
| 400 |
self.backend.taskmeta_collection = MONGODB_COLLECTION |
| 401 |
|
| 402 |
mock_database = MagicMock(spec=['__getitem__', '__setitem__']) |
| 403 |
mock_collection = Mock() |
| 404 |
mock_request = MagicMock(spec=['parent_id']) |
| 405 |
|
| 406 |
mock_get_database.return_value = mock_database |
| 407 |
mock_database.__getitem__.return_value = mock_collection |
| 408 |
mock_request.parent_id = sentinel.parent_id |
| 409 |
|
| 410 |
ret_val = self.backend._store_result( |
| 411 |
sentinel.task_id, sentinel.result, sentinel.status, |
| 412 |
request=mock_request) |
| 413 |
|
| 414 |
mock_get_database.assert_called_once_with() |
| 415 |
mock_database.__getitem__.assert_called_once_with(MONGODB_COLLECTION) |
| 416 |
parameters = mock_collection.replace_one.call_args[0][1] |
| 417 |
assert parameters['parent_id'] == sentinel.parent_id |
| 418 |
assert sentinel.result == ret_val |
| 419 |
|
| 420 |
mock_collection.replace_one.side_effect = InvalidDocument("bad") |
| 421 |
with pytest.raises(EncodeError): |
| 422 |
self.backend._store_result( |
| 423 |
sentinel.task_id, sentinel.result, sentinel.status) |
| 424 |
|
| 425 |
@patch('celery.backends.mongodb.MongoBackend._get_database') |
| 426 |
def test_get_task_meta_for(self, mock_get_database): |
| 427 |
self.backend.taskmeta_collection = MONGODB_COLLECTION |
| 428 |
|
| 429 |
mock_database = MagicMock(spec=['__getitem__', '__setitem__']) |
| 430 |
mock_collection = Mock() |
| 431 |
mock_collection.find_one.return_value = MagicMock() |
| 432 |
|
| 433 |
mock_get_database.return_value = mock_database |
| 434 |
mock_database.__getitem__.return_value = mock_collection |
| 435 |
|
| 436 |
ret_val = self.backend._get_task_meta_for(sentinel.task_id) |
| 437 |
|
| 438 |
mock_get_database.assert_called_once_with() |
| 439 |
mock_database.__getitem__.assert_called_once_with(MONGODB_COLLECTION) |
| 440 |
assert list(sorted([ |
| 441 |
'status', 'task_id', 'date_done', |
| 442 |
'traceback', 'result', 'children', |
| 443 |
])) == list(sorted(ret_val.keys())) |
| 444 |
|
| 445 |
@patch('celery.backends.mongodb.MongoBackend._get_database') |
| 446 |
def test_get_task_meta_for_result_extended(self, mock_get_database): |
| 447 |
self.backend.taskmeta_collection = MONGODB_COLLECTION |
| 448 |
|
| 449 |
mock_database = MagicMock(spec=['__getitem__', '__setitem__']) |
| 450 |
mock_collection = Mock() |
| 451 |
mock_collection.find_one.return_value = MagicMock() |
| 452 |
|
| 453 |
mock_get_database.return_value = mock_database |
| 454 |
mock_database.__getitem__.return_value = mock_collection |
| 455 |
|
| 456 |
self.app.conf.result_extended = True |
| 457 |
ret_val = self.backend._get_task_meta_for(sentinel.task_id) |
| 458 |
|
| 459 |
mock_get_database.assert_called_once_with() |
| 460 |
mock_database.__getitem__.assert_called_once_with(MONGODB_COLLECTION) |
| 461 |
assert list(sorted([ |
| 462 |
'status', 'task_id', 'date_done', |
| 463 |
'traceback', 'result', 'children', |
| 464 |
'name', 'args', 'queue', 'kwargs', 'worker', 'retries', |
| 465 |
])) == list(sorted(ret_val.keys())) |
| 466 |
|
| 467 |
@patch('celery.backends.mongodb.MongoBackend._get_database') |
| 468 |
def test_get_task_meta_for_no_result(self, mock_get_database): |
| 469 |
self.backend.taskmeta_collection = MONGODB_COLLECTION |
| 470 |
|
| 471 |
mock_database = MagicMock(spec=['__getitem__', '__setitem__']) |
| 472 |
mock_collection = Mock() |
| 473 |
mock_collection.find_one.return_value = None |
| 474 |
|
| 475 |
mock_get_database.return_value = mock_database |
| 476 |
mock_database.__getitem__.return_value = mock_collection |
| 477 |
|
| 478 |
ret_val = self.backend._get_task_meta_for(sentinel.task_id) |
| 479 |
|
| 480 |
mock_get_database.assert_called_once_with() |
| 481 |
mock_database.__getitem__.assert_called_once_with(MONGODB_COLLECTION) |
| 482 |
assert {'status': states.PENDING, 'result': None} == ret_val |
| 483 |
|
| 484 |
@patch('celery.backends.mongodb.MongoBackend._get_database') |
| 485 |
def test_save_group(self, mock_get_database): |
| 486 |
self.backend.groupmeta_collection = MONGODB_GROUP_COLLECTION |
| 487 |
|
| 488 |
mock_database = MagicMock(spec=['__getitem__', '__setitem__']) |
| 489 |
mock_collection = Mock() |
| 490 |
|
| 491 |
mock_get_database.return_value = mock_database |
| 492 |
mock_database.__getitem__.return_value = mock_collection |
| 493 |
res = [self.app.AsyncResult(i) for i in range(3)] |
| 494 |
ret_val = self.backend._save_group( |
| 495 |
sentinel.taskset_id, res, |
| 496 |
) |
| 497 |
mock_get_database.assert_called_once_with() |
| 498 |
mock_database.__getitem__.assert_called_once_with( |
| 499 |
MONGODB_GROUP_COLLECTION, |
| 500 |
) |
| 501 |
mock_collection.replace_one.assert_called_once_with(ANY, ANY, |
| 502 |
upsert=True) |
| 503 |
assert res == ret_val |
| 504 |
|
| 505 |
@patch('celery.backends.mongodb.MongoBackend._get_database') |
| 506 |
def test_restore_group(self, mock_get_database): |
| 507 |
self.backend.groupmeta_collection = MONGODB_GROUP_COLLECTION |
| 508 |
|
| 509 |
mock_database = MagicMock(spec=['__getitem__', '__setitem__']) |
| 510 |
mock_collection = Mock() |
| 511 |
mock_collection.find_one.return_value = { |
| 512 |
'_id': sentinel.taskset_id, |
| 513 |
'result': [uuid(), uuid()], |
| 514 |
'date_done': 1, |
| 515 |
} |
| 516 |
self.backend.decode.side_effect = lambda r: r |
| 517 |
|
| 518 |
mock_get_database.return_value = mock_database |
| 519 |
mock_database.__getitem__.return_value = mock_collection |
| 520 |
|
| 521 |
ret_val = self.backend._restore_group(sentinel.taskset_id) |
| 522 |
|
| 523 |
mock_get_database.assert_called_once_with() |
| 524 |
mock_collection.find_one.assert_called_once_with( |
| 525 |
{'_id': sentinel.taskset_id}) |
| 526 |
assert (sorted(['date_done', 'result', 'task_id']) == |
| 527 |
sorted(list(ret_val.keys()))) |
| 528 |
|
| 529 |
mock_collection.find_one.return_value = None |
| 530 |
self.backend._restore_group(sentinel.taskset_id) |
| 531 |
|
| 532 |
@patch('celery.backends.mongodb.MongoBackend._get_database') |
| 533 |
def test_delete_group(self, mock_get_database): |
| 534 |
self.backend.taskmeta_collection = MONGODB_COLLECTION |
| 535 |
|
| 536 |
mock_database = MagicMock(spec=['__getitem__', '__setitem__']) |
| 537 |
mock_collection = Mock() |
| 538 |
|
| 539 |
mock_get_database.return_value = mock_database |
| 540 |
mock_database.__getitem__.return_value = mock_collection |
| 541 |
|
| 542 |
self.backend._delete_group(sentinel.taskset_id) |
| 543 |
|
| 544 |
mock_get_database.assert_called_once_with() |
| 545 |
mock_collection.delete_one.assert_called_once_with( |
| 546 |
{'_id': sentinel.taskset_id}) |
| 547 |
|
| 548 |
@patch('celery.backends.mongodb.MongoBackend._get_database') |
| 549 |
def test__forget(self, mock_get_database): |
| 550 |
# note: here tested _forget method, not forget method |
| 551 |
self.backend.taskmeta_collection = MONGODB_COLLECTION |
| 552 |
|
| 553 |
mock_database = MagicMock(spec=['__getitem__', '__setitem__']) |
| 554 |
mock_collection = Mock() |
| 555 |
|
| 556 |
mock_get_database.return_value = mock_database |
| 557 |
mock_database.__getitem__.return_value = mock_collection |
| 558 |
|
| 559 |
self.backend._forget(sentinel.task_id) |
| 560 |
|
| 561 |
mock_get_database.assert_called_once_with() |
| 562 |
mock_database.__getitem__.assert_called_once_with( |
| 563 |
MONGODB_COLLECTION) |
| 564 |
mock_collection.delete_one.assert_called_once_with( |
| 565 |
{'_id': sentinel.task_id}) |
| 566 |
|
| 567 |
@patch('celery.backends.mongodb.MongoBackend._get_database') |
| 568 |
def test_cleanup(self, mock_get_database): |
| 569 |
self.backend.taskmeta_collection = MONGODB_COLLECTION |
| 570 |
self.backend.groupmeta_collection = MONGODB_GROUP_COLLECTION |
| 571 |
|
| 572 |
mock_database = Mock(spec=['__getitem__', '__setitem__'], |
| 573 |
name='MD') |
| 574 |
self.backend.collections = mock_collection = Mock() |
| 575 |
|
| 576 |
mock_get_database.return_value = mock_database |
| 577 |
mock_database.__getitem__ = Mock(name='MD.__getitem__') |
| 578 |
mock_database.__getitem__.return_value = mock_collection |
| 579 |
|
| 580 |
def now_func(): |
| 581 |
return datetime.datetime.now(datetime.timezone.utc) |
| 582 |
|
| 583 |
self.backend.app.now = now_func |
| 584 |
self.backend.cleanup() |
| 585 |
|
| 586 |
mock_get_database.assert_called_once_with() |
| 587 |
mock_collection.delete_many.assert_called() |
| 588 |
|
| 589 |
self.backend.collections = mock_collection = Mock() |
| 590 |
self.backend.expires = None |
| 591 |
|
| 592 |
self.backend.cleanup() |
| 593 |
mock_collection.delete_many.assert_not_called() |
| 594 |
|
| 595 |
def test_prepare_client_options(self): |
| 596 |
with patch('pymongo.version_tuple', new=(3, 0, 3)): |
| 597 |
options = self.backend._prepare_client_options() |
| 598 |
assert options == { |
| 599 |
'maxPoolSize': self.backend.max_pool_size |
| 600 |
} |
| 601 |
|
| 602 |
def test_as_uri_include_password(self): |
| 603 |
assert self.backend.as_uri(True) == self.default_url |
| 604 |
|
| 605 |
def test_as_uri_exclude_password(self): |
| 606 |
assert self.backend.as_uri() == self.sanitized_default_url |
| 607 |
|
| 608 |
def test_as_uri_include_password_replica_set(self): |
| 609 |
backend = MongoBackend(app=self.app, url=self.replica_set_url) |
| 610 |
assert backend.as_uri(True) == self.replica_set_url |
| 611 |
|
| 612 |
def test_as_uri_exclude_password_replica_set(self): |
| 613 |
backend = MongoBackend(app=self.app, url=self.replica_set_url) |
| 614 |
assert backend.as_uri() == self.sanitized_replica_set_url |
| 615 |
|
| 616 |
def test_regression_worker_startup_info(self): |
| 617 |
self.app.conf.result_backend = ( |
| 618 |
'mongodb://user:[email protected]:43437,host1.com:43437' |
| 619 |
'/work4us?replicaSet=rs&ssl=true' |
| 620 |
) |
| 621 |
worker = self.app.Worker() |
| 622 |
with conftest.stdouts(): |
| 623 |
worker.on_start() |
| 624 |
assert worker.startup_info() |
| 625 |
|
| 626 |
|
| 627 |
@pytest.fixture(scope="function") |
| 628 |
def mongo_backend_factory(app): |
| 629 |
"""Return a factory that creates MongoBackend instance with given serializer, including BSON.""" |
| 630 |
|
| 631 |
def create_mongo_backend(serializer): |
| 632 |
# NOTE: `bson` is a only mongodb-specific type and can be set only directly on MongoBackend instance. |
| 633 |
if serializer == "bson": |
| 634 |
beckend = MongoBackend(app=app) |
| 635 |
beckend.serializer = serializer |
| 636 |
else: |
| 637 |
app.conf.accept_content = ['json', 'pickle', 'msgpack', 'yaml'] |
| 638 |
app.conf.result_serializer = serializer |
| 639 |
beckend = MongoBackend(app=app) |
| 640 |
return beckend |
| 641 |
|
| 642 |
yield create_mongo_backend |
| 643 |
|
| 644 |
|
| 645 |
@pytest.mark.parametrize("serializer,encoded_into", [ |
| 646 |
('bson', int), |
| 647 |
('json', str), |
| 648 |
('pickle', Binary), |
| 649 |
('msgpack', Binary), |
| 650 |
('yaml', str), |
| 651 |
]) |
| 652 |
class test_MongoBackend_no_mock: |
| 653 |
|
| 654 |
def test_encode(self, mongo_backend_factory, serializer, encoded_into): |
| 655 |
backend = mongo_backend_factory(serializer=serializer) |
| 656 |
assert isinstance(backend.encode(10), encoded_into) |
| 657 |
|
| 658 |
def test_encode_decode(self, mongo_backend_factory, serializer, |
| 659 |
encoded_into): |
| 660 |
backend = mongo_backend_factory(serializer=serializer) |
| 661 |
decoded = backend.decode(backend.encode(12)) |
| 662 |
assert decoded == 12 |
| 663 |
|
| 664 |
|
| 665 |
class _MyTestClass: |
| 666 |
|
| 667 |
def __init__(self, a): |
| 668 |
self.a = a |
| 669 |
|
| 670 |
def __eq__(self, other): |
| 671 |
assert self.__class__ == type(other) |
| 672 |
return self.a == other.a |
| 673 |
|
| 674 |
|
| 675 |
SUCCESS_RESULT_TEST_DATA = [ |
| 676 |
# json types |
| 677 |
{ |
| 678 |
"result": "A simple string", |
| 679 |
"serializers": ["bson", "pickle", "yaml", "json", "msgpack"], |
| 680 |
}, |
| 681 |
{ |
| 682 |
"result": 100, |
| 683 |
"serializers": ["bson", "pickle", "yaml", "json", "msgpack"], |
| 684 |
}, |
| 685 |
{ |
| 686 |
"result": 9.1999999999999999, |
| 687 |
"serializers": ["bson", "pickle", "yaml", "json", "msgpack"], |
| 688 |
}, |
| 689 |
{ |
| 690 |
"result": {"foo": "simple result"}, |
| 691 |
"serializers": ["bson", "pickle", "yaml", "json", "msgpack"], |
| 692 |
}, |
| 693 |
{ |
| 694 |
"result": ["a", "b"], |
| 695 |
"serializers": ["bson", "pickle", "yaml", "json", "msgpack"], |
| 696 |
}, |
| 697 |
{ |
| 698 |
"result": False, |
| 699 |
"serializers": ["bson", "pickle", "yaml", "json", "msgpack"], |
| 700 |
}, |
| 701 |
{ |
| 702 |
"result": None, |
| 703 |
"serializers": ["bson", "pickle", "yaml", "json", "msgpack"], |
| 704 |
}, |
| 705 |
# advanced essential types |
| 706 |
{ |
| 707 |
"result": datetime.datetime(2000, 1, 1, 0, 0, 0, 0), |
| 708 |
"serializers": ["bson", "pickle", "yaml"], |
| 709 |
}, |
| 710 |
{ |
| 711 |
"result": datetime.datetime(2000, 1, 1, 0, 0, 0, 0, tzinfo=ZoneInfo("UTC")), |
| 712 |
"serializers": ["pickle", "yaml"], |
| 713 |
}, |
| 714 |
# custom types |
| 715 |
{ |
| 716 |
"result": _MyTestClass("Hi!"), |
| 717 |
"serializers": ["pickle"], |
| 718 |
}, |
| 719 |
] |
| 720 |
|
| 721 |
|
| 722 |
class test_MongoBackend_store_get_result: |
| 723 |
|
| 724 |
@pytest.fixture(scope="function", autouse=True) |
| 725 |
def fake_mongo_collection_patch(self, monkeypatch): |
| 726 |
"""A fake collection with serialization experience close to MongoDB.""" |
| 727 |
bson = pytest.importorskip("bson") |
| 728 |
|
| 729 |
class FakeMongoCollection: |
| 730 |
def __init__(self): |
| 731 |
self.data = {} |
| 732 |
|
| 733 |
def replace_one(self, task_id, meta, upsert=True): |
| 734 |
self.data[task_id['_id']] = bson.encode(meta) |
| 735 |
|
| 736 |
def find_one(self, task_id): |
| 737 |
return bson.decode(self.data[task_id['_id']]) |
| 738 |
|
| 739 |
monkeypatch.setattr(MongoBackend, "collection", FakeMongoCollection()) |
| 740 |
|
| 741 |
@pytest.mark.parametrize("serializer,result_type,result", [ |
| 742 |
(s, type(i['result']), i['result']) for i in SUCCESS_RESULT_TEST_DATA |
| 743 |
for s in i['serializers']] |
| 744 |
) |
| 745 |
def test_encode_success_results(self, mongo_backend_factory, serializer, |
| 746 |
result_type, result): |
| 747 |
backend = mongo_backend_factory(serializer=serializer) |
| 748 |
backend.store_result(TASK_ID, result, 'SUCCESS') |
| 749 |
recovered = backend.get_result(TASK_ID) |
| 750 |
assert isinstance(recovered, result_type) |
| 751 |
assert recovered == result |
| 752 |
|
| 753 |
@pytest.mark.parametrize("serializer", |
| 754 |
["bson", "pickle", "yaml", "json", "msgpack"]) |
| 755 |
def test_encode_chain_results(self, mongo_backend_factory, serializer): |
| 756 |
backend = mongo_backend_factory(serializer=serializer) |
| 757 |
mock_request = MagicMock(spec=['children']) |
| 758 |
children = [self.app.AsyncResult(uuid()) for i in range(10)] |
| 759 |
mock_request.children = children |
| 760 |
backend.store_result(TASK_ID, 0, 'SUCCESS', request=mock_request) |
| 761 |
recovered = backend.get_children(TASK_ID) |
| 762 |
def tuple_to_list(t): return [list(t[0]), t[1]] |
| 763 |
assert recovered == [tuple_to_list(c.as_tuple()) for c in children] |
| 764 |
|
| 765 |
@pytest.mark.parametrize("serializer", |
| 766 |
["bson", "pickle", "yaml", "json", "msgpack"]) |
| 767 |
def test_encode_exception_error_results(self, mongo_backend_factory, |
| 768 |
serializer): |
| 769 |
backend = mongo_backend_factory(serializer=serializer) |
| 770 |
exception = Exception("Basic Exception") |
| 771 |
traceback = 'Traceback:\n Exception: Basic Exception\n' |
| 772 |
backend.store_result(TASK_ID, exception, 'FAILURE', traceback) |
| 773 |
recovered = backend.get_result(TASK_ID) |
| 774 |
assert isinstance(recovered, type(exception)) |
| 775 |
assert recovered.args == exception.args |