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 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387
|
import os
import platform
import re
import sys
import warnings
from collections.abc import Generator
from collections.abc import Iterable
from collections.abc import Iterator
from contextlib import contextmanager
from typing import Any
from typing import Callable
from unittest.mock import AsyncMock
from unittest.mock import MagicMock
import pytest
from pytest_mock import MockerFixture
from pytest_mock import PytestMockWarning
pytest_plugins = "pytester"
# could not make some of the tests work on PyPy, patches are welcome!
skip_pypy = pytest.mark.skipif(
platform.python_implementation() == "PyPy", reason="could not make it work on pypy"
)
# Python 3.11.7 changed the output formatting, https://github.com/python/cpython/issues/111019
NEWEST_FORMATTING = sys.version_info >= (3, 11, 7)
@pytest.fixture
def needs_assert_rewrite(pytestconfig):
"""
Fixture which skips requesting test if assertion rewrite is disabled (#102)
Making this a fixture to avoid accessing pytest's config in the global context.
"""
option = pytestconfig.getoption("assertmode")
if option != "rewrite":
pytest.skip(
"this test needs assertion rewrite to work but current option "
'is "{}"'.format(option)
)
class UnixFS:
"""
Wrapper to os functions to simulate a Unix file system, used for testing
the mock fixture.
"""
@classmethod
def rm(cls, filename):
os.remove(filename)
@classmethod
def ls(cls, path):
return os.listdir(path)
class TestObject:
"""
Class that is used for testing create_autospec with child mocks
"""
def run(self) -> str:
return "not mocked"
@pytest.fixture
def check_unix_fs_mocked(
tmpdir: Any, mocker: MockerFixture
) -> Callable[[Any, Any], None]:
"""
performs a standard test in a UnixFS, assuming that both `os.remove` and
`os.listdir` have been mocked previously.
"""
def check(mocked_rm, mocked_ls):
assert mocked_rm is os.remove
assert mocked_ls is os.listdir
file_name = tmpdir / "foo.txt"
file_name.ensure()
UnixFS.rm(str(file_name))
mocked_rm.assert_called_once_with(str(file_name))
assert os.path.isfile(str(file_name))
mocked_ls.return_value = ["bar.txt"]
assert UnixFS.ls(str(tmpdir)) == ["bar.txt"]
mocked_ls.assert_called_once_with(str(tmpdir))
mocker.stopall()
assert UnixFS.ls(str(tmpdir)) == ["foo.txt"]
UnixFS.rm(str(file_name))
assert not os.path.isfile(str(file_name))
return check
def mock_using_patch_object(mocker: MockerFixture) -> tuple[MagicMock, MagicMock]:
return mocker.patch.object(os, "remove"), mocker.patch.object(os, "listdir")
def mock_using_patch(mocker: MockerFixture) -> tuple[MagicMock, MagicMock]:
return mocker.patch("os.remove"), mocker.patch("os.listdir")
def mock_using_patch_multiple(mocker: MockerFixture) -> tuple[MagicMock, MagicMock]:
r = mocker.patch.multiple("os", remove=mocker.DEFAULT, listdir=mocker.DEFAULT)
return r["remove"], r["listdir"]
@pytest.mark.parametrize(
"mock_fs", [mock_using_patch_object, mock_using_patch, mock_using_patch_multiple]
)
def test_mock_patches(
mock_fs: Any,
mocker: MockerFixture,
check_unix_fs_mocked: Callable[[Any, Any], None],
) -> None:
"""
Installs mocks into `os` functions and performs a standard testing of
mock functionality. We parametrize different mock methods to ensure
all (intended, at least) mock API is covered.
"""
# mock it twice on purpose to ensure we unmock it correctly later
mock_fs(mocker)
mocked_rm, mocked_ls = mock_fs(mocker)
check_unix_fs_mocked(mocked_rm, mocked_ls)
mocker.resetall()
mocker.stopall()
def test_mock_patch_dict(mocker: MockerFixture) -> None:
"""
Testing
:param mock:
"""
x = {"original": 1}
mocker.patch.dict(x, values=[("new", 10)], clear=True)
assert x == {"new": 10}
mocker.stopall()
assert x == {"original": 1}
def test_mock_patch_dict_resetall(mocker: MockerFixture) -> None:
"""
We can call resetall after patching a dict.
:param mock:
"""
x = {"original": 1}
mocker.patch.dict(x, values=[("new", 10)], clear=True)
assert x == {"new": 10}
mocker.resetall()
assert x == {"new": 10}
@pytest.mark.parametrize(
"name",
[
"ANY",
"call",
"MagicMock",
"Mock",
"mock_open",
"NonCallableMagicMock",
"NonCallableMock",
"PropertyMock",
"sentinel",
"seal",
],
)
def test_mocker_aliases(name: str, pytestconfig: Any) -> None:
from pytest_mock._util import get_mock_module
mock_module = get_mock_module(pytestconfig)
mocker = MockerFixture(pytestconfig)
assert getattr(mocker, name) is getattr(mock_module, name)
def test_mocker_resetall(mocker: MockerFixture) -> None:
listdir = mocker.patch("os.listdir", return_value="foo")
open = mocker.patch("os.open", side_effect=["bar", "baz"])
mocked_object = mocker.create_autospec(TestObject)
mocked_object.run.return_value = "mocked"
assert listdir("/tmp") == "foo"
assert open("/tmp/foo.txt") == "bar"
assert mocked_object.run() == "mocked"
listdir.assert_called_once_with("/tmp")
open.assert_called_once_with("/tmp/foo.txt")
mocked_object.run.assert_called_once()
mocker.resetall()
assert not listdir.called
assert not open.called
assert not mocked_object.called
assert listdir.return_value == "foo"
assert list(open.side_effect) == ["baz"]
assert mocked_object.run.return_value == "mocked"
mocker.resetall(return_value=True, side_effect=True)
assert isinstance(listdir.return_value, mocker.Mock)
assert open.side_effect is None
assert mocked_object.run.return_value != "mocked"
class TestMockerStub:
def test_call(self, mocker: MockerFixture) -> None:
stub = mocker.stub()
stub("foo", "bar")
stub.assert_called_once_with("foo", "bar")
def test_repr_with_no_name(self, mocker: MockerFixture) -> None:
stub = mocker.stub()
assert "name" not in repr(stub)
def test_repr_with_name(self, mocker: MockerFixture) -> None:
test_name = "funny walk"
stub = mocker.stub(name=test_name)
assert f"name={test_name!r}" in repr(stub)
def __test_failure_message(self, mocker: MockerFixture, **kwargs: Any) -> None:
expected_name = kwargs.get("name") or "mock"
if NEWEST_FORMATTING:
msg = "expected call not found.\nExpected: {0}()\n Actual: not called."
else:
msg = "expected call not found.\nExpected: {0}()\nActual: not called."
expected_message = msg.format(expected_name)
stub = mocker.stub(**kwargs)
with pytest.raises(AssertionError, match=re.escape(expected_message)):
stub.assert_called_with()
def test_failure_message_with_no_name(self, mocker: MagicMock) -> None:
self.__test_failure_message(mocker)
@pytest.mark.parametrize("name", (None, "", "f", "The Castle of aaarrrrggh"))
def test_failure_message_with_name(self, mocker: MagicMock, name: str) -> None:
self.__test_failure_message(mocker, name=name)
def test_async_stub_type(self, mocker: MockerFixture) -> None:
assert isinstance(mocker.async_stub(), AsyncMock)
def test_instance_method_spy(mocker: MockerFixture) -> None:
class Foo:
def bar(self, arg):
return arg * 2
foo = Foo()
other = Foo()
spy = mocker.spy(foo, "bar")
assert foo.bar(arg=10) == 20
assert other.bar(arg=10) == 20
foo.bar.assert_called_once_with(arg=10) # type:ignore[attr-defined]
assert foo.bar.spy_return == 20 # type:ignore[attr-defined]
assert foo.bar.spy_return_iter is None # type:ignore[attr-defined]
assert foo.bar.spy_return_list == [20] # type:ignore[attr-defined]
spy.assert_called_once_with(arg=10)
assert spy.spy_return == 20
assert foo.bar(arg=11) == 22
assert foo.bar(arg=12) == 24
assert spy.spy_return == 24
assert spy.spy_return_iter is None
assert spy.spy_return_list == [20, 22, 24]
# Ref: https://docs.python.org/3/library/exceptions.html#exception-hierarchy
@pytest.mark.parametrize(
"exc_cls",
(
BaseException,
Exception,
GeneratorExit, # BaseException
KeyboardInterrupt, # BaseException
RuntimeError, # regular Exception
SystemExit, # BaseException
),
)
def test_instance_method_spy_exception(
exc_cls: type[BaseException],
mocker: MockerFixture,
) -> None:
class Foo:
def bar(self, arg):
raise exc_cls(f"Error with {arg}")
foo = Foo()
spy = mocker.spy(foo, "bar")
expected_calls = []
for i, v in enumerate([10, 20]):
with pytest.raises(exc_cls, match=f"Error with {v}"):
foo.bar(arg=v)
expected_calls.append(mocker.call(arg=v))
assert foo.bar.call_args_list == expected_calls # type:ignore[attr-defined]
assert str(spy.spy_exception) == f"Error with {v}"
def test_instance_class_static_method_spy_autospec_true(mocker: MockerFixture) -> None:
class Foo:
def bar(self, arg):
return arg * 2
@classmethod
def baz(cls, arg):
return arg * 2
@staticmethod
def qux(arg):
return arg * 2
foo = Foo()
instance_method_spy = mocker.spy(foo, "bar")
with pytest.raises(
AttributeError, match="'function' object has no attribute 'fake_assert_method'"
):
instance_method_spy.fake_assert_method(arg=5)
class_method_spy = mocker.spy(Foo, "baz")
with pytest.raises(
AttributeError, match="Mock object has no attribute 'fake_assert_method'"
):
class_method_spy.fake_assert_method(arg=5)
static_method_spy = mocker.spy(Foo, "qux")
with pytest.raises(
AttributeError, match="Mock object has no attribute 'fake_assert_method'"
):
static_method_spy.fake_assert_method(arg=5)
def test_spy_reset(mocker: MockerFixture) -> None:
class Foo:
def bar(self, x):
if x == 0:
raise ValueError("invalid x")
return x * 3
spy = mocker.spy(Foo, "bar")
assert spy.spy_return is None
assert spy.spy_return_iter is None
assert spy.spy_return_list == []
assert spy.spy_exception is None
Foo().bar(10)
assert spy.spy_return == 30
assert spy.spy_return_iter is None
assert spy.spy_return_list == [30]
assert spy.spy_exception is None
# Testing spy can still be reset (#237).
mocker.resetall()
with pytest.raises(ValueError):
Foo().bar(0)
assert spy.spy_return is None
assert spy.spy_return_iter is None
assert spy.spy_return_list == []
assert str(spy.spy_exception) == "invalid x"
Foo().bar(15)
assert spy.spy_return == 45
assert spy.spy_return_iter is None
assert spy.spy_return_list == [45]
assert spy.spy_exception is None
@skip_pypy
def test_instance_method_by_class_spy(mocker: MockerFixture) -> None:
class Foo:
def bar(self, arg):
return arg * 2
spy = mocker.spy(Foo, "bar")
foo = Foo()
other = Foo()
assert foo.bar(arg=10) == 20
assert other.bar(arg=10) == 20
calls = [mocker.call(foo, arg=10), mocker.call(other, arg=10)]
assert spy.call_args_list == calls
@skip_pypy
def test_instance_method_by_subclass_spy(mocker: MockerFixture) -> None:
class Base:
def bar(self, arg):
return arg * 2
class Foo(Base):
pass
spy = mocker.spy(Foo, "bar")
foo = Foo()
other = Foo()
assert foo.bar(arg=10) == 20
assert other.bar(arg=10) == 20
calls = [mocker.call(foo, arg=10), mocker.call(other, arg=10)]
assert spy.call_args_list == calls
assert spy.spy_return == 20
assert spy.spy_return_iter is None
assert spy.spy_return_list == [20, 20]
@skip_pypy
def test_class_method_spy(mocker: MockerFixture) -> None:
class Foo:
@classmethod
def bar(cls, arg):
return arg * 2
spy = mocker.spy(Foo, "bar")
assert Foo.bar(arg=10) == 20
Foo.bar.assert_called_once_with(arg=10) # type:ignore[attr-defined]
assert Foo.bar.spy_return == 20 # type:ignore[attr-defined]
assert Foo.bar.spy_return_iter is None # type:ignore[attr-defined]
assert Foo.bar.spy_return_list == [20] # type:ignore[attr-defined]
spy.assert_called_once_with(arg=10)
assert spy.spy_return == 20
assert spy.spy_return_iter is None
assert spy.spy_return_list == [20]
@skip_pypy
def test_class_method_subclass_spy(mocker: MockerFixture) -> None:
class Base:
@classmethod
def bar(self, arg):
return arg * 2
class Foo(Base):
pass
spy = mocker.spy(Foo, "bar")
assert Foo.bar(arg=10) == 20
Foo.bar.assert_called_once_with(arg=10) # type:ignore[attr-defined]
assert Foo.bar.spy_return == 20 # type:ignore[attr-defined]
assert Foo.bar.spy_return_iter is None # type:ignore[attr-defined]
assert Foo.bar.spy_return_list == [20] # type:ignore[attr-defined]
spy.assert_called_once_with(arg=10)
assert spy.spy_return == 20
assert spy.spy_return_iter is None
assert spy.spy_return_list == [20]
@skip_pypy
def test_class_method_with_metaclass_spy(mocker: MockerFixture) -> None:
class MetaFoo(type):
pass
class Foo:
__metaclass__ = MetaFoo
@classmethod
def bar(cls, arg):
return arg * 2
spy = mocker.spy(Foo, "bar")
assert Foo.bar(arg=10) == 20
Foo.bar.assert_called_once_with(arg=10) # type:ignore[attr-defined]
assert Foo.bar.spy_return == 20 # type:ignore[attr-defined]
assert Foo.bar.spy_return_iter is None # type:ignore[attr-defined]
assert Foo.bar.spy_return_list == [20] # type:ignore[attr-defined]
spy.assert_called_once_with(arg=10)
assert spy.spy_return == 20
assert spy.spy_return_iter is None
assert spy.spy_return_list == [20]
@skip_pypy
def test_static_method_spy(mocker: MockerFixture) -> None:
class Foo:
@staticmethod
def bar(arg):
return arg * 2
spy = mocker.spy(Foo, "bar")
assert Foo.bar(arg=10) == 20
Foo.bar.assert_called_once_with(arg=10) # type:ignore[attr-defined]
assert Foo.bar.spy_return == 20 # type:ignore[attr-defined]
assert Foo.bar.spy_return_iter is None # type:ignore[attr-defined]
assert Foo.bar.spy_return_list == [20] # type:ignore[attr-defined]
spy.assert_called_once_with(arg=10)
assert spy.spy_return == 20
assert spy.spy_return_iter is None
assert spy.spy_return_list == [20]
@skip_pypy
def test_static_method_subclass_spy(mocker: MockerFixture) -> None:
class Base:
@staticmethod
def bar(arg):
return arg * 2
class Foo(Base):
pass
spy = mocker.spy(Foo, "bar")
assert Foo.bar(arg=10) == 20
Foo.bar.assert_called_once_with(arg=10) # type:ignore[attr-defined]
assert Foo.bar.spy_return == 20 # type:ignore[attr-defined]
assert Foo.bar.spy_return_iter is None # type:ignore[attr-defined]
assert Foo.bar.spy_return_list == [20] # type:ignore[attr-defined]
spy.assert_called_once_with(arg=10)
assert spy.spy_return == 20
assert spy.spy_return_iter is None
assert spy.spy_return_list == [20]
def test_callable_like_spy(testdir: Any, mocker: MockerFixture) -> None:
testdir.makepyfile(
uut="""
class CallLike(object):
def __call__(self, x):
return x * 2
call_like = CallLike()
"""
)
testdir.syspathinsert()
uut = __import__("uut")
spy = mocker.spy(uut, "call_like")
uut.call_like(10)
spy.assert_called_once_with(10)
assert spy.spy_return == 20
assert spy.spy_return_iter is None
assert spy.spy_return_list == [20]
@pytest.mark.parametrize("iterator", [(i for i in range(3)), iter([0, 1, 2])])
def test_spy_return_iter_duplicates_iterator_when_enabled(
mocker: MockerFixture, iterator: Iterator[int]
) -> None:
class Foo:
def bar(self) -> Iterator[int]:
return iterator
foo = Foo()
spy = mocker.spy(foo, "bar", duplicate_iterators=True)
result = list(foo.bar())
assert result == [0, 1, 2]
assert spy.spy_return is not None
assert spy.spy_return_iter is not None
assert list(spy.spy_return_iter) == result
[return_value] = spy.spy_return_list
assert isinstance(return_value, Iterator)
@pytest.mark.parametrize("iterator", [(i for i in range(3)), iter([0, 1, 2])])
def test_spy_return_iter_is_not_set_when_disabled(
mocker: MockerFixture, iterator: Iterator[int]
) -> None:
class Foo:
def bar(self) -> Iterator[int]:
return iterator
foo = Foo()
spy = mocker.spy(foo, "bar", duplicate_iterators=False)
result = list(foo.bar())
assert result == [0, 1, 2]
assert spy.spy_return is not None
assert spy.spy_return_iter is None
[return_value] = spy.spy_return_list
assert isinstance(return_value, Iterator)
@pytest.mark.parametrize("iterable", [(0, 1, 2), [0, 1, 2], range(3)])
def test_spy_return_iter_ignores_plain_iterable(
mocker: MockerFixture, iterable: Iterable[int]
) -> None:
class Foo:
def bar(self) -> Iterable[int]:
return iterable
foo = Foo()
spy = mocker.spy(foo, "bar", duplicate_iterators=True)
result = foo.bar()
assert result == iterable
assert spy.spy_return == result
assert spy.spy_return_iter is None
assert spy.spy_return_list == [result]
def test_spy_return_iter_resets(mocker: MockerFixture) -> None:
class Foo:
iterables: Any = [
(i for i in range(3)),
99,
]
def bar(self) -> Any:
return self.iterables.pop(0)
foo = Foo()
spy = mocker.spy(foo, "bar", duplicate_iterators=True)
result_iterator = list(foo.bar())
assert result_iterator == [0, 1, 2]
assert list(spy.spy_return_iter) == result_iterator
assert foo.bar() == 99
assert spy.spy_return_iter is None
@pytest.mark.asyncio
async def test_instance_async_method_spy(mocker: MockerFixture) -> None:
class Foo:
async def bar(self, arg):
return arg * 2
foo = Foo()
spy = mocker.spy(foo, "bar")
result = await foo.bar(10)
spy.assert_called_once_with(10)
assert result == 20
@contextmanager
def assert_traceback() -> Generator[None, None, None]:
"""
Assert that this file is at the top of the filtered traceback
"""
try:
yield
except AssertionError as e:
assert e.__traceback__.tb_frame.f_code.co_filename == __file__ # type:ignore
else:
raise AssertionError("DID NOT RAISE")
@contextmanager
def assert_argument_introspection(left: Any, right: Any) -> Generator[None, None, None]:
"""
Assert detailed argument introspection is used
"""
try:
yield
except AssertionError as e:
# this may be a bit too assuming, but seems nicer then hard-coding
import _pytest.assertion.util as util
# NOTE: we assert with either verbose or not, depending on how our own
# test was run by examining sys.argv
verbose = any(a.startswith("-v") for a in sys.argv)
if int(pytest.__version__.split(".")[0]) < 8:
expected = "\n ".join(util._compare_eq_iterable(left, right, verbose)) # type:ignore[arg-type]
else:
expected = "\n ".join(
util._compare_eq_iterable(left, right, lambda t, *_, **__: t, verbose) # type:ignore[arg-type]
)
assert expected in str(e)
else:
raise AssertionError("DID NOT RAISE")
def test_assert_not_called_wrapper(mocker: MockerFixture) -> None:
stub = mocker.stub()
stub.assert_not_called()
stub()
with assert_traceback():
stub.assert_not_called()
def test_assert_called_with_wrapper(mocker: MockerFixture) -> None:
stub = mocker.stub()
stub("foo")
stub.assert_called_with("foo")
with assert_traceback():
stub.assert_called_with("bar")
def test_assert_called_once_with_wrapper(mocker: MockerFixture) -> None:
stub = mocker.stub()
stub("foo")
stub.assert_called_once_with("foo")
stub("foo")
with assert_traceback():
stub.assert_called_once_with("foo")
def test_assert_called_once_wrapper(mocker: MockerFixture) -> None:
stub = mocker.stub()
if not hasattr(stub, "assert_called_once"):
pytest.skip("assert_called_once not available")
stub("foo")
stub.assert_called_once()
stub("foo")
with assert_traceback():
stub.assert_called_once()
def test_assert_called_wrapper(mocker: MockerFixture) -> None:
stub = mocker.stub()
if not hasattr(stub, "assert_called"):
pytest.skip("assert_called_once not available")
with assert_traceback():
stub.assert_called()
stub("foo")
stub.assert_called()
stub("foo")
stub.assert_called()
@pytest.mark.usefixtures("needs_assert_rewrite")
def test_assert_called_args_with_introspection(mocker: MockerFixture) -> None:
stub = mocker.stub()
complex_args = ("a", 1, {"test"})
wrong_args = ("b", 2, {"jest"})
stub(*complex_args)
stub.assert_called_with(*complex_args)
stub.assert_called_once_with(*complex_args)
with assert_argument_introspection(complex_args, wrong_args):
stub.assert_called_with(*wrong_args)
stub.assert_called_once_with(*wrong_args)
@pytest.mark.usefixtures("needs_assert_rewrite")
def test_assert_called_kwargs_with_introspection(mocker: MockerFixture) -> None:
stub = mocker.stub()
complex_kwargs = dict(foo={"bar": 1, "baz": "spam"})
wrong_kwargs = dict(foo={"goo": 1, "baz": "bran"})
stub(**complex_kwargs)
stub.assert_called_with(**complex_kwargs)
stub.assert_called_once_with(**complex_kwargs)
with assert_argument_introspection(complex_kwargs, wrong_kwargs):
stub.assert_called_with(**wrong_kwargs)
stub.assert_called_once_with(**wrong_kwargs)
def test_assert_any_call_wrapper(mocker: MockerFixture) -> None:
stub = mocker.stub()
stub("foo")
stub("foo")
stub.assert_any_call("foo")
with assert_traceback():
stub.assert_any_call("bar")
def test_assert_has_calls(mocker: MockerFixture) -> None:
stub = mocker.stub()
stub("foo")
stub.assert_has_calls([mocker.call("foo")])
with assert_traceback():
stub.assert_has_calls([mocker.call("bar")])
def test_assert_has_calls_multiple_calls(mocker: MockerFixture) -> None:
stub = mocker.stub()
stub("foo")
stub("bar")
stub("baz")
stub.assert_has_calls([mocker.call("foo"), mocker.call("bar"), mocker.call("baz")])
with assert_traceback():
stub.assert_has_calls(
[
mocker.call("foo"),
mocker.call("bar"),
mocker.call("baz"),
mocker.call("bat"),
]
)
with assert_traceback():
stub.assert_has_calls(
[mocker.call("foo"), mocker.call("baz"), mocker.call("bar")]
)
def test_assert_has_calls_multiple_calls_subset(mocker: MockerFixture) -> None:
stub = mocker.stub()
stub("foo")
stub("bar")
stub("baz")
stub.assert_has_calls([mocker.call("bar"), mocker.call("baz")])
with assert_traceback():
stub.assert_has_calls([mocker.call("foo"), mocker.call("baz")])
with assert_traceback():
stub.assert_has_calls(
[mocker.call("foo"), mocker.call("bar"), mocker.call("bat")]
)
with assert_traceback():
stub.assert_has_calls([mocker.call("baz"), mocker.call("bar")])
def test_assert_has_calls_multiple_calls_any_order(mocker: MockerFixture) -> None:
stub = mocker.stub()
stub("foo")
stub("bar")
stub("baz")
stub.assert_has_calls(
[mocker.call("foo"), mocker.call("baz"), mocker.call("bar")], any_order=True
)
with assert_traceback():
stub.assert_has_calls(
[
mocker.call("foo"),
mocker.call("baz"),
mocker.call("bar"),
mocker.call("bat"),
],
any_order=True,
)
def test_assert_has_calls_multiple_calls_any_order_subset(
mocker: MockerFixture,
) -> None:
stub = mocker.stub()
stub("foo")
stub("bar")
stub("baz")
stub.assert_has_calls([mocker.call("baz"), mocker.call("foo")], any_order=True)
with assert_traceback():
stub.assert_has_calls(
[mocker.call("baz"), mocker.call("foo"), mocker.call("bat")], any_order=True
)
def test_assert_has_calls_no_calls(
mocker: MockerFixture,
) -> None:
stub = mocker.stub()
stub.assert_has_calls([])
with assert_traceback():
stub.assert_has_calls([mocker.call("foo")])
def test_monkeypatch_ini(testdir: Any, mocker: MockerFixture) -> None:
# Make sure the following function actually tests something
stub = mocker.stub()
assert stub.assert_called_with.__module__ != stub.__module__
testdir.makepyfile(
"""
def test_foo(mocker):
stub = mocker.stub()
assert stub.assert_called_with.__module__ == stub.__module__
"""
)
testdir.makeini(
"""
[pytest]
mock_traceback_monkeypatch = false
"""
)
result = testdir.runpytest_subprocess()
assert result.ret == 0
def test_parse_ini_boolean() -> None:
from pytest_mock._util import parse_ini_boolean
assert parse_ini_boolean("True") is True
assert parse_ini_boolean("false") is False
with pytest.raises(ValueError):
parse_ini_boolean("foo")
def test_patched_method_parameter_name(mocker: MockerFixture) -> None:
"""Test that our internal code uses uncommon names when wrapping other
"mock" methods to avoid conflicts with user code (#31).
"""
class Request:
@classmethod
def request(cls, method, args):
pass
m = mocker.patch.object(Request, "request")
Request.request(method="get", args={"type": "application/json"})
m.assert_called_once_with(method="get", args={"type": "application/json"})
def test_monkeypatch_native(testdir: Any) -> None:
"""Automatically disable monkeypatching when --tb=native."""
testdir.makepyfile(
"""
def test_foo(mocker):
stub = mocker.stub()
stub(1, greet='hello')
stub.assert_called_once_with(1, greet='hey')
"""
)
result = testdir.runpytest_subprocess("--tb=native")
assert result.ret == 1
assert "During handling of the above exception" not in result.stdout.str()
assert "Differing items:" not in result.stdout.str()
traceback_lines = [
x
for x in result.stdout.str().splitlines()
if "Traceback (most recent call last)" in x
]
assert (
len(traceback_lines) == 1
) # make sure there are no duplicated tracebacks (#44)
def test_monkeypatch_no_terminal(testdir: Any) -> None:
"""Don't crash without 'terminal' plugin."""
testdir.makepyfile(
"""
def test_foo(mocker):
stub = mocker.stub()
stub(1, greet='hello')
stub.assert_called_once_with(1, greet='hey')
"""
)
result = testdir.runpytest_subprocess("-p", "no:terminal", "-s")
assert result.ret == 1
assert result.stdout.lines == []
def test_standalone_mock(testdir: Any) -> None:
"""Check that the "mock_use_standalone" is being used."""
pytest.importorskip("mock")
testdir.makepyfile(
"""
import mock
def test_foo(mocker):
assert mock.MagicMock is mocker.MagicMock
"""
)
testdir.makeini(
"""
[pytest]
mock_use_standalone_module = true
"""
)
result = testdir.runpytest_subprocess()
assert result.ret == 0
@pytest.mark.usefixtures("needs_assert_rewrite")
def test_detailed_introspection(testdir: Any) -> None:
"""Check that the "mock_use_standalone" is being used."""
testdir.makeini(
"""
[pytest]
asyncio_mode=auto
"""
)
testdir.makepyfile(
"""
def test(mocker):
m = mocker.Mock()
m('fo')
m.assert_called_once_with('', bar=4)
"""
)
result = testdir.runpytest("-s")
expected_lines = [
"*AssertionError: expected call not found.",
"*Expected: mock('', bar=4)",
"*Actual: mock('fo')",
]
expected_lines += [
"*pytest introspection follows:*",
"*Args:",
"*assert ('fo',) == ('',)",
"*At index 0 diff: 'fo' != ''*",
"*Use -v to*",
"*Kwargs:*",
"*assert {} == {'bar': 4}*",
"*Right contains* more item*",
"*{'bar': 4}*",
"*Use -v to*",
]
result.stdout.fnmatch_lines(expected_lines)
@pytest.mark.usefixtures("needs_assert_rewrite")
def test_detailed_introspection_async(testdir: Any) -> None:
"""Check that the "mock_use_standalone" is being used."""
testdir.makeini(
"""
[pytest]
asyncio_mode=auto
"""
)
testdir.makepyfile(
"""
import pytest
async def test(mocker):
m = mocker.AsyncMock()
await m('fo')
m.assert_awaited_once_with('', bar=4)
"""
)
result = testdir.runpytest("-s")
expected_lines = [
"*AssertionError: expected await not found.",
"*Expected: mock('', bar=4)",
"*Actual: mock('fo')",
"*pytest introspection follows:*",
"*Args:",
"*assert ('fo',) == ('',)",
"*At index 0 diff: 'fo' != ''*",
"*Use -v to*",
"*Kwargs:*",
"*assert {} == {'bar': 4}*",
"*Right contains* more item*",
"*{'bar': 4}*",
"*Use -v to*",
]
result.stdout.fnmatch_lines(expected_lines)
def test_missing_introspection(testdir: Any) -> None:
testdir.makepyfile(
"""
def test_foo(mocker):
mock = mocker.Mock()
mock('foo')
mock('test')
mock.assert_called_once_with('test')
"""
)
result = testdir.runpytest()
assert "pytest introspection follows:" not in result.stdout.str()
def test_assert_called_with_unicode_arguments(mocker: MockerFixture) -> None:
"""Test bug in assert_call_with called with non-ascii unicode string (#91)"""
stub = mocker.stub()
stub(b"l\xc3\xb6k".decode("UTF-8"))
with pytest.raises(AssertionError):
stub.assert_called_with("lak")
def test_plain_stopall(testdir: Any) -> None:
"""patch.stopall() in a test should not cause an error during unconfigure (#137)"""
testdir.makeini(
"""
[pytest]
asyncio_mode=auto
"""
)
testdir.makepyfile(
"""
import random
def get_random_number():
return random.randint(0, 100)
def test_get_random_number(mocker):
patcher = mocker.mock_module.patch("random.randint", lambda x, y: 5)
patcher.start()
assert get_random_number() == 5
mocker.mock_module.patch.stopall()
"""
)
result = testdir.runpytest_subprocess()
result.stdout.fnmatch_lines("* 1 passed in *")
assert "RuntimeError" not in result.stderr.str()
def test_warn_patch_object_context_manager(mocker: MockerFixture) -> None:
class A:
def doIt(self):
return False
a = A()
expected_warning_msg = (
"Mocks returned by pytest-mock do not need to be used as context managers. "
"The mocker fixture automatically undoes mocking at the end of a test. "
"This warning can be ignored if it was triggered by mocking a context manager. "
"https://pytest-mock.readthedocs.io/en/latest/usage.html#usage-as-context-manager"
)
with pytest.warns(
PytestMockWarning, match=re.escape(expected_warning_msg)
) as warn_record:
with mocker.patch.object(a, "doIt", return_value=True):
assert a.doIt() is True
assert warn_record[0].filename == __file__
def test_warn_patch_context_manager(mocker: MockerFixture) -> None:
expected_warning_msg = (
"Mocks returned by pytest-mock do not need to be used as context managers. "
"The mocker fixture automatically undoes mocking at the end of a test. "
"This warning can be ignored if it was triggered by mocking a context manager. "
"https://pytest-mock.readthedocs.io/en/latest/usage.html#usage-as-context-manager"
)
with pytest.warns(
PytestMockWarning, match=re.escape(expected_warning_msg)
) as warn_record:
with mocker.patch("json.loads"):
pass
assert warn_record[0].filename == __file__
def test_context_manager_patch_example(mocker: MockerFixture) -> None:
"""Our message about misusing mocker as a context manager should not affect mocking
context managers (see #192)"""
class dummy_module:
class MyContext:
def __enter__(self, *args, **kwargs):
return 10
def __exit__(self, *args, **kwargs):
pass
def my_func():
with dummy_module.MyContext() as v:
return v
mocker.patch.object(dummy_module, "MyContext")
assert isinstance(my_func(), mocker.MagicMock)
def test_patch_context_manager_with_context_manager(mocker: MockerFixture) -> None:
"""Test that no warnings are issued when an object patched with
patch.context_manager is used as a context manager (#221)"""
class A:
def doIt(self):
return False
a = A()
with warnings.catch_warnings(record=True) as warn_record:
with mocker.patch.context_manager(a, "doIt", return_value=True):
assert a.doIt() is True
assert len(warn_record) == 0
def test_abort_patch_context_manager_with_stale_pyc(testdir: Any) -> None:
"""Ensure we don't trigger an error in case the frame where mocker.patch is being
used doesn't have a 'context' (#169)"""
import compileall
py_fn = testdir.makepyfile(
c="""
class C:
x = 1
def check(mocker):
mocker.patch.object(C, "x", 2)
assert C.x == 2
"""
)
testdir.syspathinsert()
testdir.makepyfile(
"""
from c import check
def test_foo(mocker):
check(mocker)
"""
)
result = testdir.runpytest()
result.assert_outcomes(passed=1)
assert compileall.compile_file(str(py_fn), legacy=True)
pyc_fn = str(py_fn) + "c"
assert os.path.isfile(pyc_fn)
py_fn.remove()
result = testdir.runpytest()
result.assert_outcomes(passed=1)
def test_used_with_class_scope(testdir: Any) -> None:
testdir.makeini(
"""
[pytest]
asyncio_mode=auto
"""
)
testdir.makepyfile(
"""
import pytest
import random
import unittest
def get_random_number():
return random.randint(0, 1)
@pytest.fixture(autouse=True, scope="class")
def randint_mock(class_mocker):
return class_mocker.patch("random.randint", lambda x, y: 5)
class TestGetRandomNumber(unittest.TestCase):
def test_get_random_number(self):
assert get_random_number() == 5
"""
)
result = testdir.runpytest_subprocess()
assert "AssertionError" not in result.stderr.str()
result.stdout.fnmatch_lines("* 1 passed in *")
def test_used_with_module_scope(testdir: Any) -> None:
testdir.makeini(
"""
[pytest]
asyncio_mode=auto
"""
)
testdir.makepyfile(
"""
import pytest
import random
def get_random_number():
return random.randint(0, 1)
@pytest.fixture(autouse=True, scope="module")
def randint_mock(module_mocker):
return module_mocker.patch("random.randint", lambda x, y: 5)
def test_get_random_number():
assert get_random_number() == 5
"""
)
result = testdir.runpytest_subprocess()
assert "AssertionError" not in result.stderr.str()
result.stdout.fnmatch_lines("* 1 passed in *")
def test_used_with_package_scope(testdir: Any) -> None:
testdir.makeini(
"""
[pytest]
asyncio_mode=auto
"""
)
testdir.makepyfile(
"""
import pytest
import random
def get_random_number():
return random.randint(0, 1)
@pytest.fixture(autouse=True, scope="package")
def randint_mock(package_mocker):
return package_mocker.patch("random.randint", lambda x, y: 5)
def test_get_random_number():
assert get_random_number() == 5
"""
)
result = testdir.runpytest_subprocess()
assert "AssertionError" not in result.stderr.str()
result.stdout.fnmatch_lines("* 1 passed in *")
def test_used_with_session_scope(testdir: Any) -> None:
testdir.makeini(
"""
[pytest]
asyncio_mode=auto
"""
)
testdir.makepyfile(
"""
import pytest
import random
def get_random_number():
return random.randint(0, 1)
@pytest.fixture(autouse=True, scope="session")
def randint_mock(session_mocker):
return session_mocker.patch("random.randint", lambda x, y: 5)
def test_get_random_number():
assert get_random_number() == 5
"""
)
result = testdir.runpytest_subprocess()
assert "AssertionError" not in result.stderr.str()
result.stdout.fnmatch_lines("* 1 passed in *")
def test_stop_patch(mocker):
class UnSpy:
def foo(self):
return 42
m = mocker.patch.object(UnSpy, "foo", return_value=0)
assert UnSpy().foo() == 0
mocker.stop(m)
assert UnSpy().foo() == 42
with pytest.raises(ValueError):
mocker.stop(m)
def test_stop_instance_patch(mocker):
class UnSpy:
def foo(self):
return 42
m = mocker.patch.object(UnSpy, "foo", return_value=0)
un_spy = UnSpy()
assert un_spy.foo() == 0
mocker.stop(m)
assert un_spy.foo() == 42
def test_stop_spy(mocker):
class UnSpy:
def foo(self):
return 42
spy = mocker.spy(UnSpy, "foo")
assert UnSpy().foo() == 42
assert spy.call_count == 1
mocker.stop(spy)
assert UnSpy().foo() == 42
assert spy.call_count == 1
def test_stop_instance_spy(mocker):
class UnSpy:
def foo(self):
return 42
spy = mocker.spy(UnSpy, "foo")
un_spy = UnSpy()
assert un_spy.foo() == 42
assert spy.call_count == 1
mocker.stop(spy)
assert un_spy.foo() == 42
assert spy.call_count == 1
def test_stop_multiple_patches(mocker: MockerFixture) -> None:
"""Regression for #420."""
class Class1:
@staticmethod
def get():
return 1
class Class2:
@staticmethod
def get():
return 2
def handle_get():
return 3
mocker.patch.object(Class1, "get", handle_get)
mocker.patch.object(Class2, "get", handle_get)
mocker.stopall()
assert Class1.get() == 1
assert Class2.get() == 2
|