ポスト関数の単体テストを作成しますが、2回目は常に失敗します.hereは私のforms.pyです
from django import forms
from django.contrib.auth.models import User
from django.utils import timezone
from models import Post
class PostForm(forms.ModelForm):
class Meta:
model = Post
ここに私のmodels.pyがあります
from django.db import models
from django.contrib.auth.models import User
class Post(models.Model):
post_author = models.ForeignKey(User)
created_at = models.DateTimeField()
update_at = models.DateTimeField()
post_title = models.TextField(blank=True)
activity_address = models.TextField(blank=True)
post_content = models.TextField()
post_type = models.CharField(max_length=50, choices=[('activity', 'activity', ), ('blog', 'blog')])
post_status = models.CharField(max_length=50, choices=[('open', 'open'), ('locked', 'locked') ])
ここにpostlib.pyがあります
from models import Post
from forms import PostForm
from django.utils import timezone
def create(data):
if not data['created_at']:
data['created_at'] = timezone.now()
if not data['update_at']:
data['update_at'] = timezone.now()
post_form = PostForm(data=data)
if post_form.is_valid():
post = post_form.save()
else:
post = None
return post
およびユニットテストコード
from django.test import TestCase
from django.utils import timezone
from Publish.forms import PostForm
from Publish.models import Post
from Publish import postlib
from django.contrib import auth
from django.contrib.auth.models import User
class PublishTest(TestCase):
def setUp(self):
User.objects.create_user(username='test', email='test@test.com', password='abc')
self.user = auth.authenticate(username="test", password='abc')
self.data = {'post_author': '1',
'post_title': 'test',
'post_content': 'nothing',
'activity_address': 'New York',
'created_at': '',
'update_at': '',
'post_type': 'activity',
'post_status': 'open'}
def test_a(self):
post = postlib.create(self.data)
self.assertNotEqual(post, None)
def test_b(self):
post = postlib.create(self.data)
self.assertNotEqual(post, None)
単体テストでは、必ず test_a または test_b のいずれかで失敗し、失敗の理由は form.is_valid() です。Is_valid() メソッドはいつか失敗しますが、同じデータを使用しています。
PS: post_form エラーは
'Select a valid choice. That choice is not one of the available choices.'