Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unittest.TestCase Method to Verify Arrays are of Equal Length

How do I pass variables declared from the python command line to the testcase instance? Edit: a and b are inputs to the method func().

a = [1,2,3]
b = np.array([1,2])

Filename: code.py

import unittest
import numpy as np

def func(a,b)
    c = a*b
    return (c)

class TestCases(unittest.TestCase):
    def test_length_a_equals_length_b(self):
        self.assertEqual(len(a), len(b), msg="len(a) != len(b)")

How would I input a and b into the test case, so an error occurs when they are not the same length?

I get the following error when I run the file from terminal:

ERROR: test_a_len_equals_len_b (main.TestCases)  
---------------------------------------------------------------------- 
Traceback (most recent call last): 
 File "code.py", in test_length_a_equals_length_b 
   self.assertEqual(len(a), len(b), msg="len(a) != len(b)") 
NameError: global name 'a' is not defined
like image 294
MyopicVisage Avatar asked Oct 26 '25 07:10

MyopicVisage


1 Answers

Instead of using assertNotEqual, use assertEqual. This will fail when a and b aren't the same length.

Edit to answer the comment: Where are 'a' and 'b' defined? You could just define them in your module scope (just in the begining of code.py file) or you could define then in your test method, like this:

def test_length_a_equals_length_b(self):
    a = [1,2,3]
    b = np.array([1,2])
    self.assertEqual(len(a), len(b), msg="len(a) != len(b)")
like image 59
Juca Avatar answered Oct 28 '25 20:10

Juca



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!