'pytest make unit tests execution independent from each other
I am trying to develop a python test environment using pytest where I have some test functions as follows:
from my_app import __main_app__
def run_main_application(var):
__main_app__.execute_python_script(var)
def test_firts():
run_main_application("setting1")
def test_second():
run_main_application("setting2")
Basically for each test, the __main_app__ python application which is handled in execute_python_script(var) is executed with a specific setting and configuration defined in var.
Everything is working as expected but the execution of the second test is affected by the all variables and settings of the first one. This means that the two executions are not independent.
Is there a way to make each test unit independent from the others? I would expect that __main_app__ initialization/definition inside def run_main_application(var) to be deleted once the method is ended.
Solution 1:[1]
Adding fixture could help in your case,
@pytest.fixture # @pytest.fixture(scope='function') default scope
def run_main_application():
return __main_app__.execute_python_script
def test_firts(run_main_application):
run_main_application("setting1")
def test_second(run_main_application):
run_main_application("setting2")
Solution 2:[2]
I mange to solve this using the reload function as follows:
__main_app__ = reload(__main_app__)
This is applied at the end of the run_main_application(var) method. Thus:
from my_app import __main_app__
def run_main_application(var):
__main_app__.execute_python_script(var)
__main_app__ = reload(__main_app__)
def test_firts():
run_main_application("setting1")
def test_second():
run_main_application("setting2")
In this manner, all the test executions are independent from each other.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | rebatoma |
