(Djangoting)断言

2024-04-27 19:08:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试了一个简单的测试,并在控制台中收到以下错误消息:

 AIL: test_get (navbar.test.ContextManagerTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/media/me/049C11249C1111B2/backup me/Freizeit/Django Projekte/mysitetest/lib/navbar/test.py", line 16, in test_get
    self.assertIs(cm.get('hi/du',0), 'hi')
AssertionError: 'hi' is not 'hi'

我们可以看到在最后一行,cm.get('hi/du',0)返回了'hi'。但是为什么测试失败了呢?在


首先,我认为可能有错误,但代码行都没有:

^{pr2}$

也不是这个:

self.assertIs(['hi'][0],'hi')

也不是这个:

self.assertIs(cm.get('hi',0),'hi')

失败了。在


为了更好地理解,我添加了cm.get(mypattern,number)的代码:

def get(self, mypattern, number):
  parts = mypattern.split('/').strip()
  return parts[number]

以下是失败测试的代码:

def test_get(self):
        cm = context.ContextManager([])

        self.assertIs(cm.get('hi',0), 'hi')
        self.assertIs(cm.get('hi/du',0), 'hi') #this line failed
        self.assertIs(cm.get('hi/du',1), 'du')

看起来split()函数有一些问题,但是,至少,cm.get('hi/du',0)返回了{},就像我们在上面的stacktrace中一样。在

为了记住,我加上了相关的几行:

self.assertIs(cm.get('hi/du',0), 'hi')
    AssertionError: 'hi' is not 'hi'

小细节(我不知道这是否重要):我用python3 manage.py test lib/navbar开始测试。在


你知道为什么失败了吗?或者你至少有一些猜测? 感谢您阅读本文!在


Tags: 代码pytestselfnumbergetlib错误
1条回答
网友
1楼 · 发布于 2024-04-27 19:08:13

您需要的断言方法是assertEqual,而不是assertIs。在

assertEqual(a, b):比较a和b的值

assertIs(a, b):检查a和b是否指向同一个对象,即a和b的id是否相同

相关问题 更多 >