在 python unittest 中模拟数据库

时间:2021-03-04 10:26:37

标签: python pytest python-unittest python-mock pytest-mock

我试图通过模拟 sql 连接来模拟 unittest 模拟中 get_count 函数返回的值。但是我遇到了这个错误。

断言错误:12939 !=

app.py

import pyodbc

try:

    def get_count(conn):
        cursor = conn.cursor()
        cursor.execute('SELECT COUNT(ID) FROM mydb.dbo.Company')
        count = cursor.fetchone()[0]
        return count
except pyodbc.Error as e:
    print(e)


if __name__ == '__main__':
    server = 'xx.x.xx.xxx'
    database = 'mydb' 
    username = 'user1' 
    password = '12424124'
    conn = pyodbc.connect('DRIVER={ODBC Driver 11 for SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)
    cursor = conn.cursor()
    print(get_count(conn))

test_count.py

import unittest
from unittest import mock
from app import get_count
class Test_count(unittest.TestCase):

    def fix_dbc(self):
        dbc = mock.MagicMock(spec=['cursor'])
        return dbc

    def fix_count(self):    
        count = 12939
        return count

    def test_get_count_method(self):
        dbc = self.fix_dbc()
        count = self.fix_count()
        self.assertEqual(count, get_count(dbc))
if __name__ == '__main__':
    unittest.main(argv=['', '-v'])

这是我的代码,任何人都可以帮助我

1 个答案:

答案 0 :(得分:0)

您在模拟初始化过程中离开了:"eslintConfig": { "extends": "react-app", "rules": { "no-unused-vars": "off" } }, 是您提供给 dbc 的魔法模拟。所以你会在 get_count 上调用其他方法后得到 dbc.cursor().fetchone()[0]

您必须配置您的模拟以返回适当的值:

dbc.cursor()