Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a piece of python code tell if it's running under unittest

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?

like image 201
tomdee Avatar asked Jul 29 '14 22:07

tomdee


People also ask

Does Python come with 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.


2 Answers

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 
like image 77
kwarnke Avatar answered Oct 06 '22 06:10

kwarnke


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') 
like image 44
Franco Avatar answered Oct 06 '22 06:10

Franco