简体   繁体   中英

Can't listen to print function in __main__.py with unittest.mock

I am trying to listen to the print function from __main__.py . I use the patch function from unittest.mock .

def main_tester(command):
    fake_command()
    capturedoutput = io.StringIO()
    sys.stdout = capturedoutput
    with patch('sys.argv', command.split(" ")):
        from SIESTAstepper import __main__ as rtmain
    sys.stdout = sys.__stdout__
    return capturedoutput.getvalue()

The problem is, it returns an empty string "" instead of the captured output.

The code is from here if you are willing to see the full project.

Your __main__ module should probably not unconditionally call the main function. It is common practice to put that in the if __name__ == '__main__': block. It is one of the most viewed threads on this platform.

If you put the main call behind that if-statement, you can safely import from your __main__ module without the import causing the execution of the main function.

Then you can properly test main because you can import it in your test module and simply call it with whatever arguments you want for testing purposes.

To test specific print statements, you can patch/mock the print function in the module being tested . Something like this for example:

from unittest.mock import MagicMock, patch

@patch("module_being_tested.print")
def test_some_function_that_should_call_print(mock_print: MagicMock) -> None:
    ...
    some_function(some_argument)
    mock_print.assert_called_once_with(
        "A string it should have been called with"
    )

In your comment you mentioned you were new to unit testing. I just wanted to draw your attention to the definition of unit testing. Because it seems like main_tester is supposed to test behavior that is not even part of the __main__.main function at all. You should make sure that you actually isolate the units (the functions) you are testing from all your other code. That is where mocking comes in handy.

When you are testing main , you should actually only test main and not other functions being called by main .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM