python - Make sure function cannot be called during tests -
first of all: feel free tell me antipattern!
in code, have functions responsible calling external api's. prime candidate mocking in tests make sure external api not hit when tests run.
the thing is, way mocking works in python (at least way have been taught), mock position in imported module structure explicitly, e.g.
import mymodule def test_api(): mocker.patch('mymodule.mysubmodule.json_apis.my_api_wrapper_function') [...]
this mock out my_api_wrapper_function
function test. however, if refactoring moves function or renames it, etc.? if test not updated, pass, , external api hit, because new location of function has not been mocked.
i see 2 solutions question, not sure how implement of them
- mock stuff in better way, sure not have problems when refactoring
- create decorator, wrap function , raise exception if function called in test context (i suppose depends on test runner used? in case,
pytest
)
first of sentence
if test not updated, pass, , external api hit, because new location of function has not been mocked.
is wrong.
if try mock not exist , don't use create=true
attribute patch fail!
>>> mock import patch >>> patch("doesnt.exist").start() traceback (most recent call last): file "<stdin>", line 1, in <module> file "/usr/local/lib/python2.7/dist-packages/mock.py", line 1396, in start result = self.__enter__() file "/usr/local/lib/python2.7/dist-packages/mock.py", line 1252, in __enter__ self.target = self.getter() file "/usr/local/lib/python2.7/dist-packages/mock.py", line 1414, in <lambda> getter = lambda: _importer(target) file "/usr/local/lib/python2.7/dist-packages/mock.py", line 1098, in _importer thing = __import__(import_path) importerror: no module named doesnt
moreover if use refactoring tool 1 integrated in pycharm fix string path when move something.
Comments
Post a Comment