Search code examples
pythonarraysnumpyunit-testing

ValueError for numpy array with unittest Python


I have the the following question.

I have these function:

def string_to_2Darray(flat_string):

    """converts a string of type '0,1,0,1,1,1,0,1,0'"""

    array1d = np.fromstring(flat_string, dtype=int, sep=',')
    return np.reshape(array1d, (-1,3)) 

and I wrote a unittest Class for this function which goes like that:

class StringTo2DArray(unittest.TestCase):

    def test_string_2DArray(self):
        string_example_0 = '0,1,0,1,1,1,0,1,0'
        array_example_0 = string_to_2Darray(string_example_0)
        print(array_example_0)
        print(type(array_example_0))
        self.assertEqual([[0,1,0],[1,1,1],[0,1,0]], array_example_0)

See that I am adding some print statements within the body of the test_string_2Darray module within the StringTo2DArray class in the unittest.

When I run python -m unittest then I get the following Error message:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I don't know why it happens since the string is correctly transformed to 2D numpy array and does not match the array [[0,1,0],[1,1,1],[0,1,0]] that I passed in the assert. Equal for my test.


Solution

  • @Roger Almengor,

    As @lllllIIIIll replied, it's a known bug in Python's TestCase implementation. The assertEqual(a, b) implemenation assumes the a==b operation will return one True or one False, but if it returns a composited value which including multiple boolean values, it'll raise this error. E.g, if the a, b are numpy's data array or Tensorflow's tensor, this bug will be triggered.

    There are two solutions to work around this bug:

    1. Converting the numpy data arry or tensors to a list, because a_list==b_list will return one boolean value, so TestCase assertEqual() could handle it correctly.
    2. Using numpy or tesorflow's customized version TestCase implementation, they have their own versions' for assertEqual() function implenentation for numpy array and tensors, e.g. assert_array_equal()# In numpy, or assertAllEqual() ## in Tensorflow.test.TestCase