0

I am trying to mock the value returned by get_count function in unittest mock by mocking sql connection. But I got this error.

AssertionError: 12939 != <MagicMock name='mock.cursor().fetchone().getitem()' id='1053090478792'

app.py

import pyodbc

try:

    def get_count(conn):
        cursor = conn.cursor()
        cursor.execute('SELECT COUNT(ID) FROM mydb.dbo.Company')
        count = cursor.fetchone()[0]
        return count
except pyodbc.Error as e:
    print(e)


if __name__ == '__main__':
    server = 'xx.x.xx.xxx'
    database = 'mydb' 
    username = 'user1' 
    password = '12424124'
    conn = pyodbc.connect('DRIVER={ODBC Driver 11 for SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)
    cursor = conn.cursor()
    print(get_count(conn))

test_count.py

import unittest
from unittest import mock
from app import get_count
class Test_count(unittest.TestCase):

    def fix_dbc(self):
        dbc = mock.MagicMock(spec=['cursor'])
        return dbc

    def fix_count(self):    
        count = 12939
        return count

    def test_get_count_method(self):
        dbc = self.fix_dbc()
        count = self.fix_count()
        self.assertEqual(count, get_count(dbc))
if __name__ == '__main__':
    unittest.main(argv=['', '-v'])

This is my code anyone help me

  • why do you have `try/except` around your function declaration? doesn't make much sense, you probably meant to put it inside the function? – gold_cy Mar 04 '21 at 12:13

1 Answers1

0

You left in the middle of mock initialization: dbc is a magick Mock that you give to get_count. So you will get dbc.cursor().fetchone()[0] after calling other methods on dbc.cursor().

You must configure your mock to return the appropriate values:

def fix_dbc(self):
    dbc = mock.MagicMock(spec=['cursor'],
                         **{'cursor.return_value': mock.MagickMock(
                             spec=['execute', 'fetchone'],
                             **{'fetchone.return_value': [12939]})})
    return dbc
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252