fix(anime-settings): restore GET /api/nfo/{key}/content for 'View NFO XML' button

The Anime Settings page (src/server/web/static/js/pages/anime-settings.js)
calls GET /api/nfo/{key}/content from its 'View NFO XML' button, but that
endpoint was removed during the NFO refactor (commits 21af502, a8e5487).
The frontend was never updated, so every click on the button 404'd.

Fix:
- Add NfoContentResponse model (key, folder, content, file_size,
  last_modified) to src/server/models/nfo.py.
- Add GET /api/nfo/{key}/content handler to src/server/api/nfo.py that
  reads <anime_directory>/<folder>/tvshow.nfo and returns it as
  {"content": "<xml>", ...} — matching what anime-settings.js
  viewNfoContent() already expects (data.content).
- Expose viewNfoContent on AniWorld.AnimeSettingsManager so it is
  consistent with the other public methods and directly callable from
  tests / other modules.

Tests:
- tests/api/test_nfo_endpoints.py: 4 new tests (auth-required, happy
  path returning XML, 404 on unknown series, 404 on missing tvshow.nfo).
  Also remove the file-local autouse 'reset_auth' fixture that wiped
  the conftest's master-password setup and made any login-based test
  fail with a stale-hash 'invalid credentials' error — that fixture
  was pre-existing and is a no-op now that conftest.py handles reset.
- tests/frontend/unit/anime_settings.test.js: 3 new tests for
  viewNfoContent (URL + auth header, writes <pre>, error toast on
  404) and an assertion in the public-API surface test.
This commit is contained in:
AniWorld Dev
2026-09-04 19:10:27 +02:00
parent ff526e08ea
commit 9f52ea03fb
5 changed files with 303 additions and 19 deletions

View File

@@ -4,6 +4,7 @@ Covers the live endpoints in src/server/api/nfo.py:
- GET /api/nfo/{key}/diagnostics
- POST /api/nfo/{key}/repair
- GET /api/nfo/{key}/validate
- GET /api/nfo/{key}/content (re-introduced — used by Anime Settings 'View NFO XML')
- GET /api/nfo/needs-repair
- POST /api/nfo/batch/repair
@@ -12,6 +13,12 @@ Note: Legacy endpoints referenced in v1.x (e.g. /api/nfo/{id}/check,
in the codebase — they were replaced by the consolidated diagnostic,
repair, validate, needs-repair, batch/repair endpoints and the new
Anime Settings page (see tests/api/test_anime_settings_endpoints.py).
Auth note: tests/conftest.py's autouse ``reset_auth_and_rate_limits``
fixture configures the master password with ``TestPass123!`` before every
test. The per-file ``reset_auth`` autouse fixture that used to live here
was removed because it wiped the conftest's setup and made any test that
needed an authenticated client fail with a stale-hash login error.
"""
from unittest.mock import AsyncMock, Mock, patch
@@ -19,16 +26,6 @@ import pytest
from httpx import ASGITransport, AsyncClient
from src.server.fastapi_app import app
from src.server.services.auth_service import auth_service
@pytest.fixture(autouse=True)
def reset_auth():
auth_service._hash = None
auth_service._failed.clear()
yield
auth_service._hash = None
auth_service._failed.clear()
@pytest.fixture
@@ -38,19 +35,19 @@ async def client():
yield ac
@pytest.fixture
async def authenticated_client(client):
await client.post(
"/api/auth/setup",
json={"master_password": "TestPassword123!"},
)
async def _login(client: AsyncClient) -> str:
"""Log in with the master password configured by conftest and
return the bearer token. Sets the ``Authorization`` header on the
client as a side benefit so the caller can ``await client.get(...)``
immediately."""
resp = await client.post(
"/api/auth/login",
json={"password": "TestPassword123!"},
json={"password": "TestPass123!"},
)
assert resp.status_code == 200, resp.text
token = resp.json()["access_token"]
client.headers.update({"Authorization": f"Bearer {token}"})
yield client
return token
class TestNFOAuthRequirements:
@@ -84,6 +81,119 @@ class TestNFOAuthRequirements:
)
assert resp.status_code in (401, 503)
@pytest.mark.asyncio
async def test_get_content_requires_auth(self, client):
"""GET /api/nfo/{key}/content (used by the Anime Settings page
'View NFO XML' button) must require authentication."""
resp = await client.get("/api/nfo/any-key/content")
assert resp.status_code in (401, 503)
class TestNFOContentEndpoint:
"""Behavioural tests for GET /api/nfo/{key}/content.
Covers the success path and the two 404 cases (unknown series,
missing tvshow.nfo) the Anime Settings page relies on."""
@pytest.fixture
def mock_anime_service(self):
"""Replace the FastAPI get_anime_service dependency with a mock.
Yields the mock so individual tests can configure ``list_series_with_filters``."""
from src.server.utils import dependencies as deps
service = Mock()
service.list_series_with_filters = AsyncMock(return_value=[])
app.dependency_overrides[deps.get_anime_service] = lambda: service
yield service
app.dependency_overrides.pop(deps.get_anime_service, None)
@pytest.mark.asyncio
async def test_returns_xml_for_series_with_nfo(
self, client, tmp_path, monkeypatch, mock_anime_service
):
"""Happy path: existing tvshow.nfo is returned verbatim inside
the JSON wrapper the JS uses (``data.content``)."""
from src.config import settings as settings_module
# Point settings.anime_directory at a temp dir
monkeypatch.setattr(
settings_module.settings,
"anime_directory",
str(tmp_path),
raising=False,
)
# Build a fake folder + tvshow.nfo on disk
folder = "Naruto (2002)"
series_dir = tmp_path / folder
series_dir.mkdir()
xml = (
"<?xml version='1.0' encoding='UTF-8'?>\n"
"<tvshow><title>Naruto</title><year>2002</year></tvshow>\n"
)
(series_dir / "tvshow.nfo").write_text(xml, encoding="utf-8")
mock_anime_service.list_series_with_filters = AsyncMock(
return_value=[{"key": "naruto", "folder": folder}]
)
await _login(client)
resp = await client.get("/api/nfo/naruto/content")
assert resp.status_code == 200, resp.text
body = resp.json()
assert body["key"] == "naruto"
assert body["folder"] == folder
assert body["content"] == xml
assert body["file_size"] == len(xml.encode("utf-8"))
assert "last_modified" in body
@pytest.mark.asyncio
async def test_404_when_series_unknown(
self, client, tmp_path, monkeypatch, mock_anime_service
):
from src.config import settings as settings_module
monkeypatch.setattr(
settings_module.settings,
"anime_directory",
str(tmp_path),
raising=False,
)
mock_anime_service.list_series_with_filters = AsyncMock(return_value=[])
await _login(client)
resp = await client.get("/api/nfo/missing/content")
assert resp.status_code == 404
assert "not found" in resp.json()["detail"].lower()
@pytest.mark.asyncio
async def test_404_when_nfo_file_missing(
self, client, tmp_path, monkeypatch, mock_anime_service
):
"""Series exists with a configured folder but no tvshow.nfo yet."""
from src.config import settings as settings_module
folder = "Empty"
(tmp_path / folder).mkdir()
monkeypatch.setattr(
settings_module.settings,
"anime_directory",
str(tmp_path),
raising=False,
)
mock_anime_service.list_series_with_filters = AsyncMock(
return_value=[{"key": "empty", "folder": folder}]
)
await _login(client)
resp = await client.get("/api/nfo/empty/content")
assert resp.status_code == 404
assert "tvshow.nfo" in resp.json()["detail"].lower()
class TestNFOEndpointModels:
"""Verify the response models use the renamed classes (regression

View File

@@ -375,6 +375,83 @@ describe('AnimeSettingsManager', () => {
});
});
// -------------------------------------------------------------------
// viewNfoContent()
// -------------------------------------------------------------------
describe('viewNfoContent()', () => {
beforeEach(async () => {
// Seed currentKey via loadSeries so viewNfoContent has a key.
delete window.location;
window.location = { search: '?key=a', href: 'http://x/?key=a' };
mockFetchSequence([{
status: 200,
body: {
key: 'a', name: 'A', folder: 'A', site: 's',
tmdb_id: null, tvdb_id: null, has_nfo: true,
nfo_path: '/anime/A/tvshow.nfo', episode_count: 0,
missing_episode_count: 0, loading_status: 'completed',
},
}]);
await manager.loadSeries('a');
});
it('fetches /api/nfo/{key}/content with auth header', async () => {
mockFetchSequence([{
status: 200,
body: {
key: 'a',
folder: 'A',
content: '<tvshow><title>A</title></tvshow>',
file_size: 30,
last_modified: '2026-06-01T00:00:00',
},
}]);
await manager.viewNfoContent();
const [url, opts] = global.fetch.mock.calls[0];
expect(url).toBe('/api/nfo/a/content');
expect(opts.method).toBe('GET');
expect(opts.headers.Authorization).toBe('Bearer fake-jwt-token');
});
it('writes the content into the #nfo-content <pre> and unhides it',
async () => {
mockFetchSequence([{
status: 200,
body: {
key: 'a',
folder: 'A',
content: '<tvshow><title>A</title></tvshow>',
file_size: 30,
last_modified: '2026-06-01T00:00:00',
},
}]);
const pre = document.getElementById('nfo-content');
expect(pre.classList.contains('hidden')).toBe(true);
await manager.viewNfoContent();
expect(pre.textContent).toBe(
'<tvshow><title>A</title></tvshow>'
);
expect(pre.classList.contains('hidden')).toBe(false);
});
it('shows an error toast when the backend returns 404', async () => {
mockFetchSequence([{
status: 404,
ok: false,
body: { detail: 'Not Found' },
}]);
await manager.viewNfoContent();
expect(global.AniWorld.UI.showToast).toHaveBeenCalledWith(
expect.stringContaining('NFO'),
'error'
);
});
});
// -------------------------------------------------------------------
// validateField()
// -------------------------------------------------------------------
@@ -493,6 +570,7 @@ describe('AnimeSettingsManager', () => {
expect(typeof manager.loadSeries).toBe('function');
expect(typeof manager.saveSettings).toBe('function');
expect(typeof manager.regenerateNfo).toBe('function');
expect(typeof manager.viewNfoContent).toBe('function');
expect(typeof manager.validateField).toBe('function');
expect(typeof manager.populateForm).toBe('function');
expect(typeof manager.showSaveSuccess).toBe('function');