hypothesis-graphql


Namehypothesis-graphql JSON
Version 0.11.1 PyPI version JSON
download
home_pageNone
SummaryHypothesis strategies for GraphQL queries
upload_time2024-08-06 18:32:25
maintainerNone
docs_urlNone
authorNone
requires_python>=3.8
licenseNone
keywords graphql hypothesis testing
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # hypothesis-graphql

[![Build](https://github.com/Stranger6667/hypothesis-graphql/workflows/build/badge.svg)](https://github.com/Stranger6667/hypothesis-graphql/actions)
[![Coverage](https://codecov.io/gh/Stranger6667/hypothesis-graphql/branch/master/graph/badge.svg)](https://codecov.io/gh/Stranger6667/hypothesis-graphql/branch/master)
[![Version](https://img.shields.io/pypi/v/hypothesis-graphql.svg)](https://pypi.org/project/hypothesis-graphql/)
[![Python versions](https://img.shields.io/pypi/pyversions/hypothesis-graphql.svg)](https://pypi.org/project/hypothesis-graphql/)
[![Chat](https://img.shields.io/discord/938139740912369755)](https://discord.gg/VnxfdFmBUp)
[![License](https://img.shields.io/pypi/l/hypothesis-graphql.svg)](https://opensource.org/licenses/MIT)

<h4 align="center">
Generate queries matching your GraphQL schema, and use them to verify your backend implementation
</h4>

It is a Python library that provides a set of [Hypothesis](https://github.com/HypothesisWorks/hypothesis/tree/master/hypothesis-python) 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](https://github.com/schemathesis/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:

```python
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:

```python
@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.

```python
@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`:

```python
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](https://opensource.org/licenses/MIT).
By contributing to `hypothesis-graphql`, you agree that your contributions will be licensed under its MIT license.

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "hypothesis-graphql",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": "Dmitry Dygalo <dmitry@dygalo.dev>",
    "keywords": "graphql, hypothesis, testing",
    "author": null,
    "author_email": "Dmitry Dygalo <dmitry@dygalo.dev>",
    "download_url": "https://files.pythonhosted.org/packages/14/65/edad164cc4d359bff8c36a2294ab7c60c95a528b600bc22a8f7d9928f9e1/hypothesis_graphql-0.11.1.tar.gz",
    "platform": null,
    "description": "# hypothesis-graphql\n\n[![Build](https://github.com/Stranger6667/hypothesis-graphql/workflows/build/badge.svg)](https://github.com/Stranger6667/hypothesis-graphql/actions)\n[![Coverage](https://codecov.io/gh/Stranger6667/hypothesis-graphql/branch/master/graph/badge.svg)](https://codecov.io/gh/Stranger6667/hypothesis-graphql/branch/master)\n[![Version](https://img.shields.io/pypi/v/hypothesis-graphql.svg)](https://pypi.org/project/hypothesis-graphql/)\n[![Python versions](https://img.shields.io/pypi/pyversions/hypothesis-graphql.svg)](https://pypi.org/project/hypothesis-graphql/)\n[![Chat](https://img.shields.io/discord/938139740912369755)](https://discord.gg/VnxfdFmBUp)\n[![License](https://img.shields.io/pypi/l/hypothesis-graphql.svg)](https://opensource.org/licenses/MIT)\n\n<h4 align=\"center\">\nGenerate queries matching your GraphQL schema, and use them to verify your backend implementation\n</h4>\n\nIt is a Python library that provides a set of [Hypothesis](https://github.com/HypothesisWorks/hypothesis/tree/master/hypothesis-python) strategies that\nlet you write tests parametrized by a source of examples.\nGenerated queries have arbitrary depth and may contain any subset of GraphQL types defined in the input schema.\nThey expose edge cases in your code that are unlikely to be found otherwise.\n\n[Schemathesis](https://github.com/schemathesis/schemathesis) provides a higher-level interface around this library and finds server crashes automatically.\n\n## Usage\n\n`hypothesis-graphql` provides the `from_schema` function, which takes a GraphQL schema and returns a Hypothesis strategy for\nGraphQL queries matching the schema:\n\n```python\nfrom hypothesis import given\nfrom hypothesis_graphql import from_schema\nimport requests\n\n# Strings and `graphql.GraphQLSchema` are supported\nSCHEMA = \"\"\"\ntype Book {\n  title: String\n  author: Author\n}\n\ntype Author {\n  name: String\n  books: [Book]\n}\n\ntype Query {\n  getBooks: [Book]\n  getAuthors: [Author]\n}\n\ntype Mutation {\n  addBook(title: String!, author: String!): Book!\n  addAuthor(name: String!): Author!\n}\n\"\"\"\n\n\n@given(from_schema(SCHEMA))\ndef test_graphql(query):\n    # Will generate samples like these:\n    #\n    # {\n    #   getBooks {\n    #     title\n    #   }\n    # }\n    #\n    # mutation {\n    #   addBook(title: \"H4Z\\u7869\", author: \"\\u00d2\"){\n    #     title\n    #   }\n    # }\n    response = requests.post(\"http://127.0.0.1/graphql\", json={\"query\": query})\n    assert response.status_code == 200\n    assert response.json().get(\"errors\") is None\n```\n\nIt is also possible to generate queries or mutations separately with `hypothesis_graphql.queries` and `hypothesis_graphql.mutations`.\n\n### Customization\n\nTo restrict the set of fields in generated operations use the `fields` argument:\n\n```python\n@given(from_schema(SCHEMA, fields=[\"getAuthors\"]))\ndef test_graphql(query):\n    # Only `getAuthors` will be generated\n    ...\n```\n\nYou can customize the string generation with these arguments to `from_schema`:\n\n- `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.\n- `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.\n\n```python\n@given(from_schema(SCHEMA, allow_x00=False, codec=\"ascii\"))\ndef test_graphql(query):\n    assert \"\\0\" not in query\n    query.encode(\"ascii\")\n```\n\nIt is also possible to generate custom scalars. For example, `Date`:\n\n```python\nfrom hypothesis import strategies as st, given\nfrom hypothesis_graphql import from_schema, nodes\n\nSCHEMA = \"\"\"\nscalar Date\n\ntype Query {\n  getByDate(created: Date!): Int\n}\n\"\"\"\n\n\n@given(\n    from_schema(\n        SCHEMA,\n        custom_scalars={\n            # Standard scalars work out of the box, for custom ones you need\n            # to pass custom strategies that generate proper AST nodes\n            \"Date\": st.dates().map(nodes.String)\n        },\n    )\n)\ndef test_graphql(query):\n    # Example:\n    #\n    #  { getByDate(created: \"2000-01-01\") }\n    #\n    ...\n```\n\nThe `hypothesis_graphql.nodes` module includes a few helpers to generate various node types:\n\n- `String` -> `graphql.StringValueNode`\n- `Float` -> `graphql.FloatValueNode`\n- `Int` -> `graphql.IntValueNode`\n- `Object` -> `graphql.ObjectValueNode`\n- `List` -> `graphql.ListValueNode`\n- `Boolean` -> `graphql.BooleanValueNode`\n- `Enum` -> `graphql.EnumValueNode`\n- `Null` -> `graphql.NullValueNode` (a constant, not a function)\n\nThey exist because classes like `graphql.StringValueNode` can't be directly used in `map` calls due to kwarg-only arguments.\n\n## License\n\nThe code in this project is licensed under [MIT license](https://opensource.org/licenses/MIT).\nBy contributing to `hypothesis-graphql`, you agree that your contributions will be licensed under its MIT license.\n",
    "bugtrack_url": null,
    "license": null,
    "summary": "Hypothesis strategies for GraphQL queries",
    "version": "0.11.1",
    "project_urls": {
        "Bug Tracker": "https://github.com/Stranger6667/hypothesis-graphql",
        "Changelog": "https://github.com/Stranger6667/hypothesis-graphql/blob/master/CHANGELOG.md",
        "Funding": "https://github.com/sponsors/Stranger6667",
        "Source Code": "https://github.com/Stranger6667/hypothesis-graphql"
    },
    "split_keywords": [
        "graphql",
        " hypothesis",
        " testing"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "2a06fde2bf77d6cc7b77c4c944cc292e73bc1ed0a093afbd8e4444688168f675",
                "md5": "68467300f80820a4697631c5bfac1d52",
                "sha256": "a6968f703bcdc31fbe1b26be69185aa2c824eb3b478057a66aa85967c81cadca"
            },
            "downloads": -1,
            "filename": "hypothesis_graphql-0.11.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "68467300f80820a4697631c5bfac1d52",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 16368,
            "upload_time": "2024-08-06T18:32:27",
            "upload_time_iso_8601": "2024-08-06T18:32:27.105182Z",
            "url": "https://files.pythonhosted.org/packages/2a/06/fde2bf77d6cc7b77c4c944cc292e73bc1ed0a093afbd8e4444688168f675/hypothesis_graphql-0.11.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "1465edad164cc4d359bff8c36a2294ab7c60c95a528b600bc22a8f7d9928f9e1",
                "md5": "710dbf07ebe8a41f174ad4cd75a96a78",
                "sha256": "bd49ab6804a3f488ecab2e39c20dba6dfc2101525c6742f5831cfa9eff95285a"
            },
            "downloads": -1,
            "filename": "hypothesis_graphql-0.11.1.tar.gz",
            "has_sig": false,
            "md5_digest": "710dbf07ebe8a41f174ad4cd75a96a78",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 741872,
            "upload_time": "2024-08-06T18:32:25",
            "upload_time_iso_8601": "2024-08-06T18:32:25.546195Z",
            "url": "https://files.pythonhosted.org/packages/14/65/edad164cc4d359bff8c36a2294ab7c60c95a528b600bc22a8f7d9928f9e1/hypothesis_graphql-0.11.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-08-06 18:32:25",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "Stranger6667",
    "github_project": "hypothesis-graphql",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "tox": true,
    "lcname": "hypothesis-graphql"
}
        
Elapsed time: 0.39445s