Python测试assertContains - AttributeError:'响应'对象没有属性'流媒体'

时间:2018-03-16 16:27:11

标签: python testing

我正在使用assertContains测试html响应对象:

from __future__ import unicode_literals

from django.test import TestCase

from .signals import check_mailchimp_campaign
from django.db.models.signals import post_save

from wagchimp.models import WagchimpCampaign, MailchimpSetting

class WagchimpCampaignTestCase(TestCase):

    fixtures = ['sites.json']

    def setUp(self):
        MailchimpSetting.objects.create(api_key='9b69a8e3a3116aea899-us1',
            note='names', site_id='2')
        a = WagchimpCampaign.objects.create(name="jons",
            campaign_id="1", subject_line="New email",
            top_line="Hi")
        apikey = MailchimpSetting.objects.get().api_key
        a.rss_feed.add = 'skeletal'

    def test_mailchimp_api_response_on_signal_handler(self):
        r = check_mailchimp_campaign(post_save)
        status_code = str(r.status_code)
        self.assertEquals(status_code, '200')

在以下信号中测试与Mailchimp API的连接:

from django.db.models.signals import post_save
from django.dispatch import receiver
import requests

from .models import RSSFeed, WagchimpCampaign, MailchimpSetting

@receiver(post_save, sender=WagchimpCampaign)
def check_mailchimp_campaign(sender, **kwargs):
    apikey = MailchimpSetting.objects.get().api_key
    r = requests.get('https://us1.api.mailchimp.com/3.0/',
        auth=('user', apikey))
    return r

我收到了错误:

Traceback (most recent call last):
  File "/Users/technical/code/pb/tests.py", line 46, in test_mailchimp_api_response_on_signal_handler
    self.assertContains(r, "", status_code=200)
  File "/Users/technical/.virtualenvs/wagtest6-PGdhJpMT/lib/python2.7/site-packages/django/test/testcases.py", line 385, in assertContains
    response, text, status_code, msg_prefix, html)
  File "/Users/technical/.virtualenvs/wagtest6-PGdhJpMT/lib/python2.7/site-packages/django/test/testcases.py", line 360, in _assert_contains
    if response.streaming:
AttributeError: 'Response' object has no attribute 'streaming'

响应对象附带200状态代码,似乎格式正确。如果没有流属性,为什么会失败?

1 个答案:

答案 0 :(得分:1)

有关assertContains使用Response实例的文档中的提及,具体是指从Django测试客户端返回的内部Response类,描述为further up that page

无论如何,正如我所提到的,你绝对不应该在测试中查询外部API。根据定义,单元测试应该只运用代码单元 - 其他一切都是外部的。测试API是否有效有什么用呢?您应该测试的是,给定API的特定响应,您自己的代码会执行预期的操作。你可以使用模拟。