python - 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_3和test_cal_cube_4
是否有任何库可以实现这一点。我读过它可以通过检查库来实现。欢迎任何其他建议。
解决方案
我希望检查库对您有所帮助。通过使用getsource函数,您可以检查函数的定义是否包含字符串"mathlib.cal_cube"。您还可以使用getmembers和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)
推荐阅读
- sql-server - 如何编写查询以连接 Northwind 数据库中 3 个单独表中的列
- c - 与测量工具不一致的时钟周期,这种不一致的周期究竟来自哪里?
- java - 我的代码违反了 DRY 原则,但不确定如何进行重构
- flutter - 向 CircleAvatar 添加颜色叠加
- macos - docker-compose keeps previous environment variables after restart
- mysql - 绑定子表单未加载
- arrays - 对象中的 Nuxt/Vue 访问对象
- django - 运行 Django 服务器时出现错误请求或路径错误
- r - 如何将按列逻辑应用于数据框?
- python - 按 F5(我也认为其他 F)不起作用