Mocking python function based on input arguments

后端 未结 8 537
无人及你
无人及你 2020-12-22 21:15

We have been using Mock for python for a while.

Now, we have a situation in which we want to mock a function

def foo(self, my_param):
    #do someth         


        
8条回答
  •  一个人的身影
    2020-12-22 21:54

    You can also use @mock.patch.object:

    Let's say a module my_module.py uses pandas to read from a database and we would like to test this module by mocking pd.read_sql_table method (which takes table_name as argument).

    What you can do is to create (inside your test) a db_mock method that returns different objects depending on the argument provided:

    def db_mock(**kwargs):
        if kwargs['table_name'] == 'table_1':
            # return some DataFrame
        elif kwargs['table_name'] == 'table_2':
            # return some other DataFrame
    

    In your test function you then do:

    import my_module as my_module_imported
    
    @mock.patch.object(my_module_imported.pd, "read_sql_table", new_callable=lambda: db_mock)
    def test_my_module(mock_read_sql_table):
        # You can now test any methods from `my_module`, e.g. `foo` and any call this 
        # method does to `read_sql_table` will be mocked by `db_mock`, e.g.
        ret = my_module_imported.foo(table_name='table_1')
        # `ret` is some DataFrame returned by `db_mock`
    

提交回复
热议问题