脚本执行完美,那么为什么单元测试会抛出IndexError?

时间:2019-06-28 01:19:36

标签: python

我目前正在为python脚本编写一些测试。该脚本完全按照我的预期运行,没有任何问题。 我遇到的问题是,当我从单元测试中调用一个函数时,出现了:IndexError:列表索引超出范围消息。

对于下面显示的单元测试,我遵循了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

2 个答案:

答案 0 :(得分:0)

您面临的问题是,在运行测试时如何整理

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

返回一个空集。如果测试类没有引起Templates的填充,这就是您会看到的。

答案 1 :(得分:0)

表中根本没有数据,或者至少没有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创建了一组空数据库表,您可以根据需要用查询或更常用的夹具来填充它们。