-
Notifications
You must be signed in to change notification settings - Fork 87
Expand file tree
/
Copy pathAssetUploader.test.ts
More file actions
313 lines (270 loc) · 8.94 KB
/
Copy pathAssetUploader.test.ts
File metadata and controls
313 lines (270 loc) · 8.94 KB
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import {
clientVersionQueryParam,
devvitScriptUrl,
} from '@devvit/shared-types/web-view-scripts-constants.js';
import { JSDOM } from 'jsdom';
import { afterEach, describe, expect, it, vi } from 'vitest';
const appClient = vi.hoisted(() => ({
CheckIfMediaExists: vi.fn(),
UploadNewMedia: vi.fn(),
}));
vi.mock('./clientGenerators.js', () => ({
createAppClient: () => appClient,
}));
vi.mock('@oclif/core', () => ({
ux: {
action: {
start: vi.fn(),
stop: vi.fn(),
},
error: vi.fn(),
info: vi.fn(),
},
}));
import { AssetUploader, queryAssets, transformHTML } from './AssetUploader.js';
import type { DevvitCommand } from './commands/DevvitCommand.js';
describe('HTML Transformation', () => {
describe('transformHTML', () => {
it('should add script tag to head when head exists', () => {
const input = `
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<h1>Hello</h1>
</body>
</html>
`;
const result = transformHTML(input, '1.2.3');
const dom = new JSDOM(result);
const document = dom.window.document;
// Verify script tag exists in head
const script = selectScript(document);
assertScriptExpectations(script);
// Verify original content is preserved
expect(document.querySelector('title')?.textContent).toBe('Test');
expect(document.querySelector('h1')?.textContent).toBe('Hello');
});
it('should create head tag and add script when head does not exist', () => {
const input = `
<!DOCTYPE html>
<html>
<body>
<h1>Hello</h1>
</body>
</html>
`;
const result = transformHTML(input, '1.2.3');
const dom = new JSDOM(result);
const document = dom.window.document;
// Verify head tag exists
const head = document.querySelector('head');
expect(head).not.toBeNull();
// Verify script tag exists in head
const script = selectScript(document);
assertScriptExpectations(script);
// Verify body content is preserved
expect(document.querySelector('h1')?.textContent).toBe('Hello');
});
it('should handle malformed HTML gracefully', () => {
const input = `
<html>
<head>
<title>Test
</head>
<body>
<h1>Hello
</body>
</html>
`;
const result = transformHTML(input, '1.2.3');
const dom = new JSDOM(result);
const document = dom.window.document;
// Verify script tag exists
const script = document.querySelector(
`script[src="${devvitScriptUrl}?${clientVersionQueryParam}=1.2.3"]`
);
assertScriptExpectations(script);
});
it('should handle non-HTML gracefully', () => {
const input = `
<
`;
const result = transformHTML(input, '1.2.3');
const dom = new JSDOM(result);
const document = dom.window.document;
// Verify script tag exists
const script = document.querySelector(
`script[src="${devvitScriptUrl}?${clientVersionQueryParam}=1.2.3"]`
);
assertScriptExpectations(script);
});
it('should handle HTML with existing script tags', () => {
const input = `
<!DOCTYPE html>
<html>
<head>
<script src="other.js"></script>
</head>
<body>
<h1>Hello</h1>
</body>
</html>
`;
const result = transformHTML(input, '1.2.3');
const dom = new JSDOM(result);
const document = dom.window.document;
// Verify both script tags exist
const scripts = document.querySelectorAll('head script');
expect(scripts.length).toBe(2);
const otherScript = document.querySelector('script[src="other.js"]');
expect(otherScript).not.toBeNull();
const devvitScript = selectScript(document);
assertScriptExpectations(devvitScript);
});
});
});
describe('assertAssetCanBeAnIcon', () => {
const TEST_IMAGE_FILES = [
'1024x1024.gif',
'1024x1024.jpg',
'1024x1024.png',
'256x256.png',
'256x512.png',
'420x420.png',
'512x512.png',
'notAnImage.txt',
];
for (const fileName of TEST_IMAGE_FILES) {
it(`should match the snapshot for image file: ${fileName}`, async () => {
const cmd = {
error: vi.fn(() => {
throw new Error('Mocked error');
}),
warn: vi.fn(),
};
const assetUploader = new AssetUploader(cmd as unknown as DevvitCommand, 'some-slug', {
verbose: false,
});
const filePath = `../../testing-images/${fileName}`;
const fileContent = fs.readFileSync(path.join(__dirname, filePath));
// Don't care if this resolves or rejects, just want to test the error handling
await Promise.allSettled([assetUploader.assertAssetCanBeAnIcon(fileContent)]);
expect(cmd.error.mock.calls).toMatchSnapshot(`${fileName}-err`);
expect(cmd.warn.mock.calls).toMatchSnapshot(`${fileName}-warn`);
});
}
});
describe('syncAssets()', () => {
let tmpDir: string;
beforeEach(() => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'devvit-assets-test-'));
fs.writeFileSync(path.join(tmpDir, 'header-logo.svg'), '<svg></svg>');
fs.writeFileSync(path.join(tmpDir, 'footer-logo.svg'), '<svg></svg>');
appClient.CheckIfMediaExists.mockImplementation(
async ({ signatures }: { signatures: { filePath: string }[] }) => ({
statuses: signatures.map((signature, index) => ({
...signature,
isNew: true,
uploadUrl: `https://uploads.example.com/assets/${index}?signature=test`,
uploadHeaders: {},
})),
})
);
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue({
ok: true,
})
);
});
afterEach(() => {
fs.rmSync(tmpDir, { recursive: true, force: true });
vi.clearAllMocks();
vi.unstubAllGlobals();
});
it('maps duplicate WebView asset paths to the same uploaded URL', async () => {
const cmd = {
project: {
root: tmpDir,
mediaDir: undefined,
clientDir: '.',
appConfig: undefined,
},
error: vi.fn((message: string) => {
throw new Error(message);
}),
log: vi.fn(),
warn: vi.fn(),
};
const assetUploader = new AssetUploader(cmd as unknown as DevvitCommand, 'some-slug', {
verbose: false,
});
const result = await assetUploader.syncAssets();
expect(fetch).toHaveBeenCalledTimes(1);
expect(result.webViewAssetMap).toEqual({
'footer-logo.svg': 'https://uploads.example.com/assets/0',
'header-logo.svg': 'https://uploads.example.com/assets/0',
});
});
});
describe('queryAssets()', () => {
let tmpDir: string;
beforeEach(() => {
const htmlContent = `
<!DOCTYPE html>
<html>
<head>
<title>Test Page</title>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>
`;
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'devvit-test-'));
fs.writeFileSync(path.join(tmpDir, 'index.html'), htmlContent);
});
afterEach(() => {
fs.rmSync(tmpDir, { recursive: true, force: true });
});
it('should transform HTML files with Devvit script injection', async () => {
const assets = await queryAssets(tmpDir, [], 'Client', '1.2.3', false);
// Verify that one asset was found.
expect(assets).toHaveLength(1);
expect(assets[0].filePath).toBe('index.html');
expect(assets[0].isWebviewAsset).toBe(true);
// Verify that the HTML was transformed.
const transformedContent = new TextDecoder('utf-8').decode(assets[0].contents);
expect(transformedContent).toContain(
`<script src="${devvitScriptUrl}?${clientVersionQueryParam}=1.2.3"></script>`
);
expect(transformedContent).toContain('<title>Test Page</title>');
expect(transformedContent).toContain('<h1>Hello World</h1>');
});
it('should skip HTML transformation when skipWebViewScriptInjection is true', async () => {
const assets = await queryAssets(tmpDir, [], 'Client', '1.2.3', true);
// Verify that one asset was found.
expect(assets).toHaveLength(1);
expect(assets[0].filePath).toBe('index.html');
expect(assets[0].isWebviewAsset).toBe(true);
// Verify that the HTML was NOT transformed.
const untransformedContent = new TextDecoder('utf-8').decode(assets[0].contents);
expect(untransformedContent).not.toContain(devvitScriptUrl);
expect(untransformedContent).toContain('<title>Test Page</title>');
expect(untransformedContent).toContain('<h1>Hello World</h1>');
});
});
function selectScript(document: Document): Element | null {
return document.querySelector(
`head script[src="${devvitScriptUrl}?${clientVersionQueryParam}=1.2.3"]`
);
}
function assertScriptExpectations(script: Element | null) {
expect(script).not.toBeNull();
}