As a 30-year software developer, mostly in OO languages, but a newbie at python, I'm looking to find what is best practise for isolating unit tests in python.
Let's say I have the following, semi-pseudo-code. I know some_database_client isn't a real database client:
from some_database_client import connection
connection.connect('server_id', 'username', 'password')
def function_under_test():
return connection.get_value('some_value_reference') + 10
If I write a test for function_under_test()
, then I'm effectively testing the potentially enormous amount of logic in connecting and retrieving the data from connection
.
Instead, I really want to test that function_under_test()
adds ten to the value retrieved.
This relates to a practical real-world example where the module-level variable connection
(or it's real-world equivalent) is referenced heavily all over the code.
Therefore, it would involve a large and therefore very risky change to pass connection
as an argument to all the functions that use it. Without doing this though, I can't easily separate the variable connection
when I'm trying to unit-test the functions that use it. connection
is instantiated before I even get to run the unit-test.
Is there a recommended way to isolate functions like this for testing? I can certainly think of many, many ways, but I suspect that some have more of the "Zen of Python" about them than others. e.g. Wrapping everything in classes is a possibility, but that is perhaps moving too far away from keeping stuff simple, which is a goal of python.