-
Notifications
You must be signed in to change notification settings - Fork 10
Ensure SDK matches live API behaviour and broaden coverage #36
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
Open
basit3407
wants to merge
3
commits into
quran:main
Choose a base branch
from
basit3407:test_sdk_2
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -14,5 +14,4 @@ dist | |
| env.d.ts | ||
| next-env.d.ts | ||
| **/.vscode | ||
|
|
||
| .env | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,75 @@ | ||
| import { afterEach, describe, expect, it, vi } from "vitest"; | ||
|
|
||
| import { QuranClient } from "../src"; | ||
| import { QuranFetcher } from "../src/sdk/fetcher"; | ||
| import { Language } from "../src/types"; | ||
|
|
||
| const baseConfig = { | ||
| clientId: "client-id", | ||
| clientSecret: "client-secret", | ||
| }; | ||
|
|
||
| describe("QuranClient", () => { | ||
| afterEach(() => { | ||
| vi.restoreAllMocks(); | ||
| }); | ||
|
|
||
| it("exposes a cloned configuration object with resolved defaults", () => { | ||
| const client = new QuranClient(baseConfig); | ||
|
|
||
| const config = client.getConfig(); | ||
|
|
||
| expect(config.contentBaseUrl).toBe("https://apis.quran.foundation"); | ||
| expect(config.authBaseUrl).toBe("https://oauth2.quran.foundation"); | ||
| expect(config.defaults?.language).toBe(Language.ARABIC); | ||
| }); | ||
|
|
||
| it("merges updates and forwards the new config to the fetcher", () => { | ||
| const client = new QuranClient({ | ||
| ...baseConfig, | ||
| defaults: { | ||
| perPage: 10, | ||
| }, | ||
| }); | ||
|
|
||
| const updateSpy = vi.spyOn(QuranFetcher.prototype, "updateConfig"); | ||
|
|
||
| client.updateConfig({ | ||
| contentBaseUrl: "https://custom.example.com", | ||
| defaults: { | ||
| language: Language.ENGLISH, | ||
| }, | ||
| }); | ||
|
|
||
| const updatedConfig = client.getConfig(); | ||
|
|
||
| expect(updatedConfig.contentBaseUrl).toBe( | ||
| "https://custom.example.com", | ||
| ); | ||
| expect(updatedConfig.defaults?.language).toBe(Language.ENGLISH); | ||
| expect(updatedConfig.defaults?.perPage).toBe(10); | ||
|
|
||
| expect(updateSpy).toHaveBeenCalledWith( | ||
| expect.objectContaining({ | ||
| contentBaseUrl: "https://custom.example.com", | ||
| defaults: expect.objectContaining({ | ||
| language: Language.ENGLISH, | ||
| perPage: 10, | ||
| }), | ||
| }), | ||
| ); | ||
| }); | ||
|
|
||
| it("delegates token clearing to the fetcher", () => { | ||
| const client = new QuranClient(baseConfig); | ||
|
|
||
| const clearSpy = vi.spyOn( | ||
| QuranFetcher.prototype, | ||
| "clearCachedToken", | ||
| ); | ||
|
|
||
| client.clearCachedToken(); | ||
|
|
||
| expect(clearSpy).toHaveBeenCalledTimes(1); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,150 @@ | ||
| import { describe, expect, it, vi } from "vitest"; | ||
|
|
||
| import { QuranFetcher } from "../src/sdk/fetcher"; | ||
| import { Language } from "../src/types"; | ||
|
|
||
| const baseConfig = { | ||
| clientId: "client-id", | ||
| clientSecret: "client-secret", | ||
| contentBaseUrl: "https://apis.quran.foundation", | ||
| authBaseUrl: "https://oauth2.quran.foundation", | ||
| defaults: { | ||
| language: Language.ENGLISH, | ||
| perPage: 25, | ||
| }, | ||
| } as const; | ||
|
|
||
| type MockResponse = { | ||
| ok: boolean; | ||
| status: number; | ||
| statusText: string; | ||
| json: () => Promise<unknown>; | ||
| }; | ||
|
|
||
| const createResponse = <T>( | ||
| data: T, | ||
| overrides: Partial<MockResponse> = {}, | ||
| ): MockResponse => | ||
| ({ | ||
| ok: true, | ||
| status: 200, | ||
| statusText: "OK", | ||
| json: async () => data, | ||
| ...overrides, | ||
| }); | ||
|
|
||
| describe("QuranFetcher", () => { | ||
| it("requests an access token once and reuses it for subsequent API calls", async () => { | ||
| const fetchMock = vi | ||
| .fn<[string, RequestInit?], Promise<MockResponse>>() | ||
| .mockResolvedValueOnce( | ||
| createResponse({ | ||
| access_token: "token-123", | ||
| token_type: "bearer", | ||
| expires_in: 3600, | ||
| scope: "content", | ||
| }), | ||
| ) | ||
| .mockResolvedValueOnce( | ||
| createResponse({ | ||
| sample_value: 42, | ||
| }), | ||
| ) | ||
| .mockResolvedValueOnce( | ||
| createResponse({ | ||
| sample_value: 84, | ||
| }), | ||
| ); | ||
|
|
||
| const fetcher = new QuranFetcher({ | ||
| ...baseConfig, | ||
| fetch: fetchMock, | ||
| }); | ||
|
|
||
| const firstResult = await fetcher.fetch<{ sampleValue: number }>( | ||
| "/content/api/v4/example", | ||
| { | ||
| page: 2, | ||
| words: true, | ||
| }, | ||
| ); | ||
|
|
||
| const secondResult = await fetcher.fetch<{ sampleValue: number }>( | ||
| "/content/api/v4/example", | ||
| { page: 3 }, | ||
| ); | ||
|
|
||
| expect(firstResult.sampleValue).toBe(42); | ||
| expect(secondResult.sampleValue).toBe(84); | ||
|
|
||
| expect(fetchMock).toHaveBeenCalledTimes(3); | ||
|
|
||
| const [tokenUrl, tokenOptions] = fetchMock.mock.calls[0]; | ||
| expect(tokenUrl).toBe(`${baseConfig.authBaseUrl}/oauth2/token`); | ||
| expect(tokenOptions?.method).toBe("POST"); | ||
| expect(tokenOptions?.headers).toMatchObject({ | ||
| Authorization: expect.stringContaining("Basic "), | ||
| "Content-Type": "application/x-www-form-urlencoded", | ||
| Accept: "application/json", | ||
| }); | ||
|
|
||
| const tokenBody = new URLSearchParams( | ||
| tokenOptions?.body as string, | ||
| ); | ||
| expect(tokenBody.get("grant_type")).toBe("client_credentials"); | ||
| expect(tokenBody.get("scope")).toBe("content"); | ||
|
|
||
| const [firstDataUrl, firstDataOptions] = fetchMock.mock.calls[1]; | ||
| const firstUrl = new URL(firstDataUrl as string); | ||
| expect(firstUrl.origin + firstUrl.pathname).toBe( | ||
| `${baseConfig.contentBaseUrl}/content/api/v4/example`, | ||
| ); | ||
| expect(firstUrl.searchParams.get("language")).toBe(Language.ENGLISH); | ||
| expect(firstUrl.searchParams.get("per_page")).toBe("25"); | ||
| expect(firstUrl.searchParams.get("page")).toBe("2"); | ||
| expect(firstUrl.searchParams.get("words")).toBe("true"); | ||
|
|
||
| const [secondDataUrl, secondDataOptions] = fetchMock.mock.calls[2]; | ||
| const secondUrl = new URL(secondDataUrl as string); | ||
| expect(secondUrl.searchParams.get("page")).toBe("3"); | ||
|
|
||
| expect(firstDataOptions?.headers).toMatchObject({ | ||
| "x-auth-token": "token-123", | ||
| "x-client-id": baseConfig.clientId, | ||
| "Content-Type": "application/json", | ||
| }); | ||
|
|
||
| expect(secondDataOptions?.headers).toMatchObject({ | ||
| "x-auth-token": "token-123", | ||
| "x-client-id": baseConfig.clientId, | ||
| }); | ||
| }); | ||
|
|
||
| it("throws an error when the API response is not ok", async () => { | ||
| const fetchMock = vi | ||
| .fn<[string, RequestInit?], Promise<MockResponse>>() | ||
| .mockResolvedValueOnce( | ||
| createResponse({ | ||
| access_token: "token-456", | ||
| token_type: "bearer", | ||
| expires_in: 3600, | ||
| scope: "content", | ||
| }), | ||
| ) | ||
| .mockResolvedValueOnce( | ||
| createResponse( | ||
| { error: "server failure" }, | ||
| { ok: false, status: 500, statusText: "Server Error" }, | ||
| ), | ||
| ); | ||
|
|
||
| const fetcher = new QuranFetcher({ | ||
| ...baseConfig, | ||
| fetch: fetchMock, | ||
| }); | ||
|
|
||
| await expect( | ||
| fetcher.fetch("/content/api/v4/example"), | ||
| ).rejects.toThrowError("500 Server Error"); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,45 @@ | ||
| import { describe, expect, it, vi } from "vitest"; | ||
|
|
||
| import { retry } from "../src/lib/retry"; | ||
|
|
||
| describe("retry helper", () => { | ||
| it("retries until the wrapped promise resolves", async () => { | ||
| vi.useFakeTimers(); | ||
|
|
||
| try { | ||
| const task = vi | ||
| .fn<[], Promise<string>>() | ||
| .mockRejectedValueOnce(new Error("first failure")) | ||
| .mockResolvedValueOnce("success"); | ||
|
|
||
| const promise = retry(task, { retries: 1 }); | ||
| const expectation = expect(promise).resolves.toBe("success"); | ||
|
|
||
| await vi.runAllTimersAsync(); | ||
|
|
||
| await expectation; | ||
| expect(task).toHaveBeenCalledTimes(2); | ||
| } finally { | ||
| vi.useRealTimers(); | ||
| } | ||
| }); | ||
|
|
||
| it("propagates the last error once retries are exhausted", async () => { | ||
| vi.useFakeTimers(); | ||
|
|
||
| try { | ||
| const error = new Error("always failing"); | ||
| const task = vi.fn<[], Promise<never>>().mockRejectedValue(error); | ||
|
|
||
| const promise = retry(task, { retries: 2 }); | ||
| const expectation = expect(promise).rejects.toBe(error); | ||
|
|
||
| await vi.runAllTimersAsync(); | ||
|
|
||
| await expectation; | ||
| expect(task).toHaveBeenCalledTimes(3); | ||
| } finally { | ||
| vi.useRealTimers(); | ||
| } | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,51 @@ | ||
| import { describe, expect, it } from "vitest"; | ||
|
|
||
| import { paramsToString, removeBeginningSlash } from "../src/lib/url"; | ||
| import { Language } from "../src/types"; | ||
|
|
||
| describe("URL helpers", () => { | ||
| it("removes a leading slash from paths", () => { | ||
| expect(removeBeginningSlash("/content/api")).toBe("content/api"); | ||
| expect(removeBeginningSlash("content/api")).toBe("content/api"); | ||
| }); | ||
|
|
||
| it("returns an empty string when no params are supplied", () => { | ||
| expect(paramsToString()).toBe(""); | ||
| expect(paramsToString({})).toBe(""); | ||
| }); | ||
|
|
||
| it("serialises complex query parameters correctly", () => { | ||
| const query = paramsToString({ | ||
| language: Language.ENGLISH, | ||
| page: 2, | ||
| perPage: 25, | ||
| words: true, | ||
| translations: [1, 2, 3], | ||
| fields: { | ||
| textUthmani: true, | ||
| codeV1: false, | ||
| }, | ||
| wordFields: { | ||
| textUthmani: true, | ||
| codeV2: true, | ||
| }, | ||
| translationFields: { | ||
| verseKey: true, | ||
| languageName: false, | ||
| }, | ||
| }); | ||
|
|
||
| expect(query.startsWith("?")).toBe(true); | ||
|
|
||
| const searchParams = new URLSearchParams(query.slice(1)); | ||
|
|
||
| expect(searchParams.get("language")).toBe(Language.ENGLISH); | ||
| expect(searchParams.get("page")).toBe("2"); | ||
| expect(searchParams.get("per_page")).toBe("25"); | ||
| expect(searchParams.get("words")).toBe("true"); | ||
| expect(searchParams.get("translations")).toBe("1,2,3"); | ||
| expect(searchParams.get("fields")).toBe("text_uthmani"); | ||
| expect(searchParams.get("word_fields")).toBe("text_uthmani,code_v2"); | ||
| expect(searchParams.get("translation_fields")).toBe("verse_key"); | ||
| }); | ||
| }); | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧹 Nitpick | 🔵 Trivial
LGTM! Comprehensive validation of the parameter serialization fix.
This test effectively validates the core fix described in the PR:
The use of URLSearchParams for validation mirrors the implementation approach, which strengthens the test.
Optional: Consider adding edge case tests to further strengthen coverage:
Additional test cases to consider:
translations: []fields: { textUthmani: false, codeV1: false }Apply this diff to add an edge case test:
📝 Committable suggestion
🤖 Prompt for AI Agents