Answer a question

I have a test class with few test methods and I want to patch some app classes and methods from the test methods. In pytest docs I found an example of how to use monkeypatch module for tests. It that example all tests are just functions, not testclass methods.

But I have a class with test methods:

class MyTest(TestCase):
   def setUp():
     pass

   def test_classmethod(self, monkeypatch):
     # here I want to use monkeypatch.setattr()
     pass

And just passing monkeypatch as method param is obviously doesn't work. So looks like py.test magic doesn't work this way.

So the question is simple and maybe stupid: how can I use monkeypatch.setattr() for pytest inside from the test class method?

Answers

It can't work in this form

While pytest supports receiving fixtures via test function arguments for non-unittest test methods, unittest.TestCase methods cannot directly receive fixture function arguments as implementing that is likely to inflict on the ability to run general unittest.TestCase test suites.

You might create monkeypatch directly

from _pytest.monkeypatch import MonkeyPatch

class MyTest(TestCase):
   def setUp():
     self.monkeypatch = MonkeyPatch()

   def test_classmethod(self):
     self.monkeypatch.setattr ...
     ...

or create own fixture, which will add monkeypatch to your class, and use @pytest.mark.usefixtures

@pytest.fixture(scope="class")
def monkeypatch_for_class(request):
    request.cls.monkeypatch = MonkeyPatch()

@pytest.mark.usefixtures("monkeypatch_for_class")
class MyTest(TestCase):
   def setUp():
     pass

   def test_classmethod(self):
     self.monkeypatch.setattr ...
     ...
Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐