如何在Python中进行此模拟数据库测试?

时间:2019-05-08 16:32:43

标签: python mysql mocking pytest python-unittest

我是第一次使用Python编写测试。我希望编写一个模拟与MySQL的数据库连接并确保将进行正确更改的测试。

我已经根据可以在网上找到的东西设置了测试的结构,如下所示:

这是测试文件tests / test_modules.py:

import pytest
import modules
from unittest import mock
import dbx_aws
from decimal import Decimal

class TestAddData():
    @mock.patch('modules.AddView.db_add')
    def test_add_raw_materials_query(self, mysql_mock):
        modules.AddView.db_add('raw_materials', ('Bottles', 'ALB 2L', 500, 2.63, 1315.00))
        mysql_mock.assert_called_with('raw_materials', ('Bottles', 'ALB 2L', 500, 2.63, 1315.00))
        conn = dbx_aws.db_conn()
        data = dbx_aws.db_exec(conn, "SELECT * FROM raw_materials").data
        assert ('Bottles', 'ALB 2L', 500, Decimal('2.63'), Decimal('1315.00')) in data

这是我要测试的方法'db_add',是modules.py中AddView类的方法:

def db_add(self, table, data):
        self.conn = dbx_aws.db_conn()
        self.cur = self.conn.cursor()
        self.str1 = "({}%s)".format("%s,"*(len(data) - 1)) #(%s,%s,..,%s)
        self.query = "INSERT INTO {} VALUES {}".format(table, self.str1)
        self.cur.execute(self.query, data)
        self.conn.commit()
        self.cur.close()
        self.conn.close()

我希望模拟数据库连接具有更改,在“ data”变量中返回这些更新值,并检查是否存在我添加的新值。我没有得到这些价值。我收到以下错误:

AssertionError: assert ('Bottles', 'ALB 2L', 500, Decimal('2.63'), Decimal('1315.00')) in [('Bottles', 'Water', 300,
Decimal('2.5300'), Decimal('759.0000'))]

0 个答案:

没有答案