首页 > 解决方案 > python中有什么方法可以找出调用其他方法的方法吗?

问题描述

我正在尝试在 pytest 中编写代码,它在 pytest 中标识使用特定方法的测试文件。

例如:

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

因此,如果我提供“cal_cube”作为函数名称,则需要列出test_cal_cube_3test_cal_cube_4

是否有任何库可以实现这一点。我读过它可以通过检查库来实现。欢迎任何其他建议。

标签: pythonpytest

解决方案


我希望检查库对您有所帮助。通过使用getsource函数,您可以检查函数的定义是否包含字符串"mathlib.cal_cube"。您还可以使用getmembersisfunction的组合列出所有函数。

例如在您的代码中:

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)

推荐阅读