Py.test:对类中的测试用例进行参数化

Py.test: parametrize test cases from classes(Py.test:对类中的测试用例进行参数化)
本文介绍了Py.test:对类中的测试用例进行参数化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我目前正在关注这个 py.test 示例,当我不这样做时它会成功使用类,但是当我将测试用例引入类时我失败了.

I'm currently following this py.test example and it works out when I do not use classes, however when I introduce test cases into classes I am failing.

我设法写的最小的情况如下:

The smallest case I managed to write is the following:

import unittest

import pytest

class FixtureTestCase(unittest.TestCase):

    @pytest.mark.parametrize("test_input,expected", [
    ("3+5", 8),
    ("2+4", 6),
    ("6*9", 42),
    ])
    def test_1(self, a, b):
        self.assertEqual(a, b)

不幸的是当我执行时

  py.test  test_suite.py

我收到错误消息:

  TypeError: test_1() takes exactly 3 arguments (1 given)

如何才能生成一组 test_1 测试?

How can I do in order to generate a battery of test_1 tests?

推荐答案

如果你从 unittest.TestCase 继承,你的测试方法不能有额外的参数.如果您只是从 object 子类化,它会起作用(尽管您必须使用常规的 assert 语句而不是 TestCase.assertEqual 方法.

If you subclass from unittest.TestCase, your test methods cannot have additional arguments. If you simply subclass from object, it will work (though you'll have to use regular assert statements instead of the TestCase.assertEqual methods.

import unittest

import pytest

class TestCase(object):

    @pytest.mark.parametrize("test_input,expected", [
    ("3+5", 8),
    ("2+4", 6),
    ("6*9", 42),
    ])
    def test_1(self, a, b):
        assert eval(a) == b

不过,在这一点上,它有点引出了一个问题,为什么您使用类而不是仅仅定义函数,因为测试本质上是相同的,但需要更少的整体样板和代码.

At that point though, it kind of begs the question why you're using classes instead of just defining functions, since the test will essentially be the same, but require less overall boilerplate and code.

这篇关于Py.test:对类中的测试用例进行参数化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

build conda package from local python package(从本地 python 包构建 conda 包)
How can I see all packages that depend on a certain package with PIP?(如何使用 PIP 查看依赖于某个包的所有包?)
How to organize multiple python files into a single module without it behaving like a package?(如何将多个 python 文件组织到一个模块中而不像一个包一样?)
Check if requirements are up to date(检查要求是否是最新的)
How to upload new versions of project to PyPI with twine?(如何使用 twine 将新版本的项目上传到 PyPI?)
Why #egg=foo when pip-installing from git repo(为什么从 git repo 进行 pip 安装时 #egg=foo)