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

标签 python pytest

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

相关文章:

python - 如何在Python中执行断言自省(introspection)

python - 如何在不生成重复结果但使用固定数量的字符 Python 的情况下生成排列

python - Py.test mixin类无法访问 `self`

Python层无法读取caffe框架中的hdf5文件

javascript - 屏幕抓取建议 : Interactive graph

python - 在独立的 pytest 测试中使用 unittest 类断言(如 assertNotIn)的最佳实践?

python - 我可以重试 Pytest 中失败的测试吗

python - 最无缝的 TDD/测试技术

python - 使用 gensim 加载 FastText 的法语预训练模型时出错

python - 无法为 pyjq 构建轮子 |没有这样的文件或目录 : 'autoreconf' : 'autoreconf'