Lesson 39 - Django Test Design
LEARN
Office Hours
- If you need help please attend office hours
- MWF 1:30-2:30 by Zoom
- Zoom: https://unco.zoom.us/j/99180652183
- Email: mark.seaman@unco.edu
Today
- Django Test Design Patterns
Catalog of Design Patterns
- Design Patterns
- Use this catalog of patterns as you work on projects
- Django Tests
Django Tests Design Pattern
- Create tests without thinking
- Build a test suite in 5 minutes
- Generate full test coverage
Steps to Design Pattern
- Define data model
- Define Data Test class
- Define View Test class
- Use template to create automatic code
Django Test Database
- Before every test case a blank database is created
- All database operations are performed on this test database
- Test do not share a database
Setup
- Initialization steps can be added to the setUp function which is run before every test case.
- Objects needed by multiple tests are added to setUp.
python
def setUp(self):
self.user, self.user_args = create_test_user()
self.author = Author.objects.create(user=self.user, name='Mark')
self.course = Course.objects.create(title='BACS 350', author=self.author)
Fixtures
- JSON test fixture can set the blank database to any known state
- Test can be run in that database context
Standard test design
- Use a standard template for generating new tests
- Customize class name, object name, field names
- Comment out all new test code
- Debug one test case at a time
Data Test (CRUD)
- Test for each operation (CREATE, READ, UPDATE, DELETE)
- Use consistent naming
```python class LessonDataTest(TestCase):
def setUp(self):
pass
def test_add_lesson(self):
pass
def test_lesson_list(self):
pass
def test_lesson_edit(self):
pass
def test_lesson_delete(self):
pass
```
Views Test
- Test all five views: list, detail, add, edit, delete
- Use consistent naming
```python class LessonViewsTest(TestCase):
def login(self):
pass
def setUp(self):
pass
def test_lesson_list_view(self):
pass
def test_lesson_detail_view(self):
pass
def test_lesson_add_view(self):
pass
def test_lesson_edit_view(self):
pass
def test_lesson_delete_view(self):
pass
```
Basic tests
- Count objects
- Check object fields
- Test for login check
- Check status code
- Check missing pages
- Check page content
- Check the URL
- Check for redirect
- Ensure bad content not present
Assertions
- Django Test Assertions
- Most useful assertions
- assertTemplateUsed, assertTemplateNotUsed
- assertContains, assertNotContains
- assertEqual, assertNotEqual
- assertTrue, assertFalse
BUILD
Practice
- Clone my repo and study the code in 'week14/CourseBuilder'
- Read the Design Patterns
- Build the code and experiment with it
Course Builder
- Explore the Course Builder App
- Data
- Views
- Templates
- Tests