-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathtest-wrapper.mts
More file actions
168 lines (149 loc) · 5.37 KB
/
test-wrapper.mts
File metadata and controls
168 lines (149 loc) · 5.37 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
/**
* @fileoverview Test wrapper for the project.
* Handles test execution with Vitest, including:
* - Glob pattern expansion for test file selection
* - Memory optimization for RegExp-heavy tests
* - Cross-platform compatibility (Windows/Unix)
* - Build validation before running tests
* - Environment variable loading from .env.test (via loadEnvFile)
* - Inlined variable injection from bundle-tools.json
*/
import { existsSync } from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import fastGlob from 'fast-glob'
import { WIN32 } from '@socketsecurity/lib/constants/platform'
import { getDefaultLogger } from '@socketsecurity/lib/logger'
import { spawn } from '@socketsecurity/lib/spawn'
import { EnvironmentVariables } from './environment-variables.mts'
import { loadEnvFile } from './utils/load-env.mts'
const logger = getDefaultLogger()
const __dirname = path.dirname(fileURLToPath(import.meta.url))
const rootPath = path.join(__dirname, '..')
const rootNodeModulesBinPath = path.join(
rootPath,
'..',
'..',
'node_modules',
'.bin',
)
/**
* Check if required build artifacts exist.
*/
function checkBuildArtifacts() {
const requiredArtifacts = ['build/cli.js', 'dist/index.js']
for (const artifact of requiredArtifacts) {
const fullPath = path.join(rootPath, artifact)
if (!existsSync(fullPath)) {
logger.error(`Required build artifact missing: ${artifact}`)
logger.error('Run `pnpm build` before running tests')
return false
}
}
return true
}
/**
* Main test execution flow.
*/
async function main() {
try {
// Validate build artifacts exist.
if (!checkBuildArtifacts()) {
process.exitCode = 1
return
}
// Parse command line arguments.
let args = process.argv.slice(2)
// Remove the -- separator if it's the first argument.
if (args[0] === '--') {
args = args.slice(1)
}
// Check for and warn about environment variables that can cause snapshot mismatches.
// These are all aliases for the Socket API token that should not be set during tests.
const problematicEnvVars = [
'SOCKET_CLI_API_KEY',
'SOCKET_CLI_API_TOKEN',
'SOCKET_SECURITY_API_KEY',
'SOCKET_SECURITY_API_TOKEN',
]
const foundEnvVars = problematicEnvVars.filter(v => process.env[v])
if (foundEnvVars.length > 0) {
logger.warn(
`Detected environment variable(s) that may cause snapshot test failures: ${foundEnvVars.join(', ')}`,
)
logger.warn(
'These will be cleared for the test run to ensure consistent snapshots.',
)
logger.warn(
'Tests use .env.test configuration which should not include real API tokens.',
)
}
// Load external tool versions for INLINED_* env vars.
// Delegate to unified EnvironmentVariables module.
const externalToolVersions = EnvironmentVariables.getTestVariables()
const spawnEnv = {
...process.env,
// Increase Node.js heap size to prevent out of memory errors.
// Use 8GB in CI, 4GB locally.
// Add --max-semi-space-size for better GC with RegExp-heavy tests.
NODE_OPTIONS:
`${process.env.NODE_OPTIONS || ''} --max-old-space-size=${process.env.CI ? 8192 : 4096} --max-semi-space-size=512`.trim(),
// Clear problematic environment variables that cause snapshot mismatches.
// Tests should use .env.test configuration instead.
SOCKET_CLI_API_KEY: undefined,
SOCKET_CLI_API_TOKEN: undefined,
SOCKET_SECURITY_API_KEY: undefined,
SOCKET_SECURITY_API_TOKEN: undefined,
// Inject external tool versions (normally inlined at build time).
...externalToolVersions,
}
// Load .env.test configuration.
const testEnv = loadEnvFile(path.join(rootPath, '.env.test'))
// Handle Windows vs Unix for vitest executable.
const vitestCmd = WIN32 ? 'vitest.cmd' : 'vitest'
const vitestPath = path.join(rootNodeModulesBinPath, vitestCmd)
// Expand glob patterns in arguments.
const expandedArgs = []
for (const arg of args) {
// Check if argument looks like a glob pattern.
if (arg.includes('*') && !arg.startsWith('-')) {
const files = fastGlob.sync(arg, { cwd: rootPath })
if (files.length === 0) {
logger.warn(`No files matched pattern: ${arg}`)
}
expandedArgs.push(...files)
} else {
expandedArgs.push(arg)
}
}
// On Windows, .cmd files need shell: true.
const spawnOptions = {
cwd: rootPath,
env: {
...testEnv,
...spawnEnv,
},
stdio: 'inherit',
...(WIN32 ? { shell: true } : {}),
}
// --passWithNoTests: a scoped run where the expanded args don't
// resolve to any test file should succeed rather than error with
// "No test files found". Keeps pre-commit hooks passing when an edit
// touches only non-testable code.
const result = await spawn(
vitestPath,
['run', '--passWithNoTests', ...expandedArgs],
spawnOptions,
)
// `code === null` means the process was killed by a signal — treat
// as a failure so SIGKILL / SIGABRT aren't silently reported as 0.
process.exitCode = typeof result?.code === 'number' ? result.code : 1
} catch (e) {
logger.error('Failed to spawn test process:', e)
process.exitCode = 1
}
}
main().catch(e => {
logger.error('Unexpected error:', e)
process.exitCode = 1
})