unitSphere
unitSphere

Reputation: 311

Mock not overriding the return of a function in Python

I am implementing unit test on one of the classes of my project. The method that I want to test is queryCfsNoteVariations:

class PdfRaportDaoImpl:
        def queryCfsNoteVariations(self, reportId):
        sql = """
select v.* from item_value_table v
where v.table_id in
(select table_id from table_table t
    where t.report_id=%s and table_name='CFS')
"""
        cfsItemList = dbFind(sql, (reportId))

        sql = "select * from variations_cfs_note"
        cfsNoteVariations = dbFind(sql)
        if cfsNoteVariations == None or len(cfsNoteVariations) == 0:
            raise Exception("cfs note variations is null!")

        cfsNoteVariationList = []
        for itemInfo in cfsItemList:
            for cfsNoteVariation in cfsNoteVariations:
                if (
                        cfsNoteVariation["item_name_cfs"].lower()
                        == itemInfo["item_name"].lower()
                ):
                    cfsNoteVariationList.append(cfsNoteVariation["item_name_cfs_note"])
            if len(cfsNoteVariationList) > 0:
                return cfsNoteVariationList, itemInfo["item_note"]
        return None, None

Which has a path: /com/pdfgather/PDFReportDao.py

In my test I am doing patch on dbFind() method which is located in /com/pdfgather/GlobalHelper.py. My current test looks like this:

from com.pdfgather.PDFReportDao import PdfReportDaoImpl


@patch("com.pdfgather.GlobalHelper.dbFind")
    def test_query_cfs_note_variations(self, mock_find):
        mock_find.side_effect = iter([
[{"item_name" : "foo"}, {"item_name" : "hey"}], 
        [{"item_name_cfs": "foo"},
         {"item_name_cfs": "foo"},
         {"item_name_cfs": "hey"}]]
])
        report_id = 3578
        result = TestingDao.dao.queryCfsNoteVariations(report_id)

        # Printing result
        print(result)

However I am not getting my desired result which is getting inside a loop and returning from inside a loop. Instead the dbFind is returning nothing (but it shouldn't as I already preassigned returning values for dbFind).

Thanks in advance!

Upvotes: 1

Views: 590

Answers (1)

ishefi
ishefi

Reputation: 573

Python refers com.pdfgather.PDFReportDao.dbFind and com.pdfgather.GlobalHelper.dbFind as two different classes. The second one is the import you want to patch. Try changing your patch to:

@patch("com.pdfgather.PDFReportDao.dbFind")

Upvotes: 2

Related Questions