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
.