【问题标题】:Script executes perfectly, so why does the unittest throw an IndexError?脚本完美执行,为什么unittest会抛出IndexError?
【发布时间】:2019-11-10 00:01:37
【问题描述】:

我目前正在为 python 脚本编写一些测试。该脚本完全按照我的预期运行,没有任何问题。 我遇到的问题是,当我从单元测试中调用一个函数时,我收到一条:IndexError: list index out of range 消息。

对于下面显示的单元测试,我遵循this 示例。

我无法通过谷歌搜索找到类似的问题,所以我什至不知道从哪里开始。如果我从脚本打印项目,它会打印我期望的值。

def build_message(self, {some other into}):
    # Get email templates
    template = Templates.objects.filter(template_id=1)
    # This next line is what gives me the error.
    fields = template[0]

我在这样的单元测试中调用它:

def test_send_email(self):
    # Mock 'smtplib.SMTP' class
    with patch("smtplib.SMTP") as mock_smtp:
        # Build test message
        to_address = "email@address
        # Build message
        msg = handle_command.build_message(self, {some other info})

我得到的错误是这样的。我不明白为什么这里说索引超出范围,运行我的脚本时效果很好。

    fields = template[0]
  File "/usr/local/lib/python3.5/dist-packages/django/db/models/query.py", line 307, in __getitem__
    return qs._result_cache[0]
IndexError: list index out of range

【问题讨论】:

标签: python


【解决方案1】:

您面临的问题是如何确定测试何时运行

template = Templates.objects.filter(template_id=1)

正在返回一个空集。如果测试类没有导致 Templates 被填充,这就是您将看到的。

【讨论】:

    【解决方案2】:

    您的表中要么根本没有数据,要么至少没有 template_id = 1 的数据。请参阅我刚刚运行的这个测试,它产生了相同的错误(行号实际上不同,但也许我们正在运行不同版本的 Django)。

    >>> from cato.models import *
    >>> Menu.objects.all()
    <QuerySet []>
    >>> m = Menu.objects.filter(id=1)
    >>> len(m)
    0
    >>> m[0]
    Traceback (most recent call last):
      File "<console>", line 1, in <module>
      File "C:\Users\csullivan\responsive\env\lib\site-packages\django\db\models\query.py", line 291, in __getitem__
        return self._result_cache[k]
    IndexError: list index out of range
    >>>
    

    您可以看到我导入了我的模型,并从 Menu 模型中获取所有对象。没有,因为它返回一个空的查询集。然后我在 id=1 上使用过滤器,它是成功的,但也返回一个空查询集,当然长度为零。然后,如果我尝试访问不存在的元素 0,则会收到相同的错误。

    不要忘记 Django TestCase 会创建一组新的空数据库表,您可以使用查询或更常见的夹具来填充它们。

    【讨论】:

    • 谢谢!这很有意义。我不知何故忘记了 Django TestCase 会创建空表。
    猜你喜欢
    • 2013-09-30
    • 2016-08-05
    • 2021-08-04
    • 1970-01-01
    • 1970-01-01
    • 2011-10-10
    • 2011-10-04
    • 1970-01-01
    • 2011-11-30
    相关资源
    最近更新 更多