Skip to main content

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
    ...

You can customize the string generation with these arguments to from_schema:

  • allow_x00 (default True): Determines whether to allow the generation of \x00 bytes within strings. It is useful to avoid rejecting tests as invalid by some web servers.
  • codec (default utf-8): Specifies the codec used for generating strings. It helps if you need to restrict the inputs to, for example, the ASCII range.
@given(from_schema(SCHEMA, allow_x00=False, codec="ascii"))
def test_graphql(query):
    assert "\0" not in query
    query.encode("ascii")

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.

Negative Testing

hypothesis-graphql supports generating invalid GraphQL queries for negative testing. This is useful for testing error handling and validation logic in your GraphQL server.

Use the mode=Mode.NEGATIVE parameter to generate queries that should be rejected:

from hypothesis import given
from hypothesis_graphql import queries, Mode
import requests

SCHEMA = """
type Query {
    getUser(id: Int!, name: String!): User
}

type User {
    id: Int!
    name: String!
}
"""


@given(queries(SCHEMA, mode=Mode.NEGATIVE))
def test_server_rejects_invalid_queries(query):
    # Generates queries with violations like:
    # - Wrong types (String where Int expected)
    # - Missing required arguments
    # - Out-of-range integers
    # - Null for non-null fields
    # - Invalid enum values
    response = requests.post("http://127.0.0.1/graphql", json={"query": query})

    # Server should reject with 400 or return errors
    if response.status_code == 200:
        assert "errors" in response.json()

The mode parameter works with queries(), mutations(), and from_schema().

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.

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.13.2.tar.gz (751.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

hypothesis_graphql-0.13.2-py3-none-any.whl (22.9 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: hypothesis_graphql-0.13.2.tar.gz
  • Upload date:
  • Size: 751.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: Hatch/1.18.0 {"ci":true,"cpu":"x86_64","distro":{"id":"noble","libc":{"lib":"glibc","version":"2.39"},"name":"Ubuntu","version":"24.04"},"implementation":{"name":"CPython","version":"3.14.7"},"installer":{"name":"hatch","version":"1.18.0"},"openssl_version":"OpenSSL 3.0.13 30 Jan 2024","python":"3.14.7","system":{"name":"Linux","release":"6.17.0-1022-azure"}} HTTPX2/2.12.0

File hashes

Hashes for hypothesis_graphql-0.13.2.tar.gz
Algorithm Hash digest
SHA256 6d6f8a7c28aa2aa78830713cb1fff49bd3ea0b0045a5490c216ead7dc02e0276
MD5 75f498403dfc5d3d42bac8fa5af82ff7
BLAKE2b-256 a8b8aa6cfa4d99a5a451c71db6120cdb67850b6fe0b86bfb8df7e1affc565274

See more details on using hashes here.

File details

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

File metadata

  • Download URL: hypothesis_graphql-0.13.2-py3-none-any.whl
  • Upload date:
  • Size: 22.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: Hatch/1.18.0 {"ci":true,"cpu":"x86_64","distro":{"id":"noble","libc":{"lib":"glibc","version":"2.39"},"name":"Ubuntu","version":"24.04"},"implementation":{"name":"CPython","version":"3.14.7"},"installer":{"name":"hatch","version":"1.18.0"},"openssl_version":"OpenSSL 3.0.13 30 Jan 2024","python":"3.14.7","system":{"name":"Linux","release":"6.17.0-1022-azure"}} HTTPX2/2.12.0

File hashes

Hashes for hypothesis_graphql-0.13.2-py3-none-any.whl
Algorithm Hash digest
SHA256 fafcc07b901f04d64ac9c6c2e0c48a66817f04bd330766bd8b91bf76dc341a6a
MD5 ca4aa1704ff67971c9438913e883fc20
BLAKE2b-256 bd9743bff05d23714bb533599c55f1bf8cd6810c1e0ca76df674e07421d79007

See more details on using hashes here.

Release history Release notifications | RSS feed

This release

0.13.2 This release

2 files

0.13.1

2 files

0.13.0

2 files

0.12.0

2 files

0.11.1

2 files

0.11.0

2 files

0.10.0

2 files

0.9.2

2 files

0.9.1

2 files

0.9.0

2 files

0.8.2

2 files

0.8.1

2 files

0.8.0

2 files

0.7.1

2 files

0.7.0

2 files

0.6.1

2 files

0.6.0

2 files

0.5.1

2 files

0.5.0

2 files

0.4.2

2 files

0.4.1

2 files

0.4.0

2 files

0.3.3

2 files

0.3.2

2 files

0.3.1

2 files

0.3.0

2 files

0.2.0

2 files

0.1.0

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page