Django form test fails -


i'm trying perform simple test on form confirm it's not valid when there no data given , valid when data given.

when running tests pytest (py.test) test no data works fine i'm getting error test data present:

assertionerror: should valid if data given e       assert false true e        +  false = <bound method baseform.is_valid of <postform bound=true, valid=false, fields=(title;content;author;image;published;draft;category;read_time)>>() e        +    <bound method baseform.is_valid of <postform bound=true, valid=false, fields=(title;content;author;image;published;draft;category;read_time)>> = <postform bound=true, valid=false, fields=(title;content;author;image;published;draft;category;read_time)>.is_valid  posts/tests/test_forms.py:21: assertionerror 

my models.py:

from django.db import models django.core.urlresolvers import reverse django.conf import settings django.db.models.signals import pre_save django.utils import timezone  django.utils.text import slugify .utils import read_time  class category(models.model):     name = models.charfield(max_length=120, unique=true)     timestamp = models.datetimefield(auto_now_add=true, auto_now=false)     updated = models.datetimefield(auto_now_add=false, auto_now=true)     slug = models.slugfield(unique=true)      def __str__(self):         return self.name      def save(self, *args, **kwargs):         if not self.id: # prevent changing slug on updates             self.slug = slugify(self.name)         return super(category, self).save(*args, **kwargs)  def upload_location(instance, filename):     return '%s/%s'%(instance.id, filename)  class postmanager(models.manager):     def active(self):         return super(postmanager, self).filter(draft=false, published__lte=timezone.now())  class post(models.model):     title = models.charfield(max_length=120)     slug = models.slugfield(unique=true)     content = models.textfield()     author = models.foreignkey(settings.auth_user_model, on_delete=models.cascade)     image = models.imagefield(         upload_to=upload_location,         null=true,         blank=true)     timestamp = models.datetimefield(auto_now_add=true, auto_now=false)     updated = models.datetimefield(auto_now_add=false, auto_now=true)     published = models.datefield(auto_now=false, auto_now_add=false)     draft = models.booleanfield(default=false)     category = models.manytomanyfield(category)     read_time = models.integerfield(default=0)     objects = postmanager()      def __str__(self):         return self.title      def get_absolute_url(self):         return reverse('posts:detail', kwargs={'pk': self.pk})      def save_no_img(self):         self.image = none         return super(post, self).save()   def create_slug(instance, new_slug=none):     slug = slugify(instance.title)     if new_slug not none:         slug = new_slug     qs = post.objects.filter(slug=slug).order_by("-id")     exists = qs.exists()     if exists:         new_slug = "%s-%s" %(slug, qs.first().id)         return create_slug(instance, new_slug=new_slug)     return slug   def pre_save_post_receiver(sender, instance, *args, **kwargs):     if not instance.slug:         instance.slug = create_slug(instance)     html_content = instance.content     instance.read_time = read_time(html_content)  pre_save.connect(pre_save_post_receiver, sender=post) 

my forms.py:

from django import forms .models import post pagedown.widgets import pagedownwidget  class postform(forms.modelform):     published = forms.datefield(widget=forms.selectdatewidget)     content = forms.charfield(widget=pagedownwidget())     class meta:         model = post         # fields = ['author', 'title', 'content', 'image', 'draft', 'published', 'category']         exclude = ['objects', 'updated', 'timestamp', 'slug'] 

test_forms.py:

import pytest .. import forms posts.models import category mixer.backend.django import mixer pytestmark = pytest.mark.django_db   class testpostform():     def test_empty_form(self):         form = forms.postform(data={})         assert form.is_valid() false, 'should invalid if no data given'      def test_not_empty_form(self):         staff_user = mixer.blend('auth.user', is_staff=true)         category = mixer.blend('posts.category')         data={'content': 'some content',             'author': staff_user,             'title': 'some title',             'category': category,}         form = forms.postform(data=data)         assert form.is_valid() true, 'should valid if data given' 

update: collected more specific errors using:

assert form.errors == {}, 'should empty' 

errors:

{'author': ['select valid choice. choice not 1 of  available choices.'], 'category': ['enter list of values.'], 'published': ['this field required.'], 'read_time': ['this field required.']} 

how address them?

update 2: nadège suggested modified data include published , read_time, changed category list , created user without mixer.

staff_user = user.objects.create_superuser(is_staff=true,                                         email='oo@gm.com',                                         username='staffuser',                                         password='somepass') category = mixer.blend('posts.category') today = date.today() data={'content': 'some content',     'author': staff_user,     'title': 'some title',     'published': today,     'read_time': 1,     'category': [category],} 

there still error regarding 'author':

{'author': ['select valid choice. choice not 1 of available choices.']}

update 3: reason 'author' had provided id, working code test looks this:

class testpostform():     def test_empty_form(self):         form = forms.postform(data={})         assert form.is_valid() false, 'should invalid if no data given'      def test_not_empty_form(self):         staff_user = mixer.blend('auth.user')         category = mixer.blend('posts.category')         today = date.today()         data={'content': 'some content',             'author': staff_user.id,             'title': 'some title',             'published': today,             'read_time': 1,             'category': [category],}         form = forms.postform(data=data)         assert form.errors == {}, 'shoud empty'         assert form.is_valid() true, 'should valid if data given' 

ok when have invalid form, first thing check why, errors of form. new information can fix each problem. form has 4 validations errors. last 2 pretty straightforward.

'published': ['this field required.'], 'read_time': ['this field required.'] 

those 2 fields in form required didn't filled them. have 2 options,

  • add value fields in data give form
  • remove fields form: add them exclude

you can set published field not required this:

published = forms.datefield(widget=forms.selectdatewidget, required=false) 

for read_time, field required or not, depending on corresponding field in model. if model field not nullable, field in form set required.

next there

'category': ['enter list of values.'] 

you provided value type not expected. category in model manytomany can't give 1 category, must list (even if has 1 element!)

'category': [category], 

finally author,

'author': ['select valid choice. choice not 1 of available choices.'] 

there provided value not valid. validation doesn't recognize value proper auth.user. i'm not familiar mixer, maybe ask new question mixer , django forms foreignkey.


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -