Hi all,

happy to announce a better developer experience with pytest-when fixture.

With pytest-mock you can define the complex mocking behavior via natural 
interface:

```
when(some_object, "attribute").called_with(1, 2).then_return("mocked")
```

In this case the some_object.attribute(1, 2) == "mocked". But if it will be 
called with any other
arguments, it will return what it is suppose to return.


Project GitHub:
https://github.com/zhukovgreen/pytest-when
zhukovgreen/pytest-when: Pytest plugin for more readable mocking
github.com

Support python>=3.8 and tested until 3.11


Small example from the docs:
# class which we're going to mock in the test
class Klass1:
    def some_method(
        self,
        arg1: str,
        arg2: int,
        *,
        kwarg1: str,
        kwarg2: str,
    ) -> str:
        return "Not mocked"


def test_should_properly_patch_calls(when):
    when(Klass1, "some_method").called_with(
        "a",
        when.markers.any,
        kwarg1="b",
        kwarg2=when.markers.any,
    ).then_return("Mocked")

    assert (
        Klass1().some_method(
            "a",
            1,
            kwarg1="b",
            kwarg2="c",
        )
        == "Mocked"
    )
    assert (
        Klass1().some_method(
            "not mocked param",
            1,
            kwarg1="b",
            kwarg2="c",
        )
        == "Not mocked"
    )

# if you need to patch a function
def test_patch_a_function(when):
    when(example_module, "some_normal_function").called_with(
        "a",
        when.markers.any,
        kwarg1="b",
        kwarg2=when.markers.any,
    ).then_return("Mocked")

    assert (
            example_module.some_normal_function(
                "a",
                1,
                kwarg1="b",
                kwarg2="c",
            )
            == "Mocked"
    )
    assert (
            example_module.some_normal_function(
                "not mocked param",
                1,
                kwarg1="b",
                kwarg2="c",
            )
            == "Not mocked"
    )


Thank you for any feedback

--
zhukovgreen,

Data Engineer @Paylocity
https://github.com/zhukovgreen

_______________________________________________
Python-announce-list mailing list -- python-announce-list@python.org
To unsubscribe send an email to python-announce-list-le...@python.org
https://mail.python.org/mailman3/lists/python-announce-list.python.org/
Member address: arch...@mail-archive.com

Reply via email to