lundi 6 juillet 2015

How to mock a database queries?

For unit testing ,I am trying to implement MOCK object into my code but no luck so far.I'm not able to understand how to use MOCK object to mock my database.

If someone can please help me in understanding that what changes i need to make in below given unit test and Insert query to implement mock it would be a great help.

Unit test case When Insert query will be successful:

from app import app
import os,json
import unittest

class testing(unittest.TestCase):
  def testinsert(self):
    tester = app.test_client(self)
    response = tester.post('/user?name=guri&email=gur@gmail.com',      content_type='application/json')
    self.assertEqual(response.status_code, 200)

if __name__ == '__main__':
 unittest.main()

Insert query:

@app.route('/user', methods=['POST'])
def insert():
  name=request.args.get('name')
  email=request.args.get('email')
  try:
    cursor = g['db'].cursor()
    query = "INSERT INTO testmysql (name,email) VALUES (%s,%s)"
    cursor.execute(query,(name,email)
    g['db'].commit()
    last_id=cursor.lastrowid
    select = 'SELECT name,email from testmysql where id=%s'
    cursor.execute(select, (last_id,))
    columns=cursor.fetchall()
    for row in columns:
      data = dict(Id=last_id, name=row[0],email=row[1])
      resp = jsonify(data)
    cursor.close()
except mysql.connector.errors.Error as err:
    resp = jsonify({'status': 500, 'error': "Error:{}".format(err)})
    resp.status_code = 500
return resp

Aucun commentaire:

Enregistrer un commentaire