mercredi 30 décembre 2015

How do I test a model in django?

More specifically, I am following a course and the only import so far is TestCase from django.test. We are given a coding challenge related to testing of a model. So, this is very specific. I'm not sure how to accomplish what is being asked. Let me show what is asked first: "Now add a test that creates an instance of the Writer model and, using self.assertIn, make sure the email attribute is in the output of the mailto() method."

So, the model in question has this:

class Writer(models.Model):
    name = models.CharField(max_length=255)
    email = models.EmailField()
    bio = models.TextField()

    def __str__(self):
        return self.name

    def mailto(self):
        return '{} <{}>'.format(self.name, self.email)

What I did to test this, is (all in one file but in steps here):

from .models import Writer
'''that worked fine...'''

Then we have the following (My task part was to fill in everything from def test_writer_creation(self) on):

class WriterModelTestCase(TestCase):
'''Tests for the Writer model'''
    def test_writer_creation(self):
        writer = Writer.objects.create(
            name = "Bruce Whealton",
            email = "bruce@example.com",
            bio = "Here is a short bio about bruce for testing purposes."
         )
  self.assertIn('bruce@example.com', writer.mailto())

The writer instance should be ok, it seems straightforward. The mailto function should just return a string. So, in this file, articles/tests.py should I not expect the email value to be in the string output from writer.mailto()?
What am I doing wrong?

Thanks, Bruce

Aucun commentaire:

Enregistrer un commentaire