gpt4 book ai didi

python - 如何使用 pytest 测试简单的堆栈类

转载 作者:行者123 更新时间:2023-12-01 07:47:27 24 4
gpt4 key购买 nike

我正在尝试编写一个简单的堆栈类来了解 TDD。但问题是它无法使用正确的代码通过测试。

这是代码:

class Stack:
def __init__(self):
self.stack = []

def push(self,new_item):
self.stack.append(new_item)

def pop(self):
return int(self.stack.pop(0))

这是测试类:

import pytest
from Stack import Stack

def test_it_can_push():
stack = Stack()
stack.push(2)
assert stack.stack is [2]

这是错误:

    def test_it_can_push():
stack = Stack()
stack.push(2)
> assert stack.stack is [2]
E assert [2] is [2]
E + where [2] = <Stack.Stack instance at 0x7f2273491560>.stack

test_stack.py:7: AssertionError

有人可以告诉我如何解决这个问题吗?

最佳答案

您正在使用 is 进行身份检查(id——CPython 中的内存位置),它永远不会相等,因为操作数是两个不同的列表(其中是可变对象),尽管它们具有相同的元素,您可以使用 id 进行检查。

进行股权测试:

assert stack.stack == [2]

关于python - 如何使用 pytest 测试简单的堆栈类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56400021/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com