我有3个文件module.py,其中包含一个示例函数,用于测试输入是否为数字。我有一个名为test_mymodule_long.py是成功测试和使用py.test和hypothesis通过几种类型的输入文件。我使用的Python 3.6,但这不应该(如果你不是,只是删除类型提示)。对于这个特定的功能,将这些分离出来对我来说没有帮助;如果假设找到了边缘案例,我只想知道有问题的输入和引发的异常。因此,我想按照test_mymodule_short.py中的说明编写此测试,但这不起作用。使用假设和py.test来测试python中的复合策略,我必须一次测试它们吗?
我的问题是这样的:有没有比在test_mymodule_long.py中更有效地写出假设策略的方法?
下面是每个文件中的代码:
'''
mymodule.py
'''
from typing import Union
Number = Union[int, float]
def is_numeric(x: Number):
try:
y = float(x)
return True
except:
return False
# -------------------------------------------
'''
test_mymodule_long.py [This code works]
(using pytest to discover tests automatically)
'''
from hypothesis import given, example
import hypothesis.strategies as st
import mymodule
@given(st.integers())
def test_is_numeric_integer(num):
result = stats.is_numeric(num)
assert isinstance(result, bool)
@given(st.floats())
def test_is_numeric_float(num):
result = stats.is_numeric(num)
assert isinstance(result, bool)
@given(st.text())
def test_is_numeric_text(num):
result = stats.is_numeric(num)
assert isinstance(result, bool)
@given(st.lists(st.floats()))
def test_is_numeric_list(num):
result = stats.is_numeric(num)
assert isinstance(result, bool)
# -------------------------------------------
'''
test_mymodule_short.py [This code fails!]
(using pytest to discover tests automatically)
'''
from hypothesis import given, example
import hypothesis.strategies as st
import mymodule
@given(st.integers())
@given(st.floats())
@given(st.text())
@given(st.lists(st.floats()))
def test_is_numeric_list(num):
result = mymodule.is_numeric(num)
assert isinstance(result, bool)
请注意,我不认为该错误信息真正的问题在这里,它更是一个这-isn't知识 - 你 - 做 - 的它的情况,我正在寻求建议是否有一种紧凑的方法来测试一个功能与多种假设策略。另外,我知道一个正确的is_numeric函数会被编程得不同(假设你真的需要这样的函数)。我也知道这里指出的测试不足以知道它是否工作。这些只是让我的问题清楚的例子。