Django测试没有得到模型Obj

2024-09-30 14:33:02 发布

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

我只是触及了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)

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

^{pr2}$

我在heroku本地环境中工作,因此我运行以下测试: heroku local:run python manage.py test advertising

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

ValueError: Cannot assign None: "Impression.ad" does not allow null values.

这说明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
    )

Tags: pathintestimageselfgetobjectsos