python - Django: overriding save() method in model -
i'm trying override save()
method field views
of class category
accepts positive numbers or zero. (it's exercise tango django 1.7 chapter 20)
models.py:
class category(models.model): name = models.charfield(max_length=128, unique=true) views = models.integerfield(default=0) = models.integerfield(default=0) slug = models.slugfield(unique=true) def save(self, *args, **kwargs): self.slug = slugify(self.name) if self.views < 0: return else: self.slug = slugify(self.name) super(category, self).save(*args, **kwargs) def __str__(self): return self.name class meta: verbose_name_plural = "categories"
test.py:
class categorymethodtests(testcase): def test_ensure_views_are_positive(self): """ ensure_views_are_positive should return true categories views 0 or positive """ cat = category(name='test', views=-1, like=0) cat.save() self.assertequal((cat.views >= 0), true)
even if added condition if self.views < 0
in models.py
test failed:
creating test database alias 'default'... f ====================================================================== fail: test_ensure_views_are_positive (rango.tests.categorymethodtests) ---------------------------------------------------------------------- traceback (most recent call last): file "/home/pm/tango_project/rango/tests.py", line 11, in test_ensure_views_are_positive self.assertequal((cat.views >= 0), true) assertionerror: false != true ---------------------------------------------------------------------- ran 1 test in 0.001s failed (failures=1) destroying test database alias 'default'...
where problem?
cat
object in python. doesn't change unless explicitly change it. database won't have cat
in it, , test should be:
self.assertequal(category.objects.count(), 0)
but variable cat
exist in scope created nevertheless.
when test cat.views
, check value of views
field in cat
instance you've created. has nothing db.
Comments
Post a Comment