python Unittest essertionError:0!= []
我是Python Unittest的新手,我正在尝试访问此列表:
def setUp(self):
self.customers = [
{"name": "Mary", "pets": [], "cash": 1000},
{"name": "Alan", "pets": [], "cash": 50},
{"name": "Richard", "pets": [], "cash": 100},
]
要进行此测试:
def test_customer_pet_count(self):
count = get_customer_pet_count(self.customers[0])
self.assertEqual(0, count)
我创建了此功能:
def get_customer_pet_count(customer_number):
if ["pets"] == 0 or ["pets"] == []:
return 0
return customer_number["pets"]
但是我一直遇到此错误: essertionError: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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
让我们看一下这部分,
get_customer_pet_count
函数:首先,您不是将其传递给“客户号码”或索引,而是将其传递给实际的客户字典。像
{“名称”:“玛丽”,“宠物”:[],“现金”:1000}
。其次,此比较:
[“ PETS”] == 0
检查“如果一个带有一个元素的列表,即字符串'Pets'等于数字0”。这永远不可能是真的。 永远不会 等于 一个数字。列表 使用一个元素,字符串“宠物”等于一个空列表”。那也永远不会是真的。空列表不能等于非空的列表。
如果您将其编写为
def get_customer_pet_count(customer):
,则可能更清楚。您正在将其传递给客户 info 的字典,而不是客户 number 。另外,您的功能说pet_count
,因此应该是宠物列表的长度:*忽略用户定义的类型伪造该行为。
Let's take a look at this part, the
get_customer_pet_count
function: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 sayspet_count
so it should be the length of the pets list:*Ignoring user-defined types faking that behaviour.
self.customers [0]是空列表[]。您应该使用len(self.customers [0])或这样修改函数:
self.customers[0] is empty list []. You should use len(self.customers[0]) or modify the function like this: