Python 3.7中单元测试期间异常部分的奇怪行为

时间:2018-10-10 14:59:22

标签: python unit-testing xunit python-3.7

我有一些sqlite DB创建代码。有多个选项-文件是否存在,或者出现错误(写入HDD,错误的数据库名称,格式等)。如果该方法正确运行,则返回True,如果引发异常,则返回False:

def create_db():
    try:
        db = sqlite3.connect(db_name)
        with db:
            db.execute("SELECT name FROM db_name WHERE type='table'")
        if os.path.isfile(db_name):
            my_logger.info('The DB already existed!')
            return 'DB existed'
        else:
            db = sqlite3.connect(db_name)
            with db:
                db.execute('''CREATE TABLE IF NOT EXISTS City_Weather (fields_description_here)''')
                my_logger.info('The DB was created successfully!')
            return 'DB created'

    except Exception as e:
        my_logger.info(e)
        return False

然后我为此功能编写了单元测试:

class ReadersTest(unittest.TestCase):

def test_create_db(self):
    self.assertEqual(create_db(), 'DB existed')

奇怪的行为始于我尝试初始化测试的地方:

DB existed != False

Expected :False
Actual   :DB existed
<Click to see difference>

Traceback (most recent call last):
  File "C:\Program Files\JetBrains\PyCharm 2018.2.2\helpers\pycharm\teamcity\diff_tools.py", line 32, in _patched_equals
old(self, first, second, msg)
 File     
"C:\Users\path\AppData\Local\Programs\Python\Python37\lib\unittest\case.py", line 839, in assertEqual
assertion_func(first, second, msg=msg)
 File "C:\Users\path\AppData\Local\Programs\Python\Python37\lib\unittest\case.py", 
line 832, in _baseAssertEqual
    raise self.failureException(msg)
AssertionError: False != 'DB existed'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File 
"C:\Users\path\AppData\Local\Programs\Python\Python37\lib\unittest\case.py", 
line 59, in testPartExecutor
  yield
  File "C:\Users\path\AppData\Local\Programs\Python\Python37\lib\unittest\case.py", line 615, in run
testMethod()
File "C:\file_path_to_project\utest.py", line 12, in test_create_db
  self.assertEqual(readers.Readers.create_db(), 'DB existed')

单元测试模块为什么要等待“ False”语句正确?在测试过程中,创建了我的数据库,它应该通过此测试,但是没有通过。

谢谢!

1 个答案:

答案 0 :(得分:1)

此断言失败

self.assertEqual(create_db(), 'DB existed')

实际上您正在等待'DB existed',但是该函数正在返回False,因此您必须具有导致其返回False的异常