首页 > 解决方案 > 在 Python 中处理夹具数据的正确方法

问题描述

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

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

标签: pythonfixtures

解决方案


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

有了鼻子,固定装置在文档的早期就已经介绍过了。他们给出的例子看起来像

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使用预期值进行更新。此过程不像在运行时键入它那样动态,但它具有易于版本控制和控制的优点。


推荐阅读