85 lines
2.6 KiB
Python
85 lines
2.6 KiB
Python
from __future__ import annotations
|
|
|
|
import json
|
|
from pathlib import Path
|
|
|
|
import app as app_module
|
|
|
|
|
|
class _MockResponse:
|
|
def __init__(self, payload: dict):
|
|
self._payload = payload
|
|
|
|
def raise_for_status(self) -> None:
|
|
return None
|
|
|
|
def json(self) -> dict:
|
|
return dict(self._payload)
|
|
|
|
|
|
def _write_linuxdo_settings(path: Path) -> None:
|
|
payload = {
|
|
"linuxdo_oauth": {
|
|
"enabled": True,
|
|
"client_id": "cid_test",
|
|
"client_secret": "secret_test",
|
|
"authorize_url": "https://connect.linux.do/oauth2/authorize",
|
|
"token_url": "https://connect.linux.do/oauth2/token",
|
|
"userinfo_url": "https://connect.linux.do/api/user",
|
|
"scope": "read",
|
|
}
|
|
}
|
|
path.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")
|
|
|
|
|
|
def test_linuxdo_callback_uses_linuxdo_username(client, monkeypatch, tmp_path):
|
|
settings_path = tmp_path / "settings.json"
|
|
_write_linuxdo_settings(settings_path)
|
|
monkeypatch.setattr(app_module, "SETTINGS_FILE", settings_path)
|
|
monkeypatch.setattr(
|
|
app_module.requests,
|
|
"post",
|
|
lambda *args, **kwargs: _MockResponse({"access_token": "token_1"}),
|
|
)
|
|
monkeypatch.setattr(
|
|
app_module.requests,
|
|
"get",
|
|
lambda *args, **kwargs: _MockResponse({"id": 101, "username": "Neo_User", "name": "Neo"}),
|
|
)
|
|
|
|
with client.session_transaction() as sess:
|
|
sess["linuxdo_oauth_state"] = "state_1"
|
|
|
|
callback = client.get("/api/auth/oauth/linuxdo/callback?state=state_1&code=code_1")
|
|
assert callback.status_code == 302
|
|
|
|
me = client.get("/api/me").get_json()
|
|
assert me["logged_in"] is True
|
|
assert me["user"]["username"] == "neo_user"
|
|
|
|
|
|
def test_linuxdo_callback_fallback_to_id_when_username_invalid(client, monkeypatch, tmp_path):
|
|
settings_path = tmp_path / "settings.json"
|
|
_write_linuxdo_settings(settings_path)
|
|
monkeypatch.setattr(app_module, "SETTINGS_FILE", settings_path)
|
|
monkeypatch.setattr(
|
|
app_module.requests,
|
|
"post",
|
|
lambda *args, **kwargs: _MockResponse({"access_token": "token_2"}),
|
|
)
|
|
monkeypatch.setattr(
|
|
app_module.requests,
|
|
"get",
|
|
lambda *args, **kwargs: _MockResponse({"id": "A-1", "username": "%%%"}),
|
|
)
|
|
|
|
with client.session_transaction() as sess:
|
|
sess["linuxdo_oauth_state"] = "state_2"
|
|
|
|
callback = client.get("/api/auth/oauth/linuxdo/callback?state=state_2&code=code_2")
|
|
assert callback.status_code == 302
|
|
|
|
me = client.get("/api/me").get_json()
|
|
assert me["logged_in"] is True
|
|
assert me["user"]["username"] == "linuxdo_a_1"
|