Skip to main content

Hypothesis strategies for GraphQL queries

Project description

hypothesis-graphql

Build Coverage Version Python versions Chat License

Generate queries matching your GraphQL schema, and use them to verify your backend implementation

It is a Python library that provides a set of Hypothesis strategies that let you write tests parametrized by a source of examples. Generated queries have arbitrary depth and may contain any subset of GraphQL types defined in the input schema. They expose edge cases in your code that are unlikely to be found otherwise.

Schemathesis provides a higher-level interface around this library and finds server crashes automatically.

Usage

hypothesis-graphql provides the from_schema function, which takes a GraphQL schema and returns a Hypothesis strategy for GraphQL queries matching the schema:

from hypothesis import given
from hypothesis_graphql import from_schema
import requests

# Strings and `graphql.GraphQLSchema` are supported
SCHEMA = """
type Book {
  title: String
  author: Author
}

type Author {
  name: String
  books: [Book]
}

type Query {
  getBooks: [Book]
  getAuthors: [Author]
}

type Mutation {
  addBook(title: String!, author: String!): Book!
  addAuthor(name: String!): Author!
}
"""


@given(from_schema(SCHEMA))
def test_graphql(query):
    # Will generate samples like these:
    #
    # {
    #   getBooks {
    #     title
    #   }
    # }
    #
    # mutation {
    #   addBook(title: "H4Z\u7869", author: "\u00d2"){
    #     title
    #   }
    # }
    response = requests.post("http://127.0.0.1/graphql", json={"query": query})
    assert response.status_code == 200
    assert response.json().get("errors") is None

It is also possible to generate queries or mutations separately with hypothesis_graphql.queries and hypothesis_graphql.mutations.

Customization

To restrict the set of fields in generated operations use the fields argument:

@given(from_schema(SCHEMA, fields=["getAuthors"]))
def test_graphql(query):
    # Only `getAuthors` will be generated
    ...

It is also possible to generate custom scalars. For example, Date:

from hypothesis import strategies as st, given
from hypothesis_graphql import from_schema, nodes

SCHEMA = """
scalar Date

type Query {
  getByDate(created: Date!): Int
}
"""


@given(
    from_schema(
        SCHEMA,
        custom_scalars={
            # Standard scalars work out of the box, for custom ones you need
            # to pass custom strategies that generate proper AST nodes
            "Date": st.dates().map(nodes.String)
        },
    )
)
def test_graphql(query):
    # Example:
    #
    #  { getByDate(created: "2000-01-01") }
    #
    ...

The hypothesis_graphql.nodes module includes a few helpers to generate various node types:

  • String -> graphql.StringValueNode
  • Float -> graphql.FloatValueNode
  • Int -> graphql.IntValueNode
  • Object -> graphql.ObjectValueNode
  • List -> graphql.ListValueNode
  • Boolean -> graphql.BooleanValueNode
  • Enum -> graphql.EnumValueNode
  • Null -> graphql.NullValueNode (a constant, not a function)

They exist because classes like graphql.StringValueNode can't be directly used in map calls due to kwarg-only arguments.

License

The code in this project is licensed under MIT license. By contributing to hypothesis-graphql, you agree that your contributions will be licensed under its MIT license.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

hypothesis_graphql-0.11.0.tar.gz (305.2 kB view details)

Uploaded Source

Built Distribution

hypothesis_graphql-0.11.0-py3-none-any.whl (16.1 kB view details)

Uploaded Python 3

File details

Details for the file hypothesis_graphql-0.11.0.tar.gz.

File metadata

  • Download URL: hypothesis_graphql-0.11.0.tar.gz
  • Upload date:
  • Size: 305.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: python-httpx/0.25.2

File hashes

Hashes for hypothesis_graphql-0.11.0.tar.gz
Algorithm Hash digest
SHA256 a1a1b693170591dd37d9b40a94e6f37181770c21cebad993e2e14e58ddfebaba
MD5 8a50b5e52fbb1e12d790d67ee2d6c459
BLAKE2b-256 d7d2d81cf17dfdd83482dd13c0e1e22f38375db2e14affae5f9f1e23e57db78c

See more details on using hashes here.

File details

Details for the file hypothesis_graphql-0.11.0-py3-none-any.whl.

File metadata

File hashes

Hashes for hypothesis_graphql-0.11.0-py3-none-any.whl
Algorithm Hash digest
SHA256 1beb3b75d60626526f1e40321a9fb42ee13aefb8ff8990c91a1af9108ed1d3e6
MD5 37cd4bcc167405ea5e913197cdf3da1f
BLAKE2b-256 4cd753032581e87f1e2597ee5af0390e90fb2738ca3b3bf2f6b391814487c1f1

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page