Skip to content

Commit

Permalink
Update README.md
Browse files Browse the repository at this point in the history
  • Loading branch information
HmbleCreator authored Oct 24, 2024
1 parent b318f59 commit 42339c2
Showing 1 changed file with 64 additions and 19 deletions.
83 changes: 64 additions & 19 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,20 +23,17 @@ Create a new file `app.py`:
```python
import strawberry


@strawberry.type
class User:
name: str
age: int


@strawberry.type
class Query:
@strawberry.field
def user(self) -> User:
return User(name="Patrick", age=100)


schema = strawberry.Schema(query=Query)
```

Expand Down Expand Up @@ -93,35 +90,83 @@ pip install 'uvicorn[standard]'

## Testing

Strawberry provides built-in testing utilities through `BaseGraphQLTestClient`:
Strawberry provides built-in testing utilities through `BaseGraphQLTestClient`. Here's a complete example showing how to test a GraphQL API using different HTTP clients:

```python
from strawberry.test import BaseGraphQLTestClient


class MyTestClient(BaseGraphQLTestClient):
def request(self, body, headers=None, files=None):
# Implement request logic
pass

import httpx # or any other HTTP client of your choice

# Example using httpx
class HttpxTestClient(BaseGraphQLTestClient):
def __init__(self):
self.client = httpx.Client(base_url="http://localhost:8000")

def request(self, body: str, headers=None, files=None):
headers = headers or {}
response = self.client.post(
"/graphql",
json=body,
headers=headers,
files=files
)
return response.json()

# Example using requests
from requests import Session

class RequestsTestClient(BaseGraphQLTestClient):
def __init__(self):
self.client = Session()
self.client.base_url = "http://localhost:8000"

def request(self, body: str, headers=None, files=None):
headers = headers or {}
response = self.client.post(
f"{self.client.base_url}/graphql",
json=body,
headers=headers,
files=files
)
return response.json()

def test_query():
client = MyTestClient(http_client)
# Choose your preferred client implementation
client = HttpxTestClient() # or RequestsTestClient()

response = client.query("""
{
user {
name
age
}
}
""")

assert response.data["user"]["name"] == "Patrick"
assert not response.errors

# Example with variables
def test_query_with_variables():
client = HttpxTestClient()

response = client.query(
"""
{
user {
name
age
}
query GetUser($id: ID!) {
user(id: $id) {
name
age
}
}
"""
""",
variables={"id": "123"}
)

assert response.data["user"]["name"] == "Patrick"
assert not response.errors
```

The examples above show two different implementations using popular HTTP clients (httpx and requests). You can choose the one that best fits your project's needs or implement your own client using any HTTP library.

## Examples & Resources

- [Official Examples Repository](https://github.com/strawberry-graphql/examples)
Expand Down

0 comments on commit 42339c2

Please sign in to comment.