使用断言后,valuerror使用np.all()或np.any()

时间:2017-01-27 11:26:42

标签: 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.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()

1 个答案:

答案 0 :(得分:0)

assert np.all(obs == expected_output)有效:

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 ================================