From ff8d787cd51efa1ab6afccc882877cd686abe0cf Mon Sep 17 00:00:00 2001 From: Florian Bruhin Date: Tue, 19 May 2015 22:59:49 +0200 Subject: [PATCH] Fix monkeypatch.setenv with string and raising=False. Fixes #746. --- _pytest/monkeypatch.py | 9 +++++---- testing/test_monkeypatch.py | 5 +++++ 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/_pytest/monkeypatch.py b/_pytest/monkeypatch.py index 7cdc1379a..d3a59327b 100644 --- a/_pytest/monkeypatch.py +++ b/_pytest/monkeypatch.py @@ -27,7 +27,7 @@ def pytest_funcarg__monkeypatch(request): -def derive_importpath(import_path): +def derive_importpath(import_path, raising): import pytest if not isinstance(import_path, _basestring) or "." not in import_path: raise TypeError("must be absolute import path string, not %r" % @@ -51,7 +51,8 @@ def derive_importpath(import_path): attr = rest.pop() obj = getattr(obj, attr) attr = rest[0] - getattr(obj, attr) + if raising: + getattr(obj, attr) except AttributeError: __tracebackhide__ = True pytest.fail("object %r has no attribute %r" % (obj, attr)) @@ -95,7 +96,7 @@ class monkeypatch: "setattr(target, value) with target being a dotted " "import string") value = name - name, target = derive_importpath(target) + name, target = derive_importpath(target, raising) oldval = getattr(target, name, notset) if raising and oldval is notset: @@ -124,7 +125,7 @@ class monkeypatch: raise TypeError("use delattr(target, name) or " "delattr(target) with target being a dotted " "import string") - name, target = derive_importpath(target) + name, target = derive_importpath(target, raising) if not hasattr(target, name): if raising: diff --git a/testing/test_monkeypatch.py b/testing/test_monkeypatch.py index 99f77a646..b501b8609 100644 --- a/testing/test_monkeypatch.py +++ b/testing/test_monkeypatch.py @@ -62,6 +62,11 @@ class TestSetattrWithImportPath: pytest.raises(pytest.fail.Exception, lambda: monkeypatch.setattr("os.path.qweqwe", None)) + def test_unknown_attr_non_raising(self, monkeypatch): + # https://bitbucket.org/pytest-dev/pytest/issue/746/ + monkeypatch.setattr('os.path.qweqwe', 42, raising=False) + assert os.path.qweqwe == 42 + def test_delattr(self, monkeypatch): monkeypatch.delattr("os.path.abspath") assert not hasattr(os.path, "abspath")