模拟python数据库查询

时间:2015-07-14 21:15:38

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

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

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

我希望调用execute()并使用create_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"]}')

我做错了什么?有人可以告诉我如何解决它

1 个答案:

答案 0 :(得分:1)

我认为您需要在关闭光标之前添加更改,否则执行将不会发生。尝试在cursor.commit()之前(或代替)添加cursor.close()