mardi 2 février 2016

Mocking members of immutable classes in Python

I have a class which uses a sqlite3 database and want to write a test suite for it. In particular, I want to check that sqlite3.Cursor.execute is called with the correct SQL command. However, I have run into trouble with mocking this method since sqlite3.Cursor seems to be written in C and thus the class is immutable. This means I can't just patch the execute method, but if I try to patch the whole class, the assert fails, saying that execute was never called.

Below is my best attempt so far, but the assert fails, saying that there was no call. I would appreciate some suggestions as to what I'm doing wrong. Thanks.

myclass.py

import sqlite3
class MyClass:
    def __init__(self):
        self.db = sqlite3.connect('somedb.db')

    def query(self, sql_squery):
        c = self.db.cursor()
        c.execute(sql_query)

test_myclass.py

import unittest
import mock
import myclass

class MyClassTestCase(unittest.TestCase):
    @patch('myclass.sqlite3.Cursor')
    def test_query(self, mock_sql_cursor):
        mc = myclass.MyClass()
        mc.query('test')
        mock_sql_cursor.execute.assert_called_with('test')

Aucun commentaire:

Enregistrer un commentaire