assertRaises没有捕获异常,即使函数作为可调用函数传递

时间:2016-08-28 17:57:06

标签: python python-3.x

当我运行以下单元测试时,我得到以下输出。

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

所以它正在抛出正确的错误,但是没有被捕获,即使我将函数作为可调用函数传递?我搞砸了什么?

提前致谢!

1 个答案:

答案 0 :(得分:2)

异常来自构造函数。要在unittest中断言它,可以使用assertRaises作为上下文管理器,并将构造函数移动到上下文管理器主体。

class TestSpotifyScraperAPI(unittest.TestCase):

    def test_find_playlist_file_invalid(self):
        with self.assertRaises(OSError):
            SpotifyScraperAPI("non_existent_dir")