Skip to content

Commit

Permalink
(test): add 3 simple tests covering core usage
Browse files Browse the repository at this point in the history
- all 3 are taken straight from the README as well, and cover
  whitelists, one-to-one relations, and foreign key relations
  - should add more tests for larger sets of relations, but these do
    cover the vast majority of functionality and most common use cases
    (that are even in the README)

(env): gitignore pytest_cache directory
  • Loading branch information
agilgur5 committed Oct 26, 2019
1 parent 420378d commit db19da0
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# we use multiple versions of Python and deps, so lockfile doesn't quite fit
# may add it back in later once Poetry usage stabilizes
poetry.lock
.pytest_cache/

# Created by https://www.gitignore.io/api/python

Expand Down
57 changes: 57 additions & 0 deletions tests/test_project/test_app/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import pytest
from .models import User, Settings, Post


@pytest.mark.django_db
def test_whitelist():
new_user = User.objects.create(
name='John Doe',
email='[email protected]',
)

assert new_user.serialize() == {'name': 'John Doe'}


@pytest.mark.django_db
def test_one_to_one():
new_user = User.objects.create(
name='John Doe',
email='[email protected]',
)
Settings.objects.create(user=new_user)

new_user_refreshed = (User.objects.select_related('settings')
.get(pk=new_user.pk))

assert new_user_refreshed.serialize() == {'name': 'John Doe'}
# recursively serialize Settings object by passing the join in
assert new_user_refreshed.serialize('settings') == \
{'name': 'John Doe', 'settings': {'email_notifications': False}}


@pytest.mark.django_db
def test_foreign_key():
new_user = User.objects.create(
name='John Doe',
email='[email protected]',
)
Post.objects.create(user=new_user, text='wat a nice post')
Post.objects.create(user=new_user, text='another nice post')

serialized_posts = [
{'id': 1, 'text': 'wat a nice post', 'user_id': 1},
{'id': 2, 'text': 'another nice post', 'user_id': 1}
]

# called on QuerySet
# adds an _id to the foreign key name, just like when using `.values()`
assert Post.objects.all().serialize() == serialized_posts

# called on Manager
assert User.objects.get(pk=new_user.pk).post_set.serialize() == \
serialized_posts

# recursively serialize Post objects by passing the join in
assert (User.objects.prefetch_related('post_set').get(pk=new_user.pk)
.serialize('post_set')) == \
{'name': 'John Doe', 'post_set': serialized_posts}

0 comments on commit db19da0

Please sign in to comment.