Last active
December 14, 2015 20:49
-
-
Save eevee/5147107 to your computer and use it in GitHub Desktop.
more like rspec i guess
This file contains 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 mock | |
import pytest | |
@pytest.fixture | |
def mp(request): | |
coll = PatchCollector() | |
request.addfinalizer(coll.revert) | |
return coll | |
class PatchCollector(object): | |
def __init__(self): | |
self.patches = [] | |
def patch(self, thing, attr): | |
def decorator(f): | |
patcher = mock.patch.object(thing, attr, f) | |
self.patches.append(patcher) | |
patcher.start() | |
return f | |
return decorator | |
def revert(self): | |
for patcher in self.patches: | |
try: | |
patcher.stop() | |
except Exception: | |
pass | |
self.patches = [] | |
class SomeObject(object): | |
def foo(self): | |
return "foo" | |
def bar(self): | |
return "bar" | |
def test_multiple_mocks(mp): | |
obj = SomeObject() | |
assert obj.foo() == "foo" | |
assert obj.bar() == "bar" | |
@mp.patch(SomeObject, 'foo') | |
def foo(self): | |
return "patched foo" | |
@mp.patch(SomeObject, 'bar') | |
def bar(self): | |
return "patched bar" | |
assert obj.foo() == "patched foo" | |
assert obj.bar() == "patched bar" | |
def test_mocks_undone(): | |
obj = SomeObject() | |
assert obj.foo() == "foo" | |
assert obj.bar() == "bar" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment