26

I want to use the pytest monkeypatch plugin, but I can't figure out how to import it. I've tried:

  • import monkeypath
  • import pytest.monkeypatch
  • from pytest import monkeypatch
1
  • 1
    pytest's internals, such as the MonkeyPatch class, are located in a package named _pytest. You can import it, but the leading underscore is basically a polite indicator that whatever name you're importing is private and you should think carefully about using it. PEP8 explains this convention here: python.org/dev/peps/pep-0008/#descriptive-naming-styles Apr 2, 2019 at 14:15

2 Answers 2

36

It's not a plugin, it's a built-in pytest fixture.

In a nutshell, that means you simply write a test with a monkeypatch argument, and the test will get the monkeypatch object as that argument.

The page you linked has a simple example:

def test_some_interaction(monkeypatch):
    monkeypatch.setattr("os.getcwd", lambda: "/")
11

Just to confirm Eric Fulmer's comment, if you do happen to want to use MonkeyPatch from within Python for whatever reason, it worked for me like this (based on The Compiler's answer)

from _pytest.monkeypatch import MonkeyPatch

def test_some_interaction(monkeypatch):
    monkeypatch.setattr("os.getcwd", lambda: "/")

test_some_interaction(MonkeyPatch())

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.