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
John Bachir
  • 22,495
  • 29
  • 154
  • 227
  • 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: https://www.python.org/dev/peps/pep-0008/#descriptive-naming-styles – Eric Fulmer Apr 02 '19 at 14:15

2 Answers2

35

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: "/")
dnsh
  • 3,516
  • 2
  • 22
  • 47
The Compiler
  • 11,126
  • 4
  • 40
  • 54
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())
jshd
  • 187
  • 3
  • 9