简体   繁体   English

单元测试Pyodbc数据库连接

[英]Unit Test Pyodbc Database Connection

I wrote the following unit test to test whether the connection has been successfully established or not. 我编写了以下单元测试,以测试连接是否已成功建立。

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

If the connection can be established, the test says: 如果可以建立连接,则测试将显示:

Ran 1 test in 0.001s

OK

Process finished with exit code 0

In case the connection could not be established, I'll get the following: 如果无法建立连接,我将得到以下信息:

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)
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.

Why is the exception OperationalError not caught by the test case and why does it say: Empty test suite ? 为什么测试用例没有捕获到OperationalError异常,为什么它说: Empty test suite

You are connecting to PyODBC outside of the test, before the test can run. 您正在连接到PyODBC测试之外 ,在测试前可以运行。

You are doing so in the databse_access_pyodbc module. 您正在databse_access_pyodbc模块中执行此databse_access_pyodbc The traceback shows you this; 追溯显示给您; I've only included interesting lines with annotations from the traceback here: 我仅在此处包含来自追溯的注释的有趣行:

  1. PyCharm uses its own test runner, which calls unittest.main() here: PyCharm使用自己的测试运行程序,在此处调用unittest.main()

     main(argv=args, module=None, testRunner=unittestpy.TeamcityTestRunner, buffer=not JB_DISABLE_BUFFERING) 
  2. the unittest.main() code starts loading your test module here unittest.main()代码开始在此处加载测试模块

     File "xxx\\Python36\\lib\\unittest\\loader.py", line 153, in loadTestsFromName module = __import__(module_name) 
  3. This is the test module you posted in your question, and line 2 your test module imports your databse_access_pyodbc module 这是您在问题中发布的测试模块,测试模块的第二行导入了databse_access_pyodbc模块

     File "xxx\\tests\\test_database_access_pyodbc.py", line 2, in <module> from databse_access_pyodbc import * 
  4. You didn't post the code for databse_access_pyodbc , but on line 40 of the module-level code it calls get_db_connection() : 您没有发布databse_access_pyodbc的代码,但是在模块级代码的第40行,它调用get_db_connection()

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

That call then fails to connect and an exception is raised. 然后,该呼叫无法连接,并引发异常。 Because the exception is raised while trying to load your test module , the remainder of the code in that module is never executed, the class TestDatabseConnection definition never happens, and so no tests are found. 由于尝试加载测试模块时会引发异常,因此该模块中的其余代码将永远不会执行, class TestDatabseConnection定义也不会发生,因此找不到测试。

You can't test get_db_connection() independently if the module that defines the function also calls it at the top level of the module. 如果定义函数的模块也在模块的顶层调用了该函数,则无法独立测试get_db_connection() Remove that function call there. 在那里删除该函数调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM