pytest monkeypatch.setattr() inside of test class method

为君一笑 提交于 2019-12-10 15:27:24

问题


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?


回答1:


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 ...
     ...



回答2:


If it's a method in a class, the first argument has to be always self (edit: it does not work anyway).

So define the test as a top-level function:

def test_something(monkeypatch):
    # or this
    pass


来源:https://stackoverflow.com/questions/42332030/pytest-monkeypatch-setattr-inside-of-test-class-method

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!