从灯具返回结构化数据的正确方法是什么?

时间:2019-10-17 16:05:43

标签: python testing pytest

目前,我有这样的设置:

./
  src/
    mylib.py
  tests/
    __init__.py
    conftest.py
    test_mylib.py

mylib.py包含:

def add(x, y):
    return x + y

conftest.py包含:

import attr
import pytest

@attr.s(slots=True)
class AdditionTestCase:
    input1 = attr.ib()
    input2 = attr.ib()
    output_expected = attr.ib()

@pytest.fixture
def addition_test_case() -> AdditionTestCase:
    # make up some data
    return AdditionTestCase(1, 2, 3)

test_mylib.py包含:

from mylib import add
from tests.conftest import AdditionTestCase

def test_add(addition_test_case: AdditionTestCase):
    input1 = addition_test_case.input1
    input2 = addition_test_case.input2
    output_expected = addition_test_case.output_expected

    output_actual = add(input1, input2)
    assert output_actual == output_expected

这是出于任何原因的问题吗?有更好的方法吗?如果从类型导入定义被认为是不好的做法,则可以将类型定义移到conftest.py之外。

1 个答案:

答案 0 :(得分:1)

通常这可以通过不带额外类型的参数化来解决

@pytest.mark.parametrize("left, right, expected_output", [
   (1, 1, 2),
   (2, 2, 4),
]
def test_add(left, right, expected_output):
  output = add(left, right)
  assert output == expected_output