techno
techno

Reputation: 111

Mocking a python database query

I am trying to test by mocking a database query, but receiving an error:

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

I want to execute() to be called and use create_table() to return response for asserting against pre-defined values.

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"]}')

What am I doing wrong?Can someone please tell me how to fix it

Upvotes: 1

Views: 4959

Answers (1)

FTA
FTA

Reputation: 345

I believe you need to add your changes before closing the cursor, or the execute won't occur. Try adding cursor.commit() before (or instead of) cursor.close().

Upvotes: 1

Related Questions