简体   繁体   English

在 python 中使用 globals() 动态创建 function

[英]Dynamic function creation using globals() in python

I am trying to call a dynamic method created using exec() , after calling globals() it is considering params as fixture and returning error as fixture 'Template_SI' not found.我正在尝试调用使用exec()创建的动态方法,在调用globals()之后,它将params视为夹具并返回错误,因为未找到夹具'Template_SI'。

can someone help on how to pass dynamic parameters using globals()function_name(params)有人可以帮助如何使用globals()function_name(params)传递动态参数

import pytest 
import input_csv

datalist = input_csv.csvdata()


def display():
    return 10 + 5


for data in datalist:
    functionname = data['TCID']
    parameters = [data['Template_name'], data['File_Type']]
    body = 'print(display())'


    def createfunc(name, *params, code):
        exec('''
@pytest.mark.regression
def {}({}):
    {}'''.format(name, ', '.join(params), code), globals(), globals())


    createfunc(functionname, data['Template_name'], data['File_Type'], code=body)
    templateName = data['Template_name']
    fileType = data['File_Type']
    globals()[functionname](templateName, fileType)

It looks like you're trying to automate the generation of lots of different tests based on different input data.看起来您正在尝试根据不同的输入数据自动生成许多不同的测试。 If that's the case, using exec is probably not the best way to go.如果是这种情况,使用exec可能不是 go 的最佳方式。

pytest provides parameterized tests: https://docs.pytest.org/en/6.2.x/example/parametrize.html pytest provides parameterized tests: https://docs.pytest.org/en/6.2.x/example/parametrize.html

which accomplish test generation by hiding all the details inside Metafunc.parameterize() .它通过隐藏Metafunc.parameterize()中的所有细节来完成测试生成。

If you really want to generate the tests yourself, consider adapting Metafunc to your own purposes.如果您真的想自己生成测试,请考虑根据您自己的目的调整 Metafunc。 Or, alternatively, checking the unittest framework.或者,或者,检查单元测试框架。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM