Lesson 37 - JSON & Test Fixtures
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
- JSON data
- Test Fixtures
Catalog of Design Patterns
- Design Patterns
- Use this catalog of patterns as you work on projects
JSON data
- https://www.w3schools.com/python/python_json.asp
```python import json
x = { "model": "book.chapter", "pk": 2, "fields": { "book": 1, "order": 2, "title": "Technical Debt", "markdown": "", "html": "", "document": "02.md" } }
sort the result alphabetically by keys:
print(json.dumps(x, indent=4, sort_keys=True)) ```
Working with Data
- dumpdata
- loaddata
- tests with data
dumpdata
- Export data records to a file
- Select Module and Table to export
- Indent for readability
```bash $ python manage.py dumpdata
$ python manage.py dumpdata --indent 4 book.chapters ```
loaddata
- Import data records from a file
- Select the file to read
```bash $ python manage.py loaddata
$ python manage.py loaddata Documents/Test/data.chapters.json ```
Tests with Data
- Build data in database
- Export JSON
- Import to restore in blank or existing database
Test Fixtures
- Snapshot of JSON data
- Start your tests from a known state
- Setup the test database to run tests
```python class BookFixtureTest(TestCase): fixtures = ['Documents/Test/data.json']
def test_with_data(self):
self.assertEqual(len(Author.objects.all()), 1)
self.assertEqual(len(Book.objects.all()), 2)
self.assertEqual(len(Chapter.objects.all()), 70)
```
Django Documents
BUILD
Practice
- Clone my repo and study the code in 'week13/BookBuilder'
- Read the Design Patterns
- Build the code and experiment with it