如何在Python中编写单元测试用例以检查与SQL Server的数据库连接?

时间:2019-06-21 12:01:54

标签: python-unittest

我刚刚开始在Python中使用unittest编写测试用例,我有一个与SQL Server建立连接的函数。

sql_connection.py

def getConnection():
    connection = pyodbc.connect("Driver={ODBC Driver 13 for SQL Server};"
            "Server="+appConfig['sql_server']['server']+";"
            "Database="+appConfig['sql_server']['database']+";"
            "UID="+appConfig['sql_server']['uid']+";"
            "PWD="+appConfig['sql_server']['password']+";"
            "Trusted_Connection=no;",
            )
    return connection

我已经在下面的测试用例中尝试过检查数据库是否连接。

test_connection.py

import pyodbc

getConnection1=getConnection()

class TestDatabseConnection(unittest.TestCase):
    def test_getConnection(self):
        try:
            db_connection = getConnection1.connection
        except pyodbc.Error as ex:
            sqlstate = ex.args[1]
            print(sqlstate)
            self.fail(
                "getConnection() raised pyodbc.OperationalError. " +
                "Connection to database failed. Detailed error message: " + sqlstate)
        self.assertIsNone(db_connection)

但仍然无法获得成功。

======================================================================
ERROR: test_getConnection (__main__.TestDatabseConnection)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test_connection.py", line 23, in test_getConnection
    db_connection = getConnection1.connection
AttributeError: 'pyodbc.Connection' object has no attribute 'connection'

----------------------------------------------------------------------
Ran 1 test in 0.001s

FAILED (errors=1)

请帮助我。

1 个答案:

答案 0 :(得分:0)

getConnection的单元测试如下所示。我建议使用unittest.mock中的补丁和模拟。使用单元测试,您只对测试getConnection的功能感兴趣,应该“模拟”函数中的所有其他函数调用。如果您想测试pyodbc.connect的全部潜力,那么我建议您进行实际连接到数据库的功能测试,而不再是单元测试。有关补丁和模拟的更多信息,请查看文档。这些功能非常强大,使单元测试变得轻松有趣! unittest.mock

import unittest
from unittest.mock import patch, Mock

import pyodbc

def getConnection():
    appConfig = {'sql_server': {'server':'', 'database':'', 'uid':'', 'password':''}}
    connection = pyodbc.connect("Driver={ODBC Driver 13 for SQL Server};"
            "Server="+appConfig['sql_server']['server']+";"
            "Database="+appConfig['sql_server']['database']+";"
            "UID="+appConfig['sql_server']['uid']+";"
            "PWD="+appConfig['sql_server']['password']+";"
            "Trusted_Connection=no;",
            )
    return connection


@patch('pyodbc_example.pyodbc')
class TestDatabseConnection(unittest.TestCase):
    def test_getConnection(self, pyodbc_mock):
        pyodbc_mock.connect.return_value = Mock()
        connection = getConnection()
        self.assertEqual(connection, pyodbc_mock.connect.return_value)