Sahtelerle test
@safran/kit/testing, Safran kullanan kodu ve onun için yazılmış bağlayıcıları ağ, iş takip hesabı veya gömme modeli olmadan test etmek için gereken her şeyi barındırır. Bu sayfa, bir Safran örneği alan kod için eksiksiz bir bun:test dosyasını, mockFetch ile eksiksiz bir bağlayıcı testini ve her sahtenin ne yaptığını gösterir.
Sahteler, sözleşmelerin bellek üzerinde çalışan gerçek uygulamalarıdır. FakeTracker bir Tracker nesnesidir; onun üzerine kurulan örnek, üretimde çalıştırdığı yönlendirme, yetenek denetimi, sayfalama ve iptal kodunun aynısını çalıştırır. Yalnızca en uçtaki sistem değiştirilmiştir.
| Dışa aktarım | Ne olduğu |
|---|---|
FakeTracker | Kayıtları, yorumları, bağlantıları, ekleri, geçmişi ve araması olan bellek içi bir Tracker. |
FakeCodeHost | Repoları ve birleştirilmiş pull request'leri olan bellek içi bir CodeHost. |
FakeDocSource | Tek bir kökeni sahiplenen ve sayfaları URL'ye göre sunan bellek içi bir DocSource. |
FakeCodeIndex | Bellek içi bir CodeIndex: verdiğiniz dosyalarda arar, grep yapar ve okur. |
FakeEmbedder | Belirlenimci, çevrimdışı bir Embedder. |
fakeTrackerPlugin, fakeCodeHostPlugin, fakeDocSourcePlugin, fakeEmbedderPlugin, fakePlugins | Bu bağlayıcıları createSafran çağrısına veren, fake tipinde eklentiler. |
mockFetch | Bir rota tablosundan yanıt veren ve her isteği kaydeden bir fetch. |
Safran örneği kullanan kodu test etmek
Test edilen kod, bir insanın bir kayda başlaması için gerekenleri toplar. Örneği argüman olarak alır; bir testin ihtiyaç duyduğu bütün "bağımlılık enjeksiyonu" bundan ibarettir:
import type { CallOptions, Safran } from "@safran/core";
export interface Triage {
key: string;
title: string;
/** Teams that own the ticket's project, by declaration. */
owners: string[];
/** The query that was searched, after glossary expansion. */
searchedFor: string;
/** Distinct `repo/path` of the best code hits. */
files: string[];
/** URLs the ticket links to that a doc source can fetch. */
docs: string[];
}
/** Collects what a person needs to start on a ticket: who owns it, where the code is, what to read. */
export async function triage(safran: Safran, ref: string, options: CallOptions = {}): Promise<Triage> {
const ticket = await safran.tickets.get(ref, options);
const { teams } = await safran.company.whoOwns({ project: ticket.project }, options);
const search = await safran.code.search(ticket.title, { limit: 5, ...options });
// Links are optional: a tracker without them still gets a triage.
const { tracker } = safran.tickets.resolve(ref);
const links = tracker.capabilities.has("links") ? await safran.tickets.links(ref, options) : [];
return {
key: ticket.key,
title: ticket.title,
owners: teams.map((team) => team.name),
searchedFor: search.effectiveQuery,
files: [...new Set(search.hits.map((hit) => `${hit.repo}/${hit.path}`))],
docs: links.flatMap((link) => (link.kind === "web" && link.url !== undefined && safran.docs.canFetch(link.url) ? [link.url] : [])),
};
}Bir düzenek acme hikâyesini bellekte kurar. Örneğin yanında sahteleri de döndürür; böylece testler onları değiştirebilir ve onlara ne sorulduğunu doğrulayabilir:
import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { createSafran, defineProfile, type Safran, type TrackerCapability } from "@safran/core";
import { FakeCodeHost, FakeCodeIndex, FakeDocSource, FakeTracker, fakePlugins } from "@safran/kit/testing";
export const WIKI_PAGE = "https://acme.atlassian.net/wiki/spaces/PAY/pages/4711/Refund-runbook";
export interface Acme {
safran: Safran;
jira: FakeTracker;
azure: FakeCodeHost;
wiki: FakeDocSource;
index: FakeCodeIndex;
}
/** The acme story in memory. Every test gets its own instance and its own data directory. */
export async function createAcme(options: { trackerCapabilities?: TrackerCapability[] } = {}): Promise<Acme> {
const jira = new FakeTracker({
id: "jira",
baseUrl: "https://acme.atlassian.net",
...(options.trackerCapabilities === undefined ? {} : { capabilities: options.trackerCapabilities }),
tickets: [
{
key: "PAY-1423",
title: "Kısmi iade işlemi İstanbul şubesinde başarısız oluyor",
type: "Bug",
status: "Done",
statusCategory: "done",
comments: [{ id: "c1", body: "Yuvarlama hatası görünüyor." }],
links: [
{ kind: "ticket", relation: "blocks", ticket: { key: "PAY-1500", title: "Refund webhook retries are not idempotent" } },
{ kind: "web", relation: "mentioned in", url: WIKI_PAGE, title: "Refund runbook" },
{ kind: "web", relation: "mentioned in", url: "https://intranet.acme.test/handbook" },
],
},
{ key: "PAY-1500", title: "Refund webhook retries are not idempotent", statusCategory: "in_progress" },
{ key: "PAY-1501", title: "Checkout basket total ignores the campaign discount", statusCategory: "todo" },
],
});
const azure = new FakeCodeHost({
id: "azure",
repos: [{ name: "payments-api" }, { name: "ledger" }],
pullRequests: [
{ id: "101", repo: "payments-api", title: "PAY-1423 fix partial refund rounding", description: "", mergedAt: "2026-10-20T09:00:00Z", linkedTicketKeys: [], changedFiles: ["src/refund/service.ts", "src/refund/policy.ts"] },
],
});
const wiki = new FakeDocSource({
id: "wiki",
origin: "https://acme.atlassian.net",
pages: { [WIKI_PAGE]: { title: "Refund runbook", content: "# Refund runbook\n\nPartial refunds are rounded to two decimals." } },
});
const index = new FakeCodeIndex({
groups: { backend: ["payments-api", "ledger"] },
files: {
"payments-api": {
"src/refund/service.ts": "export class RefundService {\n createPartialRefund() {}\n}\n",
"src/refund/policy.ts": "export class RefundPolicy {\n roundRefundAmount() {}\n}\n",
"src/webhook/retry.ts": "export function handleRefundWebhook() {}\n",
},
ledger: { "src/entry.ts": "export function chargebackEntry() {}\n" },
},
});
const safran = await createSafran({
profile: defineProfile({
version: 1,
company: "acme",
languages: { tickets: "tr", code: "en" },
trackers: [{ id: "jira", type: "fake", projects: ["PAY", "MOB", "WEB"] }],
code: { hosts: [{ id: "azure", type: "fake" }], groups: { backend: ["payments-api", "ledger"] } },
docs: [{ id: "wiki", type: "fake" }],
teams: [{ name: "Payments", projects: ["PAY"], repos: ["payments-api", "ledger"] }],
glossary: [{ term: "İade", code: ["refund", "chargeback"] }],
}),
dataDir: mkdtempSync(join(tmpdir(), "acme-test-")),
builtinPlugins: false,
plugins: fakePlugins({ trackers: [jira], hosts: [azure], docs: [wiki] }),
index,
});
return { safran, jira, azure, wiki, index };
}İçindeki üç tercih kopyalanmaya değer:
fakePlugins(...)ile birliktebuiltinPlugins: false: kayıt defterinde yalnızca sahteler bulunur; düzenekteki bir yazım hatası gerçek bir servise ulaşamaz.indexbirFakeCodeIndexnesnesidir: SQLite dosyası yok, gömme modeli yok.- Her örnek için yeni bir
dataDir: bağlantı deposu gerçek bir SQLite dosyasıdır ve testler tek bir depoyu paylaşmamalıdır.
Testler:
import { describe, expect, test } from "bun:test";
import { isSafranError } from "@safran/core";
import { createAcme, WIKI_PAGE } from "./acme";
import { triage } from "./triage";
describe("triage", () => {
test("collects owners, code and fetchable docs for a ticket", async () => {
const acme = await createAcme();
await using safran = acme.safran;
const result = await triage(safran, "pay-1423");
expect(result.key).toBe("PAY-1423");
expect(result.owners).toEqual(["Payments"]);
// The glossary turned "iade" into the words the code uses.
expect(result.searchedFor).toBe("Kısmi iade işlemi İstanbul şubesinde başarısız oluyor refund chargeback");
expect(result.files).toContain("payments-api/src/refund/service.ts");
// Only the link a configured doc source recognises; the intranet URL is left out.
expect(result.docs).toEqual([WIKI_PAGE]);
});
test("asks the index once, with the expanded query and the limit", async () => {
const acme = await createAcme();
await using safran = acme.safran;
await triage(safran, "PAY-1423");
expect(acme.index.count("search")).toBe(1);
const [query, options] = acme.index.last("search");
expect(query).toContain("refund chargeback");
expect(options).toMatchObject({ limit: 5 });
// The tracker was reached with the canonical key, whatever was typed.
expect(acme.jira.calls.filter((call) => call.method === "getTicket").map((call) => call.args[0])).toEqual(["PAY-1423"]);
});
test("a tracker without links still gets a triage", async () => {
const acme = await createAcme({ trackerCapabilities: ["comments", "search"] });
await using safran = acme.safran;
const result = await triage(safran, "PAY-1423");
expect(result.docs).toEqual([]);
expect(acme.jira.calls.some((call) => call.method === "getLinks")).toBe(false);
});
test("an unknown ticket is NOT_FOUND, not an empty triage", async () => {
const acme = await createAcme();
await using safran = acme.safran;
const failure = await triage(safran, "PAY-9999").catch((error: unknown) => error);
expect(isSafranError(failure, "NOT_FOUND")).toBe(true);
// Nothing was searched for a ticket that does not exist.
expect(acme.index.count("search")).toBe(0);
});
test("a failing index surfaces its error", async () => {
const acme = await createAcme();
await using safran = acme.safran;
acme.index.failure = new Error("disk full");
await expect(triage(safran, "PAY-1423")).rejects.toThrow("disk full");
});
test("cancellation stops a search that hangs", async () => {
const acme = await createAcme();
await using safran = acme.safran;
acme.index.hang = true;
const failure = await triage(safran, "PAY-1423", { signal: AbortSignal.timeout(50) }).catch((error: unknown) => error);
expect(isSafranError(failure, "ABORTED")).toBe(true);
});
test("the rest of the instance works on the same fakes", async () => {
const acme = await createAcme();
await using safran = acme.safran;
const page = await safran.docs.fetch(WIKI_PAGE);
expect(page.title).toBe("Refund runbook");
const report = await safran.links.refresh({ since: "2026-01-01" });
expect(report.repos.map((row) => [row.repo, row.status, row.linked])).toEqual([
["payments-api", "ok", 1],
["ledger", "ok", 0],
]);
expect((await safran.links.query({ ticket: "PAY-1423" })).flatMap((record) => record.changedFiles)).toEqual(["src/refund/service.ts", "src/refund/policy.ts"]);
const grep = await safran.code.grep("Refund", { groups: ["backend"], pathGlob: "*.ts" });
expect(grep.total).toBe(5);
});
});Bir bağlayıcıyı mockFetch ile test etmek
Bağlayıcı bir kat aşağıda test edilir: onu Safran'ın kurduğu gibi kurun, bir tablodan yanıt veren bir fetch verin ve ne döndürdüğünü, ne gönderdiğini doğrulayın. Buradaki bağlayıcı, eklentiler sayfasındaki doküman kaynağıdır; bu sayfa kendi başına eksiksiz olsun diye yinelenmiştir:
import { asRecord, asString, createHttpClient, defineDocSource, envVarName, httpUrl, isoDate, SafranError, type DocPage, type HttpClient } from "@safran/kit";
import { z } from "zod";
const configSchema = z.strictObject({
id: z.string().min(1),
type: z.literal("acme-handbook"),
url: httpUrl,
token_env: envVarName,
});
export const acmeHandbook = defineDocSource({
type: "acme-handbook",
description: "Pages of the Acme Handbook",
configSchema,
create(config, ctx) {
const origin = new URL(config.url).origin;
let client: HttpClient | undefined;
const http = (): HttpClient =>
(client ??= createHttpClient({
service: "Acme Handbook",
baseUrl: `${origin}/api`,
headers: { authorization: `Bearer ${ctx.secret(config.token_env)}` },
fetch: ctx.fetch,
logger: ctx.logger,
notFoundHint: "Check the link in the ticket; the page may have been moved or deleted.",
}));
/** `/p/<slug>` on our own origin, or undefined. Parsed, never prefix-matched. */
const slugOf = (url: string): string | undefined => {
try {
const parsed = new URL(url);
if (parsed.origin !== origin) return undefined;
return /^\/p\/([a-z0-9-]+)\/?$/.exec(parsed.pathname)?.[1];
} catch {
return undefined;
}
};
return {
id: config.id,
type: "acme-handbook",
matchUrl: (url) => slugOf(url) !== undefined,
async getPage(url, options): Promise<DocPage> {
const slug = slugOf(url);
// Safran only calls getPage after matchUrl; a connector still never fetches what it does not own.
if (slug === undefined) throw new SafranError("INVALID_INPUT", "Not an Acme Handbook page URL");
const body = await http().json({ path: `pages/${slug}`, ...(options?.signal ? { signal: options.signal } : {}) });
const page = asRecord(body);
const updatedAt = isoDate(page?.updated_at);
return {
source: config.id,
url,
title: asString(page?.title) ?? slug,
content: asString(page?.markdown) ?? "",
...(updatedAt === undefined ? {} : { updatedAt }),
};
},
};
},
});import { describe, expect, test } from "bun:test";
import { isSafranError, parsePluginConfig, silentLogger, type DocSource, type PluginContext } from "@safran/kit";
import { mockFetch, type MockRoute } from "@safran/kit/testing";
import { acmeHandbook } from "./handbook";
const PAGE_URL = "https://handbook.acme.test/p/refund-policy";
const API_URL = "https://handbook.acme.test/api/pages/refund-policy";
/** Builds the connector the way Safran does: validated config, then `create` with a context. */
async function connect(routes: MockRoute[], env: Record<string, string> = { HANDBOOK_TOKEN: "test-token" }) {
const mock = mockFetch(routes);
const context: PluginContext = {
company: "acme",
logger: silentLogger,
fetch: mock.fetch,
dataDir: "/work/acme/data/cache/handbook",
secret(name) {
const value = env[name];
if (value === undefined) throw new Error(`test setup: ${name} is not set`);
return value;
},
optionalSecret: (name) => (name === undefined ? undefined : env[name]),
};
const config = parsePluginConfig(acmeHandbook, { id: "handbook", type: "acme-handbook", url: "https://handbook.acme.test", token_env: "HANDBOOK_TOKEN" }, "docs.0");
const source: DocSource = await acmeHandbook.create(config, context);
return { source, requests: mock.requests };
}
describe("acme-handbook", () => {
test("claims only its own page URLs", async () => {
const { source, requests } = await connect([]);
expect(source.matchUrl(PAGE_URL)).toBe(true);
expect(source.matchUrl("https://handbook.acme.test/admin")).toBe(false);
expect(source.matchUrl("https://handbook.acme.test.attacker.test/p/refund-policy")).toBe(false);
expect(source.matchUrl("not a url")).toBe(false);
// Matching is offline.
expect(requests).toHaveLength(0);
});
test("happy path: fetches a page and maps it", async () => {
const { source, requests } = await connect([
{ method: "GET", url: API_URL, reply: { json: { title: "Refund policy", markdown: "Refunds are rounded to two decimals.", updated_at: "2026-10-01T12:00:00+0300" } } },
]);
const page = await source.getPage(PAGE_URL);
expect(page).toEqual({
source: "handbook",
url: PAGE_URL,
title: "Refund policy",
content: "Refunds are rounded to two decimals.",
updatedAt: "2026-10-01T09:00:00.000Z",
});
// The token travels in the header, to the right origin, and nowhere else.
expect(requests).toHaveLength(1);
expect(requests[0]?.headers.get("authorization")).toBe("Bearer test-token");
expect(requests[0]?.url.href).toBe(API_URL);
});
test("401 becomes AUTH_FAILED, without the token in the error", async () => {
const { source } = await connect([{ url: API_URL, reply: { status: 401, json: { error: "invalid token" } } }]);
const failure = await source.getPage(PAGE_URL).catch((error: unknown) => error);
expect(isSafranError(failure, "AUTH_FAILED")).toBe(true);
expect(JSON.stringify(failure)).not.toContain("test-token");
});
test("404 becomes NOT_FOUND with the connector's hint", async () => {
const { source } = await connect([{ url: API_URL, reply: { status: 404, text: "no such page" } }]);
const failure = await source.getPage(PAGE_URL).catch((error: unknown) => error);
expect(isSafranError(failure, "NOT_FOUND") && failure.hint).toBe("Check the link in the ticket; the page may have been moved or deleted.");
});
test("429 then success: the request is retried", async () => {
const { source, requests } = await connect([
{
url: API_URL,
// A list is consumed one reply per call; the last one repeats.
reply: [{ status: 429, headers: { "retry-after": "0" } }, { json: { title: "Refund policy", markdown: "Refunds are rounded." } }],
},
]);
const page = await source.getPage(PAGE_URL);
expect(page.title).toBe("Refund policy");
expect(requests).toHaveLength(2);
});
test("a request without a route fails loudly", async () => {
const { source } = await connect([]);
const failure = await source.getPage(PAGE_URL).catch((error: unknown) => error);
expect(isSafranError(failure, "INTERNAL") && failure.message).toBe(`mockFetch: no route for GET ${API_URL}`);
});
test("a cancelled call is ABORTED and makes no request", async () => {
const { source, requests } = await connect([{ url: API_URL, reply: { json: {} } }]);
const failure = await source.getPage(PAGE_URL, { signal: AbortSignal.abort() }).catch((error: unknown) => error);
expect(isSafranError(failure, "ABORTED")).toBe(true);
expect(requests).toHaveLength(0);
});
});İki dosyayı çalıştırın:
$ bun test triage.test.ts handbook.test.ts
bun test v1.3.2 (b131639c)
14 pass
0 fail
36 expect() calls
Ran 14 tests across 2 files. [130.00ms]Test dosyalarının nerede durması gerektiği, Safran içe aktaran her betik için sorulan sorunun aynısıdır: @safran/core ve @safran/kit paketlerini bağımlılık olarak bildiren bir paketin içinde. Bkz. kurulum.
mockFetch
mockFetch(routes), { fetch, requests } döndürür. fetch değerini bir fetch kabul edilen her yere verin: onu her bağlayıcıya ileten createSafran({ fetch }) çağrısına ya da yukarıdaki gibi bir PluginContext içine.
| Rota alanı | Anlamı |
|---|---|
method | İsteğe bağlı. Verilirse yalnızca bu metotla yapılan istekler eşleşir. |
url | Dize, isteğin sorgusuz kökeni ve yoluyla karşılaştırılır: eşitse ya da istek onunla bitiyorsa eşleşir (dolayısıyla "/api/pages/refund-policy" yeterlidir). RegExp ise köken, yol ve sorguya karşı sınanır. |
reply | Tek bir yanıt; çağrı başına biri tüketilen ve sonuncusu yinelenen bir liste; ya da kaydedilen isteğin bir işlevi. |
Yanıt bir Response nesnesi ya da status (varsayılan 200), json, text, bytes ve headers alanlarından herhangi birini taşıyan bir nesnedir. Eşleşen ilk rota yanıt verir; bu yüzden özel rotaları genel olanlardan önce yazın.
| Kaydedilen alan | Anlamı |
|---|---|
method | HTTP metodu. |
url | Ayrıştırılmış bir URL: pathname ve searchParams üzerinde doğrulama yapın. |
headers | İstek başlıkları; bir jetonun gönderildiğini (ve nereye gönderildiğini) denetlemek için. |
body | Metin olarak istek gövdesi ya da undefined. |
redirect | Çağıranın fetch çağrısına verdiği yönlendirme kipi, verdiyse. |
Üç davranış testleri güvenilir kılar:
- Rotası olmayan istek gürültüyle başarısız olur. Kodu
INTERNALolan, iletisinde metot ve URL bulunan birSafranErrorfırlatır. Bir test yanlışlıkla ağa ulaşamaz; rotadaki bir yazım hatası da saniyeler süren yeniden deneme beklemesinden sonra değil, hemen ortaya çıkar. - Her istek kaydedilir, başarısız olan da. Böylece "hiç istek yapılmadı" yazabileceğiniz bir doğrulamadır.
- Yeniden denemeler gerçektir. HTTP istemcisinin beklemesi üretimdeki gibi çalışır. Yeniden denenen isteğe, 429 testindeki gibi
retry-after: 0ile yanıt verin ki test beklemesin.
export interface MockRoute {
method?: string;
/** Matched against `origin + pathname` (string: exact or suffix match). */
url: string | RegExp;
/** A single reply, or a list consumed one per call (the last one repeats). */
reply: MockReply | MockReply[] | ((request: RecordedRequest) => MockReply | Promise<MockReply>);
}
export type MockReply = Response | { status?: number; json?: unknown; text?: string; headers?: Record<string, string>; bytes?: Uint8Array };
export interface RecordedRequest {
method: string;
url: URL;
headers: Headers;
body: string | undefined;
/** Redirect policy the caller passed to `fetch`, when it passed one. */
redirect?: "follow" | "manual" | "error";
}
export interface MockFetch {
fetch: typeof fetch;
requests: RecordedRequest[];
}tanımlandığı yer: packages/kit/src/testing.ts
Sahtelerin ayrıntıları
FakeTracker
| Seçenek | Varsayılan | Anlamı |
|---|---|---|
id | "fake" | Bağlayıcının kimliği. fakePlugins üzerinden kullanıldığında profil girişinin kimliğine eşit olmalıdır. |
type | "fake" | tracker.type olarak bildirilir. |
projects | kayıt anahtarlarından türetilir | matchTicketRef metodunun kabul ettiği ve listProjects metodunun döndürdüğü projeler. |
tickets | yok | FakeTicket nesneleri: key ve title zorunludur, her Ticket alanı verilebilir; ayrıca comments, attachments, links ve history. |
capabilities | altısı da | Kodunuzun kısıtlı bir sistemle ne yaptığını test etmek için daraltın. |
baseUrl | https://tracker.test | Kayıt URL'leri <baseUrl>/browse/<KEY> biçimindedir ve matchTicketRef bu biçimi kabul eder. |
Bildiği projeler için KEY-123 biçimini her harf büyüklüğünde ve kendi browse URL'lerini tanır. addTicket(ticket) sonradan kayıt ekler. calls, her metot çağrısını { method, args } olarak kaydeder. Arama, text değerini başlık ve açıklamada alt dize olarak eşleştirir ve diğer sorgu alanlarını uygular; sayfalama, gerçek bağlayıcılarla aynı limit kuralına uyar ve varsayılan sayfa 50 öğedir.
FakeCodeHost
| Seçenek | Varsayılan | Anlamı |
|---|---|---|
id | "fake" | Bağlayıcının kimliği. |
type | "fake" | host.type olarak bildirilir. |
repos | yok | Repolar; yalnızca name zorunludur. fullName varsayılanı fake/<name>, defaultBranch varsayılanı main, cloneUrl varsayılanı https://git.test/fake/<name>.git olur. |
pullRequests | yok | Birleştirilmiş pull request'ler; en yeniden eskiye sunulur ve mergedSince ile süzülür. |
auth | yok | gitAuth() çağrısının döndürdüğü değer. |
capabilities | pull-requests, remote-head | Geçmişi olmayan bir barındırıcıyı test etmek için pull-requests yeteneğini çıkarın. |
remoteHeads | yok | getRemoteHead yanıtları; anahtar biçimi <repo>@<branch>. |
Listeleme, links.refresh ve sahiplik onun üzerinde olduğu gibi çalışır. repos.sync() ise yer tutucu URL üzerinde git clone çalıştırırdı: senkronizasyon testi için her repoya mutlak bir dizin yolu olan bir cloneUrl verin. Safran o zaman onu, local barındırıcıda yaptığı gibi, yerinde okur.
FakeDocSource
| Seçenek | Varsayılan | Anlamı |
|---|---|---|
id | "fake" | Bağlayıcının kimliği. |
type | "fake" | source.type olarak bildirilir. |
origin | https://docs.test | URL'lerini sahiplendiği köken. Gerçek bir kaynağın yapması gerektiği gibi, ayrıştırılmış köken olarak karşılaştırılır. |
pages | yok | Tam URL'ye göre sayfalar: title, content, isteğe bağlı olarak updatedAt ve author. |
Kendi kökeninde olup sayfası bulunmayan bir URL NOT_FOUND hatasıdır. addPage(url, page) sayfa ekler; calls, getPage çağrılarını kaydeder.
FakeCodeIndex
| Seçenek | Anlamı |
|---|---|
embedder | status().embedder değerinin bildirdiği şey. Varsayılan fake:hash-256. |
files | Repo adı → repo köküne göre yol → dosya metni. Bu repolar baştan indekslenmiş sayılır. |
groups | status() için grup → repo adları. |
hits | Betiklenmiş arama sonuçları: bir liste ya da sorgunun bir işlevi. Süzgeçler ve limit yine uygulanır. Verilmezse arama, files üzerinde sözcük eşleştirmesidir. |
repos | Burada dosyası olmayan repolar için ek status() satırları. |
CodeIndex metotlarının ötesinde, gerçeğinde üretmesi zor durumlar için anahtarları vardır:
| Üye | Kullanımı |
|---|---|
calls, count(method), last(method) | İndekse ne soruldu. last, en son çağrının argümanlarını döndürür. |
addFile(repo, path, text), files | Çağrılar arasında içeriği değiştirin. |
hits | Arama sonuçlarını betiklenmiş olanlarla değiştirin. |
grepResult | grep çağrısına bunu yanıtlatın; örneğin incomplete taşıyan bir sonuç. |
failure | Verildiğinde close dışındaki her metot onu fırlatır. |
hang | true iken search, grep ve indexRepo yalnızca sinyalleri iptal edildiğinde sonuçlanır. İptal ve zaman aşımı testleri için. |
failOn | indexRepo çağrısı UPSTREAM ile başarısız olan repo adları; failed satırlı bir senkronizasyon raporunu test etmek için. |
indexed | indexRepo çağrısına en son verilen değer, repo adına göre. |
closed | close() çağrılarının sayısı; indeks sahipliğini doğrulamak için. |
Sınırları kendisine aittir (10 sonuç, 50 grep eşleşmesi, okuma başına 200 satır, en çok 400) ve DEFAULT_FAKE_* sabitleri olarak dışa açılır. Gerçek varsayılanları yansıtırlar; ancak gerçek indeks, sahtede bulunmayan üst sınırlara da çeker.
Örneğin, indeksi çağırmadan önce groups değerini profilden çözdüğünü unutmayın; testteki grup adları profilin code.groups alanından gelir.
FakeEmbedder
new FakeEmbedder(), kimliği fake:hash-256 olan bir Embedder nesnesidir. Sözcükleri ve üçlü karakter dizilerini 256 boyutlu bir birim vektöre özetler: aynı metin her zaman aynı vektörü verir, sözcük paylaşan metinler birbirine yakın düşer. embedded, kendisinden istenen metinleri sayar; önbelleklemeyi test edilebilir kılan budur.
Gerçek indeksi bir testte çalıştırmanızı sağlar; bu da taramayı, parçalamayı, artımlı indekslemeyi ve sözcüksel kanalı gömme sunucusu olmadan kapsar:
import { expect, test } from "bun:test";
import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { createSafran, defineProfile } from "@safran/core";
import { FakeEmbedder } from "@safran/kit/testing";
test("sync indexes a local repository and search finds it, without an embedding server", async () => {
const root = mkdtempSync(join(tmpdir(), "acme-index-"));
mkdirSync(join(root, "payments-api/src/refund"), { recursive: true });
writeFileSync(join(root, "payments-api/src/refund/policy.ts"), "export class RefundPolicy {\n roundRefundAmount(amount: number): number {\n return Math.round(amount * 100) / 100;\n }\n}\n");
const embedder = new FakeEmbedder();
await using safran = await createSafran({
profile: defineProfile({
version: 1,
company: "acme",
code: { hosts: [{ id: "disk", type: "local", repos: [{ name: "payments-api", path: join(root, "payments-api") }] }] },
}),
dataDir: join(root, "data"),
embedder,
});
const first = await safran.repos.sync();
expect(first.results.map((row) => row.status)).toEqual(["ok"]);
expect(first.results[0]?.index?.filesIndexed).toBe(1);
const embeddedOnce = embedder.embedded;
expect(embeddedOnce).toBeGreaterThan(0);
// Nothing changed: the second sync re-chunks and re-embeds nothing.
const second = await safran.repos.sync();
expect(second.results[0]?.index).toMatchObject({ filesIndexed: 0, filesUnchanged: 1, embeddingsComputed: 0 });
expect(embedder.embedded).toBe(embeddedOnce);
const { hits } = await safran.code.search("RefundPolicy", { mode: "lexical" });
expect(hits[0]).toMatchObject({ repo: "payments-api", path: "src/refund/policy.ts" });
expect((await safran.code.status()).embedder).toBe("fake:hash-256");
});Test bilerek mode: "lexical" ile arar: sözcüksel kanal gerçektir; özetlenmiş sözcüklerden oluşan yoğun bir sıralama ise hiçbir şey kanıtlamazdı.
Sahte eklentiler
createSafran bağlayıcıları profil girişlerinden kurar; bu yüzden sahteler ona fake tipinde eklentiler olarak ulaşır:
fakePlugins alanı | Hangi girişler için bağlayıcı |
|---|---|
trackers | type: fake taşıyan trackers[] girişleri; id ile eşleştirilir. |
hosts | code.hosts[] girişleri; id ile eşleştirilir. |
docs | docs[] girişleri; id ile eşleştirilir. |
embedder | embeddings girişi. Verilmezse her kurulum yeni bir FakeEmbedder verir. |
fakePlugins(connectors), dört eklentiyi birden döndürür. fake tipindeki her profil girişi aynı id değerini taşıyan bir bağlayıcıya ihtiyaç duyar; eksik olan, "Test setup: no fake tracker for profile entry …" diyen bir iletiyle kurulumu durdurur; böylece düzenekteki bir hata ürün hatası gibi görünmez.
Tek türlük yardımcılar daha fazla biçim kabul eder:
| Çağrı | Sonuç |
|---|---|
fakeTrackerPlugin(tracker) | O tek sistem, fake tipindeki her iş takip girişine hizmet eder. |
fakeTrackerPlugin([a, b]) | Sistemler girişlerle id üzerinden eşleştirilir. |
fakeTrackerPlugin({ tickets }) | Giriş başına, girişin id değerini alan yeni bir FakeTracker. |
fakeCodeHostPlugin(...) | Kod barındırıcılar için aynı üç biçim. |
fakeDocSourcePlugin(source) veya ([a, b]) | Tek bir kaynak ya da id ile eşleştirilen birkaç kaynak. |
fakeEmbedderPlugin(embedder?) | Verilen gömme modeli ya da kurulum başına yeni bir FakeEmbedder. |
Her biri ikinci bir argüman alır: { type, onCreate }. type, eklentiyi başka bir tip adıyla kaydeder (düzenlemek istemediğiniz bir profilde, builtinPlugins: false ile birlikte, jira yerine geçmesi için); onCreate(config, context) ise her kurulumda çağrılır; bir test PluginContext nesnesini böyle yakalar ya da bir gizli değerin gerçek bir bağlayıcının okuduğu gibi okunduğunu böyle denetler.
Sahte eklentiler profil girişindeki her ek anahtarı (projects, include, uydurma alanlar) kabul eder; bir test profilinin gerçek bir bağlayıcının şemasını karşılaması gerekmez.
Sık yapılan hatalar
| Belirti | Neden |
|---|---|
INTERNAL: Test setup: no fake tracker for profile entry "jira" | fakePlugins çağrısına o id değerini taşıyan bir bağlayıcı verilmemiş. |
Bir testte NOT_FOUND: No tracker recognises "PAY-1" | FakeTracker nesnesinin PAY projesinde kaydı yok ve projects seçeneği de verilmemiş. |
| Test asılı kalıyor | Sinyal olmadan index.hang = true, ya da iptali yok sayan bir çağrıyı bekleyen await using örneği. |
| Yeniden deneme testi saniyeler sürüyor | Yeniden denenen yanıtta retry-after: 0 başlığı yok; gerçek bekleme çalışıyor. |
| Testler birbirini etkiliyor | Bir dataDir (tek bağlantı deposu) ya da tek bir sahte nesne paylaşıyorlar. İkisini de test başına kurun. |
| Sahtelerde geçen, gerçekte başarısız olan bir sıralama doğrulaması | Sahteler anlama göre sıralamaz. Hangi dosyanın önce geldiğini değil, ne sorulduğunu doğrulayın. |