Skip to content

Commit

Permalink
Merge branch 'master' into async_sync_graceful_shutdown
Browse files Browse the repository at this point in the history
  • Loading branch information
leszekhanusz committed Jun 14, 2020
2 parents 26c577f + a21ff73 commit 6220bff
Show file tree
Hide file tree
Showing 10 changed files with 107 additions and 21 deletions.
2 changes: 1 addition & 1 deletion CODEOWNERS
Validating CODEOWNERS rules …
Original file line number Diff line number Diff line change
@@ -1 +1 @@
/ @syrusakbary @ekampf @cito
/ @syrusakbary @ekampf @cito @leszekhanusz @KingDarBoja
53 changes: 49 additions & 4 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,16 +57,44 @@ And you ready to start development!

<!-- TODO: Provide environment.yml file for conda env -->

## Coding guidelines

Several tools are used to ensure a coherent coding style.
You need to make sure that your code satisfy those requirements
or the automated tests will fail.

- [black code formatter](https://github.com/psf/black)
- [flake8 style enforcement](https://flake8.pycqa.org/en/latest/index.html)
- [mypy static type checker](http://mypy-lang.org/)
- [isort to sort imports alphabetically](https://isort.readthedocs.io/en/stable/)

On Linux or MacOS, you can fix and check your code style by running
the Makefile command `make check` (this is also checked by running
the automated tests with tox but it is much faster with make)

In addition to the above checks, it is asked that:

- [type hints are used](https://docs.python.org/3/library/typing.html)
- tests are added to ensure complete code coverage

## Running tests

After developing, the full test suite can be evaluated by running:

```sh
pytest tests --cov=gql -vv
pytest tests --cov=gql --cov-report=term-missing -vv
```

If you are using Linux or MacOS, you can make use of Makefile command
`make tests`, which is a shortcut for the above python command.
Please note that some tests which require external online resources are not
done in the automated tests. You can run those tests by running:

```sh
pytest tests --cov=gql --cov-report=term-missing --run-online -vv
```

If you are using Linux or MacOS, you can make use of Makefile commands
`make tests` and `make all_tests`, which are shortcuts for the above
python commands.

You can also test on several python environments by using tox.

Expand All @@ -91,7 +119,24 @@ conda install -c conda-forge tox-conda

This install tox underneath so no need to install it before.

Then uncomment the `requires = tox-conda` line on `tox.ini` file.
Then add the line `requires = tox-conda` in the `tox.ini` file under `[tox]`.

Run `tox` and you will see all the environments being created
and all passing tests. :rocket:

## How to create a good Pull Request

1. Make a fork of the master branch on github
2. Clone your forked repo on your computer
3. Create a feature branch `git checkout -b feature_my_awesome_feature`
4. Modify the code
5. Verify that the [Coding guidelines](#coding-guidelines) are respected
6. Verify that the [automated tests](#running-tests) are passing
7. Make a commit and push it to your fork
8. From github, create the pull request. Automated tests from travis
and coveralls will then automatically run the tests and check the code coverage
9. If other modifications are needed, you are free to create more commits and
push them on your branch. They'll get added to the PR automatically.

Once the Pull Request is accepted and merged, you can safely
delete the branch (and the forked repo if no more development is needed).
8 changes: 4 additions & 4 deletions gql/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,10 +71,10 @@ def __init__(
session.fetch_schema()

def validate(self, document):
if not self.schema:
raise Exception(
"Cannot validate the document locally, you need to pass a schema."
)
assert (
self.schema
), "Cannot validate the document locally, you need to pass a schema."

validation_errors = validate(self.schema, document)
if validation_errors:
raise validation_errors[0]
Expand Down
2 changes: 1 addition & 1 deletion gql/dsl.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ def selection_field(field):
if isinstance(field, DSLField):
return field

raise Exception(f'Received incompatible query field: "{field}".')
raise TypeError(f'Received incompatible query field: "{field}".')


def query(*fields, **kwargs):
Expand Down
6 changes: 2 additions & 4 deletions gql/gql.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
from graphql import Source, parse
from graphql import DocumentNode, Source, parse


def gql(request_string):
if not isinstance(request_string, str):
raise Exception(f'Received incompatible request "{request_string}".')
def gql(request_string: str) -> DocumentNode:
source = Source(request_string, "GraphQL request")
return parse(source)
9 changes: 6 additions & 3 deletions gql/transport/aiohttp.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,12 +103,15 @@ async def execute(
"""

query_str = print_ast(document)
payload = {
payload: Dict[str, Any] = {
"query": query_str,
"variables": variable_values or {},
"operationName": operation_name or "",
}

if variable_values:
payload["variables"] = variable_values
if operation_name:
payload["operationName"] = operation_name

post_args = {
"json": payload,
}
Expand Down
2 changes: 1 addition & 1 deletion scripts/gql-cli
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ async def main():
elif scheme in ["http", "https"]:
transport = AIOHTTPTransport(url=args.server)
else:
raise Exception("URL protocol should be one of: http, https, ws, wss")
raise ValueError("URL protocol should be one of: http, https, ws, wss")

async with Client(transport=transport) as session:

Expand Down
4 changes: 2 additions & 2 deletions tests/starwars/test_validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,9 +75,9 @@ def validation_errors(client, query):


def test_incompatible_request_gql(client):
with pytest.raises(Exception) as exc_info:
with pytest.raises(TypeError) as exc_info:
gql(123)
assert "Received incompatible request" in str(exc_info.value)
assert "body must be a string" in str(exc_info.value)


def test_nested_query_with_fragment(client):
Expand Down
40 changes: 40 additions & 0 deletions tests/test_aiohttp.py
Original file line number Diff line number Diff line change
Expand Up @@ -222,3 +222,43 @@ async def handler(request):
africa = continents[0]

assert africa["code"] == "AF"


query2_str = """
query getEurope ($code: ID!) {
continent (code: $code) {
name
}
}
"""

query2_server_answer = '{"data": {"continent": {"name": "Europe"}}}'


@pytest.mark.asyncio
async def test_aiohttp_query_variable_values(event_loop, aiohttp_server):
async def handler(request):
return web.Response(text=query2_server_answer, content_type="application/json")

app = web.Application()
app.router.add_route("POST", "/", handler)
server = await aiohttp_server(app)

url = server.make_url("/")

sample_transport = AIOHTTPTransport(url=url, timeout=10)

async with Client(transport=sample_transport,) as session:

params = {"code": "EU"}

query = gql(query2_str)

# Execute query asynchronously
result = await session.execute(
query, variable_values=params, operation_name="getEurope"
)

continent = result["continent"]

assert continent["name"] == "Europe"
2 changes: 1 addition & 1 deletion tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ def test_retries_on_transport(execute_mock):


def test_no_schema_exception():
with pytest.raises(Exception) as exc_info:
with pytest.raises(AssertionError) as exc_info:
client = Client()
client.validate("")
assert "Cannot validate the document locally, you need to pass a schema." in str(
Expand Down

0 comments on commit 6220bff

Please sign in to comment.