单元测试 Pyodbc 数据库连接

Unit Test Pyodbc Database Connection

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

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-02.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)
pyodbc.OperationalError: ('08001', '[08001] [Microsoft][ODBC Driver 11 for SQL Server]Named Pipes-Anbieter: Es konnte keine Verbindung zu SQL Server hergestellt werden [53].  (53) (SQLDriverConnect); [08001] [Microsoft][ODBC Driver 11 for SQL Server]Anmeldungstimeout abgelaufen (0); [08001] [Microsoft][ODBC Driver 11 for SQL Server]Netzwerkbezogener oder instanzspezifischer Fehler beim Herstellen einer Verbindung mit SQL Server. Der Server wurde nicht gefunden, oder auf ihn kann nicht zugegriffen werden. Überprüfen Sie, ob der Instanzname richtig ist und ob SQL Server Remoteverbindungen zulässt. Weitere Informationen erhalten Sie in der SQL Server-Onlinedokumentation. (53)')

Process finished with exit code 1
Empty test suite.

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

您正在测试外部连接PyODBC,在测试之前可以运行.

您正在 databse_access_pyodbc 模块中这样做。追溯向您展示了这一点;我只在此处添加了带有回溯注释的有趣行:

  1. PyCharm 使用自己的测试 运行ner,它在这里调用 unittest.main()

    main(argv=args, module=None, testRunner=unittestpy.TeamcityTestRunner, buffer=not JB_DISABLE_BUFFERING)
    
  2. unittest.main() 代码开始在此处加载您的测试模块

    File "xxx\Python36\lib\unittest\loader.py", line 153, in loadTestsFromName
      module = __import__(module_name)
    
  3. 这是您在问题中 post 编写的测试模块,第 2 行您的测试模块导入了您的 databse_access_pyodbc 模块

    File "xxx\tests\test_database_access_pyodbc.py", line 2, in <module>
      from databse_access_pyodbc import *
    
  4. 您没有 post databse_access_pyodbc 的代码,但在模块级代码的第 40 行它调用 get_db_connection():

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

该调用无法连接并引发异常。因为在尝试加载测试模块时 引发了异常 ,所以该模块中的其余代码永远不会执行,class TestDatabseConnection 定义永远不会发生,因此没有测试找到了。

如果定义函数的模块也在模块的顶层调用它,则无法独立测试 get_db_connection()。删除那里的函数调用。