简体   繁体   中英

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 ?

You are connecting to PyODBC outside of the test, before the test can run.

You are doing so in the databse_access_pyodbc module. 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:

     main(argv=args, module=None, testRunner=unittestpy.TeamcityTestRunner, buffer=not JB_DISABLE_BUFFERING) 
  2. the unittest.main() code starts loading your test module here

     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

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

     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.

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. Remove that function call there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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