模拟python数据库查询

模拟python数据库查询,python,unit-testing,mocking,mysql-python,python-unittest,Python,Unit Testing,Mocking,Mysql Python,Python Unittest,我试图通过模拟数据库查询进行测试,但收到一个错误: Asssertion error:AssertionError: Expected call: execute() Not called and create_table() not defined. 我希望调用execute(),并使用create\u table()返回响应,以根据预定义值进行断言 app.py from flask import Flask,g @app.before_request def before_reques

我试图通过模拟数据库查询进行测试,但收到一个错误:

Asssertion error:AssertionError: Expected call: execute()
Not called
and create_table() not defined.
我希望调用
execute()
,并使用
create\u table()
返回响应,以根据预定义值进行断言

app.py

from flask import Flask,g

@app.before_request
def before_request():
       g.db = mysql.connector.connect(user='root', password='root', database='mysql')

def create_table():
    try:     
        cur = g.db.cursor() #here g is imported form Flask module
        cursor.execute ('CREATE TABLE IF NOT EXISTS Man (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, name VARCHAR(40)')
        data = dict(Table='Man is created')
        resp = jsonify(data)
        cursor.close()
        return resp
test.py

  import unittest
  from app import *
  from mock import patch

  class Test(unittest.TestCase): 
  def test_create(self):
   with patch("app.g") as mock_g:
     mock_g.db.cursor()
     mock_g.execute.assert_called_with()
     resp = create_table()
     assertEqual(json, '{"Table":"Testmysql is created","Columns": ["id","name","email"]}')

我做错了什么?有人能告诉我如何修复它吗?我相信您需要在关闭光标之前添加更改,否则将不会执行。尝试将
cursor.commit()
添加到(或代替)
cursor.close()

之前。它也不起作用。我相信我在mocking execute()中缺少了一些东西。execute.assert\u called\u with()将尝试断言调用execute时没有参数,但在实际调用execute之前尝试检查它,此外,execute不是mock_g的方法,而是游标的方法。此外,您没有模拟数据库连接,因此它仍将尝试连接到数据库,并且测试中未定义json(除非您意外地从应用程序导入了它)-请不要使用
import*
这是一个坏习惯。