79 lines
2.4 KiB
JavaScript
79 lines
2.4 KiB
JavaScript
import { test, afterEach } from 'node:test';
|
||
import assert from 'node:assert/strict';
|
||
import { GiteaClient } from './gitea.js';
|
||
|
||
const realFetch = globalThis.fetch;
|
||
afterEach(() => { globalThis.fetch = realFetch; });
|
||
|
||
function makeClient() {
|
||
return new GiteaClient({
|
||
serverUrl: 'https://gitea.example',
|
||
owner: 'o',
|
||
repo: 'r',
|
||
token: 't',
|
||
});
|
||
}
|
||
|
||
/** 建立假的 fetch,依序回傳給定的回應。 */
|
||
function stubFetch(responses) {
|
||
const calls = [];
|
||
globalThis.fetch = async (url, opts) => {
|
||
calls.push({ url, opts });
|
||
const r = responses.shift();
|
||
return {
|
||
ok: r.status >= 200 && r.status < 300,
|
||
status: r.status,
|
||
text: async () => (r.body == null ? '' : JSON.stringify(r.body)),
|
||
};
|
||
};
|
||
return calls;
|
||
}
|
||
|
||
test('createPull: 成功建立回傳 created=true', async () => {
|
||
stubFetch([{ status: 201, body: { number: 7, html_url: 'u' } }]);
|
||
const { pull, created } = await makeClient().createPull({
|
||
head: 'feature', base: 'develop', title: 't', body: 'b',
|
||
});
|
||
assert.equal(created, true);
|
||
assert.equal(pull.number, 7);
|
||
});
|
||
|
||
test('createPull: 422 已存在時回查既有 PR,created=false', async () => {
|
||
stubFetch([
|
||
{ status: 422, body: { message: 'already exists' } },
|
||
{ status: 200, body: [
|
||
{ number: 3, head: { ref: 'feature' }, base: { ref: 'develop' } },
|
||
] },
|
||
]);
|
||
const { pull, created } = await makeClient().createPull({
|
||
head: 'feature', base: 'develop', title: 't', body: 'b',
|
||
});
|
||
assert.equal(created, false);
|
||
assert.equal(pull.number, 3);
|
||
});
|
||
|
||
test('createPull: 422 但查無對應 PR 時丟出錯誤', async () => {
|
||
stubFetch([
|
||
{ status: 422, body: { message: 'bad' } },
|
||
{ status: 200, body: [] },
|
||
]);
|
||
await assert.rejects(
|
||
() => makeClient().createPull({ head: 'feature', base: 'develop', title: 't', body: 'b' }),
|
||
/建立 PR 失敗/,
|
||
);
|
||
});
|
||
|
||
test('createPull: 其他錯誤狀態碼直接丟出', async () => {
|
||
stubFetch([{ status: 500, body: { message: '伺服器錯誤' } }]);
|
||
await assert.rejects(
|
||
() => makeClient().createPull({ head: 'feature', base: 'develop', title: 't', body: 'b' }),
|
||
/建立 PR 失敗 \(500\)/,
|
||
);
|
||
});
|
||
|
||
test('findOpenPull: 非陣列回應回傳 null', async () => {
|
||
stubFetch([{ status: 200, body: { unexpected: true } }]);
|
||
const r = await makeClient().findOpenPull('feature', 'develop');
|
||
assert.equal(r, null);
|
||
});
|