Skip to content

Commit 73f9d43

Browse files
committed
perf: optimize 1MB limit test performance
Reduce test execution from ~6s to ~1.3s by using efficient pre-calculation instead of incremental JSON building
1 parent 01d9119 commit 73f9d43

File tree

1 file changed

+25
-15
lines changed

1 file changed

+25
-15
lines changed

test/package-url-json-security.test.mts

Lines changed: 25 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -45,29 +45,39 @@ describe('PackageURL.fromJSON security features', () => {
4545
})
4646

4747
it('should handle JSON exactly at 1MB limit', () => {
48-
// Create a JSON string that's as close to 1MB as possible without going over
48+
// Create a JSON string that's exactly at the 1MB limit much more efficiently
4949
const targetSize = 1024 * 1024
50-
const baseJson = { type: 'npm', name: 'test', qualifiers: {} as any }
5150

52-
// Build up qualifiers until we're close to the limit
53-
let currentJson = JSON.stringify(baseJson)
54-
let i = 0
51+
// Calculate size of base JSON structure
52+
const baseStructure = '{"type":"npm","name":"test","qualifiers":{'
53+
const endStructure = '}}'
54+
const baseSize = baseStructure.length + endStructure.length
5555

56-
while (currentJson.length < targetSize - 1000) {
57-
baseJson.qualifiers[`q${i}`] = 'x'.repeat(100)
58-
currentJson = JSON.stringify(baseJson)
59-
i++
60-
}
56+
// Calculate size needed for qualifiers
57+
// Leave some buffer for JSON overhead
58+
const remainingSize = targetSize - baseSize - 100
6159

62-
// Fine-tune to get as close as possible without exceeding
63-
while (currentJson.length < targetSize - 10) {
64-
baseJson.qualifiers[`final${i}`] = 'x'
65-
currentJson = JSON.stringify(baseJson)
60+
// Create one large qualifier that takes up most of the space
61+
const largeValue = 'x'.repeat(Math.floor(remainingSize * 0.95))
62+
const qualifiers: Record<string, string> = { bigQualifier: largeValue }
63+
64+
// Add a few smaller qualifiers to fine-tune the size
65+
let currentSize = baseStructure.length + JSON.stringify(qualifiers).length - 1 + endStructure.length
66+
let i = 0
67+
while (currentSize < targetSize - 50) {
68+
qualifiers[`q${i}`] = 'x'.repeat(10)
69+
currentSize = baseStructure.length + JSON.stringify(qualifiers).length - 1 + endStructure.length
6670
i++
6771
}
6872

69-
const finalJson = currentJson
73+
const finalJson = JSON.stringify({
74+
type: 'npm',
75+
name: 'test',
76+
qualifiers
77+
})
78+
7079
expect(finalJson.length).toBeLessThanOrEqual(targetSize)
80+
expect(finalJson.length).toBeGreaterThan(targetSize - 1000)
7181

7282
// Should work when under the limit
7383
const result = PackageURL.fromJSON(finalJson)

0 commit comments

Comments
 (0)