assertRaises not catching Exception, even when function is passed as callable
<p>When I run the below unit test, I get the following output.</p>

<pre><code>    ======================================================================
ERROR: test_find_playlist_file_invalid (__main__.TestSpotifyScraperAPI)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/gareth/Dropbox/programming/python/spotify_ripper/test/SpotifyScraperAPITest.py", line 15, in test_find_playlist_file_invalid
    spotify_scraper_api = SpotifyScraperAPI("non_existent_dir")
  File "/home/gareth/Dropbox/programming/python/spotify_ripper/SpotifyScraperAPI.py", line 7, in __init__
    self.playlist_file = self.find_playlist_file()
  File "/home/gareth/Dropbox/programming/python/spotify_ripper/SpotifyScraperAPI.py", line 14, in find_playlist_file
    raise OSError("Given playlist folder does not exist")
OSError: Given playlist folder does not exist
</code></pre>

<p>__</p>

<pre><code>import unittest
from SpotifyScraperAPI import SpotifyScraperAPI


class TestSpotifyScraperAPI(unittest.TestCase):

    def test_find_playlist_file_invalid(self):
        spotify_scraper_api = SpotifyScraperAPI("non_existent_dir")
        self.assertRaises(OSError, spotify_scraper_api.find_playlist_file)

if __name__ == '__main__':
    unittest.main()
</code></pre>

<p>So it's throwing the correct error, but not being caught, even though I'm passing the function in as a callable? What did I screw up?</p>

<p>Thanks in advance!</p>

<p>Exception comes from constructor. To assert for it in unittest you may use <code>assertRaises</code> as context manager, and move constructor to context manager body.</p>

<pre><code>class TestSpotifyScraperAPI(unittest.TestCase):

    def test_find_playlist_file_invalid(self):
        with self.assertRaises(OSError):
            SpotifyScraperAPI("non_existent_dir")
</code></pre>

python python-3.x