This commit is contained in:
Christian Mantha
2026-03-02 19:10:52 -05:00
commit 2ca0b9ef7c
28907 changed files with 5233713 additions and 0 deletions

View File

@@ -0,0 +1,35 @@
import json
from collections.abc import Mapping
def to_key(value):
return json.dumps(value)
def insert(value, index, values):
key = to_key(value)
if key not in index:
index[key] = len(values)
values.append(value)
return len(values) - 1
return index.get(key)
def flatten(data, index, values):
if isinstance(data, (list, tuple)):
flattened = [flatten(child, index, values) for child in data]
elif isinstance(data, Mapping):
flattened = {key: flatten(child, index, values) for key, child in data.items()}
else:
flattened = data
return insert(flattened, index, values)
def crunch(data):
index = {}
values = []
flatten(data, index, values)
return values

View File

@@ -0,0 +1,280 @@
from asyncio import (
gather,
ensure_future,
get_event_loop,
iscoroutine,
iscoroutinefunction,
)
from collections import namedtuple
from collections.abc import Iterable
from functools import partial
from typing import List
Loader = namedtuple("Loader", "key,future")
def iscoroutinefunctionorpartial(fn):
return iscoroutinefunction(fn.func if isinstance(fn, partial) else fn)
class DataLoader(object):
batch = True
max_batch_size = None # type: int
cache = True
def __init__(
self,
batch_load_fn=None,
batch=None,
max_batch_size=None,
cache=None,
get_cache_key=None,
cache_map=None,
loop=None,
):
self._loop = loop
if batch_load_fn is not None:
self.batch_load_fn = batch_load_fn
assert iscoroutinefunctionorpartial(
self.batch_load_fn
), "batch_load_fn must be coroutine. Received: {}".format(self.batch_load_fn)
if not callable(self.batch_load_fn):
raise TypeError( # pragma: no cover
(
"DataLoader must be have a batch_load_fn which accepts "
"Iterable<key> and returns Future<Iterable<value>>, but got: {}."
).format(batch_load_fn)
)
if batch is not None:
self.batch = batch # pragma: no cover
if max_batch_size is not None:
self.max_batch_size = max_batch_size
if cache is not None:
self.cache = cache # pragma: no cover
self.get_cache_key = get_cache_key or (lambda x: x)
self._cache = cache_map if cache_map is not None else {}
self._queue: List[Loader] = []
@property
def loop(self):
if not self._loop:
self._loop = get_event_loop()
return self._loop
def load(self, key=None):
"""
Loads a key, returning a `Future` for the value represented by that key.
"""
if key is None:
raise TypeError( # pragma: no cover
(
"The loader.load() function must be called with a value, "
"but got: {}."
).format(key)
)
cache_key = self.get_cache_key(key)
# If caching and there is a cache-hit, return cached Future.
if self.cache:
cached_result = self._cache.get(cache_key)
if cached_result:
return cached_result
# Otherwise, produce a new Future for this value.
future = self.loop.create_future()
# If caching, cache this Future.
if self.cache:
self._cache[cache_key] = future
self.do_resolve_reject(key, future)
return future
def do_resolve_reject(self, key, future):
# Enqueue this Future to be dispatched.
self._queue.append(Loader(key=key, future=future))
# Determine if a dispatch of this queue should be scheduled.
# A single dispatch should be scheduled per queue at the time when the
# queue changes from "empty" to "full".
if len(self._queue) == 1:
if self.batch:
# If batching, schedule a task to dispatch the queue.
enqueue_post_future_job(self.loop, self)
else:
# Otherwise dispatch the (queue of one) immediately.
dispatch_queue(self) # pragma: no cover
def load_many(self, keys):
"""
Loads multiple keys, returning a list of values
>>> a, b = await my_loader.load_many([ 'a', 'b' ])
This is equivalent to the more verbose:
>>> a, b = await gather(
>>> my_loader.load('a'),
>>> my_loader.load('b')
>>> )
"""
if not isinstance(keys, Iterable):
raise TypeError( # pragma: no cover
(
"The loader.load_many() function must be called with Iterable<key> "
"but got: {}."
).format(keys)
)
return gather(*[self.load(key) for key in keys])
def clear(self, key):
"""
Clears the value at `key` from the cache, if it exists. Returns itself for
method chaining.
"""
cache_key = self.get_cache_key(key)
self._cache.pop(cache_key, None)
return self
def clear_all(self):
"""
Clears the entire cache. To be used when some event results in unknown
invalidations across this particular `DataLoader`. Returns itself for
method chaining.
"""
self._cache.clear()
return self
def prime(self, key, value):
"""
Adds the provied key and value to the cache. If the key already exists, no
change is made. Returns itself for method chaining.
"""
cache_key = self.get_cache_key(key)
# Only add the key if it does not already exist.
if cache_key not in self._cache:
# Cache a rejected future if the value is an Error, in order to match
# the behavior of load(key).
future = self.loop.create_future()
if isinstance(value, Exception):
future.set_exception(value)
else:
future.set_result(value)
self._cache[cache_key] = future
return self
def enqueue_post_future_job(loop, loader):
async def dispatch():
dispatch_queue(loader)
loop.call_soon(ensure_future, dispatch())
def get_chunks(iterable_obj, chunk_size=1):
chunk_size = max(1, chunk_size)
return (
iterable_obj[i : i + chunk_size]
for i in range(0, len(iterable_obj), chunk_size)
)
def dispatch_queue(loader):
"""
Given the current state of a Loader instance, perform a batch load
from its current queue.
"""
# Take the current loader queue, replacing it with an empty queue.
queue = loader._queue
loader._queue = []
# If a max_batch_size was provided and the queue is longer, then segment the
# queue into multiple batches, otherwise treat the queue as a single batch.
max_batch_size = loader.max_batch_size
if max_batch_size and max_batch_size < len(queue):
chunks = get_chunks(queue, max_batch_size)
for chunk in chunks:
ensure_future(dispatch_queue_batch(loader, chunk))
else:
ensure_future(dispatch_queue_batch(loader, queue))
async def dispatch_queue_batch(loader, queue):
# Collect all keys to be loaded in this dispatch
keys = [loaded.key for loaded in queue]
# Call the provided batch_load_fn for this loader with the loader queue's keys.
batch_future = loader.batch_load_fn(keys)
# Assert the expected response from batch_load_fn
if not batch_future or not iscoroutine(batch_future):
return failed_dispatch( # pragma: no cover
loader,
queue,
TypeError(
(
"DataLoader must be constructed with a function which accepts "
"Iterable<key> and returns Future<Iterable<value>>, but the function did "
"not return a Coroutine: {}."
).format(batch_future)
),
)
try:
values = await batch_future
if not isinstance(values, Iterable):
raise TypeError( # pragma: no cover
(
"DataLoader must be constructed with a function which accepts "
"Iterable<key> and returns Future<Iterable<value>>, but the function did "
"not return a Future of a Iterable: {}."
).format(values)
)
values = list(values)
if len(values) != len(keys):
raise TypeError( # pragma: no cover
(
"DataLoader must be constructed with a function which accepts "
"Iterable<key> and returns Future<Iterable<value>>, but the function did "
"not return a Future of a Iterable with the same length as the Iterable "
"of keys."
"\n\nKeys:\n{}"
"\n\nValues:\n{}"
).format(keys, values)
)
# Step through the values, resolving or rejecting each Future in the
# loaded queue.
for loaded, value in zip(queue, values):
if isinstance(value, Exception):
loaded.future.set_exception(value)
else:
loaded.future.set_result(value)
except Exception as e:
return failed_dispatch(loader, queue, e)
def failed_dispatch(loader, queue, error):
"""
Do not cache individual loads if the entire batch dispatch fails,
but still reject each request so they do not hang.
"""
for loaded in queue:
loader.clear(loaded.key)
loaded.future.set_exception(error)

View File

@@ -0,0 +1,32 @@
from collections.abc import Mapping
def deflate(node, index=None, path=None):
if index is None:
index = {}
if path is None:
path = []
if node and "id" in node and "__typename" in node:
route = ",".join(path)
cache_key = ":".join([route, str(node["__typename"]), str(node["id"])])
if index.get(cache_key) is True:
return {"__typename": node["__typename"], "id": node["id"]}
else:
index[cache_key] = True
result = {}
for field_name in node:
value = node[field_name]
new_path = path + [field_name]
if isinstance(value, (list, tuple)):
result[field_name] = [deflate(child, index, new_path) for child in value]
elif isinstance(value, Mapping):
result[field_name] = deflate(value, index, new_path)
else:
result[field_name] = value
return result

View File

@@ -0,0 +1,5 @@
from warnings import warn
def warn_deprecation(text: str):
warn(text, category=DeprecationWarning, stacklevel=2)

View File

@@ -0,0 +1,4 @@
def get_unbound_function(func):
if not getattr(func, "__self__", True):
return func.__func__
return func

View File

@@ -0,0 +1,6 @@
def is_introspection_key(key):
# from: https://spec.graphql.org/June2018/#sec-Schema
# > All types and directives defined within a schema must not have a name which
# > begins with "__" (two underscores), as this is used exclusively
# > by GraphQLs introspection system.
return str(key).startswith("__")

View File

@@ -0,0 +1,45 @@
from functools import partial
from importlib import import_module
def import_string(dotted_path, dotted_attributes=None):
"""
Import a dotted module path and return the attribute/class designated by the
last name in the path. When a dotted attribute path is also provided, the
dotted attribute path would be applied to the attribute/class retrieved from
the first step, and return the corresponding value designated by the
attribute path. Raise ImportError if the import failed.
"""
try:
module_path, class_name = dotted_path.rsplit(".", 1)
except ValueError:
raise ImportError("%s doesn't look like a module path" % dotted_path)
module = import_module(module_path)
try:
result = getattr(module, class_name)
except AttributeError:
raise ImportError(
'Module "%s" does not define a "%s" attribute/class'
% (module_path, class_name)
)
if not dotted_attributes:
return result
attributes = dotted_attributes.split(".")
traveled_attributes = []
try:
for attribute in attributes:
traveled_attributes.append(attribute)
result = getattr(result, attribute)
return result
except AttributeError:
raise ImportError(
'Module "%s" does not define a "%s" attribute inside attribute/class "%s"'
% (module_path, ".".join(traveled_attributes), class_name)
)
def lazy_import(dotted_path, dotted_attributes=None):
return partial(import_string, dotted_path, dotted_attributes)

View File

@@ -0,0 +1,39 @@
from functools import total_ordering
@total_ordering
class OrderedType:
creation_counter = 1
def __init__(self, _creation_counter=None):
self.creation_counter = _creation_counter or self.gen_counter()
@staticmethod
def gen_counter():
counter = OrderedType.creation_counter
OrderedType.creation_counter += 1
return counter
def reset_counter(self):
self.creation_counter = self.gen_counter()
def __eq__(self, other):
# Needed for @total_ordering
if isinstance(self, type(other)):
return self.creation_counter == other.creation_counter
return NotImplemented
def __lt__(self, other):
# This is needed because bisect does not take a comparison function.
if isinstance(other, OrderedType):
return self.creation_counter < other.creation_counter
return NotImplemented
def __gt__(self, other):
# This is needed because bisect does not take a comparison function.
if isinstance(other, OrderedType):
return self.creation_counter > other.creation_counter
return NotImplemented
def __hash__(self):
return hash(self.creation_counter)

View File

@@ -0,0 +1,15 @@
class _OldClass:
pass
class _NewClass:
pass
_all_vars = set(dir(_OldClass) + dir(_NewClass))
def props(x):
return {
key: vars(x).get(key, getattr(x, key)) for key in dir(x) if key not in _all_vars
}

View File

@@ -0,0 +1,11 @@
from functools import wraps
from typing_extensions import deprecated
@deprecated("This function is deprecated")
def resolve_only_args(func):
@wraps(func)
def wrapped_func(root, info, **args):
return func(root, **args)
return wrapped_func

View File

@@ -0,0 +1,17 @@
import re
# Adapted from this response in Stackoverflow
# http://stackoverflow.com/a/19053800/1072990
def to_camel_case(snake_str):
components = snake_str.split("_")
# We capitalize the first letter of each component except the first one
# with the 'capitalize' method and join them together.
return components[0] + "".join(x.capitalize() if x else "_" for x in components[1:])
# From this response in Stackoverflow
# http://stackoverflow.com/a/1176023/1072990
def to_snake_case(name):
s1 = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", name)
return re.sub("([a-z0-9])([A-Z])", r"\1_\2", s1).lower()

View File

@@ -0,0 +1,50 @@
from inspect import isclass
from .props import props
class SubclassWithMeta_Meta(type):
_meta = None
def __str__(cls):
if cls._meta:
return cls._meta.name
return cls.__name__
def __repr__(cls):
return f"<{cls.__name__} meta={repr(cls._meta)}>"
class SubclassWithMeta(metaclass=SubclassWithMeta_Meta):
"""This class improves __init_subclass__ to receive automatically the options from meta"""
def __init_subclass__(cls, **meta_options):
"""This method just terminates the super() chain"""
_Meta = getattr(cls, "Meta", None)
_meta_props = {}
if _Meta:
if isinstance(_Meta, dict):
_meta_props = _Meta
elif isclass(_Meta):
_meta_props = props(_Meta)
else:
raise Exception(
f"Meta have to be either a class or a dict. Received {_Meta}"
)
delattr(cls, "Meta")
options = dict(meta_options, **_meta_props)
abstract = options.pop("abstract", False)
if abstract:
assert not options, (
"Abstract types can only contain the abstract attribute. "
f"Received: abstract, {', '.join(options)}"
)
else:
super_class = super(cls, cls)
if hasattr(super_class, "__init_subclass_with_meta__"):
super_class.__init_subclass_with_meta__(**options)
@classmethod
def __init_subclass_with_meta__(cls, **meta_options):
"""This method just terminates the super() chain"""

View File

@@ -0,0 +1,51 @@
from pytest import mark
from ..crunch import crunch
@mark.parametrize(
"description,uncrunched,crunched",
[
["number primitive", 0, [0]],
["boolean primitive", True, [True]],
["string primitive", "string", ["string"]],
["empty array", [], [[]]],
["single-item array", [None], [None, [0]]],
[
"multi-primitive all distinct array",
[None, 0, True, "string"],
[None, 0, True, "string", [0, 1, 2, 3]],
],
[
"multi-primitive repeated array",
[True, True, True, True],
[True, [0, 0, 0, 0]],
],
["one-level nested array", [[1, 2, 3]], [1, 2, 3, [0, 1, 2], [3]]],
["two-level nested array", [[[1, 2, 3]]], [1, 2, 3, [0, 1, 2], [3], [4]]],
["empty object", {}, [{}]],
["single-item object", {"a": None}, [None, {"a": 0}]],
[
"multi-item all distinct object",
{"a": None, "b": 0, "c": True, "d": "string"},
[None, 0, True, "string", {"a": 0, "b": 1, "c": 2, "d": 3}],
],
[
"multi-item repeated object",
{"a": True, "b": True, "c": True, "d": True},
[True, {"a": 0, "b": 0, "c": 0, "d": 0}],
],
[
"complex array",
[{"a": True, "b": [1, 2, 3]}, [1, 2, 3]],
[True, 1, 2, 3, [1, 2, 3], {"a": 0, "b": 4}, [5, 4]],
],
[
"complex object",
{"a": True, "b": [1, 2, 3], "c": {"a": True, "b": [1, 2, 3]}},
[True, 1, 2, 3, [1, 2, 3], {"a": 0, "b": 4}, {"a": 0, "b": 4, "c": 5}],
],
],
)
def test_crunch(description, uncrunched, crunched):
assert crunch(uncrunched) == crunched

View File

@@ -0,0 +1,452 @@
from asyncio import gather
from collections import namedtuple
from functools import partial
from unittest.mock import Mock
from graphene.utils.dataloader import DataLoader
from pytest import mark, raises
from graphene import ObjectType, String, Schema, Field, List
CHARACTERS = {
"1": {"name": "Luke Skywalker", "sibling": "3"},
"2": {"name": "Darth Vader", "sibling": None},
"3": {"name": "Leia Organa", "sibling": "1"},
}
get_character = Mock(side_effect=lambda character_id: CHARACTERS[character_id])
class CharacterType(ObjectType):
name = String()
sibling = Field(lambda: CharacterType)
async def resolve_sibling(character, info):
if character["sibling"]:
return await info.context.character_loader.load(character["sibling"])
return None
class Query(ObjectType):
skywalker_family = List(CharacterType)
async def resolve_skywalker_family(_, info):
return await info.context.character_loader.load_many(["1", "2", "3"])
mock_batch_load_fn = Mock(
side_effect=lambda character_ids: [get_character(id) for id in character_ids]
)
class CharacterLoader(DataLoader):
async def batch_load_fn(self, character_ids):
return mock_batch_load_fn(character_ids)
Context = namedtuple("Context", "character_loader")
@mark.asyncio
async def test_basic_dataloader():
schema = Schema(query=Query)
character_loader = CharacterLoader()
context = Context(character_loader=character_loader)
query = """
{
skywalkerFamily {
name
sibling {
name
}
}
}
"""
result = await schema.execute_async(query, context=context)
assert not result.errors
assert result.data == {
"skywalkerFamily": [
{"name": "Luke Skywalker", "sibling": {"name": "Leia Organa"}},
{"name": "Darth Vader", "sibling": None},
{"name": "Leia Organa", "sibling": {"name": "Luke Skywalker"}},
]
}
assert mock_batch_load_fn.call_count == 1
assert get_character.call_count == 3
def id_loader(**options):
load_calls = []
async def default_resolve(x):
return x
resolve = options.pop("resolve", default_resolve)
async def fn(keys):
load_calls.append(keys)
return await resolve(keys)
# return keys
identity_loader = DataLoader(fn, **options)
return identity_loader, load_calls
@mark.asyncio
async def test_build_a_simple_data_loader():
async def call_fn(keys):
return keys
identity_loader = DataLoader(call_fn)
promise1 = identity_loader.load(1)
value1 = await promise1
assert value1 == 1
@mark.asyncio
async def test_can_build_a_data_loader_from_a_partial():
value_map = {1: "one"}
async def call_fn(context, keys):
return [context.get(key) for key in keys]
partial_fn = partial(call_fn, value_map)
identity_loader = DataLoader(partial_fn)
promise1 = identity_loader.load(1)
value1 = await promise1
assert value1 == "one"
@mark.asyncio
async def test_supports_loading_multiple_keys_in_one_call():
async def call_fn(keys):
return keys
identity_loader = DataLoader(call_fn)
promise_all = identity_loader.load_many([1, 2])
values = await promise_all
assert values == [1, 2]
promise_all = identity_loader.load_many([])
values = await promise_all
assert values == []
@mark.asyncio
async def test_batches_multiple_requests():
identity_loader, load_calls = id_loader()
promise1 = identity_loader.load(1)
promise2 = identity_loader.load(2)
p = gather(promise1, promise2)
value1, value2 = await p
assert value1 == 1
assert value2 == 2
assert load_calls == [[1, 2]]
@mark.asyncio
async def test_batches_multiple_requests_with_max_batch_sizes():
identity_loader, load_calls = id_loader(max_batch_size=2)
promise1 = identity_loader.load(1)
promise2 = identity_loader.load(2)
promise3 = identity_loader.load(3)
p = gather(promise1, promise2, promise3)
value1, value2, value3 = await p
assert value1 == 1
assert value2 == 2
assert value3 == 3
assert load_calls == [[1, 2], [3]]
@mark.asyncio
async def test_coalesces_identical_requests():
identity_loader, load_calls = id_loader()
promise1 = identity_loader.load(1)
promise2 = identity_loader.load(1)
assert promise1 == promise2
p = gather(promise1, promise2)
value1, value2 = await p
assert value1 == 1
assert value2 == 1
assert load_calls == [[1]]
@mark.asyncio
async def test_caches_repeated_requests():
identity_loader, load_calls = id_loader()
a, b = await gather(identity_loader.load("A"), identity_loader.load("B"))
assert a == "A"
assert b == "B"
assert load_calls == [["A", "B"]]
a2, c = await gather(identity_loader.load("A"), identity_loader.load("C"))
assert a2 == "A"
assert c == "C"
assert load_calls == [["A", "B"], ["C"]]
a3, b2, c2 = await gather(
identity_loader.load("A"), identity_loader.load("B"), identity_loader.load("C")
)
assert a3 == "A"
assert b2 == "B"
assert c2 == "C"
assert load_calls == [["A", "B"], ["C"]]
@mark.asyncio
async def test_clears_single_value_in_loader():
identity_loader, load_calls = id_loader()
a, b = await gather(identity_loader.load("A"), identity_loader.load("B"))
assert a == "A"
assert b == "B"
assert load_calls == [["A", "B"]]
identity_loader.clear("A")
a2, b2 = await gather(identity_loader.load("A"), identity_loader.load("B"))
assert a2 == "A"
assert b2 == "B"
assert load_calls == [["A", "B"], ["A"]]
@mark.asyncio
async def test_clears_all_values_in_loader():
identity_loader, load_calls = id_loader()
a, b = await gather(identity_loader.load("A"), identity_loader.load("B"))
assert a == "A"
assert b == "B"
assert load_calls == [["A", "B"]]
identity_loader.clear_all()
a2, b2 = await gather(identity_loader.load("A"), identity_loader.load("B"))
assert a2 == "A"
assert b2 == "B"
assert load_calls == [["A", "B"], ["A", "B"]]
@mark.asyncio
async def test_allows_priming_the_cache():
identity_loader, load_calls = id_loader()
identity_loader.prime("A", "A")
a, b = await gather(identity_loader.load("A"), identity_loader.load("B"))
assert a == "A"
assert b == "B"
assert load_calls == [["B"]]
@mark.asyncio
async def test_does_not_prime_keys_that_already_exist():
identity_loader, load_calls = id_loader()
identity_loader.prime("A", "X")
a1 = await identity_loader.load("A")
b1 = await identity_loader.load("B")
assert a1 == "X"
assert b1 == "B"
identity_loader.prime("A", "Y")
identity_loader.prime("B", "Y")
a2 = await identity_loader.load("A")
b2 = await identity_loader.load("B")
assert a2 == "X"
assert b2 == "B"
assert load_calls == [["B"]]
# # Represents Errors
@mark.asyncio
async def test_resolves_to_error_to_indicate_failure():
async def resolve(keys):
mapped_keys = [
key if key % 2 == 0 else Exception("Odd: {}".format(key)) for key in keys
]
return mapped_keys
even_loader, load_calls = id_loader(resolve=resolve)
with raises(Exception) as exc_info:
await even_loader.load(1)
assert str(exc_info.value) == "Odd: 1"
value2 = await even_loader.load(2)
assert value2 == 2
assert load_calls == [[1], [2]]
@mark.asyncio
async def test_can_represent_failures_and_successes_simultaneously():
async def resolve(keys):
mapped_keys = [
key if key % 2 == 0 else Exception("Odd: {}".format(key)) for key in keys
]
return mapped_keys
even_loader, load_calls = id_loader(resolve=resolve)
promise1 = even_loader.load(1)
promise2 = even_loader.load(2)
with raises(Exception) as exc_info:
await promise1
assert str(exc_info.value) == "Odd: 1"
value2 = await promise2
assert value2 == 2
assert load_calls == [[1, 2]]
@mark.asyncio
async def test_caches_failed_fetches():
async def resolve(keys):
mapped_keys = [Exception("Error: {}".format(key)) for key in keys]
return mapped_keys
error_loader, load_calls = id_loader(resolve=resolve)
with raises(Exception) as exc_info:
await error_loader.load(1)
assert str(exc_info.value) == "Error: 1"
with raises(Exception) as exc_info:
await error_loader.load(1)
assert str(exc_info.value) == "Error: 1"
assert load_calls == [[1]]
@mark.asyncio
async def test_caches_failed_fetches_2():
identity_loader, load_calls = id_loader()
identity_loader.prime(1, Exception("Error: 1"))
with raises(Exception) as _:
await identity_loader.load(1)
assert load_calls == []
# It is resilient to job queue ordering
@mark.asyncio
async def test_batches_loads_occuring_within_promises():
identity_loader, load_calls = id_loader()
async def load_b_1():
return await load_b_2()
async def load_b_2():
return await identity_loader.load("B")
values = await gather(identity_loader.load("A"), load_b_1())
assert values == ["A", "B"]
assert load_calls == [["A", "B"]]
@mark.asyncio
async def test_catches_error_if_loader_resolver_fails():
exc = Exception("AOH!")
def do_resolve(x):
raise exc
a_loader, a_load_calls = id_loader(resolve=do_resolve)
with raises(Exception) as exc_info:
await a_loader.load("A1")
assert exc_info.value == exc
@mark.asyncio
async def test_can_call_a_loader_from_a_loader():
deep_loader, deep_load_calls = id_loader()
a_loader, a_load_calls = id_loader(
resolve=lambda keys: deep_loader.load(tuple(keys))
)
b_loader, b_load_calls = id_loader(
resolve=lambda keys: deep_loader.load(tuple(keys))
)
a1, b1, a2, b2 = await gather(
a_loader.load("A1"),
b_loader.load("B1"),
a_loader.load("A2"),
b_loader.load("B2"),
)
assert a1 == "A1"
assert b1 == "B1"
assert a2 == "A2"
assert b2 == "B2"
assert a_load_calls == [["A1", "A2"]]
assert b_load_calls == [["B1", "B2"]]
assert deep_load_calls == [[("A1", "A2"), ("B1", "B2")]]
@mark.asyncio
async def test_dataloader_clear_with_missing_key_works():
async def do_resolve(x):
return x
a_loader, a_load_calls = id_loader(resolve=do_resolve)
assert a_loader.clear("A1") == a_loader

View File

@@ -0,0 +1,179 @@
import datetime
import graphene
from graphene import relay
from graphene.types.resolver import dict_resolver
from ..deduplicator import deflate
def test_does_not_modify_object_without_typename_and_id():
response = {"foo": "bar"}
deflated_response = deflate(response)
assert deflated_response == {"foo": "bar"}
def test_does_not_modify_first_instance_of_an_object():
response = {
"data": [
{"__typename": "foo", "id": 1, "name": "foo"},
{"__typename": "foo", "id": 1, "name": "foo"},
]
}
deflated_response = deflate(response)
assert deflated_response == {
"data": [
{"__typename": "foo", "id": 1, "name": "foo"},
{"__typename": "foo", "id": 1},
]
}
def test_does_not_modify_first_instance_of_an_object_nested():
response = {
"data": [
{
"__typename": "foo",
"bar1": {"__typename": "bar", "id": 1, "name": "bar"},
"bar2": {"__typename": "bar", "id": 1, "name": "bar"},
"id": 1,
},
{
"__typename": "foo",
"bar1": {"__typename": "bar", "id": 1, "name": "bar"},
"bar2": {"__typename": "bar", "id": 1, "name": "bar"},
"id": 2,
},
]
}
deflated_response = deflate(response)
assert deflated_response == {
"data": [
{
"__typename": "foo",
"bar1": {"__typename": "bar", "id": 1, "name": "bar"},
"bar2": {"__typename": "bar", "id": 1, "name": "bar"},
"id": 1,
},
{
"__typename": "foo",
"bar1": {"__typename": "bar", "id": 1},
"bar2": {"__typename": "bar", "id": 1},
"id": 2,
},
]
}
def test_does_not_modify_input():
response = {
"data": [
{"__typename": "foo", "id": 1, "name": "foo"},
{"__typename": "foo", "id": 1, "name": "foo"},
]
}
deflate(response)
assert response == {
"data": [
{"__typename": "foo", "id": 1, "name": "foo"},
{"__typename": "foo", "id": 1, "name": "foo"},
]
}
TEST_DATA = {
"events": [
{"id": "568", "date": datetime.date(2017, 5, 19), "movie": "1198359"},
{"id": "234", "date": datetime.date(2017, 5, 20), "movie": "1198359"},
],
"movies": {
"1198359": {
"id": "1198359",
"name": "King Arthur: Legend of the Sword",
"synopsis": (
"When the child Arthur's father is murdered, Vortigern, "
"Arthur's uncle, seizes the crown. Robbed of his birthright and "
"with no idea who he truly is..."
),
}
},
}
def test_example_end_to_end():
class Movie(graphene.ObjectType):
class Meta:
interfaces = (relay.Node,)
default_resolver = dict_resolver
name = graphene.String(required=True)
synopsis = graphene.String(required=True)
class Event(graphene.ObjectType):
class Meta:
interfaces = (relay.Node,)
default_resolver = dict_resolver
movie = graphene.Field(Movie, required=True)
date = graphene.types.datetime.Date(required=True)
def resolve_movie(event, info):
return TEST_DATA["movies"][event["movie"]]
class Query(graphene.ObjectType):
events = graphene.List(graphene.NonNull(Event), required=True)
def resolve_events(_, info):
return TEST_DATA["events"]
schema = graphene.Schema(query=Query)
query = """\
{
events {
__typename
id
date
movie {
__typename
id
name
synopsis
}
}
}
"""
result = schema.execute(query)
assert not result.errors
data = deflate(result.data)
assert data == {
"events": [
{
"__typename": "Event",
"id": "RXZlbnQ6NTY4",
"date": "2017-05-19",
"movie": {
"__typename": "Movie",
"id": "TW92aWU6MTE5ODM1OQ==",
"name": "King Arthur: Legend of the Sword",
"synopsis": (
"When the child Arthur's father is murdered, Vortigern, "
"Arthur's uncle, seizes the crown. Robbed of his birthright and "
"with no idea who he truly is..."
),
},
},
{
"__typename": "Event",
"id": "RXZlbnQ6MjM0",
"date": "2017-05-20",
"movie": {"__typename": "Movie", "id": "TW92aWU6MTE5ODM1OQ=="},
},
]
}

View File

@@ -0,0 +1,9 @@
from .. import deprecated
from ..deprecated import warn_deprecation
def test_warn_deprecation(mocker):
mocker.patch.object(deprecated, "warn")
warn_deprecation("OH!")
deprecated.warn.assert_called_with("OH!", stacklevel=2, category=DeprecationWarning)

View File

@@ -0,0 +1,69 @@
from pytest import raises
from graphene import ObjectType, String
from ..module_loading import import_string, lazy_import
def test_import_string():
MyString = import_string("graphene.String")
assert MyString == String
MyObjectTypeMeta = import_string("graphene.ObjectType", "__doc__")
assert MyObjectTypeMeta == ObjectType.__doc__
def test_import_string_module():
with raises(Exception) as exc_info:
import_string("graphenea")
assert str(exc_info.value) == "graphenea doesn't look like a module path"
def test_import_string_class():
with raises(Exception) as exc_info:
import_string("graphene.Stringa")
assert (
str(exc_info.value)
== 'Module "graphene" does not define a "Stringa" attribute/class'
)
def test_import_string_attributes():
with raises(Exception) as exc_info:
import_string("graphene.String", "length")
assert (
str(exc_info.value)
== 'Module "graphene" does not define a "length" attribute inside attribute/class '
'"String"'
)
with raises(Exception) as exc_info:
import_string("graphene.ObjectType", "__class__.length")
assert (
str(exc_info.value)
== 'Module "graphene" does not define a "__class__.length" attribute inside '
'attribute/class "ObjectType"'
)
with raises(Exception) as exc_info:
import_string("graphene.ObjectType", "__classa__.__base__")
assert (
str(exc_info.value)
== 'Module "graphene" does not define a "__classa__" attribute inside attribute/class '
'"ObjectType"'
)
def test_lazy_import():
f = lazy_import("graphene.String")
MyString = f()
assert MyString == String
f = lazy_import("graphene.ObjectType", "__doc__")
MyObjectTypeMeta = f()
assert MyObjectTypeMeta == ObjectType.__doc__

View File

@@ -0,0 +1,41 @@
from ..orderedtype import OrderedType
def test_orderedtype():
one = OrderedType()
two = OrderedType()
three = OrderedType()
assert one < two < three
def test_orderedtype_eq():
one = OrderedType()
two = OrderedType()
assert one == one
assert one != two
def test_orderedtype_hash():
one = OrderedType()
two = OrderedType()
assert hash(one) == hash(one)
assert hash(one) != hash(two)
def test_orderedtype_resetcounter():
one = OrderedType()
two = OrderedType()
one.reset_counter()
assert one > two
def test_orderedtype_non_orderabletypes():
one = OrderedType()
assert one.__lt__(1) == NotImplemented
assert one.__gt__(1) == NotImplemented
assert one != 1

View File

@@ -0,0 +1,13 @@
from .. import deprecated
from ..resolve_only_args import resolve_only_args
def test_resolve_only_args(mocker):
mocker.patch.object(deprecated, "warn_deprecation")
def resolver(root, **args):
return root, args
wrapped_resolver = resolve_only_args(resolver)
result = wrapped_resolver(1, 2, a=3)
assert result == (1, {"a": 3})

View File

@@ -0,0 +1,19 @@
# coding: utf-8
from ..str_converters import to_camel_case, to_snake_case
def test_snake_case():
assert to_snake_case("snakesOnAPlane") == "snakes_on_a_plane"
assert to_snake_case("SnakesOnAPlane") == "snakes_on_a_plane"
assert to_snake_case("SnakesOnA_Plane") == "snakes_on_a__plane"
assert to_snake_case("snakes_on_a_plane") == "snakes_on_a_plane"
assert to_snake_case("snakes_on_a__plane") == "snakes_on_a__plane"
assert to_snake_case("IPhoneHysteria") == "i_phone_hysteria"
assert to_snake_case("iPhoneHysteria") == "i_phone_hysteria"
def test_camel_case():
assert to_camel_case("snakes_on_a_plane") == "snakesOnAPlane"
assert to_camel_case("snakes_on_a__plane") == "snakesOnA_Plane"
assert to_camel_case("i_phone_hysteria") == "iPhoneHysteria"
assert to_camel_case("field_i18n") == "fieldI18n"

View File

@@ -0,0 +1,22 @@
from ..trim_docstring import trim_docstring
def test_trim_docstring():
class WellDocumentedObject:
"""
This object is very well-documented. It has multiple lines in its
description.
Multiple paragraphs too
"""
assert (
trim_docstring(WellDocumentedObject.__doc__)
== "This object is very well-documented. It has multiple lines in its\n"
"description.\n\nMultiple paragraphs too"
)
class UndocumentedObject:
pass
assert trim_docstring(UndocumentedObject.__doc__) is None

View File

@@ -0,0 +1,25 @@
"""
This file is used mainly as a bridge for thenable abstractions.
"""
from inspect import isawaitable
def await_and_execute(obj, on_resolve):
async def build_resolve_async():
return on_resolve(await obj)
return build_resolve_async()
def maybe_thenable(obj, on_resolve):
"""
Execute a on_resolve function once the thenable is resolved,
returning the same type of object inputed.
If the object is not thenable, it should return on_resolve(obj)
"""
if isawaitable(obj):
return await_and_execute(obj, on_resolve)
# If it's not awaitable, return the function executed over the object
return on_resolve(obj)

View File

@@ -0,0 +1,9 @@
import inspect
def trim_docstring(docstring):
# Cleans up whitespaces from an indented docstring
#
# See https://www.python.org/dev/peps/pep-0257/
# and https://docs.python.org/2/library/inspect.html#inspect.cleandoc
return inspect.cleandoc(docstring) if docstring else None