title: Check for system exit and for error logs with unittest in Python
body: <p>Is it possible to check if a program stopped with <code>sys.exit()</code> and check for the messages that were logged using the <code>logging</code> module?</p>
  <p>For example, let's say I have the following function in a file called func.py:</p>
  <pre><code>import logging
  import sys
  
  logging.basicConfig(level=logging.INFO,format='%(levelname)s:%(message)s')
  
  def my_func(word):
      if word == &quot;orange&quot;:
          logging.info(&quot;All is good with {}.&quot;.format(word))
      elif word == &quot;apple&quot;:
          logging.error(&quot;Something went wrong with {}.&quot;.format(word))
          sys.exit()
  </code></pre>
  <p>Now, I have created a couple of tests to check my function's performance. I know that, to test the messages logged--provided that the program completed its function--I can do something like this:</p>
  <pre><code>import unittest
  from func import *
  
  class Test_errors_and_messages(unittest.TestCase):
  
      def test_logs(self):
          with self.assertLogs() as captured:
              my_func(&quot;orange&quot;)
          self.assertEqual(len(captured.records), 1)
          self.assertEqual(captured.records[0].getMessage(), &quot;All is good with orange.&quot;)
  </code></pre>
  <p>And if I want to check if the program is stopping when expected, I'm doing something similar to this:</p>
  <pre><code>import unittest
  from func import *
  
  class Test_errors_and_messages(unittest.TestCase):
  
      def test_exit(self):
          with self.assertRaises(SystemExit):
              my_func(&quot;apple&quot;)
  </code></pre>
  <p>My question is: is it possible to test for a system exit and the messages logged at the same time? In other words, I would like to modify the <code>test_exit()</code> test to check (a) that the program stopped with a <code>SystemExit</code> and (b) that the message</p>
  <blockquote>
  <p>Something went wrong with apple.</p>
  </blockquote>
  <p>was logged. In particular, I want to check both of these conditions because in my real script, I have several conditions that will prompt <code>sys.exit()</code>, and I want to test that when the program stops, it is stopping for the reason that I expect.</p>