Hypothesis-GraphQL

0.12.0 · active · verified Sat Apr 11

Hypothesis-GraphQL provides Hypothesis strategies for generating arbitrary GraphQL queries that conform to a given schema. This Python library is crucial for property-based testing of GraphQL backend implementations, helping to uncover edge cases and validate server behavior against a wide range of valid and invalid inputs. It is actively maintained, with regular updates.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `hypothesis-graphql` to generate GraphQL queries based on a schema and then use `requests` to send these queries to a GraphQL endpoint. The `@given(from_schema(SCHEMA))` decorator tells Hypothesis to generate various valid queries for the provided schema, which are then passed to the `test_graphql_api` function. Remember to adapt `GRAPHQL_TEST_ENDPOINT` to your actual server.

from hypothesis import given
from hypothesis_graphql import from_schema
import requests
import os

# Define a simple GraphQL schema
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!
}
"""

# Replace with your actual GraphQL endpoint
GRAPHQL_ENDPOINT = os.environ.get('GRAPHQL_TEST_ENDPOINT', 'http://127.0.0.1:8000/graphql')

@given(from_schema(SCHEMA))
def test_graphql_api(query):
    """Tests a GraphQL endpoint with generated queries."""
    print(f"\nGenerated query:\n{query}")
    try:
        response = requests.post(GRAPHQL_ENDPOINT, json={"query": query})
        response.raise_for_status() # Raise an exception for HTTP errors
        json_response = response.json()

        # Assert no GraphQL errors, unless specifically testing negative cases
        if json_response.get("errors"):
            print(f"GraphQL Errors: {json_response['errors']}")
        
        # Further assertions can go here based on expected data or error types
        assert response.status_code == 200

    except requests.exceptions.ConnectionError:
        print(f"Warning: Could not connect to GraphQL endpoint at {GRAPHQL_ENDPOINT}. "
              "Please ensure your GraphQL server is running.")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")
        raise

# To run the test (e.g., if not using pytest):
# if __name__ == '__main__':
#     # Note: Directly calling @given decorated functions runs a single example.
#     # For property-based testing, run with pytest.
#     print("Running a single generated example. For full property testing, use pytest.")
#     test_graphql_api()

view raw JSON →