title: Unit testing __main__.py
body: <p>I have a Python package (Python 3.6, if it makes a difference) that I've designed to run as 'python -m <em>package</em> <em>arguments</em>' and I'd like to write unit tests for the __main__.py module. I specifically want to verify that it sets the exit code correctly. Is it possible to use runpy.run_module to execute my __main__.py and test the exit code? If so, how do I retrieve the exit code?</p>
  
  <p>To be more clear, my __main__.py module is very simple. It just calls a function that has been extensively unit tested. But when I originally wrote __main__.py, I forgot to pass the result of that function to exit(), so I would like unit tests where the main function is mocked to make sure the exit code is set correctly. My unit test would look something like:</p>
  
  <pre><code>@patch('my_module.__main__.my_main', return_value=2)
  def test_rc2(self, _):
      """Test that rc 2 is the exit code."""
      sys.argv = ['arg0', 'arg1', 'arg2', …]
      runpy.run_module('my_module')
      self.assertEqual(mod_rc, 2)
  </code></pre>
  
  <p>My question is, how would I get what I’ve written here as ‘mod_rc’?</p>
  
  <p>Thanks.</p>