[New-bugs-announce] [issue44052] patch object as argument should be explicit

Pierre Ossman report at bugs.python.org
Thu May 6 02:43:06 EDT 2021


New submission from Pierre Ossman <ossman at cendio.se>:

Right now if you use unittest.mock.patch() as a decorator it may or may not pass the object as an argument to the test function. The behaviour is a side effect of the argument "new" rather than something the caller can explicitly control.

In many cases this gives the desired behaviour, but not in all. So this behaviour should be possible to explicitly controlled.

One common case is when using patch() as a class decorator. If you want to avoid getting extra arguments to every test function, then "new" has to be specified. But that means that it will be the same object that will be used for every test, not a fresh one.

E.g.

@patch('foo.bar.baz', [])
class TestCases(unittest.TestCase):
    def test_a(self):
        ...
    def test_b(self):
        ...
    def test_c(self):
        ...

The tests will now be running with the same list in "foo.bar.baz" rather than a fresh empty list for each run. Ideally we could instead specify:

@patch('foo.bar.baz', new_callable=list, as_arg=False)
class TestCases(unittest.TestCase):
    def test_a(self):
        ...
    def test_b(self):
        ...
    def test_c(self):
        ...

Or something along those lines.

----------
components: Library (Lib)
messages: 393062
nosy: CendioOssman
priority: normal
severity: normal
status: open
title: patch object as argument should be explicit

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue44052>
_______________________________________


More information about the New-bugs-announce mailing list