Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Django Basics Test Time View Tests

nicole lumpkin
PLUS
nicole lumpkin
Courses Plus Student 5,328 Points

Step Model Tests

In the setUp() method, why do we instantiate a Course instance using self.course? Why not simply assign to a variable?

self.course = Course.objects.create(title='title, description='description')
# versus
course = Course.objects.create(title='title, description='description')

It seems that when you create a model instance in the setUp method we use self. But if we create a model instance in a test method, you simply use a variable. Can anyone weigh in on this?

1 Answer

Haydar Al-Rikabi
Haydar Al-Rikabi
5,971 Points

From Python docs:

Tests can be numerous, and their set-up can be repetitive. Luckily, we can factor out set-up code by implementing a method called setUp(), which the testing framework will automatically call for every single test we run.

You can only use the same self.variable across multiple functions in a test class:

class MyTestClass():
   def setUp(self):
      self.title = "Python Basics"

   def test_method(self):
      new_title = "Django Forms" # No (self) here because new_title is not used outside its function
      self.assertExact(self.title, "Python Basics") # self.title is passed from setUp()
      self.assertExact(new_title , "Django Forms")

Otherwise, (self) makes it possible to reference a class variable from within a class method.

class MyClass():
   title = "Python Basics" # Defining the variable without (self)

   def __str__(self):
      return self.title # Referring to the variable using (self)