Python 元编程。在更改变量值的情况下生成大量类似测试

Python Metaprogramming. Generating massive amount of similar tests where a variable value is changed

我们有大量的测试用例 classes 来执行一些检查。我需要生成所有这些相同的测试,但要更改变量的值。 例如:

class DynamicPivotSeriesTestCase(AuthenticatedApiTestCase):
    '''
    Test all series against a fixed category trying every format
    '''
    #binding
    ftn = utils.format_test_name

    # Test Params
    base_url, formats = API_FORMATS['pivot']
    base_test_name = 'test_pivot_series_{series}'

    # Test vars
    series = VARS

    for srs in series:
        params = {'series': srs, 'cats': 'campaign', 'from': '2013-07-31', 'to': '2013-07-31'}
        test_name = ftn(base_test_name, params)
        locals()[test_name] = utils.make_check_code(200, base_url, params, formats)

class DynamicPivotDerivedSeriesTestCase(AuthenticatedApiTestCase):
    #binding
    ftn = utils.format_test_name

    # Test Params
    base_url, formats = API_FORMATS['pivot']
    base_test_name = 'test_pivot_derived_series_{series}'

    # Test vars
    series = DERIVED_VARS

    for srs in series:
        params = {'series': srs, 'cats': 'campaign', 'from': '2013-07-31', 'to': '2013-07-31'}
        test_name = ftn(base_test_name, params)
        locals()[test_name] = utils.make_check_code(200, base_url, params, formats)

有大约 150 个这样的测试,我无法复制粘贴代码。我需要遍历全局变量,访问每个(class_name、class 对象),检查 class 是否是测试 class,如果是,我需要实例化一个新测试 class 与当前访问的 class 测试具有相同的主体,但我需要为 base_url 变量设置不同的值。这是我不明白如何实现的。

对象属性的简单更新:

if __name__ == '__main__':
    for name, thing in globals().iteritems():
        if issubclass(thing, AuthenticatedApiTestCase):
            obj = thing()
            obj.base_url = something_new

如果你不能实例化那么你可以做

new_classes = []
if issubclass(thing, AuthenticatedApiTestCase):
    class NewClasS(thing):
        base_url = something_new

    new_classes.append(NewClass)

好的,这可能不是您想要的 - 您需要动态分配 class 名称等......但也许这解决了动态生成新 classes 的初始问题修改 class vars

还有其他方法 - class 装饰器,metaclasses - 这实际上取决于你正在尝试做什么的其他细节