I have a large project that is unit tested using the Python unittest module.
I have one small method that controls large aspects of the system's behaviour. I need this method to return a fixed result when running under the UTs to give consistent test runs, but it would be expensive for me to mock this out for every single UT.
Is there a way that I can make this single method, unittest aware, so that it can modify its behaviour when running under the unittest?
The unit test framework in Python is called unittest , which comes packaged with Python. Unit testing makes your code future proof since you anticipate the cases where your code could potentially fail or produce a bug.
You can check, if the unittest
module is loaded. It should be loaded only, if a test runs.
>>> 'unittest' in sys.modules.keys() False >>> from unittest import TestCase >>> 'unittest' in sys.modules.keys() True
My solution is to set a TEST_FLAG=true
environment variable before running unittest
. For example:
TEST_FLAG=true python -m unittest discover -s tests -b
Then it is just a matter of checking if the variable is set. For example:
MONGODB_URI = os.environ.get('MONGODB_URI') if not os.environ.get('TEST_FLAG') else os.environ.get('MONGODB_TEST_URI')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With