我为post函数编写了unittest,但是第二次,它总是失败。我的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
和unittest代码
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)
在unittest中,它总是有一个失败,无论是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.'