Python _pytest.monkeypatch.MonkeyPatch() Examples

The following are 30 code examples of _pytest.monkeypatch.MonkeyPatch(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module _pytest.monkeypatch , or try the search function .
Example #1
Source File: test_monkeypatch.py    From pytest with MIT License 6 votes vote down vote up
def test_delenv() -> None:
    name = "xyz1234"
    assert name not in os.environ
    monkeypatch = MonkeyPatch()
    pytest.raises(KeyError, monkeypatch.delenv, name, raising=True)
    monkeypatch.delenv(name, raising=False)
    monkeypatch.undo()
    os.environ[name] = "1"
    try:
        monkeypatch = MonkeyPatch()
        monkeypatch.delenv(name)
        assert name not in os.environ
        monkeypatch.setenv(name, "3")
        assert os.environ[name] == "3"
        monkeypatch.undo()
        assert os.environ[name] == "1"
    finally:
        if name in os.environ:
            del os.environ[name] 
Example #2
Source File: test_monkeypatch.py    From pytest with MIT License 6 votes vote down vote up
def test_setattr() -> None:
    class A:
        x = 1

    monkeypatch = MonkeyPatch()
    pytest.raises(AttributeError, monkeypatch.setattr, A, "notexists", 2)
    monkeypatch.setattr(A, "y", 2, raising=False)
    assert A.y == 2  # type: ignore
    monkeypatch.undo()
    assert not hasattr(A, "y")

    monkeypatch = MonkeyPatch()
    monkeypatch.setattr(A, "x", 2)
    assert A.x == 2
    monkeypatch.setattr(A, "x", 3)
    assert A.x == 3
    monkeypatch.undo()
    assert A.x == 1

    A.x = 5
    monkeypatch.undo()  # double-undo makes no modification
    assert A.x == 5

    with pytest.raises(TypeError):
        monkeypatch.setattr(A, "y")  # type: ignore[call-overload] 
Example #3
Source File: test_h11.py    From hypercorn with MIT License 6 votes vote down vote up
def test_protocol_handle_max_incomplete(monkeypatch: MonkeyPatch) -> None:
    config = Config()
    config.h11_max_incomplete_size = 5
    MockHTTPStream = AsyncMock()  # noqa: N806
    MockHTTPStream.return_value = AsyncMock(spec=HTTPStream)
    monkeypatch.setattr(hypercorn.protocol.h11, "HTTPStream", MockHTTPStream)
    context = Mock()
    context.event_class.return_value = AsyncMock(spec=IOEvent)
    protocol = H11Protocol(AsyncMock(), config, context, False, None, None, AsyncMock())
    await protocol.handle(RawData(data=b"GET / HTTP/1.1\r\nHost: hypercorn\r\n"))
    protocol.send.assert_called()
    assert protocol.send.call_args_list == [
        call(
            RawData(
                data=b"HTTP/1.1 400 \r\ncontent-length: 0\r\nconnection: close\r\n"
                b"date: Thu, 01 Jan 1970 01:23:20 GMT\r\nserver: hypercorn-h11\r\n\r\n"
            )
        ),
        call(RawData(data=b"")),
        call(Closed()),
    ] 
Example #4
Source File: conftest.py    From pdbpp with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _tmphome(tmpdir_factory):
    """Set up HOME in a temporary directory.

    This ignores any real ~/.pdbrc.py then, and seems to be
    required also with linecache on py27, where it would read contents from
    ~/.pdbrc?!.
    """
    from _pytest.monkeypatch import MonkeyPatch

    mp = MonkeyPatch()

    tmphome = tmpdir_factory.mktemp("tmphome")

    mp.setenv("HOME", str(tmphome))
    mp.setenv("USERPROFILE", str(tmphome))

    with tmphome.as_cwd():
        yield tmphome 
Example #5
Source File: conftest.py    From brownie with MIT License 6 votes vote down vote up
def pytest_sessionstart():
    monkeypatch_session = MonkeyPatch()
    monkeypatch_session.setattr(
        "solcx.get_available_solc_versions",
        lambda: [
            "v0.6.7",
            "v0.6.2",
            "v0.5.15",
            "v0.5.8",
            "v0.5.7",
            "v0.5.0",
            "v0.4.25",
            "v0.4.24",
            "v0.4.22",
        ],
    )


# worker ID for xdist process, as an integer 
Example #6
Source File: test_monkeypatch.py    From pytest with MIT License 6 votes vote down vote up
def test_undo_class_descriptors_delattr() -> None:
    class SampleParent:
        @classmethod
        def hello(_cls):
            pass

        @staticmethod
        def world():
            pass

    class SampleChild(SampleParent):
        pass

    monkeypatch = MonkeyPatch()

    original_hello = SampleChild.hello
    original_world = SampleChild.world
    monkeypatch.delattr(SampleParent, "hello")
    monkeypatch.delattr(SampleParent, "world")
    assert getattr(SampleParent, "hello", None) is None
    assert getattr(SampleParent, "world", None) is None

    monkeypatch.undo()
    assert original_hello == SampleChild.hello
    assert original_world == SampleChild.world 
Example #7
Source File: lib.py    From pmatic with GNU General Public License v2.0 6 votes vote down vote up
def API(self, request):
        self._monkeypatch = monkeypatch()
        if not is_testing_with_real_ccu():
            # First hook into urlopen to fake the HTTP responses
            self._monkeypatch.setattr(pmatic.api, 'urlopen', fake_urlopen)
        else:
            # When executed with real ccu we wrap urlopen for enabling recording
            self._monkeypatch.setattr(pmatic.api, 'urlopen', wrap_urlopen)

        API = pmatic.api.RemoteAPI(
            address="http://192.168.1.26",
            credentials=("Admin", "EPIC-SECRET-PW"),
            connect_timeout=5,
            #log_level=pmatic.DEBUG,
        )

        request.addfinalizer(API.close)

        return API 
Example #8
Source File: test_config.py    From hypercorn with MIT License 6 votes vote down vote up
def test_create_sockets_ip(
    bind: str,
    expected_family: socket.AddressFamily,
    expected_binding: Tuple[str, int],
    monkeypatch: MonkeyPatch,
) -> None:
    mock_socket = Mock()
    monkeypatch.setattr(socket, "socket", mock_socket)
    config = Config()
    config.bind = [bind]
    sockets = config.create_sockets()
    sock = sockets.insecure_sockets[0]
    mock_socket.assert_called_with(expected_family, socket.SOCK_STREAM)
    sock.setsockopt.assert_called_with(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)  # type: ignore
    sock.bind.assert_called_with(expected_binding)  # type: ignore
    sock.setblocking.assert_called_with(False)  # type: ignore
    sock.set_inheritable.assert_called_with(True)  # type: ignore 
Example #9
Source File: test_monkeypatch.py    From pytest with MIT License 6 votes vote down vote up
def test_delattr() -> None:
    class A:
        x = 1

    monkeypatch = MonkeyPatch()
    monkeypatch.delattr(A, "x")
    assert not hasattr(A, "x")
    monkeypatch.undo()
    assert A.x == 1

    monkeypatch = MonkeyPatch()
    monkeypatch.delattr(A, "x")
    pytest.raises(AttributeError, monkeypatch.delattr, A, "y")
    monkeypatch.delattr(A, "y", raising=False)
    monkeypatch.setattr(A, "x", 5, raising=False)
    assert A.x == 5
    monkeypatch.undo()
    assert A.x == 1 
Example #10
Source File: test_monkeypatch.py    From pytest with MIT License 6 votes vote down vote up
def test_setitem() -> None:
    d = {"x": 1}
    monkeypatch = MonkeyPatch()
    monkeypatch.setitem(d, "x", 2)
    monkeypatch.setitem(d, "y", 1700)
    monkeypatch.setitem(d, "y", 1700)
    assert d["x"] == 2
    assert d["y"] == 1700
    monkeypatch.setitem(d, "x", 3)
    assert d["x"] == 3
    monkeypatch.undo()
    assert d["x"] == 1
    assert "y" not in d
    d["x"] = 5
    monkeypatch.undo()
    assert d["x"] == 5 
Example #11
Source File: test_auth_rule_using.py    From indy-node with Apache License 2.0 5 votes vote down vote up
def monkeymodule(self):
        from _pytest.monkeypatch import MonkeyPatch
        mpatch = MonkeyPatch()
        yield mpatch
        mpatch.undo() 
Example #12
Source File: test_monkeypatch.py    From pytest with MIT License 5 votes vote down vote up
def test_setenv_non_str_warning(self, monkeypatch: MonkeyPatch) -> None:
        value = 2
        msg = (
            "Value of environment variable PYTEST_INTERNAL_MY_VAR type should be str, "
            "but got 2 (type: int); converted to str implicitly"
        )
        with pytest.warns(pytest.PytestWarning, match=re.escape(msg)):
            monkeypatch.setenv(str(self.VAR_NAME), value)  # type: ignore[arg-type] 
Example #13
Source File: test_monkeypatch.py    From pytest with MIT License 5 votes vote down vote up
def test_setenv_prepend() -> None:
    import os

    monkeypatch = MonkeyPatch()
    monkeypatch.setenv("XYZ123", "2", prepend="-")
    monkeypatch.setenv("XYZ123", "3", prepend="-")
    assert os.environ["XYZ123"] == "3-2"
    monkeypatch.undo()
    assert "XYZ123" not in os.environ 
Example #14
Source File: test_utils.py    From bandersnatch with Academic Free License v3.0 5 votes vote down vote up
def test_rewrite_fails(tmpdir: Path, monkeypatch: MonkeyPatch) -> None:
    monkeypatch.chdir(tmpdir)
    with open("sample", "w") as f:
        f.write("bsdf")
    with pytest.raises(Exception):
        with rewrite("sample") as f:  # type: ignore
            f.write("csdf")
            raise Exception()
    assert open("sample").read() == "bsdf"  # type: ignore 
Example #15
Source File: test_terminalwriter.py    From pytest with MIT License 5 votes vote down vote up
def test_terminalwriter_dumb_term_no_markup(monkeypatch: MonkeyPatch) -> None:
    monkeypatch.setattr(os, "environ", {"TERM": "dumb", "PATH": ""})

    class MyFile:
        closed = False

        def isatty(self):
            return True

    with monkeypatch.context() as m:
        m.setattr(sys, "stdout", MyFile())
        assert sys.stdout.isatty()
        tw = terminalwriter.TerminalWriter()
        assert not tw.hasmarkup 
Example #16
Source File: test_terminalwriter.py    From pytest with MIT License 5 votes vote down vote up
def test_should_do_markup_PY_COLORS_eq_1(monkeypatch: MonkeyPatch) -> None:
    monkeypatch.setitem(os.environ, "PY_COLORS", "1")
    file = io.StringIO()
    tw = terminalwriter.TerminalWriter(file)
    assert tw.hasmarkup
    tw.line("hello", bold=True)
    s = file.getvalue()
    assert len(s) > len("hello\n")
    assert "\x1b[1m" in s
    assert "\x1b[0m" in s 
Example #17
Source File: test_terminalwriter.py    From pytest with MIT License 5 votes vote down vote up
def test_should_do_markup_PY_COLORS_eq_0(monkeypatch: MonkeyPatch) -> None:
    monkeypatch.setitem(os.environ, "PY_COLORS", "0")
    f = io.StringIO()
    f.isatty = lambda: True  # type: ignore
    tw = terminalwriter.TerminalWriter(file=f)
    assert not tw.hasmarkup
    tw.line("hello", bold=True)
    s = f.getvalue()
    assert s == "hello\n" 
Example #18
Source File: conftest.py    From renku-python with Apache License 2.0 5 votes vote down vote up
def mock_redis():
    """Monkey patch service cache with mocked redis."""
    from renku.service.cache.base import BaseCache
    from renku.service.cache.models.user import User
    from renku.service.cache.models.job import Job
    from renku.service.cache.models.file import File
    from renku.service.cache.models.project import Project
    from renku.service.jobs.queues import WorkerQueues

    monkey_patch = MonkeyPatch()
    with monkey_patch.context() as m:
        fake_redis = fakeredis.FakeRedis()
        fake_model_db = Database(connection_pool=fake_redis.connection_pool)

        m.setattr(WorkerQueues, 'connection', fake_redis)
        m.setattr(BaseCache, 'cache', fake_redis)
        m.setattr(BaseCache, 'model_db', fake_model_db)

        m.setattr(Job, '__database__', fake_model_db)
        m.setattr(User, '__database__', fake_model_db)
        m.setattr(File, '__database__', fake_model_db)
        m.setattr(Project, '__database__', fake_model_db)

        yield

    monkey_patch.undo() 
Example #19
Source File: conftest.py    From bandersnatch with Academic Free License v3.0 5 votes vote down vote up
def mirror_hash_index(
    tmpdir: Path, master: "Master", monkeypatch: MonkeyPatch
) -> "Mirror":
    monkeypatch.chdir(tmpdir)
    from bandersnatch.mirror import Mirror

    return Mirror(tmpdir, master, hash_index=True) 
Example #20
Source File: test_monkeypatch.py    From pytest with MIT License 5 votes vote down vote up
def test_chdir_with_path_local(mp: MonkeyPatch, tmpdir: py.path.local) -> None:
    mp.chdir(tmpdir)
    assert os.getcwd() == tmpdir.strpath 
Example #21
Source File: test_monkeypatch.py    From pytest with MIT License 5 votes vote down vote up
def test_setenv() -> None:
    monkeypatch = MonkeyPatch()
    with pytest.warns(pytest.PytestWarning):
        monkeypatch.setenv("XYZ123", 2)  # type: ignore[arg-type]
    import os

    assert os.environ["XYZ123"] == "2"
    monkeypatch.undo()
    assert "XYZ123" not in os.environ 
Example #22
Source File: test_monkeypatch.py    From pytest with MIT License 5 votes vote down vote up
def test_setenv_deleted_meanwhile(before: bool) -> None:
    key = "qwpeoip123"
    if before:
        os.environ[key] = "world"
    monkeypatch = MonkeyPatch()
    monkeypatch.setenv(key, "hello")
    del os.environ[key]
    monkeypatch.undo()
    if before:
        assert os.environ[key] == "world"
        del os.environ[key]
    else:
        assert key not in os.environ 
Example #23
Source File: test_monkeypatch.py    From pytest with MIT License 5 votes vote down vote up
def test_setitem_deleted_meanwhile() -> None:
    d = {}  # type: Dict[str, object]
    monkeypatch = MonkeyPatch()
    monkeypatch.setitem(d, "x", 2)
    del d["x"]
    monkeypatch.undo()
    assert not d 
Example #24
Source File: test_monkeypatch.py    From pytest with MIT License 5 votes vote down vote up
def test_delattr(self, monkeypatch: MonkeyPatch) -> None:
        monkeypatch.delattr("os.path.abspath")
        assert not hasattr(os.path, "abspath")
        monkeypatch.undo()
        assert os.path.abspath 
Example #25
Source File: test_monkeypatch.py    From pytest with MIT License 5 votes vote down vote up
def test_unknown_attr(self, monkeypatch: MonkeyPatch) -> None:
        with pytest.raises(AttributeError):
            monkeypatch.setattr("os.path.qweqwe", None) 
Example #26
Source File: test_monkeypatch.py    From pytest with MIT License 5 votes vote down vote up
def test_unknown_import(self, monkeypatch: MonkeyPatch) -> None:
        with pytest.raises(ImportError):
            monkeypatch.setattr("unkn123.classx", None) 
Example #27
Source File: test_monkeypatch.py    From pytest with MIT License 5 votes vote down vote up
def test_wrong_target(self, monkeypatch: MonkeyPatch) -> None:
        with pytest.raises(TypeError):
            monkeypatch.setattr(None, None)  # type: ignore[call-overload] 
Example #28
Source File: test_monkeypatch.py    From pytest with MIT License 5 votes vote down vote up
def test_unicode_string(self, monkeypatch: MonkeyPatch) -> None:
        monkeypatch.setattr("_pytest.config.Config", 42)
        import _pytest

        assert _pytest.config.Config == 42  # type: ignore
        monkeypatch.delattr("_pytest.config.Config") 
Example #29
Source File: test_monkeypatch.py    From pytest with MIT License 5 votes vote down vote up
def test_string_expression_class(self, monkeypatch: MonkeyPatch) -> None:
        monkeypatch.setattr("_pytest.config.Config", 42)
        import _pytest

        assert _pytest.config.Config == 42  # type: ignore 
Example #30
Source File: test_monkeypatch.py    From pytest with MIT License 5 votes vote down vote up
def mp() -> Generator[MonkeyPatch, None, None]:
    cwd = os.getcwd()
    sys_path = list(sys.path)
    yield MonkeyPatch()
    sys.path[:] = sys_path
    os.chdir(cwd)