3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

graphene-django-jwtを使ったsnapshot test

Last updated at Posted at 2019-03-09

使用技術
graphene-django
graphene-django-extras
graphene-django-jwt

Djangoでの認証を作る際に今まではfirebaseを使っていた為、自前でmiddlewareを書いて都度tokenを確認に行く様にしていた。
これに対してテストを書くときはDummyMiddlewareとしてtestuserに対してuidをうまく返していた。

今回djangoで完結できる機能要件のものに対応する為にgraphene-django-jwtを採用した。
かなり良くできていて、middlewareの設定とdecoratorでほぼ実装は終わる。

mutation/create_foo_user.py
class CreateFooUser(graphene.Mutation):
    foo_user = graphene.Field(FooUserType)

    class Arguments:
        email = graphene.String(required=True)
        password = graphene.String(required=True)
        foo_id = graphene.String(required=True)

    @superuser_required
    def mutate(self, info, **kwargs):
        user = FooUser.objects.create_user(**kwargs)
        return CreateFooUser(foo_user=user)

また、これをtestする時にgraphene-django-jwtはJSONWebTokenTestCaseを作成しており、middlewareの差し替え、またはdecorator剥がしなどせずに綺麗に書ける。

またgraphene-djangoでのtestは基本的にsnapshot testで行う為JSONWebTokenTestCaseとsnapshottest.TestCaseの両方を使う。

結構綺麗に書けてgraphene-django-jwtいいなと思った。

tests/basic_mutation_test.py
from snapshottest import TestCase
from graphql_jwt.testcases import JSONWebTokenTestCase


class FooBasicMutationTestCase(JSONWebTokenTestCase, TestCase):
    def setUp(self):
        self.user = get_user_model().objects.create(
            email='test@admin.com',
            password='testadminpass',
            is_active=True,
            is_superuser=True,
        )
        self.client.authenticate(self.user)

    def test_create_foo_user(self):
        foo = FooFactory()
        query = '''
        mutation FooUser($foo_id: String!) {
          createFooUser(email: "test@test.com", password: "password", fooId: $foo_id){
            FooUser {
              user {
                email
              }
            }
          }
        }
        '''
        variables = {
            'foo_id': foo.id,
        }
        self.assertMatchSnapshot(self.client.execute(query, variables).to_dict())

snap_test_basic_mutation.py
snapshots['FooBasicMutationTestCase::test_create_foo_user 1'] = {
    'data': {
        'createFooUser': {
            'FooUser': {
                'user': {
                    'email': 'test@test.com'
                }
            }
        }
    }
}
3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?