sparky2012 sparky2012 - 3 months ago 26
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/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


__

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()


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!

Answer

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):
            SpotifyScraperAPI("non_existent_dir")
Comments