Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

assert_called_once() is dangerous - warn against its use #624

Closed
mikedlr opened this issue Feb 22, 2017 · 2 comments
Closed

assert_called_once() is dangerous - warn against its use #624

mikedlr opened this issue Feb 22, 2017 · 2 comments

Comments

@mikedlr
Copy link

mikedlr commented Feb 22, 2017

The function assert_called_once() is a new addition to the python unittest.mock module. (see https://docs.python.org/3/library/unittest.mock.html). Unfortunately, a) if you use it against an older version of python it doesn't exist so it makes code not portable. b) if you use it anyway and then backport the code then you typically end up with a test case that passes but doesn't test anything which is nasty and dangerous.

The latter happens whenever a mock without a spec is used and the function is called against it.

mock_object.assert_called_once() # WRONG - doesn't exist in python < 3.6 / mock <

In this case, the function call is mocked so it works. Note also that calls to function names with typos will also .

mock_object.assert_call_once_with(1) # WRONG - typo - this does nothing.

Personally I think it may be a good idea for pycodestyle to warn against any use of mock_object.assert* but it should definitely warn against likely typos.

The proper way to guard against this type of thing is proper TDD style writing of test cases where we ensure they can fail as well as pass. However even that doesn't work in the case of assert_called_once() if you develop against a new version of mock and then test on an old version

This warning might be less needed once all versions of python below 3.6 were obsolete.

Edit: Links for further reference

@sigmavirus24
Copy link
Member

Thanks for putting together all this information @mikedlr!

Unfortunately, this is not the kind of warning that pycodestyle generates. You can make this into a flake8 plugin.

Cheers!

@jayvdb
Copy link
Member

jayvdb commented May 15, 2017

This is already a flake8 plugin: https://pypi.python.org/pypi/flake8-mock

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants