在许多类似的数据文件相同的测试 [英] Same tests over many similar data files

查看:200
本文介绍了在许多类似的数据文件相同的测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Python和单元测试我有test目录的结构:

With python and unittest I have this structure of test directory:

tests/
  __init__.py
  test_001.py
  data/
    data_001_in.py
    data_001_out.py

其中,


  • data_001_in.py :在函数中使用输入数据来检验

  • data_001_out.py :从函数预期的输出数据,以测试

  • data_001_in.py : the input data to use in the functions to test
  • data_001_out.py : the output data expected from the function to test

我在Python字典输入和输出,因为它比使用JSON,sqlite的,等我更容易。

I have the inputs and outputs in python dictionaries because it is easier for me than using json, sqlite, etc.

我尝试使用一组输入/输出数据具有相同的格式和在每对数据的应用试验

I try use a set of input/output data with the same format and apply the test over each pair of data:

tests/
  __init__.py
  test_001.py
  data/
    data_001_in.py
    data_001_out.py
    data_002_in.py
    data_002_out.py
    data_003_in.py
    data_003_out.py

有任何包/办法,使这项工作更容易?

Is there any package/approach to make this task more easier?

推荐答案

在inspirated问题<一href=\"http://stackoverflow.com/questions/5176396/nose-unittest-testcase-and-metaclass-auto-generated-test-methods-not-discove\">nose, unittest.TestCase的和元类:自动生成TEST_ *方法没有发现,我解决了一元类。首先,我更改目录数据结构

inspirated in the question nose, unittest.TestCase and metaclass: auto-generated test_* methods not discovered, I solved with a metaclass. First, I change the directory data structure to

├── data
│   ├── __init__.py
│   ├── data001
│   │   ├── __init__.py
│   │   ├── datain.py
│   │   ├── dataout.py
│   └── data002
│       ├── __init__.py
│       ├── datain.py
│       ├── dataout.py
└── metatest.py

第二,我做了与子目录和基础试验数据建立新的测试元类。

Second, I make a metaclass for create new test with the data in the subdirectories and base tests.

import unittest
import os
import copy

def data_dir():
    return os.path.join(os.path.dirname(__file__), 'data')

def get_subdirs(dir_name):
    """ retorna subdirectorios con path completo"""
    subdirs = []
    for f in os.listdir(dir_name):
        f_path = os.path.join(dir_name, f)
        if os.path.isdir(f_path):
            subdirs.append(f)
    return subdirs

def get_data_subdirs():
    return get_subdirs(data_dir())

def data_py_load(file_name):
    """ carga diccionario data desde archivo .py """
    name = file_name.split('.py')[0]
    path_name = 'data.' + name
    exec_str = "from {} import *".format(path_name)
    exec(exec_str)
    return data

class TestDirectories(type):

    def __new__(cls, name, bases, attrs):

        subdirs = get_data_subdirs()

        callables = dict([
            (meth_name, meth) for (meth_name, meth) in attrs.items() if
                meth_name.startswith('_test')
        ])

        data = {}
        for d in subdirs:
            data[d] = {}
            data[d]['name'] = d
            out_path = "{}.dataout.py".format(d)
            data[d]['out'] = data_py_load(out_path)
            var_path = "{}.datain.py".format(d)
            data[d]['in'] = data_py_load(var_path)

        for meth_name, meth in callables.items():
            for d in subdirs:
                new_meth_name = meth_name[1:]
                # name of test to add, _test to test
                test_name = "{}_{}".format(new_meth_name, d)
                # deep copy for dictionaries
                testeable = lambda self, func=meth, args=copy.deepcopy(data[d]): func(self, args)
                attrs[test_name] = testeable

        return type.__new__(cls, name, bases, attrs)

class TestData(unittest.TestCase):

    __metaclass__ = TestDirectories

    def _test_name(self, data):
        in_name = data['in']['name']
        out_name = data['out']['name']
        print in_name, out_name
        self.assertEquals(in_name, out_name)

if __name__ == '__main__':
    unittest.main(verbosity=2)

和,当我运行

$ python metatest.py
test_name_data001 (__main__.TestData) ... Alice Alice
ok
test_name_data002 (__main__.TestData) ... Bob Bob
ok

----------------------------------------------------------------------
Ran 2 tests in 0.001s

OK

这篇关于在许多类似的数据文件相同的测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆