我正在做一個小專案,我希望能夠測驗 post 方法,如果電子郵件不存在,則保存到資料庫中,并呈現到 index.html 以獲取下面的視圖。我查看了 YouTube 視頻和博客教程,但似乎找不到我正在尋找的答案。我已經包含了模型、視圖和我當前的測驗。
模型:
class EmailList(models.Model):
email = models.TextField(unique=True)
看法:
def home(request):
# Join Email List
if request.method == 'POST':
if request.POST.get('email'):
email = request.POST.get('email')
if not EmailList.objects.filter(email=email).exists():
emailInput = EmailList()
emailInput.email = email
emailInput.save()
return render(request, 'email/index.html', {})
else:
return render(request, 'email/index.html', {})
測驗我到目前為止:
from django.test import TestCase
from tasckq.models import EmailList
class HomeViewTest(TestCase):
@classmethod
def setUpTestData(cls):
# Create a new email to test
EmailList.objects.create(email="[email protected]")
def test_home_view_url_exists_at_desired_location(self):
response = self.client.get('')
self.assertEqual(response.status_code, 200)
def test_home_view_post_request_method(self):
response = self.client.post('', {'email' : '[email protected]'})
self.assertEqual(response.status_code, 200)
def test_home_view_save_email(self):
self.assertEqual(EmailList.objects.count(), 1)
uj5u.com熱心網友回復:
你不應該EmailList在你的setUpTestData方法中創建一個實體,因為你想檢查你的視圖是否正確地創建了一個新實體,現在你在測驗之前手動創建一個新實體。嘗試這個:
from django.test import TestCase
from tasckq.models import EmailList
class HomeViewTest(TestCase):
def test_home_view(self):
# Tests the get method
response = self.client.get('')
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, template_name='email/index.html')
# Tests the post method
email = '[email protected]'
response = self.client.post('', {'email' : email})
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, template_name='email/index.html')
# A new EmailList instance has been successfully created
self.assertTrue(EmailList.objects.filter(email=email).exists())
response = self.client.post('', {'email' : email})
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, template_name='email/index.html')
# A new EmailList instance has not been created because the email was already in use
self.assertEqual(EmailList.objects.count(), 1)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/453634.html
