sparky2012 sparky2012 - 4 months ago 31
Python Question

assertRaises not catching Exception, even when function is passed as callable

When I run the below unit test, I get the following output.

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


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__':

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?

Thanks in advance!


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

class TestSpotifyScraperAPI(unittest.TestCase):

    def test_find_playlist_file_invalid(self):
        with self.assertRaises(OSError):