Python单元测试,错误发生和异常匹配,但我的程序返回一个`AssertionError`

Python unit testing, error happened and exception matched, but my program returns an `AssertionError`

这是我的python代码。

1
2
try: ct("table_that_does_not_exist","database_that_does_not_exists")
except r.errors.ReqlOpFailedError as e: self.fail()

ct是检查数据库中是否存在表的函数。如果数据库中存在表,ct返回True,否则返回False

try: ct("table_that_does_not_exist","database_that_does_not_exists")试图检查不存在的数据库中不存在的表。这将返回一个错误。

1
2
rethinkdb.errors.ReqlOpFailedError: Database `database_that_does_not_exists` does not exist in:
r.db('database_that_does_not_exists').table_list().contains('table_that_does_not_exist')

但是,该错误在except r.errors.ReqlOpFailedError as e: self.fail()中没有捕获,返回AssertionError

我希望这能通过测试,因为ct("table_that_does_not_exist","database_that_does_not_exists")将返回r.errors.ReqlOpFailedError。但我得到了这个。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
======================================================================
FAIL: test_check_table (__main__.test)
----------------------------------------------------------------------
Traceback (most recent call last):
  File"test.py", line 61, in test_check_table
    try: ct("table_that_does_not_exist","database_that_does_not_exists")
rethinkdb.errors.ReqlOpFailedError: Database `database_that_does_not_exists` does not exist in:
r.db('database_that_does_not_exists').table_list().contains('table_that_does_not_exist')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^                                                  

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File"test.py", line 62, in test_check_table
    except r.errors.ReqlOpFailedError as e: self.fail()
AssertionError

----------------------------------------------------------------------
Ran 7 tests in 0.050s

FAILED (failures=1)

错误是匹配的,但不能通过except继续。

我的测试出了什么问题?


我相信你对此的一般做法是错误的。异常检查代码应如下所示:

1
2
with self.assertRaises(r.errors.ReqlOpFailedError):
    ct("table_that_does_not_exist","database_that_does_not_exists")