File size: 8,319 Bytes
3e8ea5d
 
 
e445b51
 
 
 
 
 
3e8ea5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e445b51
 
 
 
 
3e8ea5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e445b51
 
3e8ea5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
import assert from 'node:assert/strict';
import { describe, it } from 'node:test';

import {
    FIXTURE_IMAGE_BASE64,
    FIXTURE_IMAGE_PATH,
    MAX_JSON_BODY_BYTES,
    createFixtureServer
} from './local-image-upstream-fixture.mjs';

describe('local image upstream fixture', () => {
    it('serves Images API JSON responses', async () => {
        const fixture = await startFixture();
        try {
            const response = await fetch(`${fixture.baseUrl}/v1/images/generations`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ model: 'gpt-image-2', prompt: 'fixture json smoke', stream: false })
            });

            assert.equal(response.status, 200);
            assert.match(response.headers.get('content-type') || '', /^application\/json\b/);
            const body = await response.json();
            assert.equal(body.data[0].b64_json, FIXTURE_IMAGE_BASE64);
            assert.equal(body.fixture_request.model, 'gpt-image-2');
            assert.equal(body.fixture_request.stream, false);
        } finally {
            await fixture.close();
        }
    });

    it('serves Images API SSE responses', async () => {
        const fixture = await startFixture();
        try {
            const response = await fetch(`${fixture.baseUrl}/v1/images/generations`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ model: 'gpt-image-2', prompt: 'fixture sse smoke', stream: true })
            });

            assert.equal(response.status, 200);
            assert.match(response.headers.get('content-type') || '', /^text\/event-stream\b/);
            const events = readSseEvents(await response.text());
            assert.equal(events[0].comment, 'keepalive');
            assert.deepEqual(
                events.filter((event) => event.event).map((event) => event.event),
                ['image_generation.partial_image', 'image_generation.completed']
            );
            assert.equal(events[1].data.type, 'image_generation.partial_image');
            assert.equal(events[1].data.b64_json, FIXTURE_IMAGE_BASE64);
            assert.equal(events[2].data.type, 'image_generation.completed');
            assert.equal(events[2].data.b64_json, FIXTURE_IMAGE_BASE64);
            assert.equal(events[3].done, true);
        } finally {
            await fixture.close();
        }
    });

    it('serves Responses API JSON image outputs', async () => {
        const fixture = await startFixture();
        try {
            const response = await fetch(`${fixture.baseUrl}/v1/responses`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    model: 'gpt-5.4',
                    input: 'fixture responses json smoke',
                    stream: false,
                    tools: [{ type: 'image_generation' }],
                    tool_choice: { type: 'image_generation' }
                })
            });

            assert.equal(response.status, 200);
            assert.match(response.headers.get('content-type') || '', /^application\/json\b/);
            const body = await response.json();
            assert.equal(body.id, 'resp_fixture');
            assert.equal(body.output[0].type, 'image_generation_call');
            assert.equal(body.output[0].result, FIXTURE_IMAGE_PATH);
            const imageResponse = await fetch(`${fixture.baseUrl}${FIXTURE_IMAGE_PATH}`);
            assert.equal(imageResponse.status, 200);
            assert.match(imageResponse.headers.get('content-type') || '', /^image\/png\b/);
            assert.equal(Buffer.from(await imageResponse.arrayBuffer()).toString('base64'), FIXTURE_IMAGE_BASE64);
        } finally {
            await fixture.close();
        }
    });

    it('serves Responses API SSE image events', async () => {
        const fixture = await startFixture();
        try {
            const response = await fetch(`${fixture.baseUrl}/v1/responses`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    model: 'gpt-5.4',
                    input: 'fixture responses sse smoke',
                    stream: true,
                    tools: [{ type: 'image_generation' }],
                    tool_choice: { type: 'image_generation' }
                })
            });

            assert.equal(response.status, 200);
            assert.match(response.headers.get('content-type') || '', /^text\/event-stream\b/);
            const events = readSseEvents(await response.text());
            assert.deepEqual(
                events.filter((event) => event.event).map((event) => event.event),
                [
                    'response.image_generation_call.partial_image',
                    'response.output_item.done',
                    'response.completed'
                ]
            );
            assert.equal(events[0].data.partial_image_b64, FIXTURE_IMAGE_BASE64);
            assert.equal(events[1].data.item.type, 'image_generation_call');
            assert.equal(events[1].data.item.result, FIXTURE_IMAGE_PATH);
            assert.equal(events[2].data.response.output[0].result, FIXTURE_IMAGE_PATH);
            assert.equal(events[3].done, true);
        } finally {
            await fixture.close();
        }
    });

    it('serves model discovery and health checks', async () => {
        const fixture = await startFixture();
        try {
            const healthResponse = await fetch(`${fixture.baseUrl}/health`);
            const modelsResponse = await fetch(`${fixture.baseUrl}/v1/models`);

            assert.equal(healthResponse.status, 200);
            assert.deepEqual(await healthResponse.json(), { ok: true });
            assert.equal(modelsResponse.status, 200);
            const models = await modelsResponse.json();
            assert.deepEqual(
                models.data.map((model) => model.id),
                ['gpt-image-2', 'gpt-5.4']
            );
        } finally {
            await fixture.close();
        }
    });

    it('rejects oversized JSON request bodies', async () => {
        const fixture = await startFixture();
        try {
            const response = await fetch(`${fixture.baseUrl}/v1/images/generations`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    model: 'gpt-image-2',
                    prompt: 'x'.repeat(MAX_JSON_BODY_BYTES)
                })
            });

            assert.equal(response.status, 413);
            const body = await response.json();
            assert.match(body.error.message, /too large/);
        } finally {
            await fixture.close();
        }
    });
});

async function startFixture() {
    const server = createFixtureServer();
    await new Promise((resolve, reject) => {
        server.once('error', reject);
        server.listen(0, '127.0.0.1', resolve);
    });
    const address = server.address();
    assert.ok(address && typeof address === 'object');
    return {
        baseUrl: `http://127.0.0.1:${address.port}`,
        close: () => closeServer(server)
    };
}

function closeServer(server) {
    return new Promise((resolve, reject) => {
        server.close((error) => {
            if (error) reject(error);
            else resolve();
        });
    });
}

function readSseEvents(raw) {
    return raw
        .trim()
        .split(/\n\n+/)
        .map((chunk) => readSseEvent(chunk))
        .filter(Boolean);
}

function readSseEvent(chunk) {
    const lines = chunk.split(/\n/);
    const comment = lines.find((line) => line.startsWith(': '));
    const event = lines.find((line) => line.startsWith('event: '));
    const data = lines.find((line) => line.startsWith('data: '));
    if (comment) return { comment: comment.slice(2) };
    if (!data) return undefined;
    if (data === 'data: [DONE]') return { done: true };
    return {
        event: event ? event.slice('event: '.length) : undefined,
        data: JSON.parse(data.slice('data: '.length))
    };
}