Created
February 8, 2019 15:35
-
-
Save hectorcanto/e2741c987c7f9e48442e5b102ea3e00c to your computer and use it in GitHub Desktop.
Samples of monkeypatching with Pytest
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import time | |
import pytest | |
ENV_VAR_NAME = "DUMMY_VAR" | |
os.environ["CUSTOM_VAR"] = "Unchanged" | |
my_dict = {"a": 11, "b": 22} | |
class MockClass: | |
attribute1 = 1 | |
attribute2 = 2 | |
def test_monkeypatch_environmentals(monkeypatch): | |
assert "DUMMY_VAR" not in os.environ | |
monkeypatch.setenv(ENV_VAR_NAME, "123") | |
monkeypatch.setenv("CUSTOM_VAR", "Changed") | |
assert os.environ[ENV_VAR_NAME] == "123" | |
assert os.environ["CUSTOM_VAR"] == "Changed" | |
def test_monkeypatch_function(monkeypatch): | |
monkeypatch.setattr(time, "time", lambda: 12345) | |
assert time.time() == 12345 | |
assert time.time() == 12345 | |
def test_monkeypatch_delete_attribute(monkeypatch): | |
instance1 = MockClass() | |
monkeypatch.delattr(MockClass, "attribute2") | |
assert instance1.attribute1 == 1 | |
with pytest.raises(AttributeError): | |
assert instance1.attribute2 == 2 | |
def test_monkeypatch_dicts(monkeypatch): | |
monkeypatch.setitem(my_dict, "c", 33) | |
monkeypatch.delitem(my_dict, "b") | |
assert my_dict == {"a": 11, "c": 33} | |
def test_unpatching_works(): | |
assert ENV_VAR_NAME not in os.environ | |
assert os.environ["CUSTOM_VAR"] == "Unchanged" | |
assert MockClass().attribute2 == 2 | |
assert my_dict == {"a": 11, "b": 22} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment