Skip to content
Advertisement

Python unittest AssertionError: 0 != []

I’m new to Python unittest and I’m trying to access this list:

    def setUp(self):
        self.customers = [
            {"name": "Mary", "pets": [], "cash": 1000},
            {"name": "Alan", "pets": [], "cash": 50},
            {"name": "Richard", "pets": [], "cash": 100},
        ]

to do this test:

    def test_customer_pet_count(self):
        count = get_customer_pet_count(self.customers[0])
        self.assertEqual(0, count)

I’ve created this function:

def get_customer_pet_count(customer_number):
    if ["pets"] == 0 or ["pets"] == []:
        return 0
    return customer_number["pets"]

But I keep getting this error: AssertionError: 0 != []

Can someone help explain what I’m doing wrong in the function please?

Advertisement

Answer

Let’s take a look at this part, the get_customer_pet_count function:

def get_customer_pet_count(customer_number):
    if ["pets"] == 0 or ["pets"] == []:
        return 0
    return customer_number["pets"]

First, you’re not passing it a “customer number” or index, you’re passing it the actual customer dictionary. Like {"name": "Mary", "pets": [], "cash": 1000}.

Second, this comparison: ["pets"] == 0 checks “if a list with one element, the string ‘pets’, is equal to the number 0”. This can never be true. A list will never be equal to a number.*

The next comparison ["pets"] == [] is checking “if the list with one element, the string ‘pets’ is equal to an empty list”. That can also never be true. An empty list cannot be equal to a non-empty list.

If you wrote it as def get_customer_pet_count(customer): then it might be clearer. You’re passing it the dictionary with the customer info, not the customer number. Also, your function says pet_count so it should be the length of the pets list:

def get_customer_pet_count(customer):
    return len(customer["pets"])

*Ignoring user-defined types faking that behaviour.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement