Add comprehensive test coverage for services and utilities

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
This commit is contained in:
2026-02-14 08:08:22 +01:00
co-authored by Claude Haiku 4.5
parent e3797f32ca
commit 57f8a54dac
23 changed files with 3519 additions and 20 deletions
+159
View File
@@ -0,0 +1,159 @@
/**
* Favorites service tests
*
* TRACES: UR-017 | DR-021
*/
import { describe, it, expect, beforeEach, vi } from "vitest";
import { toggleFavorite } from "./favorites";
vi.mock("@tauri-apps/api/core", () => ({
invoke: vi.fn(async (command: string) => {
if (command === "storage_toggle_favorite") {
return undefined;
}
if (command === "storage_mark_synced") {
return undefined;
}
return null;
}),
}));
vi.mock("$lib/stores/auth", () => ({
auth: {
getUserId: vi.fn(() => "user-123"),
getRepository: vi.fn(() => ({
markFavorite: vi.fn(async () => undefined),
unmarkFavorite: vi.fn(async () => undefined),
})),
},
}));
describe("favorites service", () => {
beforeEach(() => {
vi.clearAllMocks();
});
describe("toggleFavorite", () => {
it("should toggle favorite to true", async () => {
const result = await toggleFavorite("item-123", false);
expect(result).toBe(true);
});
it("should toggle favorite to false", async () => {
const result = await toggleFavorite("item-123", true);
expect(result).toBe(false);
});
it("should update local database", async () => {
const { invoke } = await import("@tauri-apps/api/core");
const invokeSpy = vi.mocked(invoke);
await toggleFavorite("item-123", false);
const call = invokeSpy.mock.calls.find(
(c) => c[0] === "storage_toggle_favorite"
);
expect(call).toBeDefined();
expect(call![1]).toHaveProperty("itemId", "item-123");
expect(call![1]).toHaveProperty("isFavorite", true);
});
it("should include userId in storage call", async () => {
const { invoke } = await import("@tauri-apps/api/core");
const invokeSpy = vi.mocked(invoke);
await toggleFavorite("item-123", false);
const call = invokeSpy.mock.calls.find(
(c) => c[0] === "storage_toggle_favorite"
);
expect(call![1]).toHaveProperty("userId", "user-123");
});
it("should sync to server when marking as favorite", async () => {
const { auth } = await import("$lib/stores/auth");
const authModule = vi.mocked(auth);
const mockRepo = {
markFavorite: vi.fn(async () => undefined),
unmarkFavorite: vi.fn(async () => undefined),
};
authModule.getRepository = vi.fn(() => mockRepo as any);
await toggleFavorite("item-123", false);
expect(mockRepo.markFavorite).toHaveBeenCalledWith("item-123");
});
it("should sync to server when unmarking as favorite", async () => {
const { auth } = await import("$lib/stores/auth");
const authModule = vi.mocked(auth);
const mockRepo = {
markFavorite: vi.fn(async () => undefined),
unmarkFavorite: vi.fn(async () => undefined),
};
authModule.getRepository = vi.fn(() => mockRepo as any);
await toggleFavorite("item-123", true);
expect(mockRepo.unmarkFavorite).toHaveBeenCalledWith("item-123");
});
it("should mark as synced after successful server update", async () => {
const { invoke } = await import("@tauri-apps/api/core");
const invokeSpy = vi.mocked(invoke);
await toggleFavorite("item-123", false);
const markSyncedCall = invokeSpy.mock.calls.find(
(c) => c[0] === "storage_mark_synced"
);
expect(markSyncedCall).toBeDefined();
expect(markSyncedCall![1]).toHaveProperty("itemId", "item-123");
});
it("should throw error if not authenticated", async () => {
const { auth } = await import("$lib/stores/auth");
const authModule = vi.mocked(auth);
authModule.getUserId = vi.fn(() => null);
await expect(toggleFavorite("item-123", false)).rejects.toThrow(
"Not authenticated"
);
});
it("should handle server sync failure gracefully", async () => {
const { auth } = await import("$lib/stores/auth");
const authModule = vi.mocked(auth);
const mockRepo = {
markFavorite: vi.fn(async () => {
throw new Error("Server error");
}),
unmarkFavorite: vi.fn(async () => undefined),
};
authModule.getRepository = vi.fn(() => mockRepo as any);
// Ensure getUserId returns a value for this test
authModule.getUserId = vi.fn(() => "user-123");
// Should not throw, but return the new favorite state
const result = await toggleFavorite("item-123", false);
expect(result).toBe(true);
});
it("should handle multiple toggles", async () => {
const { auth } = await import("$lib/stores/auth");
const authModule = vi.mocked(auth);
authModule.getUserId = vi.fn(() => "user-123");
let result = await toggleFavorite("item-123", false);
expect(result).toBe(true);
result = await toggleFavorite("item-123", true);
expect(result).toBe(false);
result = await toggleFavorite("item-123", false);
expect(result).toBe(true);
});
});
});
+193
View File
@@ -0,0 +1,193 @@
/**
* Image cache service tests
*
* TRACES: UR-007 | DR-016
*/
import { describe, it, expect, beforeEach, vi } from "vitest";
import {
getCachedImageUrl,
getCacheStats,
setCacheLimit,
clearCache,
deleteItemCache,
formatBytes,
gbToBytes,
bytesToGb,
} from "./imageCache";
vi.mock("@tauri-apps/api/core", () => ({
invoke: vi.fn(async (command: string, args?: any) => {
if (command === "thumbnail_get_cached") {
return null; // No cached image
}
if (command === "thumbnail_get_stats") {
return {
totalSizeBytes: 1024 * 1024,
itemCount: 10,
limitBytes: 1024 * 1024 * 1024,
};
}
if (command === "thumbnail_set_limit") {
return undefined;
}
if (command === "thumbnail_clear_cache") {
return undefined;
}
if (command === "thumbnail_delete_item") {
return undefined;
}
if (command === "thumbnail_save") {
return undefined;
}
return null;
}),
convertFileSrc: vi.fn((path: string) => `asset://path/${path}`),
}));
describe("image cache service", () => {
beforeEach(() => {
vi.clearAllMocks();
});
describe("getCachedImageUrl", () => {
it("should build server URL with default image type", async () => {
const url = await getCachedImageUrl(
"http://server.local:8096",
"item-123"
);
expect(url).toContain("http://server.local:8096/Items/item-123/Images/Primary");
});
it("should build server URL with custom image type", async () => {
const url = await getCachedImageUrl(
"http://server.local:8096",
"item-123",
"Backdrop"
);
expect(url).toContain("Backdrop");
});
it("should include image options in URL", async () => {
const url = await getCachedImageUrl(
"http://server.local:8096",
"item-123",
"Primary",
{
maxWidth: 300,
maxHeight: 400,
quality: 90,
tag: "abc123",
}
);
expect(url).toContain("maxWidth=300");
expect(url).toContain("maxHeight=400");
expect(url).toContain("quality=90");
expect(url).toContain("tag=abc123");
});
it("should trigger background caching", async () => {
const { invoke } = await import("@tauri-apps/api/core");
const invokeSpy = vi.mocked(invoke);
await getCachedImageUrl("http://server.local:8096", "item-123");
const saveCall = invokeSpy.mock.calls.find(
(call) => call[0] === "thumbnail_save"
);
expect(saveCall).toBeDefined();
expect(saveCall![1]).toHaveProperty("itemId", "item-123");
expect(saveCall![1]).toHaveProperty("imageType", "Primary");
});
});
describe("cache statistics", () => {
it("should get cache statistics", async () => {
const stats = await getCacheStats();
expect(stats).toHaveProperty("totalSizeBytes");
expect(stats).toHaveProperty("itemCount");
expect(stats).toHaveProperty("limitBytes");
expect(typeof stats.totalSizeBytes).toBe("number");
expect(typeof stats.itemCount).toBe("number");
});
it("should set cache limit", async () => {
const limit = 1024 * 1024 * 1024 * 5; // 5GB
await setCacheLimit(limit);
const { invoke } = await import("@tauri-apps/api/core");
const invokeSpy = vi.mocked(invoke);
const setLimitCall = invokeSpy.mock.calls.find(
(call) => call[0] === "thumbnail_set_limit"
);
expect(setLimitCall).toBeDefined();
expect(setLimitCall![1]).toHaveProperty("limitBytes", limit);
});
});
describe("cache clearing", () => {
it("should clear all cached thumbnails", async () => {
await clearCache();
const { invoke } = await import("@tauri-apps/api/core");
const invokeSpy = vi.mocked(invoke);
expect(invokeSpy).toHaveBeenCalledWith("thumbnail_clear_cache");
});
it("should delete cache for specific item", async () => {
await deleteItemCache("item-456");
const { invoke } = await import("@tauri-apps/api/core");
const invokeSpy = vi.mocked(invoke);
const deleteCall = invokeSpy.mock.calls.find(
(call) => call[0] === "thumbnail_delete_item"
);
expect(deleteCall).toBeDefined();
expect(deleteCall![1]).toHaveProperty("itemId", "item-456");
});
});
describe("byte formatting", () => {
it("should format bytes", () => {
expect(formatBytes(512)).toContain("B");
expect(formatBytes(512)).not.toContain("KB");
});
it("should format kilobytes", () => {
expect(formatBytes(1024)).toContain("KB");
});
it("should format megabytes", () => {
expect(formatBytes(1024 * 1024)).toContain("MB");
});
it("should format gigabytes", () => {
expect(formatBytes(1024 * 1024 * 1024)).toContain("GB");
});
it("should format with correct precision", () => {
const result = formatBytes(1024 * 1.5);
expect(result).toMatch(/\d+\.\d+ KB/);
});
});
describe("unit conversion", () => {
it("should convert gigabytes to bytes", () => {
const bytes = gbToBytes(1);
expect(bytes).toBe(1024 * 1024 * 1024);
});
it("should convert bytes to gigabytes", () => {
const gb = bytesToGb(1024 * 1024 * 1024);
expect(gb).toBe(1);
});
it("should handle fractional conversions", () => {
const bytes = gbToBytes(0.5);
expect(bytes).toBe(512 * 1024 * 1024);
const gb = bytesToGb(512 * 1024 * 1024);
expect(gb).toBe(0.5);
});
});
});
+242
View File
@@ -0,0 +1,242 @@
/**
* Playback Reporting service tests
*
* TRACES: UR-005, UR-019, UR-025 | DR-028, DR-047
*/
import { describe, it, expect, beforeEach, vi } from "vitest";
import {
reportPlaybackStart,
reportPlaybackProgress,
reportPlaybackStopped,
markAsPlayed,
} from "./playbackReporting";
vi.mock("@tauri-apps/api/core", () => ({
invoke: vi.fn(async (command: string) => {
if (command.startsWith("storage_")) {
return undefined;
}
return null;
}),
}));
vi.mock("$lib/stores/auth", () => ({
auth: {
getUserId: vi.fn(() => "user-123"),
getRepository: vi.fn(() => ({
reportPlaybackStopped: vi.fn(async () => undefined),
getItem: vi.fn(async (id: string) => ({
id,
name: "Test Item",
runTimeTicks: 100000000,
})),
})),
},
}));
describe("playback reporting service", () => {
beforeEach(() => {
vi.clearAllMocks();
});
describe("reportPlaybackStart", () => {
it("should accept itemId and positionSeconds", async () => {
await expect(reportPlaybackStart("item-123", 0)).resolves.toBeUndefined();
});
it("should accept optional contextType and contextId", async () => {
await expect(
reportPlaybackStart("item-123", 0, "container", "container-456")
).resolves.toBeUndefined();
});
it("should convert seconds to ticks", async () => {
const { invoke } = await import("@tauri-apps/api/core");
const invokeSpy = vi.mocked(invoke);
await reportPlaybackStart("item-123", 60);
const call = invokeSpy.mock.calls.find(
(c) => c[0] === "storage_update_playback_context"
);
expect(call).toBeDefined();
expect(call![1]).toHaveProperty("positionTicks", 600000000); // 60 seconds
});
it("should use single context by default", async () => {
const { invoke } = await import("@tauri-apps/api/core");
const invokeSpy = vi.mocked(invoke);
await reportPlaybackStart("item-123", 30);
const call = invokeSpy.mock.calls.find(
(c) => c[0] === "storage_update_playback_context"
);
expect(call![1]).toHaveProperty("contextType", "single");
expect(call![1]).toHaveProperty("contextId", null);
});
it("should include userId in command", async () => {
const { invoke } = await import("@tauri-apps/api/core");
const invokeSpy = vi.mocked(invoke);
await reportPlaybackStart("item-123", 0);
const call = invokeSpy.mock.calls.find(
(c) => c[0] === "storage_update_playback_context"
);
expect(call![1]).toHaveProperty("userId", "user-123");
});
});
describe("reportPlaybackProgress", () => {
it("should accept itemId and positionSeconds", async () => {
await expect(reportPlaybackProgress("item-123", 30)).resolves.toBeUndefined();
});
it("should accept optional isPaused parameter", async () => {
await expect(reportPlaybackProgress("item-123", 30, true)).resolves.toBeUndefined();
});
it("should update local progress only", async () => {
const { invoke } = await import("@tauri-apps/api/core");
const invokeSpy = vi.mocked(invoke);
await reportPlaybackProgress("item-123", 30);
const call = invokeSpy.mock.calls.find(
(c) => c[0] === "storage_update_playback_progress"
);
expect(call).toBeDefined();
expect(call![1]).toHaveProperty("itemId", "item-123");
});
it("should convert seconds to ticks", async () => {
const { invoke } = await import("@tauri-apps/api/core");
const invokeSpy = vi.mocked(invoke);
await reportPlaybackProgress("item-123", 45);
const call = invokeSpy.mock.calls.find(
(c) => c[0] === "storage_update_playback_progress"
);
expect(call![1]).toHaveProperty("positionTicks", 450000000); // 45 seconds
});
});
describe("reportPlaybackStopped", () => {
it("should accept itemId and positionSeconds", async () => {
await expect(reportPlaybackStopped("item-123", 120)).resolves.toBeUndefined();
});
it("should update local progress", async () => {
const { invoke } = await import("@tauri-apps/api/core");
const invokeSpy = vi.mocked(invoke);
await reportPlaybackStopped("item-123", 120);
const call = invokeSpy.mock.calls.find(
(c) => c[0] === "storage_update_playback_progress"
);
expect(call).toBeDefined();
});
it("should report to server via repository", async () => {
const { auth } = await import("$lib/stores/auth");
const authModule = vi.mocked(auth);
const mockRepo = {
reportPlaybackStopped: vi.fn(async () => undefined),
};
authModule.getRepository = vi.fn(() => mockRepo as any);
await reportPlaybackStopped("item-123", 120);
expect(mockRepo.reportPlaybackStopped).toHaveBeenCalled();
});
it("should convert seconds to ticks for server report", async () => {
const { auth } = await import("$lib/stores/auth");
const authModule = vi.mocked(auth);
const mockRepo = {
reportPlaybackStopped: vi.fn(async () => undefined),
};
authModule.getRepository = vi.fn(() => mockRepo as any);
await reportPlaybackStopped("item-123", 90);
expect(mockRepo.reportPlaybackStopped).toHaveBeenCalledWith(
"item-123",
900000000 // 90 seconds in ticks
);
});
it("should not report to server if positionSeconds is 0", async () => {
const { auth } = await import("$lib/stores/auth");
const authModule = vi.mocked(auth);
const mockRepo = {
reportPlaybackStopped: vi.fn(async () => undefined),
};
authModule.getRepository = vi.fn(() => mockRepo as any);
await reportPlaybackStopped("item-123", 0);
expect(mockRepo.reportPlaybackStopped).not.toHaveBeenCalled();
});
});
describe("markAsPlayed", () => {
it("should mark item as played", async () => {
const { invoke } = await import("@tauri-apps/api/core");
const invokeSpy = vi.mocked(invoke);
await markAsPlayed("item-123");
const call = invokeSpy.mock.calls.find(
(c) => c[0] === "storage_mark_played"
);
expect(call).toBeDefined();
expect(call![1]).toHaveProperty("itemId", "item-123");
});
it("should report to server with full duration", async () => {
const { auth } = await import("$lib/stores/auth");
const authModule = vi.mocked(auth);
const mockRepo = {
reportPlaybackStopped: vi.fn(async () => undefined),
getItem: vi.fn(async () => ({
id: "item-123",
name: "Item",
runTimeTicks: 100000000,
})),
};
authModule.getRepository = vi.fn(() => mockRepo as any);
await markAsPlayed("item-123");
expect(mockRepo.getItem).toHaveBeenCalledWith("item-123");
expect(mockRepo.reportPlaybackStopped).toHaveBeenCalledWith(
"item-123",
100000000
);
});
it("should handle items without runTimeTicks", async () => {
const { auth } = await import("$lib/stores/auth");
const authModule = vi.mocked(auth);
const mockRepo = {
reportPlaybackStopped: vi.fn(async () => undefined),
getItem: vi.fn(async () => ({
id: "item-123",
name: "Item",
runTimeTicks: null,
})),
};
authModule.getRepository = vi.fn(() => mockRepo as any);
await markAsPlayed("item-123");
expect(mockRepo.reportPlaybackStopped).not.toHaveBeenCalled();
});
});
});
+5 -1
View File
@@ -99,6 +99,10 @@ describe("Player Events Service", () => {
await initPlayerEvents();
expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("Failed to initialize player events"));
// console.error is called with: ("Failed to initialize player events:", Error)
expect(consoleSpy).toHaveBeenCalledWith(
expect.stringContaining("Failed to initialize player events"),
expect.any(Error)
);
});
});
+215
View File
@@ -0,0 +1,215 @@
/**
* Preload service tests
*
* TRACES: UR-004, UR-011 | DR-006, DR-015
*/
import { describe, it, expect, beforeEach, vi } from "vitest";
import { preloadUpcomingTracks, updateCacheConfig, getCacheConfig } from "./preload";
vi.mock("@tauri-apps/api/core", () => ({
invoke: vi.fn(async (command: string, args?: any) => {
if (command === "player_preload_upcoming") {
return {
queuedCount: 3,
alreadyDownloaded: 2,
skipped: 1,
};
}
if (command === "player_set_cache_config") {
return undefined;
}
if (command === "player_get_cache_config") {
return {
queuePrecacheEnabled: true,
queuePrecacheCount: 5,
albumAffinityEnabled: true,
albumAffinityThreshold: 0.8,
storageLimit: 1024 * 1024 * 1024,
wifiOnly: false,
};
}
return null;
}),
}));
vi.mock("$lib/stores/auth", () => ({
auth: {
getUserId: vi.fn(() => "user-123"),
},
}));
describe("preload service", () => {
beforeEach(() => {
vi.clearAllMocks();
});
describe("preloadUpcomingTracks", () => {
it("should preload tracks without options", async () => {
await expect(preloadUpcomingTracks()).resolves.toBeUndefined();
});
it("should invoke correct backend command", async () => {
const { invoke } = await import("@tauri-apps/api/core");
const invokeSpy = vi.mocked(invoke);
await preloadUpcomingTracks();
const call = invokeSpy.mock.calls.find(
(c) => c[0] === "player_preload_upcoming"
);
expect(call).toBeDefined();
});
it("should include userId in command", async () => {
const { invoke } = await import("@tauri-apps/api/core");
const invokeSpy = vi.mocked(invoke);
await preloadUpcomingTracks();
const call = invokeSpy.mock.calls.find(
(c) => c[0] === "player_preload_upcoming"
);
expect(call![1]).toHaveProperty("userId", "user-123");
});
it("should use override userId if provided", async () => {
const { invoke } = await import("@tauri-apps/api/core");
const invokeSpy = vi.mocked(invoke);
await preloadUpcomingTracks({ userId: "user-456" });
const call = invokeSpy.mock.calls.find(
(c) => c[0] === "player_preload_upcoming"
);
expect(call![1]).toHaveProperty("userId", "user-456");
});
it("should skip if no active user", async () => {
const { auth } = await import("$lib/stores/auth");
const authModule = vi.mocked(auth);
authModule.getUserId = vi.fn(() => null);
const { invoke } = await import("@tauri-apps/api/core");
const invokeSpy = vi.mocked(invoke);
await preloadUpcomingTracks();
const call = invokeSpy.mock.calls.find(
(c) => c[0] === "player_preload_upcoming"
);
expect(call).toBeUndefined();
});
it("should handle preload result", async () => {
// Should not throw even with result
await expect(preloadUpcomingTracks()).resolves.toBeUndefined();
});
it("should handle errors gracefully", async () => {
const { invoke } = await import("@tauri-apps/api/core");
const invokeSpy = vi.mocked(invoke);
invokeSpy.mockRejectedValueOnce(new Error("Backend error"));
// Should not throw
await expect(preloadUpcomingTracks()).resolves.toBeUndefined();
});
it("should support debug option", async () => {
await expect(preloadUpcomingTracks({ debug: true })).resolves.toBeUndefined();
});
it("should support both debug and userId options", async () => {
const { invoke } = await import("@tauri-apps/api/core");
const invokeSpy = vi.mocked(invoke);
await preloadUpcomingTracks({ debug: true, userId: "user-789" });
const call = invokeSpy.mock.calls.find(
(c) => c[0] === "player_preload_upcoming"
);
expect(call![1]).toHaveProperty("userId", "user-789");
});
});
describe("updateCacheConfig", () => {
it("should update cache config", async () => {
const config = {
queuePrecacheEnabled: false,
queuePrecacheCount: 10,
};
await expect(updateCacheConfig(config)).resolves.toBeUndefined();
});
it("should invoke correct backend command", async () => {
const { invoke } = await import("@tauri-apps/api/core");
const invokeSpy = vi.mocked(invoke);
const config = { queuePrecacheEnabled: true };
await updateCacheConfig(config);
const call = invokeSpy.mock.calls.find(
(c) => c[0] === "player_set_cache_config"
);
expect(call).toBeDefined();
expect(call![1]).toHaveProperty("config", config);
});
it("should support partial config updates", async () => {
const config = { wifiOnly: true };
await expect(updateCacheConfig(config)).resolves.toBeUndefined();
});
it("should support all config options", async () => {
const config = {
queuePrecacheEnabled: true,
queuePrecacheCount: 5,
albumAffinityEnabled: false,
albumAffinityThreshold: 0.75,
storageLimit: 2 * 1024 * 1024 * 1024,
wifiOnly: true,
};
await expect(updateCacheConfig(config)).resolves.toBeUndefined();
});
});
describe("getCacheConfig", () => {
it("should get cache config", async () => {
const config = await getCacheConfig();
expect(config).toBeDefined();
expect(typeof config.queuePrecacheEnabled).toBe("boolean");
expect(typeof config.queuePrecacheCount).toBe("number");
expect(typeof config.albumAffinityEnabled).toBe("boolean");
expect(typeof config.albumAffinityThreshold).toBe("number");
expect(typeof config.storageLimit).toBe("number");
expect(typeof config.wifiOnly).toBe("boolean");
});
it("should invoke correct backend command", async () => {
const { invoke } = await import("@tauri-apps/api/core");
const invokeSpy = vi.mocked(invoke);
await getCacheConfig();
const call = invokeSpy.mock.calls.find(
(c) => c[0] === "player_get_cache_config"
);
expect(call).toBeDefined();
});
it("should return valid config structure", async () => {
const config = await getCacheConfig();
expect(config.queuePrecacheEnabled).toBe(true);
expect(config.queuePrecacheCount).toBe(5);
expect(config.albumAffinityEnabled).toBe(true);
expect(config.albumAffinityThreshold).toBe(0.8);
expect(config.storageLimit).toBe(1024 * 1024 * 1024);
expect(config.wifiOnly).toBe(false);
});
});
});