1

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

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

4

1 回答 1

1

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

做权益测试:

assert stack.stack == [2]
于 2019-05-31T18:23:29.047 回答