Django测试没有获得模型对象

时间:2018-01-31 11:53:08

标签: python django testing heroku django-models

我只是在Django中进行测试。这是我在tests.py内的测试代码:

class AdvertisingTests( TestCase ):

    def test_get_ad( self ):
        '''
        Test if the get ad feature is working, should always load an ad
        '''
        url = reverse('advertising:get_ad')
        response = self.client.get( url )
        self.assertEqual(response.status_code, 200)

此测试只是对应返回广告的视图的基本测试。这是视图代码:

from .models import Ad, Impression

def get_ad(request):
    FirstAd = Ad.objects.first()

    # +1 impression
    Impression.objects.create(ad = FirstAd)

    import json
    data = { 'url': FirstAd.url, 'image_url': FirstAd.image.url, 'title': FirstAd.title, 'desc': FirstAd.desc }
    json_data = json.dumps( data )
    return HttpResponse(json_data, content_type='application/json')

我在heroku本地环境中工作,所以我运行这样的测试: heroku local:run python manage.py test advertising

此测试失败,来自Impression.objects.create(ad = FirstAd)行:

  

ValueError:无法分配无:" Impression.ad"不允许null   值。

这告诉我的是FirstAd对象为空。好的,所以我把这样的本地shell结束:heroku local:run python manage.py shell来仔细检查。复制该代码没有错误:

In [2]: from advertising.models import Ad, Impression

In [3]: print Ad.objects.first()
Flamingo T-Shirt Corporation

In [4]: FirstAd = Ad.objects.first()

In [5]: Impression.objects.create(ad = FirstAd)
Out[5]: <Impression: Impression object>

In [6]: exit()

所以我有点卡住了。好像测试人员正在访问一个空数据库。这是测试套件的正确和期望的功能吗?

谢谢!

更新

好的,所有这一切都很正常,我应该知道。将setUp函数添加到我的测试类以初始化数据是我需要做的。像这样:

from django.core.files.uploadedfile import SimpleUploadedFile

def setUp(self):
    test_user = User.objects.create_user(username='testuser', password='12345')

    this_path = os.path.abspath(os.path.dirname(__file__))
    banner_image = os.path.join(this_path, "static/advertising/images/pic01.jpg")
    mobile_image = os.path.join(this_path, "static/advertising/images/pic02.jpg")

    Ad.objects.create(
        title = "Test Title",
        desc = "Test Description",
        image = SimpleUploadedFile(name='test_image.jpg', content=open(banner_image, 'rb').read(), content_type='image/jpeg'),
        mobile_image = SimpleUploadedFile(name='test_image.jpg', content=open(mobile_image, 'rb').read(), content_type='image/jpeg'),
        url = "https://www.jefferythewind.com",
        user = test_user
    )

1 个答案:

答案 0 :(得分:3)

Django测试创建空的临时数据库,请参阅docs,这将在测试后销毁。

使用setUp方法

预先填充测试数据库的数据
class AdvertisingTests(TestCase):
    def setUp(self):
        Ad.objects.create(name="myAd")

您也可以使用fixtures