mercredi 30 septembre 2015

Make sure function cannot be called during tests

First of all: Feel free to tell me that this is an antipattern!

In my code, I have some functions responsible for calling external API's. This is a prime candidate for mocking in the tests to make sure that the external API is not hit when tests are run.

The thing is, the way mocking works in python (at least the way I have been taught), we mock a position in the imported module structure explicitly, e.g.

import mymodule

def test_api():
    mocker.patch('mymodule.mysubmodule.json_apis.my_api_wrapper_function')
    [...]

This will mock out the my_api_wrapper_function function for the test. However, what if refactoring moves the function or renames it, etc.? If the test is not updated, it will most likely pass, AND the external API is hit, because the new location of the function has not been mocked.

I see two solutions to this question, but I am not sure how to implement any of them

  • Mock stuff in a better way, so that I am sure not to have problems when refactoring
  • Create a decorator, which will wrap a function and raise an exception if the function is called in a test context (I suppose this depends on the test runner that is used? In my case, it is pytest)

Aucun commentaire:

Enregistrer un commentaire