Search code examples
pythondjangounit-testingtestingcall

Python/Django unittest, how to handle outside calls?


I read multiple times that one should use mock to mimic outside calls and there should be no calls made to any outside service because your tests need to run regardless of outside services.

This totally makes sense....BUT

What about outside services changing? What good is a test, testing that my code works like it should if I will never know when it breaks because of the outside service being modified/updated/removed/deprecated/etc...

How can I reconcile this? The pseudocode is below

function post_tweet:
    data = {"tweet":"tweetcontent"}
    send request to twitter
    receive response 
    return response

If I mock this there is no way I will be notified that twitter changed their API and now I have to update my test...


Solution

  • There are different levels of testing.

    Unit tests are testing, as you might guess from the name, a unit. Which is for example a function or a method, maybe a class. If you interpret it wider it might include a view to be tested with Djangos test client. Unittests never test external stuff like libraries, dependencies or interfaces to other Systems. Theses thing will be mocked.

    Integration tests are testing if your interfaces and usage of outside libraries, systems and APIs is implemented properly. If the dependency changes, you will notice have to change your code and unit tests.

    There are other levels of tests as well, like behavior tests, UI tests, usability tests. You should make sure to separate theses tests classes in your project.