Created
June 20, 2016 14:34
-
-
Save whitekid/e076a28e6048ed9982f8c8d8cf3167c8 to your computer and use it in GitHub Desktop.
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
"""Test Helper""" | |
from unittest.mock import patch | |
class MockMixin(object): | |
"""TestCase Helper | |
아래처럼 사용하면, Mocking된 object가 cleanup되지 않아서 다음 테스트에도 | |
영향을 미친다. :: | |
target = MagicMock(..) | |
그래서 :: | |
with patch.object(target, 'method', return_value=...) as p: | |
... | |
또는 :: | |
@patch.object(object, 'method', return_value=...) | |
def test_func(self, patched_target): | |
... | |
처럼 해야하는데, 둘다 불편해보임 그래서 간단하게... :: | |
def test_func(self): | |
self.mock(target, 'method', return_value=...) | |
이렇게 하면 addCleanup에서 호출되어서 자동으로 mock object가 해제된다. | |
Usage :: | |
class MyTest(MockMixin, TestCase): | |
pass | |
""" | |
def mock(self, *args, **kwargs): | |
p = patch.object(*args, **kwargs) | |
p.start() | |
self.addCleanup(p.stop) | |
return p | |
class Foo: | |
def sum(self, *args): | |
return sum(args) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment