43 / 89 · 04 API & Contract Testing with AI · GraphQL Query Depth and N+1 Detection← prev⊞ allnext →☰ Read as one page
7.4Query Complexity Analysis
Beyond depth, GraphQL servers should also limit query complexity:
class TestQueryComplexity:
"""Test query complexity limits."""
def test_complexity_score_calculation(self, graphql_client):
"""Verify the server correctly calculates and limits complexity."""
# A query that requests many items with nested relations
# Each `first: N` multiplies the complexity
query = """
query {
users(first: 100) { # complexity: 100
orders(first: 50) { # complexity: 100 * 50 = 5000
items(first: 20) { # complexity: 5000 * 20 = 100000
product {
reviews(first: 10) { # complexity: 100000 * 10 = 1000000
author { name }
}
}
}
}
}
}
"""
response = graphql_client.execute(query)
# This query should be blocked due to excessive complexity
assert "errors" in response
error_messages = [e["message"] for e in response["errors"]]
assert any("complexity" in msg.lower() for msg in error_messages)