title: How do I test exceptions and errors using pytest?
body: <p>I have functions in my Python code that raise exceptions in response to certain conditions, and would like to confirm that they behave as expected in my <a href="http://pytest.org/latest/contents.html" rel="noreferrer">pytest</a> scripts.</p>
  
  <p>Currently I have </p>
  
  <pre class="lang-py prettyprint-override"><code>def test_something():
      try:
          my_func(good_args)
          assert True
      except MyError as e:
          assert False
      try:
          my_func(bad_args)
          assert False
      except MyError as e:
          assert e.message == "My expected message for bad args"
  </code></pre>
  
  <p>but this seems cumbersome (and needs to be repeated for each case).</p>
  
  <p>Is there way to test exceptions and errors using Python, or a preferred pattern for doing so?</p>
  
  <pre class="lang-py prettyprint-override"><code>def test_something():
      with pytest.raises(TypeError) as e:
          my_func(bad_args)
          assert e.message == "My expected message for bad args"
  </code></pre>
  
  <p>does not work (i.e. it passes even if I replace the assertion with <code>assert False</code>).</p>