Mocking __main__
Question: I would like to ensure with tests that: \- the application cannot be imported
\- the application can be started as a real application (i.e: python src.py)

I'm interested about that, why the following is not working:

src.py

    
    
    class A:
     def x(self):
      print('this is x')
    
    if __name__ == '__main__':
      A().x()
    

test.py (snippet)

    
    
    class Test(unittest.TestCase):
      @mock.patch('src.A.x')
      def test_main(self, mock_x):
        import src
        mock_x.assert_any_call()
    

This test fails... why?


Answer: Because the name of the module when imported is `src`, not `__main__`.

The easiest solution would be to move that code into a function:

    
    
    def main():
        A().x()
    
    if __name__ == '__main__':
        main()
    

and in your test, you would invoke `src.main()`

    
    
    @mock.patch('src.A.x')
    def test_main(self, mock_x):
        import src
        src.main()
        mock_x.assert_any_call()
    

