|
| 1 | +import {WriteStreamsMock} from "../../../src/write-streams.js"; |
| 2 | +import {handler} from "../../../src/handler.js"; |
| 3 | +import {initSpawnSpy} from "../../mocks/utils.mock.js"; |
| 4 | +import {WhenStatics} from "../../mocks/when-statics.js"; |
| 5 | +import * as state from "../../../src/state.js"; |
| 6 | +import fs from "fs-extra"; |
| 7 | +import path from "path"; |
| 8 | + |
| 9 | +const cwd = "tests/test-cases/pipeline-iid"; |
| 10 | +const stateDir = ".gitlab-ci-local"; |
| 11 | +const stateFile = path.join(cwd, stateDir, "state.yml"); |
| 12 | +const lockFile = path.join(cwd, stateDir, "state.lock"); |
| 13 | + |
| 14 | +beforeAll(() => { |
| 15 | + initSpawnSpy(WhenStatics.all); |
| 16 | +}); |
| 17 | + |
| 18 | +afterEach(() => { |
| 19 | + fs.removeSync(stateFile); |
| 20 | + fs.removeSync(lockFile); |
| 21 | +}); |
| 22 | + |
| 23 | +describe("pipeline-iid state locking", () => { |
| 24 | + test("sequential increments return 0, 1, 2", async () => { |
| 25 | + const first = await state.incrementPipelineIid(cwd, stateDir); |
| 26 | + const second = await state.incrementPipelineIid(cwd, stateDir); |
| 27 | + const third = await state.incrementPipelineIid(cwd, stateDir); |
| 28 | + |
| 29 | + expect(first).toBe(0); |
| 30 | + expect(second).toBe(1); |
| 31 | + expect(third).toBe(2); |
| 32 | + }); |
| 33 | + |
| 34 | + test("concurrent increments produce unique IIDs", async () => { |
| 35 | + const count = 20; |
| 36 | + const promises = Array.from({length: count}, () => |
| 37 | + state.incrementPipelineIid(cwd, stateDir), |
| 38 | + ); |
| 39 | + const results = await Promise.all(promises); |
| 40 | + |
| 41 | + const sorted = [...results].sort((a, b) => a - b); |
| 42 | + expect(sorted).toEqual(Array.from({length: count}, (_, i) => i)); |
| 43 | + }); |
| 44 | + |
| 45 | + test("stale lock from dead PID is auto-cleaned", async () => { |
| 46 | + fs.ensureDirSync(path.dirname(lockFile)); |
| 47 | + fs.writeFileSync(lockFile, "999999999"); |
| 48 | + |
| 49 | + const result = await state.incrementPipelineIid(cwd, stateDir); |
| 50 | + expect(result).toBe(0); |
| 51 | + expect(fs.existsSync(lockFile)).toBe(false); |
| 52 | + }); |
| 53 | +}); |
| 54 | + |
| 55 | +test("pipeline-iid handler increments IID across runs", async () => { |
| 56 | + const writeStreams = new WriteStreamsMock(); |
| 57 | + await handler({cwd: cwd}, writeStreams); |
| 58 | + |
| 59 | + const iid = await state.getPipelineIid(cwd, stateDir); |
| 60 | + expect(iid).toBe(0); |
| 61 | + |
| 62 | + const writeStreams2 = new WriteStreamsMock(); |
| 63 | + await handler({cwd: cwd}, writeStreams2); |
| 64 | + |
| 65 | + const iid2 = await state.getPipelineIid(cwd, stateDir); |
| 66 | + expect(iid2).toBe(1); |
| 67 | +}); |
0 commit comments