Getting started with GraphQL and Python most of the documentation is focused on the basics: basic queries, filtering using pre-built libraries and so forth. This is great for quick “Hello World” APIs, but there isn’t much discussion for best practices that discuss how to build out larger APIs, testing, or maintenance. Perhaps it’s just too early in the Python-GraphQL story for the best practices to have been fully established and documented.
Introductory GraphQL examples online don’t really require much testing of the resolver specifically. This is because these examples just return the results of a Django Queryset directly. For those types of fields executing a full query is usually enough. But how to you handle more complex resolvers, ones that have some processing?
Accessing your resolver directly from a unit test is difficult and cumbersome. To properly test a resolver, you’re going to need to split the parts that warrant independent testing into their own functions / classes. Then once it’s split, you can pass the required input for processing, and return the results.
However passing or returning Graphene objects to your functions will make testing them difficult in much of the same way that calling your resolver outside of a GraphQL request is difficult: you can’t access the attribute values directly – they must be resolved.
blog = Blog(title="my title") assert blog.title === "my title" # fail
Where Blog is a Graphene object, the above test will fail. As
blog.title will not be a String as you’d think, but rather a graphene wrapper that will eventually return “my title” when passed through the GraphQL machine.
There’s two ways to work around this:
- Pass in `namedtuples` that match attribute for attribute your Graphene objects in their place. This is will become a maintenance headache as each time your object changes, you’ll need to also update your named tuples to match.
- Pass/return primitive values into your functions and box them into GraphQL objects in your resolver directly before return.
I’ve done both in my code and think that the second method is a best practice when writing GraphQL apis.
By passing the values from graphene as primitives to your processing functions your code is no longer tied directly to graphene directly. You can change frameworks and re-use the same code.
It’s also easier to write tests as you pass in common objects like
int which are quite easy to assert equality and simpler to reason about.
- Break your logic out of your resolver and into specialized functions / classes.
- Pass/return primitive or other such values from these functions to maximize reuse.