Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for filtering job lists by ID #21

Merged
merged 8 commits into from
Apr 8, 2022
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion .github/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,28 @@

### New features since last release

* Following an update to the Xanadu Cloud 0.4.0 API, job lists can now be filtered by ID.
[(#21)](https://github.com/XanaduAI/xanadu-cloud-client/pull/21)

Using the CLI:

```bash
xcc job list --ids '["<UUID 1>", "<UUID 2>", ...]'
```

Using the Python API:

```python
xcc.Job.list(connection, ids=["<UUID 1>", "<UUID 2>", ...])
```


### Breaking Changes

### Bug fixes

* The license file is included in the source distribution, even when using `setuptools <56.0.0`.
[(#20)](https://github.com/XanaduAI/xanadu-cloud-client/pull/20)
[(#20)](https://github.com/XanaduAI/xanadu-cloud-client/pull/20)

### Documentation

Expand Down
2 changes: 1 addition & 1 deletion requirements-dev.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
black==21.9b0
black==22.3.0
build==0.7.0
isort[colors]==5.9.3
pylint==2.11.1
Expand Down
2 changes: 1 addition & 1 deletion tests/test_commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ class MockJob(xcc.Job):
"""

@staticmethod
def list(connection, limit=10):
def list(connection, limit=10, ids=None):
connection = xcc.commands.load_connection()
return [MockJob(id_, connection) for id_ in ("foo", "bar", "baz")][:limit]

Expand Down
32 changes: 29 additions & 3 deletions tests/test_connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,16 +136,42 @@ def test_request_failure_due_to_invalid_json(self, connection):
with pytest.raises(HTTPError, match=r"400 Client Error: Bad Request"):
connection.request("GET", "/healthz")

@pytest.mark.parametrize(
"meta, match",
[
(
{
"_schema": ["Foo", "Bar"],
"size": ["Baz"],
},
r"Foo; Bar; Baz",
),
(
{
"head": {"0": ["Foo", "Bar"]},
"tail": {"0": ["Baz"], "1": ["Bud"]},
},
r"Foo; Bar; Baz; Bud",
),
(
{
"List": ["Foo"],
"Dict": {"0": ["Bar"]},
},
r"Foo; Bar",
),
],
)
@responses.activate
def test_request_failure_due_to_validation_error(self, connection):
def test_request_failure_due_to_validation_error(self, connection, meta, match):
"""Tests that an HTTPError is raised when the HTTP response of a
connection request indicates that a validation error occurred and the
body of the response contains a non-empty "meta" field.
"""
body = {"code": "validation-error", "meta": {"_schema": ["Foo", "Bar"], "size": ["Baz"]}}
body = {"code": "validation-error", "meta": meta}
responses.add(responses.GET, connection.url("healthz"), status=400, body=json.dumps(body))

with pytest.raises(HTTPError, match=r"Foo; Bar; Baz"):
with pytest.raises(HTTPError, match=match):
connection.request("GET", "/healthz")

@responses.activate
Expand Down
48 changes: 41 additions & 7 deletions tests/test_job.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,15 +54,50 @@ class TestJob:
"""Tests the :class:`xcc.Job` class."""

@pytest.mark.parametrize(
"limit, want_names",
"limit, ids, want_params, want_names",
[
(1, ["foo"]),
(2, ["foo", "bar"]),
(
1,
None,
{"size": "1"},
["foo"],
),
(
2,
None,
{"size": "2"},
["foo", "bar"],
),
(
1,
["00000000-0000-0000-0000-000000000001"],
{"size": "1", "id": "00000000-0000-0000-0000-000000000001"},
["foo"],
),
(
2,
[
"00000000-0000-0000-0000-000000000001",
"00000000-0000-0000-0000-000000000002",
"00000000-0000-0000-0000-000000000003",
],
{
"size": "2",
"id": [
"00000000-0000-0000-0000-000000000001",
"00000000-0000-0000-0000-000000000002",
"00000000-0000-0000-0000-000000000003",
],
},
["foo", "bar"],
),
],
)
@responses.activate
def test_list(self, connection, add_response, limit, want_names):
"""Tests that the correct jobs are listed."""
def test_list(self, connection, add_response, limit, ids, want_params, want_names):
"""Tests that the correct jobs are listed and that the correct query
parameters are encoded in the HTTP request to the Xanadu Cloud platform.
"""
data = [
{
"id": "00000000-0000-0000-0000-000000000001",
Expand All @@ -82,11 +117,10 @@ def test_list(self, connection, add_response, limit, want_names):
][:limit]
add_response(body={"data": data}, path="/jobs")

have_names = [job.name for job in xcc.Job.list(connection, limit=limit)]
have_names = [job.name for job in xcc.Job.list(connection, limit=limit, ids=ids)]
assert have_names == want_names

have_params = responses.calls[0].request.params # pyright: reportGeneralTypeIssues=false
want_params = {"size": str(limit)}
assert have_params == want_params

@pytest.mark.parametrize("name", [None, "foo"])
Expand Down
7 changes: 4 additions & 3 deletions xcc/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import functools
import json
import sys
from typing import Any, Callable, Mapping, Sequence, Tuple, Union
from typing import Any, Callable, Mapping, Optional, Sequence, Tuple, Union

import fire
from fire.core import FireError
Expand Down Expand Up @@ -259,16 +259,17 @@ def get_job(


@beautify
def list_jobs(limit: int = 10) -> Sequence[Mapping]:
def list_jobs(limit: int = 5, ids: Optional[Sequence[str]] = None) -> Sequence[Mapping]:
"""Lists jobs submitted to the Xanadu Cloud.

Args:
limit (int): Maximum number of jobs to display.
ids (Sequence[str], optional): IDs of the jobs to display.

Returns:
Sequence[Mapping]: Overview of each job submitted to the Xanadu Cloud.
"""
jobs = Job.list(connection=load_connection(), limit=limit)
jobs = Job.list(connection=load_connection(), limit=limit, ids=ids)
return [job.overview for job in jobs]


Expand Down
15 changes: 11 additions & 4 deletions xcc/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
This module contains the :class:`~xcc.Connection` class.
"""
from itertools import chain
from typing import Dict, List, Optional
from typing import Dict, List, Optional, Union

import requests

Expand Down Expand Up @@ -225,9 +225,16 @@ def request(self, method: str, path: str, **kwargs) -> requests.Response:
else:
# The details of a validation error are encoded in the "meta" field.
if response.status_code == 400 and body.get("code", "") == "validation-error":
errors: Dict[str, List[str]] = body.get("meta", {})
if errors:
message = "; ".join(chain.from_iterable(errors.values()))
meta: Dict[str, Union[List[str], Dict[str, List[str]]]] = body.get("meta", {})
if meta:
errors = []
for entry in meta.values():
if isinstance(entry, list):
errors.extend(entry)
else:
errors.extend(chain.from_iterable(entry.values()))

message = "; ".join(errors)
raise requests.exceptions.HTTPError(message, response=response)

# Otherwise, the details of the error may be encoded in the "detail" field.
Expand Down
7 changes: 5 additions & 2 deletions xcc/job.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,18 +92,21 @@ class Job:
"""

@staticmethod
def list(connection: Connection, limit: int = 5) -> Sequence[Job]:
def list(
connection: Connection, limit: int = 5, ids: Optional[Sequence[str]] = None
) -> Sequence[Job]:
"""Returns jobs submitted to the Xanadu Cloud.

Args:
connection (Connection): connection to the Xanadu Cloud
limit (int): maximum number of jobs to retrieve
ids (Sequence[str], optional): IDs of the jobs to retrieve

Returns:
Sequence[Job]: jobs which were submitted on the Xanadu Cloud by the
user associated with the Xanadu Cloud connection
"""
response = connection.request("GET", "/jobs", params={"size": limit})
response = connection.request("GET", "/jobs", params={"size": limit, "id": ids})

jobs = []

Expand Down