'how to do advanced unit tests python

I am pretty new at unit tests and have seen fairly basic examples of mocks and doing asserts that test the return value of a function. I have a fairly advanced application that has many nested functions and I am not sure of the best way to test my code...

Here is an example of what I am doing and I could use some pointers on the proper way to do unit tests for this.

import mongo
from flask_socketio import emit
import someOtherClass

class myClass(someOtherClass):
    def __init__(self, data1, data2, data3):
        self.data1 = data1
        self.data2 = data2
        self.data3 = data3
          
    def add_numbers(a, b):
        return a+b

    def mongo_delete(self, mycol, *args):
        try:
            mycol.delete_one({'key': args[0]})
        except IndexError:
            pass

    def emitter(self, message):
        emit('my_response', {'data': '{0}<br>'.format(message)}, namespace='/socket')

    def create_mongoclient():
        mongo = MongoClient(host='localhost', port=27017)
        mycol = mongo.get_database('messagedb').get_collection('messages')
        return mycol

    def example_call_others():
        print(add_numbers(1,2))
        mycol = create_mongoclient()
        mongo_delete(mycol, 'my_mongo_key')
        emitter('hello world')


if __name__ == '__main__':
    mc = myClass(someOtherClass)
    mc.example_call_others()

How would you test with 100% coverage for the above script? (side note, I have not tested this above code, it's just has a few examples that I Think should work. Specifically i'm not sure how to do a test where is no return, for example mongo_delete(), I am also not sure where the proper place to use mocks.

I have been using pytest for my testing so far but am fine with other options.

Thanks for the help!



Solution 1:[1]

You can simply mock that function as following.

from mock import patch
from my_module import myClass
import unittest

class TestMyClass(unittest.TestCase):

    @patch('myClass.mongo_delete')
    def test_mongo_delete(self, mock_delete):

        my_class = myClass()
        mycol = my_class.create_mongoclient()
        # You can use this for further uses

        self.assertTrue(mock_delete.called)
        mock_delete.assert_called_with(mycol)

You may need to adjust the above code according to your needs. For more you can check the documentation for unittest mock : unittest.mock

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1