python-mock

Patch __call__ of a function

此生再无相见时 提交于 2019-11-27 06:35:45
问题 I need to patch current datetime in tests. I am using this solution: def _utcnow(): return datetime.datetime.utcnow() def utcnow(): """A proxy which can be patched in tests. """ # another level of indirection, because some modules import utcnow return _utcnow() Then in my tests I do something like: with mock.patch('***.utils._utcnow', return_value=***): ... But today an idea came to me, that I could make the implementation simpler by patching __call__ of function utcnow instead of having an

Customizing unittest.mock.mock_open for iteration

寵の児 提交于 2019-11-27 04:30:01
How should I customize unittest.mock.mock_open to handle this code? file: impexpdemo.py def import_register(register_fn): with open(register_fn) as f: return [line for line in f] My first attempt tried read_data . class TestByteOrderMark1(unittest.TestCase): REGISTER_FN = 'test_dummy_path' TEST_TEXT = ['test text 1\n', 'test text 2\n'] def test_byte_order_mark_absent(self): m = unittest.mock.mock_open(read_data=self.TEST_TEXT) with unittest.mock.patch('builtins.open', m): result = impexpdemo.import_register(self.REGISTER_FN) self.assertEqual(result, self.TEST_TEXT) This failed, presumably

Mock attributes in Python mock?

烂漫一生 提交于 2019-11-26 18:01:39
问题 I'm having a fairly difficult time using mock in Python: def method_under_test(): r = requests.post("http://localhost/post") print r.ok # prints "<MagicMock name='post().ok' id='11111111'>" if r.ok: return StartResult() else: raise Exception() class MethodUnderTestTest(TestCase): def test_method_under_test(self): with patch('requests.post') as patched_post: patched_post.return_value.ok = True result = method_under_test() self.assertEqual(type(result), StartResult, "Failed to return a

Python Mocking a function from an imported module

回眸只為那壹抹淺笑 提交于 2019-11-26 15:16:38
问题 I want to understand how to @patch a function from an imported module. This is where I am so far. app/mocking.py: from app.my_module import get_user_name def test_method(): return get_user_name() if __name__ == "__main__": print "Starting Program..." test_method() app/my_module/__init__.py: def get_user_name(): return "Unmocked User" test/mock-test.py: import unittest from app.mocking import test_method def mock_get_user(): return "Mocked This Silly" @patch('app.my_module.get_user_name')