Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
56 changes: 56 additions & 0 deletions scripts/list_apis.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
"""Print every Canvas endpoint the recipes call, one "METHOD /path" per line.

python scripts/list_apis.py

The api-docu-portal repo runs this and compares the list with the Canvas OpenAPI spec.

The list comes from the recipe tests: it runs them and records every endpoint the
recipes choose (see record_sent_requests in tests/conftest.py).
"""

import os
import re
import subprocess
import sys
import tempfile
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
API_PREFIX = "/api/v1/"
FIXED_SEGMENT = re.compile(r"[a-z_]+") # Canvas path words: courses, student_view_student


def normalize(path):
"""Replace every path parameter (a number, a slug like demo-page) with {id}."""
segments = path[len(API_PREFIX):].split("/")
return API_PREFIX + "/".join(s if FIXED_SEGMENT.fullmatch(s) else "{id}" for s in segments)


def record_requests():
"""Run the recipe tests and return the (method, path) lines they recorded."""
with tempfile.TemporaryDirectory() as folder:
record = Path(folder) / "requests.txt"
env = {**os.environ, "USED_APIS_RECORD": str(record)}
result = subprocess.run(
[sys.executable, "-m", "pytest", "tests/test_recipes.py", "-q"], cwd=ROOT, env=env, stdout=sys.stderr
)
if result.returncode != 0:
sys.exit("The recipe tests failed, so the list could not be built.")
return record.read_text().splitlines()


def build_list():
endpoints = set()
for line in record_requests():
method, path = line.split(" ", 1)
endpoints.add(f"{method} {normalize(path)}")
return "".join(f"{e}\n" for e in sorted(endpoints))


def main():
sys.stdout.write(build_list())
return 0


if __name__ == "__main__":
sys.exit(main())
38 changes: 38 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
import os
from pathlib import Path
from urllib.parse import urlsplit

import pytest

from canvaslib.client import CanvasClient

CANVAS_VARS = (
"CANVAS_BASE_URL",
"CANVAS_TOKEN",
Expand All @@ -10,6 +16,10 @@
"CANVAS_ENROLL_USER_ID",
)

# (method, path) of every endpoint the recipes chose during this test session.
# scripts/list_apis.py reads them to build used-apis.txt.
SENT_REQUESTS = set()


@pytest.fixture(autouse=True)
def clean_canvas_env(request, monkeypatch):
Expand All @@ -21,3 +31,31 @@ def clean_canvas_env(request, monkeypatch):
return
for name in CANVAS_VARS:
monkeypatch.delenv(name, raising=False)


CLIENT_METHODS = {"get": "GET", "get_all": "GET", "post": "POST", "put": "PUT", "delete": "DELETE"}


@pytest.fixture(autouse=True)
def record_sent_requests(monkeypatch):
"""Remember the endpoints recipes call. Only ones we call, not ones Canvas sends back or redirects to.
"""

def recording(original, http_method):
def call(self, path, *args, **kwargs):
if not path.startswith(("http://", "https://")):
SENT_REQUESTS.add((http_method, urlsplit(self._url(path)).path))
return original(self, path, *args, **kwargs)

return call

for name, http_method in CLIENT_METHODS.items():
monkeypatch.setattr(CanvasClient, name, recording(getattr(CanvasClient, name), http_method))


def pytest_sessionfinish(session):
"""When USED_APIS_RECORD names a file, write the recorded requests there."""
target = os.environ.get("USED_APIS_RECORD")
if target:
lines = sorted(f"{method} {path}" for method, path in SENT_REQUESTS)
Path(target).write_text("".join(f"{line}\n" for line in lines))
Loading