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



im 尝试编写一个简单的堆栈类来了解 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]

最新更新