-
-
Save podhmo/066af0861f435c5788a0 to your computer and use it in GitHub Desktop.
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
# -*- coding: utf-8 -*- | |
from datetime import datetime | |
import contextlib | |
import unittest | |
@contextlib.contextmanager | |
def mock_datetime_now(module_path, return_value): | |
""" | |
適当なモジュールの datetime.now() を mock し、適当な日付を返すようにする。 | |
>>> from datetime import datetime | |
>>> with mock_datetime_now('some_app.some_module.datetime', datetime(2015, 1, 1)): | |
... datetime.now() | |
datetime(2015, 1, 1, 0, 0, 0) | |
のように利用する。 | |
""" | |
class DummyDatetime(datetime): | |
@classmethod | |
def now(cls): | |
return return_value | |
# dateime を持つモジュールを取得する | |
module_names = module_path.rstrip('.datetime').split('.') | |
module = __import__('.'.join(module_names)) | |
for name in module_names[1:]: | |
module = getattr(module, name) | |
# 置き換えて yield | |
module.datetime = DummyDatetime | |
yield | |
# 置き換えたのを戻す | |
module.datetime = datetime | |
class DateTimeTests(unittest.TestCase): | |
def _callFUT(self, *args, **kwargs): | |
return datetime.now() | |
def test_patch(self): | |
target = 1 | |
with mock_datetime_now("__main__.datetime", target): | |
result = self._callFUT() | |
self.assertEqual(result, target) | |
def test_must_fail(self): | |
target = 1 | |
with mock_datetime_now("__main__.datetime", target): | |
raise Exception("oops") | |
def test_must_success(self): | |
self.assertNotEqual(datetime.now(), 1) | |
if __name__ == "__main__": | |
unittest.main() | |
""" | |
EF. | |
====================================================================== | |
ERROR: test_must_fail (__main__.DateTimeTests) | |
---------------------------------------------------------------------- | |
Traceback (most recent call last): | |
File "hmm.py", line 51, in test_must_fail | |
raise Exception("oops") | |
Exception: oops | |
====================================================================== | |
FAIL: test_must_success (__main__.DateTimeTests) | |
---------------------------------------------------------------------- | |
Traceback (most recent call last): | |
File "hmm.py", line 54, in test_must_success | |
self.assertNotEqual(self._callFUT(), 1) | |
AssertionError: 1 == 1 | |
---------------------------------------------------------------------- | |
Ran 3 tests in 0.001s | |
FAILED (failures=1, errors=1) | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
これ問題なくて、教わったのの感じの以下のクラスを作って利用するようにします。