1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
|
import copy
import datetime
import platform
import traceback
from contextlib import contextmanager
from unittest.mock import Mock, call, patch
import pytest
from celery import states, uuid
from celery.app.task import Context
from celery.backends.base import Backend, SyncBackendMixin
from celery.exceptions import ImproperlyConfigured, IncompleteStream, TimeoutError
from celery.result import AsyncResult, EagerResult, GroupResult, ResultSet, assert_will_not_block, result_from_tuple
from celery.utils.serialization import pickle
PYTRACEBACK = """\
Traceback (most recent call last):
File "foo.py", line 2, in foofunc
don't matter
File "bar.py", line 3, in barfunc
don't matter
Doesn't matter: really!\
"""
def mock_task(name, state, result, traceback=None):
return {
'id': uuid(), 'name': name, 'state': state,
'result': result, 'traceback': traceback,
}
def save_result(app, task):
traceback = task.get('traceback') or 'Some traceback'
if task['state'] == states.SUCCESS:
app.backend.mark_as_done(task['id'], task['result'])
elif task['state'] == states.RETRY:
app.backend.mark_as_retry(
task['id'], task['result'], traceback=traceback,
)
else:
app.backend.mark_as_failure(
task['id'], task['result'], traceback=traceback,
)
def make_mock_group(app, size=10):
tasks = [mock_task('ts%d' % i, states.SUCCESS, i) for i in range(size)]
[save_result(app, task) for task in tasks]
return [app.AsyncResult(task['id']) for task in tasks]
class _MockBackend:
def add_pending_result(self, *args, **kwargs):
return True
def wait_for_pending(self, *args, **kwargs):
return True
def remove_pending_result(self, *args, **kwargs):
return True
class test_AsyncResult:
def setup_method(self):
self.app.conf.result_cache_max = 100
self.app.conf.result_serializer = 'pickle'
self.app.conf.result_extended = True
self.task1 = mock_task('task1', states.SUCCESS, 'the')
self.task2 = mock_task('task2', states.SUCCESS, 'quick')
self.task3 = mock_task('task3', states.FAILURE, KeyError('brown'))
self.task4 = mock_task('task3', states.RETRY, KeyError('red'))
self.task5 = mock_task(
'task3', states.FAILURE, KeyError('blue'), PYTRACEBACK,
)
self.task6 = mock_task('task6', states.SUCCESS, None)
for task in (self.task1, self.task2,
self.task3, self.task4, self.task5, self.task6):
save_result(self.app, task)
@self.app.task(shared=False)
def mytask():
pass
self.mytask = mytask
def test_forget(self):
first = Mock()
second = self.app.AsyncResult(self.task1['id'], parent=first)
third = self.app.AsyncResult(self.task2['id'], parent=second)
last = self.app.AsyncResult(self.task3['id'], parent=third)
last.forget()
first.forget.assert_called_once()
assert last.result is None
assert second.result is None
def test_ignored_getter(self):
result = self.app.AsyncResult(uuid())
assert result.ignored is False
result.__delattr__('_ignored')
assert result.ignored is False
@patch('celery.result.task_join_will_block')
def test_assert_will_not_block(self, task_join_will_block):
task_join_will_block.return_value = True
with pytest.raises(RuntimeError):
assert_will_not_block()
task_join_will_block.return_value = False
assert_will_not_block()
@patch('celery.result.task_join_will_block')
def test_get_sync_subtask_option(self, task_join_will_block):
task_join_will_block.return_value = True
tid = uuid()
backend = _MockBackend()
res_subtask_async = AsyncResult(tid, backend=backend)
with pytest.raises(RuntimeError):
res_subtask_async.get()
res_subtask_async.get(disable_sync_subtasks=False)
def test_without_id(self):
with pytest.raises(ValueError):
AsyncResult(None, app=self.app)
def test_compat_properties(self):
x = self.app.AsyncResult('1')
assert x.task_id == x.id
x.task_id = '2'
assert x.id == '2'
@pytest.mark.usefixtures('depends_on_current_app')
def test_reduce_direct(self):
x = AsyncResult('1', app=self.app)
fun, args = x.__reduce__()
assert fun(*args) == x
def test_children(self):
x = self.app.AsyncResult('1')
children = [EagerResult(str(i), i, states.SUCCESS) for i in range(3)]
x._cache = {'children': children, 'status': states.SUCCESS}
x.backend = Mock()
assert x.children
assert len(x.children) == 3
def test_propagates_for_parent(self):
x = self.app.AsyncResult(uuid())
x.backend = Mock(name='backend')
x.backend.get_task_meta.return_value = {}
x.backend.wait_for_pending.return_value = 84
x.parent = EagerResult(uuid(), KeyError('foo'), states.FAILURE)
with pytest.raises(KeyError):
x.get(propagate=True)
x.backend.wait_for_pending.assert_not_called()
x.parent = EagerResult(uuid(), 42, states.SUCCESS)
assert x.get(propagate=True) == 84
x.backend.wait_for_pending.assert_called()
def test_get_children(self):
tid = uuid()
x = self.app.AsyncResult(tid)
child = [self.app.AsyncResult(uuid()).as_tuple()
for i in range(10)]
x._cache = {'children': child}
assert x.children
assert len(x.children) == 10
x._cache = {'status': states.SUCCESS}
x.backend._cache[tid] = {'result': None}
assert x.children is None
def test_build_graph_get_leaf_collect(self):
x = self.app.AsyncResult('1')
x.backend._cache['1'] = {'status': states.SUCCESS, 'result': None}
c = [EagerResult(str(i), i, states.SUCCESS) for i in range(3)]
x.iterdeps = Mock()
x.iterdeps.return_value = (
(None, x),
(x, c[0]),
(c[0], c[1]),
(c[1], c[2])
)
x.backend.READY_STATES = states.READY_STATES
assert x.graph
assert x.get_leaf() == 2
it = x.collect()
assert list(it) == [
(x, None),
(c[0], 0),
(c[1], 1),
(c[2], 2),
]
def test_iterdeps(self):
x = self.app.AsyncResult('1')
c = [EagerResult(str(i), i, states.SUCCESS) for i in range(3)]
x._cache = {'status': states.SUCCESS, 'result': None, 'children': c}
for child in c:
child.backend = Mock()
child.backend.get_children.return_value = []
it = x.iterdeps()
assert list(it) == [
(None, x),
(x, c[0]),
(x, c[1]),
(x, c[2]),
]
x._cache = None
x.ready = Mock()
x.ready.return_value = False
with pytest.raises(IncompleteStream):
list(x.iterdeps())
list(x.iterdeps(intermediate=True))
def test_eq_not_implemented(self):
assert self.app.AsyncResult('1') != object()
@pytest.mark.usefixtures('depends_on_current_app')
def test_reduce(self):
a1 = self.app.AsyncResult('uuid')
restored = pickle.loads(pickle.dumps(a1))
assert restored.id == 'uuid'
a2 = self.app.AsyncResult('uuid')
assert pickle.loads(pickle.dumps(a2)).id == 'uuid'
def test_maybe_set_cache_empty(self):
self.app.AsyncResult('uuid')._maybe_set_cache(None)
def test_set_cache__children(self):
r1 = self.app.AsyncResult('id1')
r2 = self.app.AsyncResult('id2')
r1._set_cache({'children': [r2.as_tuple()]})
assert r2 in r1.children
def test_successful(self):
ok_res = self.app.AsyncResult(self.task1['id'])
nok_res = self.app.AsyncResult(self.task3['id'])
nok_res2 = self.app.AsyncResult(self.task4['id'])
assert ok_res.successful()
assert not nok_res.successful()
assert not nok_res2.successful()
pending_res = self.app.AsyncResult(uuid())
assert not pending_res.successful()
def test_raising(self):
notb = self.app.AsyncResult(self.task3['id'])
withtb = self.app.AsyncResult(self.task5['id'])
with pytest.raises(KeyError):
notb.get()
with pytest.raises(KeyError) as excinfo:
withtb.get()
tb = [t.strip() for t in traceback.format_tb(excinfo.tb)]
assert 'File "foo.py", line 2, in foofunc' not in tb
assert 'File "bar.py", line 3, in barfunc' not in tb
assert excinfo.value.args[0] == 'blue'
assert excinfo.typename == 'KeyError'
def test_raising_remote_tracebacks(self):
pytest.importorskip('tblib')
withtb = self.app.AsyncResult(self.task5['id'])
self.app.conf.task_remote_tracebacks = True
with pytest.raises(KeyError) as excinfo:
withtb.get()
tb = [t.strip() for t in traceback.format_tb(excinfo.tb)]
assert 'File "foo.py", line 2, in foofunc' in tb
assert 'File "bar.py", line 3, in barfunc' in tb
assert excinfo.value.args[0] == 'blue'
assert excinfo.typename == 'KeyError'
def test_str(self):
ok_res = self.app.AsyncResult(self.task1['id'])
ok2_res = self.app.AsyncResult(self.task2['id'])
nok_res = self.app.AsyncResult(self.task3['id'])
assert str(ok_res) == self.task1['id']
assert str(ok2_res) == self.task2['id']
assert str(nok_res) == self.task3['id']
pending_id = uuid()
pending_res = self.app.AsyncResult(pending_id)
assert str(pending_res) == pending_id
def test_repr(self):
ok_res = self.app.AsyncResult(self.task1['id'])
ok2_res = self.app.AsyncResult(self.task2['id'])
nok_res = self.app.AsyncResult(self.task3['id'])
assert repr(ok_res) == f"<AsyncResult: {self.task1['id']}>"
assert repr(ok2_res) == f"<AsyncResult: {self.task2['id']}>"
assert repr(nok_res) == f"<AsyncResult: {self.task3['id']}>"
pending_id = uuid()
pending_res = self.app.AsyncResult(pending_id)
assert repr(pending_res) == f'<AsyncResult: {pending_id}>'
def test_hash(self):
assert (hash(self.app.AsyncResult('x0w991')) ==
hash(self.app.AsyncResult('x0w991')))
assert (hash(self.app.AsyncResult('x0w991')) !=
hash(self.app.AsyncResult('x1w991')))
def test_get_traceback(self):
ok_res = self.app.AsyncResult(self.task1['id'])
nok_res = self.app.AsyncResult(self.task3['id'])
nok_res2 = self.app.AsyncResult(self.task4['id'])
assert not ok_res.traceback
assert nok_res.traceback
assert nok_res2.traceback
pending_res = self.app.AsyncResult(uuid())
assert not pending_res.traceback
def test_get__backend_gives_None(self):
res = self.app.AsyncResult(self.task1['id'])
res.backend.wait_for = Mock(name='wait_for')
res.backend.wait_for.return_value = None
assert res.get() is None
def test_get(self):
ok_res = self.app.AsyncResult(self.task1['id'])
ok2_res = self.app.AsyncResult(self.task2['id'])
nok_res = self.app.AsyncResult(self.task3['id'])
nok2_res = self.app.AsyncResult(self.task4['id'])
none_res = self.app.AsyncResult(self.task6['id'])
callback = Mock(name='callback')
assert ok_res.get(callback=callback) == 'the'
callback.assert_called_with(ok_res.id, 'the')
assert ok2_res.get() == 'quick'
with pytest.raises(KeyError):
nok_res.get()
assert nok_res.get(propagate=False)
assert isinstance(nok2_res.result, KeyError)
assert ok_res.info == 'the'
assert none_res.get() is None
assert none_res.state == states.SUCCESS
def test_get_when_ignored(self):
result = self.app.AsyncResult(uuid())
result.ignored = True
# Does not block
assert result.get() is None
def test_eq_ne(self):
r1 = self.app.AsyncResult(self.task1['id'])
r2 = self.app.AsyncResult(self.task1['id'])
r3 = self.app.AsyncResult(self.task2['id'])
assert r1 == r2
assert r1 != r3
assert r1 == r2.id
assert r1 != r3.id
@pytest.mark.usefixtures('depends_on_current_app')
def test_reduce_restore(self):
r1 = self.app.AsyncResult(self.task1['id'])
fun, args = r1.__reduce__()
assert fun(*args) == r1
def test_get_timeout(self):
res = self.app.AsyncResult(self.task4['id']) # has RETRY state
with pytest.raises(TimeoutError):
res.get(timeout=0.001)
pending_res = self.app.AsyncResult(uuid())
with patch('celery.result.time') as _time:
with pytest.raises(TimeoutError):
pending_res.get(timeout=0.001, interval=0.001)
_time.sleep.assert_called_with(0.001)
def test_get_timeout_longer(self):
res = self.app.AsyncResult(self.task4['id']) # has RETRY state
with patch('celery.result.time') as _time:
with pytest.raises(TimeoutError):
res.get(timeout=1, interval=1)
_time.sleep.assert_called_with(1)
def test_ready(self):
oks = (self.app.AsyncResult(self.task1['id']),
self.app.AsyncResult(self.task2['id']),
self.app.AsyncResult(self.task3['id']))
assert all(result.ready() for result in oks)
assert not self.app.AsyncResult(self.task4['id']).ready()
assert not self.app.AsyncResult(uuid()).ready()
@pytest.mark.skipif(
platform.python_implementation() == "PyPy",
reason="Mocking here doesn't play well with PyPy",
)
def test_del(self):
with patch('celery.result.AsyncResult.backend') as backend:
result = self.app.AsyncResult(self.task1['id'])
result.backend = backend
result_clone = copy.copy(result)
del result
backend.remove_pending_result.assert_called_once_with(
result_clone
)
result = self.app.AsyncResult(self.task1['id'])
result.backend = None
del result
def test_get_request_meta(self):
x = self.app.AsyncResult('1')
request = Context(
task='foo',
children=None,
args=['one', 'two'],
kwargs={'kwarg1': 'three'},
hostname="foo",
retries=1,
delivery_info={'routing_key': 'celery'}
)
x.backend.store_result(task_id="1", result='foo', state=states.SUCCESS,
traceback=None, request=request)
assert x.name == 'foo'
assert x.args == ['one', 'two']
assert x.kwargs == {'kwarg1': 'three'}
assert x.worker == 'foo'
assert x.retries == 1
assert x.queue == 'celery'
assert isinstance(x.date_done, datetime.datetime)
assert x.task_id == "1"
assert x.state == "SUCCESS"
result = self.app.AsyncResult(self.task4['id'])
assert result.date_done is None
@patch('celery.app.base.to_utc')
@pytest.mark.parametrize('timezone, date', [
("UTC", "2024-08-24T00:00:00+00:00"),
("America/Los_Angeles", "2024-08-23T17:00:00-07:00"),
("Pacific/Kwajalein", "2024-08-24T12:00:00+12:00"),
("Europe/Berlin", "2024-08-24T02:00:00+02:00"),
])
def test_date_done(self, utc_datetime_mock, timezone, date):
utc_datetime_mock.return_value = datetime.datetime(2024, 8, 24, 0, 0, 0, 0, datetime.timezone.utc)
self.app.conf.timezone = timezone
del self.app.timezone # reset cached timezone
result = Backend(app=self.app)._get_result_meta(None, states.SUCCESS, None, None)
assert result.get('date_done') == date
class test_ResultSet:
def test_resultset_repr(self):
assert repr(self.app.ResultSet(
[self.app.AsyncResult(t) for t in ['1', '2', '3']]))
def test_eq_other(self):
assert self.app.ResultSet([
self.app.AsyncResult(t) for t in [1, 3, 3]]) != 1
rs1 = self.app.ResultSet([self.app.AsyncResult(1)])
rs2 = self.app.ResultSet([self.app.AsyncResult(1)])
assert rs1 == rs2
def test_get(self):
x = self.app.ResultSet([self.app.AsyncResult(t) for t in [1, 2, 3]])
b = x.results[0].backend = Mock()
b.supports_native_join = False
x.join_native = Mock()
x.join = Mock()
x.get()
x.join.assert_called()
b.supports_native_join = True
x.get()
x.join_native.assert_called()
@patch('celery.result.task_join_will_block')
def test_get_sync_subtask_option(self, task_join_will_block):
task_join_will_block.return_value = True
x = self.app.ResultSet([self.app.AsyncResult(str(t)) for t in [1, 2, 3]])
b = x.results[0].backend = Mock()
b.supports_native_join = False
with pytest.raises(RuntimeError):
x.get()
with pytest.raises(TimeoutError):
x.get(disable_sync_subtasks=False, timeout=0.1)
def test_join_native_with_group_chain_group(self):
"""Test group(chain(group)) case, join_native can be run correctly.
In group(chain(group)) case, GroupResult has no _cache property, and
AsyncBackendMixin.iter_native returns a node instead of node._cache,
this test make sure ResultSet.join_native can process correctly both
values of AsyncBackendMixin.iter_native returns.
"""
def _get_meta(tid, result=None, children=None):
return {
'status': states.SUCCESS,
'result': result,
'children': children,
'task_id': tid,
}
results = [self.app.AsyncResult(t) for t in [1, 2, 3]]
values = [(_.id, _get_meta(_.id, _)) for _ in results]
g_res = GroupResult(6, [self.app.AsyncResult(t) for t in [4, 5]])
results += [g_res]
values += [(6, g_res.children)]
x = self.app.ResultSet(results)
x.results[0].backend = Mock()
x.results[0].backend.join = Mock()
x.results[3][0].get = Mock()
x.results[3][0].get.return_value = g_res.results[0]
x.results[3][1].get = Mock()
x.results[3][1].get.return_value = g_res.results[1]
x.iter_native = Mock()
x.iter_native.return_value = values.__iter__()
x.join_native()
x.iter_native.assert_called()
def test_eq_ne(self):
g1 = self.app.ResultSet([
self.app.AsyncResult('id1'),
self.app.AsyncResult('id2'),
])
g2 = self.app.ResultSet([
self.app.AsyncResult('id1'),
self.app.AsyncResult('id2'),
])
g3 = self.app.ResultSet([
self.app.AsyncResult('id3'),
self.app.AsyncResult('id1'),
])
assert g1 == g2
assert g1 != g3
assert g1 != object()
def test_takes_app_from_first_task(self):
x = ResultSet([self.app.AsyncResult('id1')])
assert x.app is x.results[0].app
x.app = self.app
assert x.app is self.app
def test_get_empty(self):
x = self.app.ResultSet([])
assert x.supports_native_join is None
x.join = Mock(name='join')
x.get()
x.join.assert_called()
def test_add(self):
x = self.app.ResultSet([self.app.AsyncResult(1)])
x.add(self.app.AsyncResult(2))
assert len(x) == 2
x.add(self.app.AsyncResult(2))
assert len(x) == 2
@contextmanager
def dummy_copy(self):
with patch('celery.result.copy') as copy:
def pass_value(arg):
return arg
copy.side_effect = pass_value
yield
def test_add_discard(self):
x = self.app.ResultSet([])
x.add(self.app.AsyncResult('1'))
assert self.app.AsyncResult('1') in x.results
x.discard(self.app.AsyncResult('1'))
x.discard(self.app.AsyncResult('1'))
x.discard('1')
assert self.app.AsyncResult('1') not in x.results
x.update([self.app.AsyncResult('2')])
def test_clear(self):
x = self.app.ResultSet([])
r = x.results
x.clear()
assert x.results is r
class MockAsyncResultFailure(AsyncResult):
@property
def result(self):
return KeyError('baz')
@property
def state(self):
return states.FAILURE
def get(self, propagate=True, **kwargs):
if propagate:
raise self.result
return self.result
class MockAsyncResultSuccess(AsyncResult):
forgotten = False
def __init__(self, *args, **kwargs):
self._result = kwargs.pop('result', 42)
super().__init__(*args, **kwargs)
def forget(self):
self.forgotten = True
@property
def result(self):
return self._result
@property
def state(self):
return states.SUCCESS
def get(self, **kwargs):
return self.result
class SimpleBackend(SyncBackendMixin):
ids = []
def __init__(self, ids=[]):
self.ids = ids
def _ensure_not_eager(self):
pass
def get_many(self, *args, **kwargs):
return ((id, {'result': i, 'status': states.SUCCESS})
for i, id in enumerate(self.ids))
class test_GroupResult:
def setup_method(self):
self.size = 10
self.ts = self.app.GroupResult(
uuid(), make_mock_group(self.app, self.size),
)
@pytest.mark.usefixtures('depends_on_current_app')
def test_is_pickleable(self):
ts = self.app.GroupResult(uuid(), [self.app.AsyncResult(uuid())])
assert pickle.loads(pickle.dumps(ts)) == ts
ts2 = self.app.GroupResult(uuid(), [self.app.AsyncResult(uuid())])
assert pickle.loads(pickle.dumps(ts2)) == ts2
@pytest.mark.usefixtures('depends_on_current_app')
def test_reduce(self):
ts = self.app.GroupResult(uuid(), [self.app.AsyncResult(uuid())])
fun, args = ts.__reduce__()
ts2 = fun(*args)
assert ts2.id == ts.id
assert ts == ts2
def test_eq_ne(self):
ts = self.app.GroupResult(uuid(), [self.app.AsyncResult(uuid())])
ts2 = self.app.GroupResult(ts.id, ts.results)
ts3 = self.app.GroupResult(uuid(), [self.app.AsyncResult(uuid())])
ts4 = self.app.GroupResult(ts.id, [self.app.AsyncResult(uuid())])
assert ts == ts2
assert ts != ts3
assert ts != ts4
assert ts != object()
def test_len(self):
assert len(self.ts) == self.size
def test_eq_other(self):
assert self.ts != 1
def test_eq_with_parent(self):
# GroupResult instances with different .parent are not equal
grp_res = self.app.GroupResult(
uuid(), [self.app.AsyncResult(uuid()) for _ in range(10)],
parent=self.app.AsyncResult(uuid())
)
grp_res_2 = self.app.GroupResult(grp_res.id, grp_res.results)
assert grp_res != grp_res_2
grp_res_2.parent = self.app.AsyncResult(uuid())
assert grp_res != grp_res_2
grp_res_2.parent = grp_res.parent
assert grp_res == grp_res_2
@pytest.mark.usefixtures('depends_on_current_app')
def test_pickleable(self):
assert pickle.loads(pickle.dumps(self.ts))
def test_forget(self):
subs = [MockAsyncResultSuccess(uuid(), app=self.app),
MockAsyncResultSuccess(uuid(), app=self.app)]
ts = self.app.GroupResult(uuid(), subs)
ts.forget()
for sub in subs:
assert sub.forgotten
def test_get_nested_without_native_join(self):
backend = SimpleBackend()
backend.supports_native_join = False
ts = self.app.GroupResult(uuid(), [
MockAsyncResultSuccess(uuid(), result='1.1',
app=self.app, backend=backend),
self.app.GroupResult(uuid(), [
MockAsyncResultSuccess(uuid(), result='2.1',
app=self.app, backend=backend),
self.app.GroupResult(uuid(), [
MockAsyncResultSuccess(uuid(), result='3.1',
app=self.app, backend=backend),
MockAsyncResultSuccess(uuid(), result='3.2',
app=self.app, backend=backend),
]),
]),
])
with patch('celery.Celery.backend', new=backend):
vals = ts.get()
assert vals == [
'1.1',
[
'2.1',
[
'3.1',
'3.2',
]
],
]
def test_getitem(self):
subs = [MockAsyncResultSuccess(uuid(), app=self.app),
MockAsyncResultSuccess(uuid(), app=self.app)]
ts = self.app.GroupResult(uuid(), subs)
assert ts[0] is subs[0]
def test_save_restore(self):
subs = [MockAsyncResultSuccess(uuid(), app=self.app),
MockAsyncResultSuccess(uuid(), app=self.app)]
ts = self.app.GroupResult(uuid(), subs)
ts.save()
with pytest.raises(AttributeError):
ts.save(backend=object())
assert self.app.GroupResult.restore(ts.id).results == ts.results
ts.delete()
assert self.app.GroupResult.restore(ts.id) is None
with pytest.raises(AttributeError):
self.app.GroupResult.restore(ts.id, backend=object())
def test_save_restore_empty(self):
subs = []
ts = self.app.GroupResult(uuid(), subs)
ts.save()
assert isinstance(
self.app.GroupResult.restore(ts.id),
self.app.GroupResult,
)
assert self.app.GroupResult.restore(ts.id).results == ts.results == []
def test_restore_app(self):
subs = [MockAsyncResultSuccess(uuid(), app=self.app)]
ts = self.app.GroupResult(uuid(), subs)
ts.save()
restored = GroupResult.restore(ts.id, app=self.app)
assert restored.id == ts.id
def test_restore_current_app_fallback(self):
subs = [MockAsyncResultSuccess(uuid(), app=self.app)]
ts = self.app.GroupResult(uuid(), subs)
ts.save()
with pytest.raises(RuntimeError,
match="Test depends on current_app"):
GroupResult.restore(ts.id)
def test_join_native(self):
backend = SimpleBackend()
results = [self.app.AsyncResult(uuid(), backend=backend)
for i in range(10)]
ts = self.app.GroupResult(uuid(), results)
with patch('celery.Celery.backend', new=backend):
backend.ids = [result.id for result in results]
res = ts.join_native()
assert res == list(range(10))
callback = Mock(name='callback')
assert not ts.join_native(callback=callback)
callback.assert_has_calls([
call(r.id, i) for i, r in enumerate(ts.results)
])
def test_join_native_raises(self):
ts = self.app.GroupResult(uuid(), [self.app.AsyncResult(uuid())])
ts.iter_native = Mock()
ts.iter_native.return_value = iter([
(uuid(), {'status': states.FAILURE, 'result': KeyError()})
])
with pytest.raises(KeyError):
ts.join_native(propagate=True)
def test_failed_join_report(self):
res = Mock()
ts = self.app.GroupResult(uuid(), [res])
res.state = states.FAILURE
res.backend.is_cached.return_value = True
assert next(ts._failed_join_report()) is res
res.backend.is_cached.return_value = False
with pytest.raises(StopIteration):
next(ts._failed_join_report())
def test_repr(self):
assert repr(
self.app.GroupResult(uuid(), [self.app.AsyncResult(uuid())]))
def test_children_is_results(self):
ts = self.app.GroupResult(uuid(), [self.app.AsyncResult(uuid())])
assert ts.children is ts.results
def test_iter_native(self):
backend = SimpleBackend()
results = [self.app.AsyncResult(uuid(), backend=backend)
for i in range(10)]
ts = self.app.GroupResult(uuid(), results)
with patch('celery.Celery.backend', new=backend):
backend.ids = [result.id for result in results]
assert len(list(ts.iter_native())) == 10
def test_join_timeout(self):
ar = MockAsyncResultSuccess(uuid(), app=self.app)
ar2 = MockAsyncResultSuccess(uuid(), app=self.app)
ar3 = self.app.AsyncResult(uuid())
ts = self.app.GroupResult(uuid(), [ar, ar2, ar3])
with pytest.raises(TimeoutError):
ts.join(timeout=0.0000001)
ar4 = self.app.AsyncResult(uuid())
ar4.get = Mock()
ts2 = self.app.GroupResult(uuid(), [ar4])
assert ts2.join(timeout=0.1)
callback = Mock(name='callback')
assert not ts2.join(timeout=0.1, callback=callback)
callback.assert_called_with(ar4.id, ar4.get())
def test_iter_native_when_empty_group(self):
ts = self.app.GroupResult(uuid(), [])
assert list(ts.iter_native()) == []
def test___iter__(self):
assert list(iter(self.ts)) == self.ts.results
def test_join(self):
joined = self.ts.join()
assert joined == list(range(self.size))
def test_successful(self):
assert self.ts.successful()
def test_failed(self):
assert not self.ts.failed()
def test_maybe_throw(self):
self.ts.results = [Mock(name='r1')]
self.ts.maybe_throw()
self.ts.results[0].maybe_throw.assert_called_with(
callback=None, propagate=True,
)
def test_join__on_message(self):
with pytest.raises(ImproperlyConfigured):
self.ts.join(on_message=Mock())
def test_waiting(self):
assert not self.ts.waiting()
def test_ready(self):
assert self.ts.ready()
def test_completed_count(self):
assert self.ts.completed_count() == len(self.ts)
class test_pending_AsyncResult:
def test_result(self, app):
res = app.AsyncResult(uuid())
assert res.result is None
class test_failed_AsyncResult:
def setup_method(self):
self.size = 11
self.app.conf.result_serializer = 'pickle'
results = make_mock_group(self.app, 10)
failed = mock_task('ts11', states.FAILURE, KeyError('Baz'))
save_result(self.app, failed)
failed_res = self.app.AsyncResult(failed['id'])
self.ts = self.app.GroupResult(uuid(), results + [failed_res])
def test_completed_count(self):
assert self.ts.completed_count() == len(self.ts) - 1
def test_join(self):
with pytest.raises(KeyError):
self.ts.join()
def test_successful(self):
assert not self.ts.successful()
def test_failed(self):
assert self.ts.failed()
class test_pending_Group:
def setup_method(self):
self.ts = self.app.GroupResult(
uuid(), [self.app.AsyncResult(uuid()),
self.app.AsyncResult(uuid())])
def test_completed_count(self):
assert self.ts.completed_count() == 0
def test_ready(self):
assert not self.ts.ready()
def test_waiting(self):
assert self.ts.waiting()
def test_join(self):
with pytest.raises(TimeoutError):
self.ts.join(timeout=0.001)
def test_join_longer(self):
with pytest.raises(TimeoutError):
self.ts.join(timeout=1)
class test_EagerResult:
def setup_method(self):
@self.app.task(shared=False)
def raising(x, y):
raise KeyError(x, y)
self.raising = raising
def test_wait_raises(self):
res = self.raising.apply(args=[3, 3])
with pytest.raises(KeyError):
res.wait()
assert res.wait(propagate=False)
def test_wait(self):
res = EagerResult('x', 'x', states.RETRY)
res.wait()
assert res.state == states.RETRY
assert res.status == states.RETRY
def test_forget(self):
res = EagerResult('x', 'x', states.RETRY)
res.forget()
def test_revoke(self):
res = self.raising.apply(args=[3, 3])
assert not res.revoke()
@patch('celery.result.task_join_will_block')
def test_get_sync_subtask_option(self, task_join_will_block):
task_join_will_block.return_value = True
tid = uuid()
res_subtask_async = EagerResult(tid, 'x', 'x', states.SUCCESS)
with pytest.raises(RuntimeError):
res_subtask_async.get()
res_subtask_async.get(disable_sync_subtasks=False)
def test_populate_name(self):
res = EagerResult('x', 'x', states.SUCCESS, None, 'test_task')
assert res.name == 'test_task'
res = EagerResult('x', 'x', states.SUCCESS, name='test_task_named_argument')
assert res.name == 'test_task_named_argument'
class test_tuples:
def test_AsyncResult(self):
x = self.app.AsyncResult(uuid())
assert x, result_from_tuple(x.as_tuple() == self.app)
assert x, result_from_tuple(x == self.app)
def test_with_parent(self):
x = self.app.AsyncResult(uuid())
x.parent = self.app.AsyncResult(uuid())
y = result_from_tuple(x.as_tuple(), self.app)
assert y == x
assert y.parent == x.parent
assert isinstance(y.parent, AsyncResult)
def test_compat(self):
uid = uuid()
x = result_from_tuple([uid, []], app=self.app)
assert x.id == uid
def test_as_list(self):
uid = uuid()
x = self.app.AsyncResult(uid)
assert x.id == x.as_list()[0]
assert isinstance(x.as_list(), list)
def test_GroupResult(self):
x = self.app.GroupResult(
uuid(), [self.app.AsyncResult(uuid()) for _ in range(10)],
)
assert x, result_from_tuple(x.as_tuple() == self.app)
assert x, result_from_tuple(x == self.app)
def test_GroupResult_with_parent(self):
parent = self.app.AsyncResult(uuid())
result = self.app.GroupResult(
uuid(), [self.app.AsyncResult(uuid()) for _ in range(10)],
parent
)
second_result = result_from_tuple(result.as_tuple(), self.app)
assert second_result == result
assert second_result.parent == parent
def test_GroupResult_as_tuple(self):
parent = self.app.AsyncResult(uuid())
result = self.app.GroupResult(
'group-result-1',
[self.app.AsyncResult(f'async-result-{i}')
for i in range(2)],
parent
)
(result_id, parent_tuple), group_results = result.as_tuple()
assert result_id == result.id
assert parent_tuple == parent.as_tuple()
assert parent_tuple[0][0] == parent.id
assert isinstance(group_results, list)
expected_grp_res = [((f'async-result-{i}', None), None)
for i in range(2)]
assert group_results == expected_grp_res
|