"trying unit test code using unittest.mock python library". have code running database queries similar this:
app.py:
from flask import g import mysql.connector @app.route('/') def create_table(): g.db=mysql.connector.connect("credentials") cursor = g.db.cursor() cursor.execute('create table if not exists test(id int not null primary key, name varchar(40),email varchar(40) not null)') cursor.close() g.db.close() i have mocked g.db using below method, here struggling how mock cursor.execute() , cursor.close(). appreciated.
def testtable(): patch('app.mysql.connector') mock_mysql_connector: create_table() print g.db #mock execute , close# on printing g.db i'm getting mock name , id, believe means g.db mocked, have no clue how should mock execute() , close().
do have monkey patching?
if yes, please provide hint how monkey patch them?
if no, way mock them?
you use patch.multiple:
from mock import patch, default patch.multiple('app', mysql=default, g=default) dict: # mocking connector = dict[̈́'mysql'].connector db = connector.connect.return_value cursor = db.cursor.return_value # run function test create_table() # assertions assert dict['g'].db == db db.close.assert_called_once_with() cursor.close.assert_called_once_with() connector.connect.assert_called_once_with("credentials")
Comments
Post a Comment