38. Pytest fixtures MONKEYPATCH | monkey patch |tmp_path | Gorilla | Rajiv

Опубликовано: 15 Июнь 2026
на канале: The Python Gurukul
904
13

A “monkey patch” is a dynamic modification of a class or module during runtime. During testing, “monkey patching” is a convenient way to take over part of the runtime environment of the application code and replace either input dependencies or output dependencies with objects or functions that are more convenient for testing.

Why use monkey patch:
Bug fix| verification
Modify external library for tests
Modify standard library for tests
Avoid complex REST calls
Reduce execution time
Produce dry run test suites
Handy for integration testing

The monkeypatch fixture provides the following functions:
setattr(target, name, value, raising=True)—Sets an attribute
delattr(target, name, raising=True)—Deletes an attribute
setitem(dic, name, value)—Sets a dictionary entry
delitem(dic, name, raising=True)—Deletes a dictionary entry
setenv(name, value, prepend=None)—Sets an environment variable
delenv(name, raising=True)—Deletes an environment variable
syspath_prepend(path)—Prepends path to sys.path, which is Python’s list of import locations
chdir(path)—Changes the current working directory