在Python中处理夹具数据的正确方法

问题描述 投票:-1回答:2

我的程序正在编写自然语言句子。我想通过将随机种子设置为修复值来正确测试它,然后:

  • 产生预期结果;
  • 比较生成的句子和预期的结果;
  • 如果它们不同,询问用户生成的句子是否实际上是预期结果,在这种情况下,更新预期结果。

我已经在JS中遇到过这样的系统,所以我很惊讶没有在Python中找到它。你是如何处理这种情况的?

python fixtures
2个回答
1
投票

Python中有许多测试框架,其中最流行的两个是PyTestNose。 PyTest倾向于涵盖所有基础,但Nose也有很多很好的附加功能。

有了鼻子,fixtures在文档的早期就有了。他们给出的例子看起来像

def setup_func():
    "set up test fixtures"

def teardown_func():
    "tear down test fixtures"

@with_setup(setup_func, teardown_func)
def test():
    "test ..."

在您的情况下,通过手动审查,您可能需要将该逻辑直接构建到测试本身。

使用更具体的示例进行编辑

基于Nose的示例,您可以通过编写测试来解决这个问题

from nose.tools import eq_

def setup_func():
    "set your random seed"

def teardown_func():
    "whatever teardown you need"

@with_setup(setup_func, teardown_func)
def test():
    expected = "the correct answer"
    actual = "make a prediction ..."
    _eq(expected, actual, "prediction did not match!")

运行测试时,如果模型未生成正确的输出,则测试将失败,并且“预测不匹配!”。在这种情况下,您应该转到测试文件并使用预期值更新expected。此过程不像在运行时键入它那样动态,但它具有易于版本化和控制的优点。


0
投票

要求用户替换预期答案的一个缺点是无法自动运行自动测试。因此,测试框架不允许从input读取。

我真的很想要这个功能,所以我的implementation看起来像:

def compare_results(expected, results):
    if not os.path.isfile(expected):
        logging.warning("The expected file does not exist.")
    elif filecmp.cmp(expected, results):
        logging.debug("%s is accepted." % expected)
        return 
    content = Path(results).read_text()
    print("The test %s failed." % expected)
    print("Should I accept the results?")
    print(content)
    while True:
        try:
            keep = input("[y/n]")
        except OSError:
            assert False, "The test failed. Run directly this file to accept the result"
        if keep.lower() in ["y", "yes"]:
            Path(expected).write_text(content)
            break
        elif keep.lower() in ["n", "no"]:
            assert False, "The test failed and you did not accept the answer."
            break
        else:
            print("Please answer by yes or no.")


def test_example_iot_root(setup):
    ...
    compare_results(EXPECTED_DIR / "iot_root.test", tmp.name)


if __name__ == "__main__":
    from inspect import getmembers, isfunction
    def istest(o):
        return isfunction(o[1]) and  o[0].startswith("test")

    [random.seed(1) and o[1](setup) for o in getmembers(sys.modules[__name__]) \
            if istest(o)]

当我直接运行此文件时,它会询问我是否应该替换预期的结果。当我从pytest运行时,input创建了一个允许退出循环的OSError。绝对不完美。

© www.soinside.com 2019 - 2024. All rights reserved.