Python module module functions overriding module level

Associated with Python module test code that calls python functions at the OS / Module level . While testing my module, I overload some python system calls to get my tests to control the various module paths. This method is called Monkey Patch (in the corresponding question) for tests in isolation.

I am a little worried about what happens when I run Python tests in parallel, such as in Nose. What happens when two tests run in parallel and both want to mock the os.path.exists method?

Is there a way to selectively override the function of a system or module in the context of my test?

Take for example

fixture.py (say that is the module under test) def my_func(): some_stuff test_fixture.py (say this is my test case) class MyTest(unittest.TestCase): def test_mine(self): fixture.my_func = my_new_func fixture.execute_some_func_that_calls_my_func() #What happens if another test is executing at the same time and accesses #my_func I don't want it to start executing my_new_func? 
+6
source share
1 answer

I donโ€™t know if this is the best way, but I usually use try ... finally when I do this in tests to establish subsequent changes during each test.

A brief example:

 class TestRawInput(unittest.TestCase): def test_raw_input(self): orig_raw_input = raw_input try: raw_input = lambda _: 'Alice' self.assertEquals(raw_input(), 'Alice') finally: raw_input = orig_raw_input 

An alternative would be to create a context manager for this if this is a common operation in tests.

+4
source

Source: https://habr.com/ru/post/943525/


All Articles