单元测试 Pyodbc 数据库连接

我写了下面的单元测试来测试连接是否成功建立。


import unittest

from databse_access_pyodbc import *

from pyodbc import OperationalError



class TestDatabseConnection(unittest.TestCase):


    def test_connection_db(self):

        try:

            db_connection = get_db_connection()

        except OperationalError as err:

            self.fail(

                "get_db_connection() raised pyodbc.OperationalError. " +

                "Connection to database failed. Detailed error message: " + err)

        self.assertIsNone(db_connection)



if __name__ == '__main__':

    unittest.main()

如果可以建立连接,测试说:


Ran 1 test in 0.001s


OK


Process finished with exit code 0

如果无法建立连接,我将得到以下信息:


Traceback (most recent call last):

  File "xxx\PyCharm-P\ch-0\182.4505.26\helpers\pycharm\_jb_unittest_runner.py", line 35, in <module>

    main(argv=args, module=None, testRunner=unittestpy.TeamcityTestRunner, buffer=not JB_DISABLE_BUFFERING)

  File "xxx\Python36\lib\unittest\main.py", line 94, in __init__

    self.parseArgs(argv)

  File "xxx\Python36\lib\unittest\main.py", line 141, in parseArgs

    self.createTests()

  File "xxx\Python36\lib\unittest\main.py", line 148, in createTests

    self.module)

  File "xxx\Python36\lib\unittest\loader.py", line 219, in loadTestsFromNames

    suites = [self.loadTestsFromName(name, module) for name in names]

  File "xxx\Python36\lib\unittest\loader.py", line 219, in <listcomp>

    suites = [self.loadTestsFromName(name, module) for name in names]

  File "xxx\Python36\lib\unittest\loader.py", line 153, in loadTestsFromName

    module = __import__(module_name)

  File "xxx\tests\test_database_access_pyodbc.py", line 2, in <module>

    from databse_access_pyodbc import *

  File "xxx\databse_access_pyodbc.py", line 40, in <module>

    get_db_connection()

  File "xxx\databse_access_pyodbc.py", line 36, in get_db_connection

    autocommit=True)

Process finished with exit code 1

Empty test suite.

为什么OperationalError测试用例没有捕获异常,为什么它说:Empty test suite?


梵蒂冈之花
浏览 202回答 1
1回答
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python