Python ValueError在使用断言后使用np.all()或np.any()
我有以下代码:Python ValueError在使用断言后使用np.all()或np.any(),python,numpy,pytest,Python,Numpy,Pytest,我有以下代码: import numpy as np class Variables(object): def __init__(self, var_name, the_method): self.var_name = var_name self.the_method = the_method def evaluate_v(self): var_name, the_method = self.var_name, self.
import numpy as np
class Variables(object):
def __init__(self, var_name, the_method):
self.var_name = var_name
self.the_method = the_method
def evaluate_v(self):
var_name, the_method = self.var_name, self.the_method
if the_method == 'diff':
return var_name[0] - var_name[1]
这个测试代码是:
import unittest
import pytest
import numpy as np
from .variables import Variables
class TestVariables():
@classmethod
def setup_class(cls):
var_name = np.array([[1, 2, 3], [2, 3, 4]])
the_method = 'diff'
cls.variables = Variables(var_name, the_method)
@pytest.mark.parametrize(
"var_name, the_method, expected_output", [
(np.array([[1, 2, 3], [2, 3, 4]]), 'diff', np.array([-1, -1, -1]) ),
])
def test_evaluate_v_method_returns_correct_results(
self, var_name, the_method,expected_output):
var_name, the_method = self.variables.var_name, self.variables.the_method
obs = self.variables.evaluate_v()
assert obs == expected_output
if __name__ == "__main__":
unittest.main()
我想计算第一个和最后一个元素之间的差值
结果应该是一个数组[-1,-1,-1]
如果我尝试运行该测试,它将提供:
ValueError: The truth value of an array with more than one element is ambiguous.
Use a.any() or a.all()
在我的情况下,我不确定如何使用(如果必须的话)np.all()。断言np.all(obs==预期输出)
工作:
def test_evaluate_v_method_returns_correct_results(
self, var_name, the_method,expected_output):
var_name, the_method = self.variables.var_name, self.variables.the_method
obs = self.variables.evaluate_v()
assert np.all(obs == expected_output)
测试它:
py.test np_test.py
================================== test session starts ===================================
platform darwin -- Python 3.5.2, pytest-2.9.2, py-1.4.31, pluggy-0.3.1
rootdir: /Users/mike/tmp, inifile:
plugins: hypothesis-3.4.0, asyncio-0.4.1
collected 1 items
np_test.py .
================================ 1 passed in 0.10 seconds ================================
对我错过了。它很好用,谢谢!(如果你能帮忙,我对此有问题)