diff --git a/pyproject.toml b/pyproject.toml index 6a206a4..055fb00 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -58,21 +58,7 @@ requires = ["poetry-core>=1.0.0"] build-backend = "poetry.core.masonry.api" [tool.pylint.messages_control] -disable = [ - "too-many-instance-attributes", - "too-few-public-methods", - "logging-fstring-interpolation", - "too-many-function-args", - "too-many-arguments", - "bad-continuation", - "too-many-locals", - "too-many-branches", - "too-many-statements", - "too-many-public-methods", - "protected-access", - "broad-except", - "fixme", -] +disable = [] [tool.pylint.format] max-line-length = "100" diff --git a/src/flexmock/api.py b/src/flexmock/api.py index f33bccc..41b7f3a 100644 --- a/src/flexmock/api.py +++ b/src/flexmock/api.py @@ -1,6 +1,7 @@ """Flexmock public API.""" -# pylint: disable=no-self-use,too-many-lines +# pylint: disable=no-self-use,protected-access,too-many-lines import inspect +import itertools import re import sys import types @@ -28,7 +29,7 @@ RE_TYPE = type(re.compile("")) -class ReturnValue: +class ReturnValue: # pylint: disable=too-few-public-methods """ReturnValue""" def __init__(self, value: Optional[Any] = None, raises: Optional[Exception] = None) -> None: @@ -249,11 +250,12 @@ def _update_method(self, expectation: "Expectation", name: str) -> None: expectation._update_original(name, obj) method_type = type(_getattr(expectation, "_original")) try: + # pylint: disable=fixme # TODO(herman): this is awful, fix this properly. # When a class/static method is mocked out on an *instance* # we need to fetch the type from the class method_type = type(_getattr(obj.__class__, name)) - except Exception: + except Exception: # pylint: disable=broad-except pass if method_type in SPECIAL_METHODS: expectation._original_function = getattr(obj, name) @@ -311,75 +313,62 @@ def updated(self: Any) -> Any: def _create_mock_method(self, name: str) -> Callable[..., Any]: def _handle_exception_matching(expectation: Expectation) -> None: # pylint: disable=misplaced-bare-raise - return_values = _getattr(expectation, "_return_values") - if return_values: - raised, instance = sys.exc_info()[:2] - assert raised, "no exception was raised" - message = "%s" % instance - expected = return_values[0].raises - if not expected: - raise - args = return_values[0].value - expected_instance = expected(*args["kargs"], **args["kwargs"]) - expected_message = "%s" % expected_instance - if inspect.isclass(expected): - if expected is not raised and expected not in raised.__bases__: - raise ExceptionClassError("expected %s, raised %s" % (expected, raised)) - if args["kargs"] and isinstance(args["kargs"][0], RE_TYPE): - if not args["kargs"][0].search(message): - raise ( - ExceptionMessageError( - 'expected /%s/, raised "%s"' - % (args["kargs"][0].pattern, message) - ) - ) - elif expected_message and expected_message != message: + return_values = expectation._return_values + if not return_values: + raise + raised, instance = sys.exc_info()[:2] + assert raised, "no exception was raised" + message = "%s" % instance + expected = return_values[0].raises + if not expected: + raise + args = return_values[0].value + expected_message = "%s" % expected(*args["kargs"], **args["kwargs"]) + if inspect.isclass(expected): + if expected is not raised and expected not in raised.__bases__: + raise ExceptionClassError("expected %s, raised %s" % (expected, raised)) + if args["kargs"] and isinstance(args["kargs"][0], RE_TYPE): + if not args["kargs"][0].search(message): raise ( ExceptionMessageError( - 'expected "%s", raised "%s"' % (expected_message, message) + 'expected /%s/, raised "%s"' % (args["kargs"][0].pattern, message) ) ) - elif expected is not raised: - raise ExceptionClassError('expected "%s", raised "%s"' % (expected, raised)) - else: - raise + elif expected_message and expected_message != message: + raise ( + ExceptionMessageError( + 'expected "%s", raised "%s"' % (expected_message, message) + ) + ) + elif expected is not raised: + raise ExceptionClassError('expected "%s", raised "%s"' % (expected, raised)) def match_return_values(expected: Any, received: Any) -> bool: - if not isinstance(expected, tuple): - expected = (expected,) - if not isinstance(received, tuple): - received = (received,) - if len(received) != len(expected): - return False - for i, val in enumerate(received): - if not _arguments_match(val, expected[i]): - return False - return True + expected = (expected,) if not isinstance(expected, tuple) else expected + received = (received,) if not isinstance(received, tuple) else received + return len(received) == len(expected) and all( + _arguments_match(r, e) for r, e in zip(received, expected) + ) def pass_thru( expectation: Expectation, runtime_self: Any, *kargs: Any, **kwargs: Any ) -> Any: - return_values = None try: - original = _getattr(expectation, "_original") - _mock = _getattr(expectation, "_mock") - if inspect.isclass(_mock): - if type(original) in SPECIAL_METHODS: - original = _getattr(expectation, "_original_function") - return_values = original(*kargs, **kwargs) - else: - return_values = original(runtime_self, *kargs, **kwargs) - else: - return_values = original(*kargs, **kwargs) - except Exception: + return_values = ( + ( + expectation._original_function(*kargs, **kwargs) + if type(expectation._original) in SPECIAL_METHODS + else expectation._original(runtime_self, *kargs, **kwargs) + ) + if inspect.isclass(expectation._mock) + else expectation._original(*kargs, **kwargs) + ) + except Exception: # pylint: disable=broad-except return _handle_exception_matching(expectation) - expected_values = _getattr(expectation, "_return_values") + expected_values = expectation._return_values if expected_values and not match_return_values(expected_values[0].value, return_values): - raise ( - MethodSignatureError( - "expected to return %s, returned %s" - % (expected_values[0].value, return_values) - ) + raise MethodSignatureError( + "expected to return %s, returned %s" % (expected_values[0].value, return_values) ) return return_values @@ -392,26 +381,20 @@ def _handle_matched_expectation( ) expectation.times_called += 1 expectation.verify(final=False) - _pass_thru = _getattr(expectation, "_pass_thru") - _replace_with = _getattr(expectation, "_replace_with") - if _pass_thru: + if expectation._pass_thru: return pass_thru(expectation, runtime_self, *kargs, **kwargs) - if _replace_with: - return _replace_with(*kargs, **kwargs) - return_values = _getattr(expectation, "_return_values") - if return_values: - return_value = return_values[0] - del return_values[0] - return_values.append(return_value) - else: - return_value = ReturnValue() - if return_value.raises: - if inspect.isclass(return_value.raises): - raise return_value.raises( - *return_value.value["kargs"], **return_value.value["kwargs"] - ) - raise return_value.raises # pylint: disable=raising-bad-type - return return_value.value + if expectation._replace_with: + return expectation._replace_with(*kargs, **kwargs) + return_values = expectation._return_values or [ReturnValue()] + return_value = return_values.pop(0) + return_values.append(return_value) + if not return_value.raises: + return return_value.value + if inspect.isclass(return_value.raises): + raise return_value.raises( + *return_value.value["kargs"], **return_value.value["kwargs"] + ) + raise return_value.raises # pylint: disable=raising-bad-type def mock_method(runtime_self: Any, *kargs: Any, **kwargs: Any) -> Any: arguments = {"kargs": kargs, "kwargs": kwargs} @@ -419,23 +402,18 @@ def mock_method(runtime_self: Any, *kargs: Any, **kwargs: Any) -> Any: if expectation: return _handle_matched_expectation(expectation, runtime_self, *kargs, **kwargs) # inform the user which expectation(s) for the method were _not_ matched - expectations = [ - expectation + error_msg = _format_args(name, arguments) + "\n".join( + "\nDid not match expectation %s" % _format_args(name, expectation._args) for expectation in reversed(FlexmockContainer.flexmock_objects.get(self, [])) if expectation.name == name - ] - error_msg = _format_args(name, arguments) - if expectations: - for expectation in expectations: - error_msg += "\nDid not match expectation %s" % _format_args( - name, expectation._args - ) + ) # make sure to clean up expectations to ensure none of them # interfere with the runner's error reporting mechanism # e.g. open() - for _, expectations in FlexmockContainer.flexmock_objects.items(): - for expectation in expectations: - _getattr(expectation, "reset")() + for expectation in itertools.chain.from_iterable( + FlexmockContainer.flexmock_objects.values() + ): + expectation.reset() raise MethodSignatureError(error_msg) return mock_method @@ -443,26 +421,26 @@ def mock_method(runtime_self: Any, *kargs: Any, **kwargs: Any) -> Any: def flexmock_teardown() -> None: """Performs flexmock-specific teardown tasks.""" - saved = {} - instances = [] - classes = [] - for mock_object, expectations in FlexmockContainer.flexmock_objects.items(): - saved[mock_object] = expectations[:] - for expectation in expectations: - _getattr(expectation, "reset")() - for mock in saved: - obj = mock._object - if not isinstance(obj, Mock) and not inspect.isclass(obj): - instances.append(obj) - if inspect.isclass(obj): - classes.append(obj) - for obj in instances + classes: + saved_flexmock_objects = FlexmockContainer.flexmock_objects + all_expectations = list(itertools.chain.from_iterable(saved_flexmock_objects.values())) + for expectation in all_expectations[:]: + expectation.reset() + + def _is_instance_or_class(obj: Any) -> bool: + return bool( + (not isinstance(obj, Mock) and not inspect.isclass(obj)) or inspect.isclass(obj) + ) + + mocked_objects = [ + mock._object for mock in saved_flexmock_objects if _is_instance_or_class(mock._object) + ] + for obj in mocked_objects: for attr in UPDATED_ATTRS: try: obj_dict = obj.__dict__ if obj_dict[attr].__code__ is Mock.__dict__[attr].__code__: del obj_dict[attr] - except Exception: + except Exception: # pylint: disable=broad-except try: if getattr(obj, attr).__code__ is Mock.__dict__[attr].__code__: delattr(obj, attr) @@ -473,9 +451,8 @@ def flexmock_teardown() -> None: # make sure this is done last to keep exceptions here from breaking # any of the previous steps that cleanup all the changes - for mock_object, expectations in saved.items(): - for expectation in expectations: - _getattr(expectation, "verify")() + for expectation in all_expectations: + expectation.verify() class Expectation: @@ -486,6 +463,8 @@ class Expectation: raise. """ + # pylint: disable=too-many-instance-attributes + def __init__( self, mock: Mock, @@ -551,7 +530,7 @@ def _get_runnable(self) -> str: name = source.split("when(")[1].split(")")[0] elif "def " in source: name = source.split("def ")[1].split("(")[0] - except Exception: + except Exception: # pylint: disable=broad-except # couldn't get the source, oh well pass return name diff --git a/src/flexmock/integrations.py b/src/flexmock/integrations.py index b2b04b1..262a8fb 100644 --- a/src/flexmock/integrations.py +++ b/src/flexmock/integrations.py @@ -53,7 +53,7 @@ def decorated(self: unittest.TextTestResult, test: unittest.TestCase) -> None: try: flexmock_teardown() saved_add_success(self, test) - except Exception: + except Exception: # pylint: disable=broad-except if hasattr(self, "_pre_flexmock_success"): self.addFailure(test, sys.exc_info()) if hasattr(self, "_pre_flexmock_success"): @@ -73,7 +73,7 @@ def _patch_add_success(klass: Type[unittest.TextTestResult]) -> None: @wraps(klass.addSuccess) def decorated(self: unittest.TextTestResult, _test: unittest.TestCase) -> None: - self._pre_flexmock_success = True # type: ignore + self._pre_flexmock_success = True # type: ignore # pylint: disable=protected-access if klass.addSuccess is not decorated: klass.addSuccess = decorated # type: ignore diff --git a/tests/flexmock_pytest_test.py b/tests/flexmock_pytest_test.py index 28fc910..b7c7446 100644 --- a/tests/flexmock_pytest_test.py +++ b/tests/flexmock_pytest_test.py @@ -6,12 +6,12 @@ from flexmock.api import flexmock_teardown from flexmock.exceptions import MethodCallError from tests import flexmock_test -from tests.flexmock_test import assert_raises def test_module_level_test_for_pytest(): flexmock(foo="bar").should_receive("foo").once() - assert_raises(MethodCallError, flexmock_teardown) + with pytest.raises(MethodCallError): + flexmock_teardown() @pytest.fixture() @@ -26,14 +26,16 @@ def test_runtest_hook_with_fixture_for_pytest(runtest_hook_fixture): class TestForPytest(flexmock_test.RegularClass): def test_class_level_test_for_pytest(self): flexmock(foo="bar").should_receive("foo").once() - assert_raises(MethodCallError, flexmock_teardown) + with pytest.raises(MethodCallError): + flexmock_teardown() class TestUnittestClass(flexmock_test.TestFlexmockUnittest): def test_unittest(self): mocked = flexmock(a=2) mocked.should_receive("a").once() - assert_raises(MethodCallError, flexmock_teardown) + with pytest.raises(MethodCallError): + flexmock_teardown() class TestFailureOnException: diff --git a/tests/flexmock_test.py b/tests/flexmock_test.py index eb0a5bf..7bdb318 100644 --- a/tests/flexmock_test.py +++ b/tests/flexmock_test.py @@ -1,10 +1,19 @@ """Flexmock tests.""" -# pylint: disable=missing-docstring,too-many-lines,disallowed-name,no-member,invalid-name,no-self-use +# pylint: disable=missing-docstring +# pylint: disable=protected-access +# pylint: disable=too-many-lines +# pylint: disable=disallowed-name +# pylint: disable=no-member +# pylint: disable=invalid-name +# pylint: disable=no-self-use +# pylint: disable=too-few-public-methods import random import re import sys import unittest +import pytest + from flexmock.api import ( AT_LEAST, AT_MOST, @@ -49,17 +58,6 @@ def instance_method(self, a): pass -def assert_raises(exception, method, *kargs, **kwargs): - try: - method(*kargs, **kwargs) - except exception: - return - except Exception: - instance = sys.exc_info()[1] - print("%s" % instance) - raise Exception("%s not raised" % exception.__name__) - - def assert_equal(expected, received, msg=""): if not msg: msg = "expected %s, received %s" % (expected, received) @@ -67,7 +65,7 @@ def assert_equal(expected, received, msg=""): raise AssertionError("%s != %s : %s" % (expected, received, msg)) -class RegularClass: +class RegularClass: # pylint: disable=too-many-public-methods def _tear_down(self): return flexmock_teardown() @@ -172,7 +170,8 @@ def test_flexmock_should_set_expectation_call_numbers(self): mock = flexmock(name="temp") mock.should_receive("method_foo").times(1) expectation = FlexmockContainer.get_flexmock_expectation(mock, "method_foo") - assert_raises(MethodCallError, expectation.verify) + with pytest.raises(MethodCallError): + expectation.verify() mock.method_foo() expectation.verify() @@ -183,7 +182,8 @@ class FakeException(Exception): pass mock.should_receive("method_foo").and_raise(FakeException) - assert_raises(FakeException, mock.method_foo) + with pytest.raises(FakeException): + mock.method_foo() assert_equal( 1, FlexmockContainer.get_flexmock_expectation(mock, "method_foo").times_called, @@ -198,7 +198,8 @@ def __init__(self, arg, arg2): pass mock.should_receive("method_foo").and_raise(FakeException(1, arg2=2)) - assert_raises(FakeException, mock.method_foo) + with pytest.raises(FakeException): + mock.method_foo() assert_equal( 1, FlexmockContainer.get_flexmock_expectation(mock, "method_foo").times_called, @@ -213,7 +214,8 @@ def __init__(self, arg, arg2): pass mock.should_receive("method_foo").and_raise(FakeException, 1, arg2=2) - assert_raises(FakeException, mock.method_foo) + with pytest.raises(FakeException): + mock.method_foo() assert_equal( 1, FlexmockContainer.get_flexmock_expectation(mock, "method_foo").times_called, @@ -231,7 +233,8 @@ def test_flexmock_should_match_any_args_by_default(self): def test_flexmock_should_fail_to_match_exactly_no_args_when_calling_with_args(self): mock = flexmock() mock.should_receive("method_foo").with_args() - assert_raises(MethodSignatureError, mock.method_foo, "baz") + with pytest.raises(MethodSignatureError): + mock.method_foo("baz") def test_flexmock_should_match_exactly_no_args(self): class Foo: @@ -312,7 +315,8 @@ def test_flexmock_should_match_expectations_against_builtin_classes(self): mock.should_receive("method_foo").with_args(int).and_return("got an int") assert_equal("got a string", mock.method_foo("string!")) assert_equal("got an int", mock.method_foo(23)) - assert_raises(MethodSignatureError, mock.method_foo, 2.0) + with pytest.raises(MethodSignatureError): + mock.method_foo(2.0) def test_with_args_should_work_with_builtin_c_functions_and_methods(self): flexmock(sys.stdout).should_call("write") # set fall-through @@ -331,7 +335,8 @@ class Foo: mock.should_receive("method_foo").with_args(Foo).and_return("got a Foo") assert_equal("got a Foo", mock.method_foo(Foo())) - assert_raises(MethodSignatureError, mock.method_foo, 1) + with pytest.raises(MethodSignatureError): + mock.method_foo(1) def test_flexmock_configures_global_mocks_dict(self): mock = flexmock(name="temp") @@ -343,7 +348,8 @@ def test_flexmock_configures_global_mocks_dict(self): def test_flexmock_teardown_verifies_mocks(self): mock = flexmock(name="temp") mock.should_receive("verify_expectations").times(1) - assert_raises(MethodCallError, self._tear_down) + with pytest.raises(MethodCallError): + self._tear_down() def test_flexmock_teardown_does_not_verify_stubs(self): mock = flexmock(name="temp") @@ -450,7 +456,8 @@ def test_flexmock_respects_at_least_when_called_less_than_requested(self): expectation = FlexmockContainer.get_flexmock_expectation(mock, "method_foo") assert_equal(AT_LEAST, expectation._modifier) mock.method_foo() - assert_raises(MethodCallError, self._tear_down) + with pytest.raises(MethodCallError): + self._tear_down() def test_flexmock_respects_at_least_when_called_requested_number(self): mock = flexmock(name="temp") @@ -491,21 +498,24 @@ def test_flexmock_respects_at_most_when_called_more_than_requested(self): expectation = FlexmockContainer.get_flexmock_expectation(mock, "method_foo") assert_equal(AT_MOST, expectation._modifier) mock.method_foo() - assert_raises(MethodCallError, mock.method_foo) + with pytest.raises(MethodCallError): + mock.method_foo() def test_flexmock_treats_once_as_times_one(self): mock = flexmock(name="temp") mock.should_receive("method_foo").and_return("value_bar").once() expectation = FlexmockContainer.get_flexmock_expectation(mock, "method_foo") assert_equal(1, expectation._expected_calls[EXACTLY]) - assert_raises(MethodCallError, self._tear_down) + with pytest.raises(MethodCallError): + self._tear_down() def test_flexmock_treats_twice_as_times_two(self): mock = flexmock(name="temp") mock.should_receive("method_foo").twice().and_return("value_bar") expectation = FlexmockContainer.get_flexmock_expectation(mock, "method_foo") assert_equal(2, expectation._expected_calls[EXACTLY]) - assert_raises(MethodCallError, self._tear_down) + with pytest.raises(MethodCallError): + self._tear_down() def test_flexmock_works_with_never_when_true(self): mock = flexmock(name="temp") @@ -517,7 +527,8 @@ def test_flexmock_works_with_never_when_true(self): def test_flexmock_works_with_never_when_false(self): mock = flexmock(name="temp") mock.should_receive("method_foo").and_return("value_bar").never() - assert_raises(MethodCallError, mock.method_foo) + with pytest.raises(MethodCallError): + mock.method_foo() def test_flexmock_get_flexmock_expectation_should_work_with_args(self): mock = flexmock(name="temp") @@ -556,7 +567,8 @@ def __call__(self, a): return a instance = WithCall() - assert_raises(FlexmockError, flexmock(instance).should_call, "__call__") + with pytest.raises(FlexmockError): + flexmock(instance).should_call("__call__") def test_should_call_on_class_mock(self): class User: @@ -573,14 +585,16 @@ def bar(self): user1 = User() user2 = User() flexmock(User).should_call("foo").once() - assert_raises(MethodCallError, self._tear_down) + with pytest.raises(MethodCallError): + self._tear_down() flexmock(User).should_call("foo").twice() assert_equal("class", user1.foo()) assert_equal("class", user2.foo()) # Access instance attributes flexmock(User).should_call("bar").once() - assert_raises(MethodCallError, self._tear_down) + with pytest.raises(MethodCallError): + self._tear_down() flexmock(User).should_call("bar").twice() assert_equal("value", user1.bar()) assert_equal("value", user2.bar()) @@ -680,7 +694,8 @@ def method1(self): flexmock(User) Group.should_receive("method1").once() User.should_receive("method2").once() - assert_raises(MethodCallError, self._tear_down) + with pytest.raises(MethodCallError): + self._tear_down() for method in UPDATED_ATTRS: assert method not in dir(Group) for method in UPDATED_ATTRS: @@ -712,12 +727,14 @@ def method2(self, a): group = Group() flexmock(group).should_call("method1").at_least().once() - assert_raises(MethodCallError, self._tear_down) + with pytest.raises(MethodCallError): + self._tear_down() flexmock(group) group.should_call("method2").with_args("a").once() group.should_receive("method2").with_args("not a") group.method2("not a") - assert_raises(MethodCallError, self._tear_down) + with pytest.raises(MethodCallError): + self._tear_down() def test_flexmock_doesnt_error_on_properly_ordered_expectations(self): class Foo: @@ -754,7 +771,8 @@ def method1(self, a): flexmock(foo) foo.should_receive("method1").with_args("a").ordered() foo.should_receive("method1").with_args("b").ordered() - assert_raises(CallOrderError, foo.method1, "b") + with pytest.raises(CallOrderError): + foo.method1("b") def test_flexmock_should_accept_multiple_return_values(self): class Foo: @@ -812,9 +830,11 @@ def method1(self): foo = Foo() flexmock(foo).should_receive("method1").and_return(1).and_raise(Exception) assert_equal(1, foo.method1()) - assert_raises(Exception, foo.method1) + with pytest.raises(Exception): + foo.method1() assert_equal(1, foo.method1()) - assert_raises(Exception, foo.method1) + with pytest.raises(Exception): + foo.method1() def test_flexmock_should_match_types_on_multiple_arguments(self): class Foo: @@ -824,11 +844,14 @@ def method1(self, a, b): foo = Foo() flexmock(foo).should_receive("method1").with_args(str, int).and_return("ok") assert_equal("ok", foo.method1("some string", 12)) - assert_raises(MethodSignatureError, foo.method1, 12, 32) + with pytest.raises(MethodSignatureError): + foo.method1(12, 32) flexmock(foo).should_receive("method1").with_args(str, int).and_return("ok") - assert_raises(MethodSignatureError, foo.method1, 12, "some string") + with pytest.raises(MethodSignatureError): + foo.method1(12, "some string") flexmock(foo).should_receive("method1").with_args(str, int).and_return("ok") - assert_raises(MethodSignatureError, foo.method1, "string", 12, 14) + with pytest.raises(MethodSignatureError): + foo.method1("string", 12, 14) # pylint: disable=too-many-function-args def test_flexmock_should_match_types_on_multiple_arguments_generic(self): class Foo: @@ -841,9 +864,11 @@ def method1(self, a, b, c): assert_equal("ok", foo.method1((1,), None, 12)) assert_equal("ok", foo.method1(12, 14, [])) assert_equal("ok", foo.method1("some string", "another one", False)) - assert_raises(MethodSignatureError, foo.method1, "string", 12) + with pytest.raises(MethodSignatureError): + foo.method1("string", 12) # pylint: disable=no-value-for-parameter flexmock(foo).should_receive("method1").with_args(object, object, object).and_return("ok") - assert_raises(MethodSignatureError, foo.method1, "string", 12, 13, 14) + with pytest.raises(MethodSignatureError): + foo.method1("string", 12, 13, 14) # pylint: disable=too-many-function-args def test_flexmock_should_match_types_on_multiple_arguments_classes(self): class Foo: @@ -857,9 +882,11 @@ class Bar: bar = Bar() flexmock(foo).should_receive("method1").with_args(object, Bar).and_return("ok") assert_equal("ok", foo.method1("some string", bar)) - assert_raises(MethodSignatureError, foo.method1, bar, "some string") + with pytest.raises(MethodSignatureError): + foo.method1(bar, "some string") flexmock(foo).should_receive("method1").with_args(object, Bar).and_return("ok") - assert_raises(MethodSignatureError, foo.method1, 12, "some string") + with pytest.raises(MethodSignatureError): + foo.method1(12, "some string") def test_flexmock_should_match_keyword_arguments(self): class Foo: @@ -872,11 +899,14 @@ def method1(self, a, **kwargs): foo.method1(1, arg3=3, arg2=2) self._tear_down() flexmock(foo).should_receive("method1").with_args(1, arg3=3, arg2=2) - assert_raises(MethodSignatureError, foo.method1, arg2=2, arg3=3) + with pytest.raises(MethodSignatureError): + foo.method1(arg2=2, arg3=3) # pylint: disable=no-value-for-parameter flexmock(foo).should_receive("method1").with_args(1, arg3=3, arg2=2) - assert_raises(MethodSignatureError, foo.method1, 1, arg2=2, arg3=4) + with pytest.raises(MethodSignatureError): + foo.method1(1, arg2=2, arg3=4) flexmock(foo).should_receive("method1").with_args(1, arg3=3, arg2=2) - assert_raises(MethodSignatureError, foo.method1, 1) + with pytest.raises(MethodSignatureError): + foo.method1(1) def test_flexmock_should_call_should_match_keyword_arguments(self): class Foo: @@ -1048,7 +1078,8 @@ def get_stuff(self): user = User() flexmock(user).should_call("get_stuff").and_raise(FakeException, "2", "1") - assert_raises(ExceptionMessageError, user.get_stuff) + with pytest.raises(ExceptionMessageError): + user.get_stuff() def test_flexmock_should_verify_spy_matches_exception_regexp(self): class User: @@ -1067,7 +1098,8 @@ def get_stuff(self): user = User() flexmock(user).should_call("get_stuff").and_raise(Exception, re.compile("^asdf")) - assert_raises(ExceptionMessageError, user.get_stuff) + with pytest.raises(ExceptionMessageError): + user.get_stuff() def test_flexmock_should_blow_up_on_wrong_spy_exception_type(self): class User: @@ -1076,7 +1108,8 @@ def get_stuff(self): user = User() flexmock(user).should_call("get_stuff").and_raise(MethodCallError) - assert_raises(ExceptionClassError, user.get_stuff) + with pytest.raises(ExceptionClassError): + user.get_stuff() def test_flexmock_should_match_spy_exception_parent_type(self): class User: @@ -1097,9 +1130,11 @@ def get_more_stuff(self): user = User() flexmock(user).should_call("get_stuff").and_return("other", "stuff") - assert_raises(MethodSignatureError, user.get_stuff) + with pytest.raises(MethodSignatureError): + user.get_stuff() flexmock(user).should_call("get_more_stuff").and_return() - assert_raises(MethodSignatureError, user.get_more_stuff) + with pytest.raises(MethodSignatureError): + user.get_more_stuff() def test_flexmock_should_mock_same_class_twice(self): class Foo: @@ -1159,7 +1194,8 @@ def test_module_level_function_with_kwargs(self): else: mod = sys.modules["__main__"] flexmock(mod).should_receive("module_level_function").with_args(1, args="expected") - assert_raises(FlexmockError, module_level_function, 1, args="not expected") + with pytest.raises(FlexmockError): + module_level_function(1, args="not expected") def test_flexmock_should_support_mocking_classes_as_functions(self): if "tests.flexmock_test" in sys.modules: @@ -1220,17 +1256,22 @@ def quux(self): flexmock(foo).should_call("bar").and_return("bar").once() flexmock(foo).should_call("baz").and_return("bar").once() flexmock(foo).should_call("quux").and_return("bar").once() - assert_raises(FlexmockError, foo.foo) - assert_raises(FlexmockError, foo.bar) - assert_raises(FlexmockError, foo.baz) - assert_raises(FlexmockError, foo.quux) + with pytest.raises(FlexmockError): + foo.foo() + with pytest.raises(FlexmockError): + foo.bar() + with pytest.raises(FlexmockError): + foo.baz() + with pytest.raises(FlexmockError): + foo.quux() def test_new_instances_should_blow_up_on_should_receive(self): class User: pass mock = flexmock(User).new_instances(None).mock - assert_raises(FlexmockError, mock.should_receive, "foo") + with pytest.raises(FlexmockError): + mock.should_receive("foo") def test_should_call_alias_should_create_a_spy(self): class Foo: @@ -1239,14 +1280,16 @@ def get_stuff(self): foo = Foo() flexmock(foo).should_call("get_stuff").and_return("yay").once() - assert_raises(MethodCallError, self._tear_down) + with pytest.raises(MethodCallError): + self._tear_down() def test_flexmock_should_fail_mocking_nonexistent_methods(self): class User: pass user = User() - assert_raises(FlexmockError, flexmock(user).should_receive, "nonexistent") + with pytest.raises(FlexmockError): + flexmock(user).should_receive("nonexistent") def test_flexmock_should_not_explode_on_unicode_formatting(self): formatted = _format_args("method", {"kargs": (chr(0x86C7),), "kwargs": {}}) @@ -1293,13 +1336,16 @@ def method(self, arg): flexmock(foo).should_call("method").with_args("foo").once() flexmock(foo).should_call("method").with_args("bar").once() foo.method("foo") - assert_raises(MethodCallError, self._tear_down) + with pytest.raises(MethodCallError): + self._tear_down() def test_should_give_reasonable_error_for_builtins(self): - assert_raises(MockBuiltinError, flexmock, object) + with pytest.raises(MockBuiltinError): + flexmock(object) def test_should_give_reasonable_error_for_instances_of_builtins(self): - assert_raises(MockBuiltinError, flexmock, object()) + with pytest.raises(MockBuiltinError): + flexmock(object()) def test_mock_chained_method_calls_works_with_one_level(self): class Foo: @@ -1330,7 +1376,8 @@ def method1(self): assert_equal("bar", foo.method1().method2("foo")) self._tear_down() flexmock(foo).should_receive("method1.method2").with_args("foo").and_return("bar").once() - assert_raises(MethodCallError, self._tear_down) + with pytest.raises(MethodCallError): + self._tear_down() def test_mock_chained_method_calls_works_with_more_than_one_level(self): class Baz: @@ -1367,7 +1414,8 @@ def method(self, arg): foo = Foo() expectation = flexmock(foo).should_receive("method").replace_with(lambda x: x == 5) - assert_raises(FlexmockError, expectation.replace_with, lambda x: x == 3) + with pytest.raises(FlexmockError): + expectation.replace_with(lambda x: x == 3) def test_flexmock_should_mock_the_same_method_multiple_times(self): class Foo: @@ -1399,7 +1447,8 @@ class Foo: foo = Foo() flexmock(foo) - assert_raises(FlexmockError, foo.new_instances, "bar") + with pytest.raises(FlexmockError): + foo.new_instances("bar") def test_new_instances_works_with_multiple_return_values(self): class Foo: @@ -1416,7 +1465,8 @@ def bar(self): foo = Foo() flexmock(foo) - assert_raises(FlexmockError, foo.should_receive, "should_receive") + with pytest.raises(FlexmockError): + foo.should_receive("should_receive") def test_flexmock_should_not_add_methods_if_they_already_exist(self): class Foo: @@ -1492,7 +1542,8 @@ def foo(self, arg1, arg2): flexmock(foo).should_receive("foo").with_args( re.compile("^arg1.*asdf$"), arg2=re.compile("a") ).and_return("mocked") - assert_raises(MethodSignatureError, foo.foo, "arg1somejunkasdfa", arg2="a") + with pytest.raises(MethodSignatureError): + foo.foo("arg1somejunkasdfa", arg2="a") def test_arg_matching_with_regexp_fails_when_regexp_doesnt_match_kwarg(self): class Foo: @@ -1503,7 +1554,8 @@ def foo(self, arg1, arg2): flexmock(foo).should_receive("foo").with_args( re.compile("^arg1.*asdf$"), arg2=re.compile("a") ).and_return("mocked") - assert_raises(MethodSignatureError, foo.foo, "arg1somejunkasdf", arg2="b") + with pytest.raises(MethodSignatureError): + foo.foo("arg1somejunkasdf", arg2="b") def test_flexmock_class_returns_same_object_on_repeated_calls(self): class Foo: @@ -1527,7 +1579,8 @@ def test_flexmock_ordered_worked_after_default_stub(self): foo.should_receive("bar") foo.should_receive("bar").with_args("a").ordered() foo.should_receive("bar").with_args("b").ordered() - assert_raises(CallOrderError, foo.bar, "b") + with pytest.raises(CallOrderError): + foo.bar("b") def test_flexmock_ordered_works_with_same_args(self): foo = flexmock() @@ -1577,14 +1630,17 @@ def radio_is_on(): radio.should_receive("select_channel").once().when(lambda: radio.is_on) radio.should_call("adjust_volume").once().with_args(5).when(radio_is_on) - assert_raises(StateError, radio.select_channel) - assert_raises(StateError, radio.adjust_volume, 5) + with pytest.raises(StateError): + radio.select_channel() + with pytest.raises(StateError): + radio.adjust_volume(5) radio.is_on = True radio.select_channel() radio.adjust_volume(5) def test_when_parameter_should_be_callable(self): - assert_raises(FlexmockError, flexmock().should_receive("something").when, 1) + with pytest.raises(FlexmockError): + flexmock().should_receive("something").when(1) def test_support_at_least_and_at_most_together(self): class Foo: @@ -1593,12 +1649,14 @@ def bar(self): foo = Foo() flexmock(foo).should_call("bar").at_least().once().at_most().twice() - assert_raises(MethodCallError, self._tear_down) + with pytest.raises(MethodCallError): + self._tear_down() flexmock(foo).should_call("bar").at_least().once().at_most().twice() foo.bar() foo.bar() - assert_raises(MethodCallError, foo.bar) + with pytest.raises(MethodCallError): + foo.bar() flexmock(foo).should_call("bar").at_least().once().at_most().twice() foo.bar() @@ -1692,7 +1750,8 @@ class String(str): flexmock(s) s.should_call("startswith").with_args("asdf", 0, 4).ordered() s.should_call("endswith").ordered() - assert_raises(CallOrderError, s.endswith, "c") + with pytest.raises(CallOrderError): + s.endswith("c") def test_fake_object_takes_properties(self): foo = flexmock(bar=property(lambda self: "baz")) @@ -1758,16 +1817,26 @@ class Foo: foo = Foo() e = flexmock(foo).should_receive("bar").and_return(2) - assert_raises(FlexmockError, e.times, 1) - assert_raises(FlexmockError, e.with_args, ()) - assert_raises(FlexmockError, e.replace_with, lambda x: x) - assert_raises(FlexmockError, e.and_raise, Exception) - assert_raises(FlexmockError, e.when, lambda x: x) - assert_raises(FlexmockError, e.and_yield, 1) - assert_raises(FlexmockError, object.__getattribute__(e, "ordered")) - assert_raises(FlexmockError, object.__getattribute__(e, "at_least")) - assert_raises(FlexmockError, object.__getattribute__(e, "at_most")) - assert_raises(FlexmockError, object.__getattribute__(e, "one_by_one")) + with pytest.raises(FlexmockError): + e.times(1) + with pytest.raises(FlexmockError): + e.with_args(()) + with pytest.raises(FlexmockError): + e.replace_with(lambda x: x) + with pytest.raises(FlexmockError): + e.and_raise(Exception) + with pytest.raises(FlexmockError): + e.when(lambda x: x) + with pytest.raises(FlexmockError): + e.and_yield(1) + with pytest.raises(FlexmockError): + object.__getattribute__(e, "ordered")() + with pytest.raises(FlexmockError): + object.__getattribute__(e, "at_least")() + with pytest.raises(FlexmockError): + object.__getattribute__(e, "at_most")() + with pytest.raises(FlexmockError): + object.__getattribute__(e, "one_by_one")() def test_and_return_defaults_to_none_with_no_arguments(self): foo = flexmock() @@ -1842,7 +1911,8 @@ def bar(self, a, b, c=1): pass e = flexmock(Foo).should_receive("bar") - assert_raises(MethodSignatureError, e.with_args, 1) + with pytest.raises(MethodSignatureError): + e.with_args(1) def test_with_args_blows_up_on_too_few_args_with_kwargs(self): class Foo: @@ -1850,7 +1920,8 @@ def bar(self, a, b, c=1): pass e = flexmock(Foo).should_receive("bar") - assert_raises(MethodSignatureError, e.with_args, 1, c=2) + with pytest.raises(MethodSignatureError): + e.with_args(1, c=2) def test_with_args_blows_up_on_too_many_args(self): class Foo: @@ -1858,7 +1929,8 @@ def bar(self, a, b, c=1): pass e = flexmock(Foo).should_receive("bar") - assert_raises(MethodSignatureError, e.with_args, 1, 2, 3, 4) + with pytest.raises(MethodSignatureError): + e.with_args(1, 2, 3, 4) def test_with_args_blows_up_on_kwarg_overlapping_positional(self): class Foo: @@ -1866,7 +1938,8 @@ def bar(self, a, b, c=1, **kwargs): pass e = flexmock(Foo).should_receive("bar") - assert_raises(MethodSignatureError, e.with_args, 1, 2, 3, c=2) + with pytest.raises(MethodSignatureError): + e.with_args(1, 2, 3, c=2) def test_with_args_blows_up_on_invalid_kwarg(self): class Foo: @@ -1874,7 +1947,8 @@ def bar(self, a, b, c=1): pass e = flexmock(Foo).should_receive("bar") - assert_raises(MethodSignatureError, e.with_args, 1, 2, d=2) + with pytest.raises(MethodSignatureError): + e.with_args(1, 2, d=2) def test_with_args_ignores_invalid_args_on_flexmock_instances(self): foo = flexmock(bar=lambda x: x) diff --git a/tests/some_module.py b/tests/some_module.py index 73e66b0..24ed6cc 100644 --- a/tests/some_module.py +++ b/tests/some_module.py @@ -2,7 +2,7 @@ # pylint: disable=missing-docstring,disallowed-name,invalid-name -class SomeClass: +class SomeClass: # pylint: disable=too-few-public-methods def __init__(self, x, y): self.x = x self.y = y