gpt4 book ai didi

python - python中有什么方法可以找出调用其他方法的方法吗?

转载 作者:行者123 更新时间:2023-12-04 16:46:05 24 4
gpt4 key购买 nike

我正在尝试在 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_3 test_cal_cube_4
是否有任何库可以实现这一点。我读过它可以通过检查库来实现。欢迎任何其他建议。

最佳答案

希望检查 图书馆帮助你。通过使用 获取资源 函数,您可以检查函数的定义是否包含字符串 “mathlib.cal_cube” .
您也可以使用 的组合来列出所有功能。获取成员(member) isfunction .
例如在您的代码中:

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)

关于python - python中有什么方法可以找出调用其他方法的方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69887302/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com