Is there any way in python to find out the methods where other methods are being called?

Viewed 43

I am trying to write a code in pytest where it identifies the testfiles across the pytest which uses a particular method.

For Example:

import mathlib
 
#### Test case 1
def test_cal_square_1( ):
    result = mathlib.cal_square(5)
    assert == 25
 
 
#### Test case 2
def test_cal_square_2( ):
    result = mathlib.cal_square(6)
    assert == 36
 
 
#### Test case 3
def test_cal_cube_3( ):
    result = mathlib.cal_cube(3)
    assert == 27
 
 
#### Test case 4
def test_cal_cube_4( ):
    result = mathlib.cal_cube(2)
    assert == 8

So if i provide 'cal_cube' as fuunction name, it needs to list out test_cal_cube_3 and test_cal_cube_4

Are there any libraries to achieve this. I have read that it can be achieved through inspect library. Any other suggestions are welcome.

1 Answers

I hope inspect library helps you. By using getsource function you can check if your functions' definition contains the string "mathlib.cal_cube". You may also make a list of all functions with a combination of getmembers and isfunction.

For example in your code:

from inspect import getmembers, isfunction, getsource
# it helps you to refer module from inside. If your functions are defined inside another module(file) you can simply import that module.
#(i.e. replacing sys.module with the other module's name)
import sys



def test_cal_square_1( ):
    result = mathlib.cal_square(5)
    assert result == 25
 
 
#### Test case 2
def test_cal_square_2( ):
    result = mathlib.cal_square(6)
    assert result== 36
 
 
#### Test case 3
def test_cal_cube_3( ):
    result = mathlib.cal_cube(3)
    assert result== 27
 
 
#### Test case 4
def test_cal_cube_4( ):
    result = mathlib.cal_cube(2)
    assert result== 8

# getmember finds everything defined in a module we may choose the functions (remove other definitions) with isfunction
function_list= [o for o in getmembers(sys.modules[__name__]) if isfunction(o[1])]

result_list = []
for f in function_list:
    # f is a tuple. f[0] is the name of the function in string format. f[1] is the object of function, which is the parameter of getsource function 
    f_text = getsource(f[1])
    if "mathlib.cal_cube" in f_text:
        result_list.append(f[0])
print(result_list)
Related