graphene-django/graphene_django/tests/test_query.py

1068 lines
28 KiB
Python
Raw Normal View History

import base64
import datetime
import pytest
from django.db import models
from django.utils.functional import SimpleLazyObject
from py.test import raises
2017-10-11 16:43:50 +03:00
from django.db.models import Q
2019-03-27 23:56:10 +03:00
from graphql_relay import to_global_id
import graphene
from graphene.relay import Node
from ..utils import DJANGO_FILTER_INSTALLED
2017-03-03 05:38:03 +03:00
from ..compat import MissingType, JSONField
from ..fields import DjangoConnectionField
from ..types import DjangoObjectType
from ..settings import graphene_settings
2018-07-20 02:51:33 +03:00
from .models import Article, CNNReporter, Reporter, Film, FilmDetails
pytestmark = pytest.mark.django_db
def test_should_query_only_fields():
with raises(Exception):
2018-07-20 02:51:33 +03:00
class ReporterType(DjangoObjectType):
class Meta:
model = Reporter
2018-07-20 02:51:33 +03:00
only_fields = ("articles",)
schema = graphene.Schema(query=ReporterType)
2018-07-20 02:51:33 +03:00
query = """
query ReporterQuery {
articles
}
2018-07-20 02:51:33 +03:00
"""
result = schema.execute(query)
assert not result.errors
def test_should_query_simplelazy_objects():
class ReporterType(DjangoObjectType):
class Meta:
model = Reporter
2018-07-20 02:51:33 +03:00
only_fields = ("id",)
class Query(graphene.ObjectType):
reporter = graphene.Field(ReporterType)
2017-07-28 19:43:27 +03:00
def resolve_reporter(self, info):
return SimpleLazyObject(lambda: Reporter(id=1))
schema = graphene.Schema(query=Query)
2018-07-20 02:51:33 +03:00
query = """
query {
reporter {
id
}
}
2018-07-20 02:51:33 +03:00
"""
result = schema.execute(query)
assert not result.errors
2018-07-20 02:51:33 +03:00
assert result.data == {"reporter": {"id": "1"}}
def test_should_query_well():
class ReporterType(DjangoObjectType):
class Meta:
model = Reporter
class Query(graphene.ObjectType):
reporter = graphene.Field(ReporterType)
2017-07-28 19:43:27 +03:00
def resolve_reporter(self, info):
2018-07-20 02:51:33 +03:00
return Reporter(first_name="ABA", last_name="X")
2018-07-20 02:51:33 +03:00
query = """
query ReporterQuery {
reporter {
firstName,
lastName,
email
}
}
2018-07-20 02:51:33 +03:00
"""
expected = {"reporter": {"firstName": "ABA", "lastName": "X", "email": ""}}
schema = graphene.Schema(query=Query)
result = schema.execute(query)
assert not result.errors
assert result.data == expected
2018-07-20 02:51:33 +03:00
@pytest.mark.skipif(JSONField is MissingType, reason="RangeField should exist")
def test_should_query_postgres_fields():
2018-07-20 02:51:33 +03:00
from django.contrib.postgres.fields import (
IntegerRangeField,
ArrayField,
JSONField,
HStoreField,
)
class Event(models.Model):
2018-07-20 02:51:33 +03:00
ages = IntegerRangeField(help_text="The age ranges")
data = JSONField(help_text="Data")
store = HStoreField()
tags = ArrayField(models.CharField(max_length=50))
class EventType(DjangoObjectType):
class Meta:
model = Event
class Query(graphene.ObjectType):
event = graphene.Field(EventType)
2017-07-28 19:43:27 +03:00
def resolve_event(self, info):
return Event(
ages=(0, 10),
2018-07-20 02:51:33 +03:00
data={"angry_babies": True},
store={"h": "store"},
tags=["child", "angry", "babies"],
)
schema = graphene.Schema(query=Query)
2018-07-20 02:51:33 +03:00
query = """
query myQuery {
event {
ages
tags
data
store
}
}
2018-07-20 02:51:33 +03:00
"""
expected = {
2018-07-20 02:51:33 +03:00
"event": {
"ages": [0, 10],
"tags": ["child", "angry", "babies"],
"data": '{"angry_babies": true}',
"store": '{"h": "store"}',
}
}
result = schema.execute(query)
assert not result.errors
assert result.data == expected
def test_should_node():
# reset_global_registry()
# Node._meta.registry = get_global_registry()
class ReporterNode(DjangoObjectType):
class Meta:
model = Reporter
2018-07-20 02:51:33 +03:00
interfaces = (Node,)
@classmethod
2017-07-28 19:43:27 +03:00
def get_node(cls, info, id):
2018-07-20 02:51:33 +03:00
return Reporter(id=2, first_name="Cookie Monster")
2017-07-28 19:43:27 +03:00
def resolve_articles(self, info, **args):
2018-07-20 02:51:33 +03:00
return [Article(headline="Hi!")]
class ArticleNode(DjangoObjectType):
class Meta:
model = Article
2018-07-20 02:51:33 +03:00
interfaces = (Node,)
@classmethod
2017-07-28 19:43:27 +03:00
def get_node(cls, info, id):
2018-07-20 02:51:33 +03:00
return Article(
id=1, headline="Article node", pub_date=datetime.date(2002, 3, 11)
)
class Query(graphene.ObjectType):
node = Node.Field()
reporter = graphene.Field(ReporterNode)
article = graphene.Field(ArticleNode)
2017-07-28 19:43:27 +03:00
def resolve_reporter(self, info):
2018-07-20 02:51:33 +03:00
return Reporter(id=1, first_name="ABA", last_name="X")
2018-07-20 02:51:33 +03:00
query = """
query ReporterQuery {
reporter {
id,
firstName,
articles {
edges {
node {
headline
}
}
}
lastName,
email
}
myArticle: node(id:"QXJ0aWNsZU5vZGU6MQ==") {
id
... on ReporterNode {
firstName
}
... on ArticleNode {
headline
pubDate
}
}
}
2018-07-20 02:51:33 +03:00
"""
expected = {
2018-07-20 02:51:33 +03:00
"reporter": {
"id": "UmVwb3J0ZXJOb2RlOjE=",
"firstName": "ABA",
"lastName": "X",
"email": "",
"articles": {"edges": [{"node": {"headline": "Hi!"}}]},
},
"myArticle": {
"id": "QXJ0aWNsZU5vZGU6MQ==",
"headline": "Article node",
"pubDate": "2002-03-11",
},
}
schema = graphene.Schema(query=Query)
result = schema.execute(query)
assert not result.errors
assert result.data == expected
def test_should_query_onetoone_fields():
film = Film(id=1)
film_details = FilmDetails(id=1, film=film)
class FilmNode(DjangoObjectType):
class Meta:
model = Film
interfaces = (Node,)
class FilmDetailsNode(DjangoObjectType):
class Meta:
model = FilmDetails
interfaces = (Node,)
class Query(graphene.ObjectType):
film = graphene.Field(FilmNode)
film_details = graphene.Field(FilmDetailsNode)
def resolve_film(root, info):
return film
def resolve_film_details(root, info):
return film_details
query = """
query FilmQuery {
filmDetails {
id
film {
id
}
}
film {
id
details {
id
}
}
}
"""
expected = {
"filmDetails": {
"id": "RmlsbURldGFpbHNOb2RlOjE=",
"film": {"id": "RmlsbU5vZGU6MQ=="},
},
"film": {
"id": "RmlsbU5vZGU6MQ==",
"details": {"id": "RmlsbURldGFpbHNOb2RlOjE="},
},
}
schema = graphene.Schema(query=Query)
result = schema.execute(query)
assert not result.errors
assert result.data == expected
def test_should_query_connectionfields():
class ReporterType(DjangoObjectType):
class Meta:
model = Reporter
2018-07-20 02:51:33 +03:00
interfaces = (Node,)
only_fields = ("articles",)
class Query(graphene.ObjectType):
all_reporters = DjangoConnectionField(ReporterType)
2017-07-28 19:43:27 +03:00
def resolve_all_reporters(self, info, **args):
return [Reporter(id=1)]
schema = graphene.Schema(query=Query)
2018-07-20 02:51:33 +03:00
query = """
query ReporterConnectionQuery {
allReporters {
pageInfo {
hasNextPage
}
edges {
node {
id
}
}
}
}
2018-07-20 02:51:33 +03:00
"""
result = schema.execute(query)
assert not result.errors
assert result.data == {
2018-07-20 02:51:33 +03:00
"allReporters": {
"pageInfo": {"hasNextPage": False},
"edges": [{"node": {"id": "UmVwb3J0ZXJUeXBlOjE="}}],
}
}
2016-12-30 12:34:59 +03:00
def test_should_keep_annotations():
2018-07-20 02:51:33 +03:00
from django.db.models import Count, Avg
class ReporterType(DjangoObjectType):
class Meta:
model = Reporter
2018-07-20 02:51:33 +03:00
interfaces = (Node,)
only_fields = ("articles",)
class ArticleType(DjangoObjectType):
class Meta:
model = Article
2018-07-20 02:51:33 +03:00
interfaces = (Node,)
filter_fields = ("lang",)
class Query(graphene.ObjectType):
all_reporters = DjangoConnectionField(ReporterType)
all_articles = DjangoConnectionField(ArticleType)
2017-07-28 19:43:27 +03:00
def resolve_all_reporters(self, info, **args):
2018-07-20 02:51:33 +03:00
return Reporter.objects.annotate(articles_c=Count("articles")).order_by(
"articles_c"
)
2017-07-28 19:43:27 +03:00
def resolve_all_articles(self, info, **args):
2018-07-20 02:51:33 +03:00
return Article.objects.annotate(import_avg=Avg("importance")).order_by(
"import_avg"
)
schema = graphene.Schema(query=Query)
2018-07-20 02:51:33 +03:00
query = """
query ReporterConnectionQuery {
allReporters {
pageInfo {
hasNextPage
}
edges {
node {
id
}
}
}
allArticles {
pageInfo {
hasNextPage
}
edges {
node {
id
}
}
}
}
2018-07-20 02:51:33 +03:00
"""
result = schema.execute(query)
assert not result.errors
2018-07-20 02:51:33 +03:00
@pytest.mark.skipif(
not DJANGO_FILTER_INSTALLED, reason="django-filter should be installed"
)
2016-12-30 12:34:59 +03:00
def test_should_query_node_filtering():
class ReporterType(DjangoObjectType):
class Meta:
model = Reporter
2018-07-20 02:51:33 +03:00
interfaces = (Node,)
2016-12-30 12:34:59 +03:00
class ArticleType(DjangoObjectType):
class Meta:
model = Article
2018-07-20 02:51:33 +03:00
interfaces = (Node,)
filter_fields = ("lang",)
2016-12-30 12:34:59 +03:00
class Query(graphene.ObjectType):
all_reporters = DjangoConnectionField(ReporterType)
r = Reporter.objects.create(
2018-07-20 02:51:33 +03:00
first_name="John", last_name="Doe", email="johndoe@example.com", a_choice=1
2016-12-30 12:34:59 +03:00
)
Article.objects.create(
2018-07-20 02:51:33 +03:00
headline="Article Node 1",
2016-12-30 12:34:59 +03:00
pub_date=datetime.date.today(),
pub_date_time=datetime.datetime.now(),
2016-12-30 12:34:59 +03:00
reporter=r,
editor=r,
2018-07-20 02:51:33 +03:00
lang="es",
2016-12-30 12:34:59 +03:00
)
Article.objects.create(
2018-07-20 02:51:33 +03:00
headline="Article Node 2",
2016-12-30 12:34:59 +03:00
pub_date=datetime.date.today(),
pub_date_time=datetime.datetime.now(),
2016-12-30 12:34:59 +03:00
reporter=r,
editor=r,
2018-07-20 02:51:33 +03:00
lang="en",
2016-12-30 12:34:59 +03:00
)
schema = graphene.Schema(query=Query)
2018-07-20 02:51:33 +03:00
query = """
2016-12-30 12:34:59 +03:00
query NodeFilteringQuery {
allReporters {
edges {
node {
id
articles(lang: "es") {
edges {
node {
id
}
}
}
}
}
}
}
2018-07-20 02:51:33 +03:00
"""
2016-12-30 12:34:59 +03:00
2017-03-05 22:17:00 +03:00
expected = {
2018-07-20 02:51:33 +03:00
"allReporters": {
"edges": [
{
"node": {
"id": "UmVwb3J0ZXJUeXBlOjE=",
"articles": {
"edges": [{"node": {"id": "QXJ0aWNsZVR5cGU6MQ=="}}]
},
2017-03-05 22:17:00 +03:00
}
}
2018-07-20 02:51:33 +03:00
]
2017-03-05 22:17:00 +03:00
}
}
result = schema.execute(query)
assert not result.errors
assert result.data == expected
2018-07-20 02:51:33 +03:00
@pytest.mark.skipif(
not DJANGO_FILTER_INSTALLED, reason="django-filter should be installed"
)
2017-10-11 16:43:50 +03:00
def test_should_query_node_filtering_with_distinct_queryset():
class FilmType(DjangoObjectType):
class Meta:
model = Film
2018-07-20 02:51:33 +03:00
interfaces = (Node,)
filter_fields = ("genre",)
2017-10-11 16:43:50 +03:00
class Query(graphene.ObjectType):
films = DjangoConnectionField(FilmType)
# def resolve_all_reporters_with_berlin_films(self, args, context, info):
# return Reporter.objects.filter(Q(films__film__location__contains="Berlin") | Q(a_choice=1))
def resolve_films(self, info, **args):
2018-07-20 02:51:33 +03:00
return Film.objects.filter(
Q(details__location__contains="Berlin") | Q(genre__in=["ot"])
).distinct()
2017-10-11 16:43:50 +03:00
2018-07-20 02:51:33 +03:00
f = Film.objects.create()
fd = FilmDetails.objects.create(location="Berlin", film=f)
2017-10-11 16:43:50 +03:00
schema = graphene.Schema(query=Query)
2018-07-20 02:51:33 +03:00
query = """
2017-10-11 16:43:50 +03:00
query NodeFilteringQuery {
films {
edges {
node {
genre
}
}
}
}
2018-07-20 02:51:33 +03:00
"""
2017-10-11 16:43:50 +03:00
2018-07-20 02:51:33 +03:00
expected = {"films": {"edges": [{"node": {"genre": "OT"}}]}}
2017-10-11 16:43:50 +03:00
result = schema.execute(query)
assert not result.errors
assert result.data == expected
2018-07-20 02:51:33 +03:00
@pytest.mark.skipif(
not DJANGO_FILTER_INSTALLED, reason="django-filter should be installed"
)
2017-03-05 22:17:00 +03:00
def test_should_query_node_multiple_filtering():
class ReporterType(DjangoObjectType):
class Meta:
model = Reporter
2018-07-20 02:51:33 +03:00
interfaces = (Node,)
2017-03-05 22:17:00 +03:00
class ArticleType(DjangoObjectType):
class Meta:
model = Article
2018-07-20 02:51:33 +03:00
interfaces = (Node,)
filter_fields = ("lang", "headline")
2017-03-05 22:17:00 +03:00
class Query(graphene.ObjectType):
all_reporters = DjangoConnectionField(ReporterType)
r = Reporter.objects.create(
2018-07-20 02:51:33 +03:00
first_name="John", last_name="Doe", email="johndoe@example.com", a_choice=1
2017-03-05 22:17:00 +03:00
)
Article.objects.create(
2018-07-20 02:51:33 +03:00
headline="Article Node 1",
2017-03-05 22:17:00 +03:00
pub_date=datetime.date.today(),
pub_date_time=datetime.datetime.now(),
2017-03-05 22:17:00 +03:00
reporter=r,
editor=r,
2018-07-20 02:51:33 +03:00
lang="es",
2017-03-05 22:17:00 +03:00
)
Article.objects.create(
2018-07-20 02:51:33 +03:00
headline="Article Node 2",
2017-03-05 22:17:00 +03:00
pub_date=datetime.date.today(),
pub_date_time=datetime.datetime.now(),
2017-03-05 22:17:00 +03:00
reporter=r,
editor=r,
2018-07-20 02:51:33 +03:00
lang="es",
2017-03-05 22:17:00 +03:00
)
Article.objects.create(
2018-07-20 02:51:33 +03:00
headline="Article Node 3",
2017-03-05 22:17:00 +03:00
pub_date=datetime.date.today(),
pub_date_time=datetime.datetime.now(),
2017-03-05 22:17:00 +03:00
reporter=r,
editor=r,
2018-07-20 02:51:33 +03:00
lang="en",
2017-03-05 22:17:00 +03:00
)
schema = graphene.Schema(query=Query)
2018-07-20 02:51:33 +03:00
query = """
2017-03-05 22:17:00 +03:00
query NodeFilteringQuery {
allReporters {
edges {
node {
id
2017-03-06 23:00:01 +03:00
articles(lang: "es", headline: "Article Node 1") {
2017-03-05 22:17:00 +03:00
edges {
node {
id
}
}
}
}
}
}
}
2018-07-20 02:51:33 +03:00
"""
2017-03-05 22:17:00 +03:00
2016-12-30 12:34:59 +03:00
expected = {
2018-07-20 02:51:33 +03:00
"allReporters": {
"edges": [
{
"node": {
"id": "UmVwb3J0ZXJUeXBlOjE=",
"articles": {
"edges": [{"node": {"id": "QXJ0aWNsZVR5cGU6MQ=="}}]
},
2016-12-30 15:27:45 +03:00
}
}
2018-07-20 02:51:33 +03:00
]
2016-12-30 15:27:45 +03:00
}
}
result = schema.execute(query)
assert not result.errors
assert result.data == expected
def test_should_enforce_first_or_last():
graphene_settings.RELAY_CONNECTION_ENFORCE_FIRST_OR_LAST = True
class ReporterType(DjangoObjectType):
class Meta:
model = Reporter
2018-07-20 02:51:33 +03:00
interfaces = (Node,)
class Query(graphene.ObjectType):
all_reporters = DjangoConnectionField(ReporterType)
r = Reporter.objects.create(
2018-07-20 02:51:33 +03:00
first_name="John", last_name="Doe", email="johndoe@example.com", a_choice=1
)
schema = graphene.Schema(query=Query)
2018-07-20 02:51:33 +03:00
query = """
query NodeFilteringQuery {
allReporters {
edges {
node {
id
}
}
}
}
2018-07-20 02:51:33 +03:00
"""
2018-07-20 02:51:33 +03:00
expected = {"allReporters": None}
result = schema.execute(query)
assert len(result.errors) == 1
assert str(result.errors[0]) == (
2018-07-20 02:51:33 +03:00
"You must provide a `first` or `last` value to properly "
"paginate the `allReporters` connection."
)
assert result.data == expected
def test_should_error_if_first_is_greater_than_max():
graphene_settings.RELAY_CONNECTION_MAX_LIMIT = 100
class ReporterType(DjangoObjectType):
class Meta:
model = Reporter
2018-07-20 02:51:33 +03:00
interfaces = (Node,)
class Query(graphene.ObjectType):
all_reporters = DjangoConnectionField(ReporterType)
r = Reporter.objects.create(
2018-07-20 02:51:33 +03:00
first_name="John", last_name="Doe", email="johndoe@example.com", a_choice=1
)
schema = graphene.Schema(query=Query)
2018-07-20 02:51:33 +03:00
query = """
query NodeFilteringQuery {
allReporters(first: 101) {
edges {
node {
id
}
}
}
}
2018-07-20 02:51:33 +03:00
"""
2018-07-20 02:51:33 +03:00
expected = {"allReporters": None}
result = schema.execute(query)
assert len(result.errors) == 1
assert str(result.errors[0]) == (
2018-07-20 02:51:33 +03:00
"Requesting 101 records on the `allReporters` connection "
"exceeds the `first` limit of 100 records."
)
assert result.data == expected
graphene_settings.RELAY_CONNECTION_ENFORCE_FIRST_OR_LAST = False
def test_should_error_if_last_is_greater_than_max():
graphene_settings.RELAY_CONNECTION_MAX_LIMIT = 100
class ReporterType(DjangoObjectType):
class Meta:
model = Reporter
2018-07-20 02:51:33 +03:00
interfaces = (Node,)
class Query(graphene.ObjectType):
all_reporters = DjangoConnectionField(ReporterType)
r = Reporter.objects.create(
2018-07-20 02:51:33 +03:00
first_name="John", last_name="Doe", email="johndoe@example.com", a_choice=1
)
schema = graphene.Schema(query=Query)
2018-07-20 02:51:33 +03:00
query = """
query NodeFilteringQuery {
allReporters(last: 101) {
edges {
node {
id
}
}
}
}
2018-07-20 02:51:33 +03:00
"""
2018-07-20 02:51:33 +03:00
expected = {"allReporters": None}
result = schema.execute(query)
assert len(result.errors) == 1
assert str(result.errors[0]) == (
2018-07-20 02:51:33 +03:00
"Requesting 101 records on the `allReporters` connection "
"exceeds the `last` limit of 100 records."
)
assert result.data == expected
graphene_settings.RELAY_CONNECTION_ENFORCE_FIRST_OR_LAST = False
def test_should_query_promise_connectionfields():
from promise import Promise
class ReporterType(DjangoObjectType):
class Meta:
model = Reporter
2018-07-20 02:51:33 +03:00
interfaces = (Node,)
class Query(graphene.ObjectType):
all_reporters = DjangoConnectionField(ReporterType)
2017-07-28 19:43:27 +03:00
def resolve_all_reporters(self, info, **args):
return Promise.resolve([Reporter(id=1)])
2018-03-28 13:28:58 +03:00
schema = graphene.Schema(query=Query)
2018-07-20 02:51:33 +03:00
query = """
query ReporterPromiseConnectionQuery {
allReporters(first: 1) {
edges {
node {
id
}
}
}
}
2018-07-20 02:51:33 +03:00
"""
2018-07-20 02:51:33 +03:00
expected = {"allReporters": {"edges": [{"node": {"id": "UmVwb3J0ZXJUeXBlOjE="}}]}}
result = schema.execute(query)
assert not result.errors
assert result.data == expected
2018-07-20 02:51:33 +03:00
2017-12-12 20:49:02 +03:00
def test_should_query_connectionfields_with_last():
r = Reporter.objects.create(
2018-07-20 02:51:33 +03:00
first_name="John", last_name="Doe", email="johndoe@example.com", a_choice=1
2017-12-12 20:49:02 +03:00
)
2017-12-12 20:33:32 +03:00
class ReporterType(DjangoObjectType):
class Meta:
model = Reporter
2018-07-20 02:51:33 +03:00
interfaces = (Node,)
2017-12-12 20:33:32 +03:00
class Query(graphene.ObjectType):
all_reporters = DjangoConnectionField(ReporterType)
def resolve_all_reporters(self, info, **args):
2017-12-12 20:49:02 +03:00
return Reporter.objects.all()
2018-03-28 13:28:58 +03:00
2017-12-12 20:33:32 +03:00
schema = graphene.Schema(query=Query)
2018-07-20 02:51:33 +03:00
query = """
2017-12-12 20:49:02 +03:00
query ReporterLastQuery {
2017-12-12 20:33:32 +03:00
allReporters(last: 1) {
edges {
node {
id
}
}
}
}
2018-07-20 02:51:33 +03:00
"""
2017-12-12 20:33:32 +03:00
2018-07-20 02:51:33 +03:00
expected = {"allReporters": {"edges": [{"node": {"id": "UmVwb3J0ZXJUeXBlOjE="}}]}}
2017-12-12 20:33:32 +03:00
result = schema.execute(query)
assert not result.errors
assert result.data == expected
2018-07-20 02:51:33 +03:00
def test_should_query_connectionfields_with_manager():
r = Reporter.objects.create(
2018-07-20 02:51:33 +03:00
first_name="John", last_name="Doe", email="johndoe@example.com", a_choice=1
)
r = Reporter.objects.create(
2018-07-20 02:51:33 +03:00
first_name="John", last_name="NotDoe", email="johndoe@example.com", a_choice=1
)
class ReporterType(DjangoObjectType):
class Meta:
model = Reporter
2018-07-20 02:51:33 +03:00
interfaces = (Node,)
class Query(graphene.ObjectType):
2018-07-20 02:51:33 +03:00
all_reporters = DjangoConnectionField(ReporterType, on="doe_objects")
def resolve_all_reporters(self, info, **args):
return Reporter.objects.all()
2018-03-28 13:28:58 +03:00
schema = graphene.Schema(query=Query)
2018-07-20 02:51:33 +03:00
query = """
query ReporterLastQuery {
allReporters(first: 2) {
edges {
node {
id
}
}
}
}
2018-07-20 02:51:33 +03:00
"""
2018-07-20 02:51:33 +03:00
expected = {"allReporters": {"edges": [{"node": {"id": "UmVwb3J0ZXJUeXBlOjE="}}]}}
result = schema.execute(query)
assert not result.errors
assert result.data == expected
def test_should_query_dataloader_fields():
from promise import Promise
from promise.dataloader import DataLoader
def article_batch_load_fn(keys):
queryset = Article.objects.filter(reporter_id__in=keys)
2018-07-20 02:51:33 +03:00
return Promise.resolve(
[
[article for article in queryset if article.reporter_id == id]
for id in keys
]
)
article_loader = DataLoader(article_batch_load_fn)
class ArticleType(DjangoObjectType):
class Meta:
model = Article
2018-07-20 02:51:33 +03:00
interfaces = (Node,)
class ReporterType(DjangoObjectType):
class Meta:
model = Reporter
2018-07-20 02:51:33 +03:00
interfaces = (Node,)
2017-07-25 08:27:50 +03:00
use_connection = True
articles = DjangoConnectionField(ArticleType)
2017-07-28 19:43:27 +03:00
def resolve_articles(self, info, **args):
return article_loader.load(self.id)
class Query(graphene.ObjectType):
all_reporters = DjangoConnectionField(ReporterType)
r = Reporter.objects.create(
2018-07-20 02:51:33 +03:00
first_name="John", last_name="Doe", email="johndoe@example.com", a_choice=1
)
Article.objects.create(
2018-07-20 02:51:33 +03:00
headline="Article Node 1",
pub_date=datetime.date.today(),
pub_date_time=datetime.datetime.now(),
reporter=r,
editor=r,
2018-07-20 02:51:33 +03:00
lang="es",
)
Article.objects.create(
2018-07-20 02:51:33 +03:00
headline="Article Node 2",
pub_date=datetime.date.today(),
pub_date_time=datetime.datetime.now(),
reporter=r,
editor=r,
2018-07-20 02:51:33 +03:00
lang="en",
)
schema = graphene.Schema(query=Query)
2018-07-20 02:51:33 +03:00
query = """
query ReporterPromiseConnectionQuery {
allReporters(first: 1) {
edges {
node {
id
articles(first: 2) {
edges {
node {
headline
}
}
}
}
}
}
}
2018-07-20 02:51:33 +03:00
"""
expected = {
2018-07-20 02:51:33 +03:00
"allReporters": {
"edges": [
{
"node": {
"id": "UmVwb3J0ZXJUeXBlOjE=",
"articles": {
"edges": [
{"node": {"headline": "Article Node 1"}},
{"node": {"headline": "Article Node 2"}},
]
},
}
}
2018-07-20 02:51:33 +03:00
]
}
}
result = schema.execute(query)
assert not result.errors
assert result.data == expected
def test_should_handle_inherited_choices():
class BaseModel(models.Model):
2018-07-20 02:51:33 +03:00
choice_field = models.IntegerField(choices=((0, "zero"), (1, "one")))
class ChildModel(BaseModel):
class Meta:
proxy = True
class BaseType(DjangoObjectType):
class Meta:
model = BaseModel
class ChildType(DjangoObjectType):
class Meta:
model = ChildModel
class Query(graphene.ObjectType):
base = graphene.Field(BaseType)
child = graphene.Field(ChildType)
schema = graphene.Schema(query=Query)
2018-07-20 02:51:33 +03:00
query = """
query {
child {
choiceField
}
}
2018-07-20 02:51:33 +03:00
"""
result = schema.execute(query)
assert not result.errors
def test_proxy_model_support():
"""
This test asserts that we can query for all Reporters and proxied Reporters.
"""
2018-07-20 02:51:33 +03:00
class ReporterType(DjangoObjectType):
class Meta:
model = Reporter
2018-07-20 02:51:33 +03:00
interfaces = (Node,)
use_connection = True
class CNNReporterType(DjangoObjectType):
class Meta:
model = CNNReporter
interfaces = (Node,)
use_connection = True
reporter = Reporter.objects.create(
2018-07-20 02:51:33 +03:00
first_name="John", last_name="Doe", email="johndoe@example.com", a_choice=1
)
cnn_reporter = CNNReporter.objects.create(
2018-07-20 02:51:33 +03:00
first_name="Some",
last_name="Guy",
email="someguy@cnn.com",
a_choice=1,
reporter_type=2, # set this guy to be CNN
)
class Query(graphene.ObjectType):
all_reporters = DjangoConnectionField(ReporterType)
cnn_reporters = DjangoConnectionField(CNNReporterType)
schema = graphene.Schema(query=Query)
2018-07-20 02:51:33 +03:00
query = """
query ProxyModelQuery {
allReporters {
edges {
node {
id
}
}
}
cnnReporters {
edges {
node {
id
}
}
}
}
2018-07-20 02:51:33 +03:00
"""
expected = {
2018-07-20 02:51:33 +03:00
"allReporters": {
"edges": [
2019-03-27 23:56:10 +03:00
{"node": {"id": to_global_id("ReporterType", reporter.id)}},
{"node": {"id": to_global_id("ReporterType", cnn_reporter.id)}},
]
},
"cnnReporters": {
"edges": [
2019-03-27 23:56:10 +03:00
{"node": {"id": to_global_id("CNNReporterType", cnn_reporter.id)}}
]
}
}
result = schema.execute(query)
assert not result.errors
assert result.data == expected
def test_should_resolve_get_queryset_connectionfields():
reporter_1 = Reporter.objects.create(
first_name="John", last_name="Doe", email="johndoe@example.com", a_choice=1
)
reporter_2 = CNNReporter.objects.create(
first_name="Some",
last_name="Guy",
email="someguy@cnn.com",
a_choice=1,
reporter_type=2, # set this guy to be CNN
)
class ReporterType(DjangoObjectType):
class Meta:
model = Reporter
interfaces = (Node,)
@classmethod
def get_queryset(cls, queryset, info):
return queryset.filter(reporter_type=2)
class Query(graphene.ObjectType):
all_reporters = DjangoConnectionField(ReporterType)
schema = graphene.Schema(query=Query)
query = """
query ReporterPromiseConnectionQuery {
allReporters(first: 1) {
edges {
node {
id
}
}
}
}
"""
expected = {"allReporters": {"edges": [{"node": {"id": "UmVwb3J0ZXJUeXBlOjI="}}]}}
result = schema.execute(query)
assert not result.errors
assert result.data == expected