user1427026
user1427026

Reputation: 879

How do I unit test a function with a for loop in it?

I have a function like this

def fun1(self, p1, p2):

    #fun2 fetches data from db and creates doc_list - (return db.coll.find(query using p1 and p2), new query using p1 and p2)

    doc_list = self.fun2(p1, p2)       
    for doc in doc_list:
        self.fun3(p2, doc)

where fun3 currently prints a logger.info message. I want to write a unit test for this function but I'm unclear as to how this should be refactored as it has a for loop. The end goal is to have a unit test where I can spoof the data coming from the db query function with my own hardcoded data(spoof f2 data) and possibly test all the list contents while unit testing fun1. Thanks

Upvotes: 2

Views: 3692

Answers (1)

Maciej Gol
Maciej Gol

Reputation: 15854

Using mock package you can either:

  • Mock the class fun1 is contained in with your custom class that overrides fun2 and fun3
  • Mock class.fun2 and class.fun3 with a Mock(return_value=<your_mocked_return_value>) mock. To test the proper calls, you could then use mock.call_count or mock.call_args.

Upvotes: 3

Related Questions