python - 模拟 python 数据库查询

标签 python unit-testing mocking mysql-python python-unittest

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

Asssertion error:AssertionError: Expected call: execute()
Not called
and create_table() not defined.

我想要调用 execute() 并使用 create_table() 返回针对预定义值进行断言的响应。

应用程序.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

测试.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.close() 之前(或代替)添加 cursor.commit()

关于python - 模拟 python 数据库查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31417536/

相关文章:

python - 模拟父类(super class) __init__ 方法或父类(super class)作为一个整体进行测试

python - 正则表达式 Python 不返回期望的结果

Python for 循环优化

Python:如何解决 IndentationError

node.js - 用 Jest 模拟 nodemailer.createTransport.sendMail

python - 如何模拟 pysvn

python - 为什么这个 python 生成器根据 keras 没有输出?

android - Robolectric 3.0 - 使用 applicationIdSuffix 时资源未解析

visual-studio - 使用 VSTS 实现 SQL Server 单元测试自动化 - Team Services

unit-testing - 如何使用 Http 模块测试服务发送的 Angular 2 header ?