我只是触及 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)
此测试只是对应返回广告的 View 的基本测试。这是查看代码:
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 测试广告
此测试失败,来自 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
)
最佳答案
Django 测试创建空的临时数据库,请参阅 docs ,将在测试后销毁。
要使用数据预填充测试数据库,您可以使用 setUp
方法:
class AdvertisingTests(TestCase):
def setUp(self):
Ad.objects.create(name="myAd")
您也可以使用 fixtures .
关于python - Django 测试没有获取模型对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48541523/