|
| 1 | +import { describe, expect, it, vi } from "vitest"; |
| 2 | +import { createProgram } from "./webgl.js"; |
| 3 | + |
| 4 | +/** Model WebGL's rule that shader handles belong to the context that created them. */ |
| 5 | +function createMockContext() { |
| 6 | + const shaders = new Set<WebGLShader>(); |
| 7 | + const gl = { |
| 8 | + VERTEX_SHADER: 0x8b31, |
| 9 | + FRAGMENT_SHADER: 0x8b30, |
| 10 | + COMPILE_STATUS: 0x8b81, |
| 11 | + LINK_STATUS: 0x8b82, |
| 12 | + createShader: vi.fn(() => { |
| 13 | + const shader = {}; |
| 14 | + shaders.add(shader); |
| 15 | + return shader; |
| 16 | + }), |
| 17 | + shaderSource: vi.fn(), |
| 18 | + compileShader: vi.fn(), |
| 19 | + getShaderParameter: vi.fn(() => true), |
| 20 | + createProgram: vi.fn(() => ({})), |
| 21 | + attachShader: vi.fn((_program: WebGLProgram, shader: WebGLShader) => { |
| 22 | + if (!shaders.has(shader)) throw new Error("Shader belongs to another WebGL context"); |
| 23 | + }), |
| 24 | + linkProgram: vi.fn(), |
| 25 | + getProgramParameter: vi.fn(() => true), |
| 26 | + }; |
| 27 | + return gl; |
| 28 | +} |
| 29 | + |
| 30 | +describe("createProgram", () => { |
| 31 | + it("uses context-owned shaders across multiple contexts and repeated calls", () => { |
| 32 | + const first = createMockContext(); |
| 33 | + const second = createMockContext(); |
| 34 | + const fragment = "precision mediump float;void main(){gl_FragColor=vec4(1.0);}"; |
| 35 | + |
| 36 | + for (const gl of [first, second, first, second]) { |
| 37 | + // The test double implements only the WebGL methods used to create a program. |
| 38 | + expect(() => createProgram(gl as unknown as WebGLRenderingContext, fragment)).not.toThrow(); |
| 39 | + } |
| 40 | + |
| 41 | + expect(first.linkProgram).toHaveBeenCalledTimes(2); |
| 42 | + expect(second.linkProgram).toHaveBeenCalledTimes(2); |
| 43 | + }); |
| 44 | +}); |
0 commit comments