Consolidate BaseCompiler test files into a single comprehensive file

This commit consolidates all BaseCompiler test files into a single comprehensive file:
- base-compiler-tests.ts (original)
- base-compiler-tests-new.ts (new compilation tests)
- base-compiler-exec-tests.ts (execution tests)
- base-compiler-utils-tests.ts (utility tests)

The tests are organized into logical sections with clear headers, making it easier
to understand and maintain the BaseCompiler tests.

This addresses cross-platform compatibility by ensuring Windows-specific path handling
is properly taken into account in relevant tests.
This commit is contained in:
Matt Godbolt
2025-04-03 14:33:18 +01:00
parent d6853c6d95
commit 0daae02461
4 changed files with 1182 additions and 1724 deletions
-706
View File
@@ -1,706 +0,0 @@
// Copyright (c) 2025, Compiler Explorer Authors
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
import fs from 'node:fs/promises';
import path from 'node:path';
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {BaseCompiler} from '../lib/base-compiler.js';
import {CompilationEnvironment} from '../lib/compilation-env.js';
import * as exec from '../lib/exec.js';
import * as utils from '../lib/utils.js';
import type {FiledataPair} from '../types/compilation/compilation.interfaces.js';
import {ParseFiltersAndOutputOptions} from '../types/features/filters.interfaces.js';
import {createMockExecutor} from './mock/mock-utils.js';
import {
makeCompilationEnvironment,
makeFakeCompilerInfo,
makeFakeParseFiltersAndOutputOptions,
newTempDir,
} from './utils.js';
const languages = {
'c++': {id: 'c++'},
rust: {id: 'rust'},
} as const;
describe('BaseCompiler execution', () => {
let ce: CompilationEnvironment;
let compiler: BaseCompiler;
let mockExec: ReturnType<typeof createMockExecutor>;
let execSpy: any;
beforeEach(async () => {
ce = makeCompilationEnvironment({
languages,
props: {
compileTimeoutMs: 7000,
binaryExecTimeoutMs: 2000,
},
});
// Mock the findBadOptions function
ce.findBadOptions = vi.fn().mockReturnValue([]);
const compilationInfo = makeFakeCompilerInfo({
exe: '/fake/compiler/path',
remote: undefined,
lang: 'c++',
options: '-Wall -O2',
supportsExecute: true,
supportsBinary: true,
});
compiler = new BaseCompiler(compilationInfo, ce);
// Create a temporary directory for testing
await newTempDir();
// Set up our mocks
mockExec = createMockExecutor(
new Map([
[
'/fake/compiler/path -Wall -O2 -g -o output.s -S input.cpp',
{
code: 0,
stdout: 'Compilation successful',
stderr: '',
},
],
[
'/fake/compiler/path -Wall -O2 -g input.cpp -o a.out',
{
code: 0,
stdout: 'Binary compilation successful',
stderr: '',
},
],
]),
);
vi.spyOn(exec, 'execute').mockImplementation(mockExec);
execSpy = vi.spyOn(compiler, 'exec');
// Mock the exec method with a fully typed result for compilation
execSpy.mockImplementation(async () => {
return {
code: 0,
stdout: 'Compilation successful',
stderr: '',
okToCache: true,
filenameTransform: (x: string) => x,
execTime: 0,
timedOut: false,
truncated: false,
};
});
// Mock filesystem operations
vi.spyOn(fs, 'writeFile').mockImplementation(async () => {});
vi.spyOn(fs, 'readFile').mockResolvedValue('Assembly output');
// In BaseCompiler, binary execution is mocked indirectly through exec
// We don't call sandbox directly but through the compiler's internal methods
vi.spyOn(exec, 'sandbox').mockResolvedValue({
code: 0,
stdout: 'Program executed successfully',
stderr: '',
timedOut: false,
truncated: false,
filenameTransform: (x: string) => x,
execTime: 0,
okToCache: true,
});
// Need to mock handleExecution within the compiler
vi.spyOn(compiler, 'handleExecution' as any).mockImplementation(async () => {
return {
code: 0,
didExecute: true,
stdout: [{text: 'Program executed successfully'}],
stderr: [],
buildResult: {
code: 0,
stdout: [{text: 'Binary compilation successful'}],
stderr: [],
},
};
});
// Mock check source method to prevent validation issues
vi.spyOn(compiler, 'checkSource').mockReturnValue(null);
});
afterEach(async () => {
vi.restoreAllMocks();
});
it('should successfully compile and execute code', async () => {
const source = 'int main() { return 42; }';
const options = [''];
const filters: ParseFiltersAndOutputOptions = makeFakeParseFiltersAndOutputOptions({
execute: true, // Request execution
});
const result = await compiler.compile(
source,
options,
{},
filters,
false as any, // bypassCache
[], // backendOptions
{}, // filters
[], // tools
[] as FiledataPair[], // executionParams
);
expect(result.code).toBe(0);
expect(result.execResult).toBeDefined();
expect(result.execResult?.didExecute).toBe(true);
expect(result.execResult?.code).toBe(0);
expect(result.execResult?.stdout).toEqual([{text: 'Program executed successfully'}]);
});
it('should handle execution failures with non-zero return code', async () => {
const source = 'int main() { return 1; }';
const options = [''];
const filters: ParseFiltersAndOutputOptions = makeFakeParseFiltersAndOutputOptions({
execute: true, // Request execution
});
// Override handleExecution mock to simulate execution failure
vi.spyOn(compiler, 'handleExecution' as any).mockImplementation(async () => {
return {
code: 1,
didExecute: true,
stdout: [],
stderr: [{text: 'Execution failed with return code 1'}],
buildResult: {
code: 0,
stdout: [{text: 'Binary compilation successful'}],
stderr: [],
},
};
});
const result = await compiler.compile(
source,
options,
{},
filters,
false as any,
[],
{},
[],
[] as FiledataPair[],
);
expect(result.code).toBe(0); // Compilation succeeded
expect(result.execResult).toBeDefined();
expect(result.execResult?.didExecute).toBe(true);
expect(result.execResult?.code).toBe(1); // Execution failed
expect(result.execResult?.stderr).toEqual([{text: 'Execution failed with return code 1'}]);
});
it('should handle compilation failures for execution', async () => {
const source = 'int main() { error_function(); return 0; }';
const options = [''];
const filters: ParseFiltersAndOutputOptions = makeFakeParseFiltersAndOutputOptions({
execute: true, // Request execution
});
// Mock handleExecution to simulate binary compilation failure
vi.spyOn(compiler, 'handleExecution' as any).mockImplementation(async () => {
return {
code: -1,
didExecute: false,
stdout: [],
stderr: [{text: 'Build failed'}],
buildResult: {
code: 1,
stdout: [],
stderr: [{text: 'error: use of undeclared identifier "error_function"'}],
},
};
});
const result = await compiler.compile(
source,
options,
{},
filters,
false as any,
[],
{},
[],
[] as FiledataPair[],
);
expect(result.code).toBe(0); // Assembly compilation succeeded
expect(result.execResult).toBeDefined();
expect(result.execResult?.didExecute).toBe(false);
expect(result.execResult?.buildResult?.code).toBe(1);
expect(result.execResult?.buildResult?.stderr).toEqual([
{text: 'error: use of undeclared identifier "error_function"'},
]);
});
it('should handle timeouts during execution', async () => {
const source = 'int main() { while(1); return 0; }';
const options = [''];
const filters: ParseFiltersAndOutputOptions = makeFakeParseFiltersAndOutputOptions({
execute: true, // Request execution
});
// Mock handleExecution to simulate execution timeout
vi.spyOn(compiler, 'handleExecution' as any).mockImplementation(async () => {
return {
code: -1,
didExecute: true,
stdout: [],
stderr: [{text: 'Execution time out'}],
timedOut: true,
buildResult: {
code: 0,
stdout: [{text: 'Binary compilation successful'}],
stderr: [],
},
};
});
const result = await compiler.compile(
source,
options,
{},
filters,
false as any,
[],
{},
[],
[] as FiledataPair[],
);
expect(result.code).toBe(0); // Compilation succeeded
expect(result.execResult).toBeDefined();
expect(result.execResult?.didExecute).toBe(true);
expect(result.execResult?.timedOut).toBe(true);
expect(result.execResult?.stderr).toEqual([{text: 'Execution time out'}]);
});
it('should pass execution parameters to the compiler', async () => {
const source = 'int main(int argc, char** argv) { return argc > 1 ? 0 : 1; }';
const options = [''];
const filters: ParseFiltersAndOutputOptions = makeFakeParseFiltersAndOutputOptions({
execute: true, // Request execution
});
// Create a spy to capture execution params
const handleExecutionSpy = vi.spyOn(compiler, 'handleExecution' as any);
// Mock return value for execution
handleExecutionSpy.mockResolvedValue({
code: 0,
didExecute: true,
stdout: [{text: 'Program executed successfully'}],
stderr: [],
buildResult: {
code: 0,
stdout: [{text: 'Binary compilation successful'}],
stderr: [],
},
});
await compiler.compile(source, options, {}, filters, false as any, [], {}, [], [] as FiledataPair[]);
// Verify execution was called with the parameters
expect(handleExecutionSpy).toHaveBeenCalled();
// In the actual implementation, handleExecution would receive the exec params
// but since we're mocking it, we just verify it was called
});
it('should not execute when compiler does not support execution', async () => {
// Create a new compiler that doesn't support execution
const noExecCompilerInfo = makeFakeCompilerInfo({
exe: '/fake/compiler/path',
remote: undefined,
lang: 'c++',
options: '-Wall -O2',
supportsExecute: false, // No execution support
supportsBinary: true,
});
const noExecCompiler = new BaseCompiler(noExecCompilerInfo, ce);
vi.spyOn(noExecCompiler, 'exec').mockImplementation(async () => {
return {
code: 0,
stdout: 'Compilation successful',
stderr: '',
okToCache: true,
filenameTransform: (x: string) => x,
execTime: 0,
timedOut: false,
truncated: false,
};
});
// Mock handleExecution to indicate compiler doesn't support execution
vi.spyOn(noExecCompiler, 'handleExecution' as any).mockImplementation(async () => {
return {
code: -1,
didExecute: false,
stdout: [],
stderr: [{text: 'Compiler does not support execution'}],
buildResult: {
code: 0,
stdout: [],
stderr: [],
},
};
});
const source = 'int main() { return 0; }';
const options = [''];
const filters: ParseFiltersAndOutputOptions = makeFakeParseFiltersAndOutputOptions({
execute: true, // Request execution despite no support
});
const result = await noExecCompiler.compile(
source,
options,
{},
filters,
false as any,
[],
{},
[],
[] as FiledataPair[],
);
expect(result.code).toBe(0);
expect(result.execResult).toBeDefined();
expect(result.execResult?.didExecute).toBe(false);
expect(result.execResult?.stderr).toEqual([{text: 'Compiler does not support execution'}]);
});
});
describe('BaseCompiler error handling', () => {
let ce: CompilationEnvironment;
let compiler: BaseCompiler;
let execSpy: any;
beforeEach(async () => {
ce = makeCompilationEnvironment({
languages,
props: {
compileTimeoutMs: 7000,
binaryExecTimeoutMs: 2000,
},
});
ce.findBadOptions = vi.fn().mockReturnValue([]);
const compilationInfo = makeFakeCompilerInfo({
exe: '/fake/compiler/path',
remote: undefined,
lang: 'c++',
options: '-Wall -O2',
});
compiler = new BaseCompiler(compilationInfo, ce);
execSpy = vi.spyOn(compiler, 'exec');
// Mock filesystem operations
vi.spyOn(fs, 'writeFile').mockImplementation(async () => {});
vi.spyOn(fs, 'readFile').mockResolvedValue('Assembly output');
// Mock check source method to prevent validation issues
vi.spyOn(compiler, 'checkSource').mockReturnValue(null);
});
afterEach(async () => {
vi.restoreAllMocks();
});
it('should handle compilation timeouts properly', async () => {
// Simulate a timeout during compilation
execSpy.mockResolvedValue({
code: -1,
stdout: '',
stderr: '',
okToCache: true,
filenameTransform: (x: string) => x,
execTime: 0,
timedOut: true,
truncated: false,
});
const source = 'int main() { return 0; }';
const options = [''];
const filters: ParseFiltersAndOutputOptions = makeFakeParseFiltersAndOutputOptions({});
const result = await compiler.compile(
source,
options,
{},
filters,
false as any,
[],
{},
[],
[] as FiledataPair[],
);
expect(result.code).toBe(-1);
expect(result.timedOut).toBe(true);
// The actual message might be different, but we know it should indicate compilation failure
expect(result.asm[0].text).toContain('<Compilation failed>');
});
it('should handle output truncation', async () => {
// Simulate truncated output
execSpy.mockResolvedValue({
code: 0,
stdout: 'Truncated stdout',
stderr: 'Truncated stderr',
okToCache: true,
filenameTransform: (x: string) => x,
execTime: 0,
timedOut: false,
truncated: true,
});
const source = 'int main() { return 0; }';
const options = [''];
const filters: ParseFiltersAndOutputOptions = makeFakeParseFiltersAndOutputOptions({});
const result = await compiler.compile(
source,
options,
{},
filters,
false as any,
[],
{},
[],
[] as FiledataPair[],
);
expect(result.code).toBe(0);
expect(result.truncated).toBe(true);
// The actual assembly text may vary in different environments
expect(result.stdout).toEqual([{text: 'Truncated stdout'}]);
expect(result.stderr).toEqual([{text: 'Truncated stderr'}]);
});
it('should handle corrupted output files', async () => {
// Successful compilation
execSpy.mockResolvedValue({
code: 0,
stdout: 'Compilation successful',
stderr: '',
okToCache: true,
filenameTransform: (x: string) => x,
execTime: 0,
timedOut: false,
truncated: false,
});
// But readFile throws an error
vi.spyOn(fs, 'readFile').mockRejectedValue(new Error('Could not read output file'));
const source = 'int main() { return 0; }';
const options = [''];
const filters: ParseFiltersAndOutputOptions = makeFakeParseFiltersAndOutputOptions({});
const result = await compiler.compile(
source,
options,
{},
filters,
false as any,
[],
{},
[],
[] as FiledataPair[],
);
expect(result.code).toBe(0); // Compilation succeeded
// The actual error message may contain the specific error details
expect(result.asm[0].text).toContain('<');
});
it('should handle source validation', async () => {
// Mock the checkSource method for testing
vi.spyOn(compiler, 'checkSource').mockImplementation((source: string) => {
if (source.includes('</etc/passwd>')) {
return '<stdin>:1:1: no absolute or relative includes please';
}
return null;
});
// Create a simple test case for source validation
const validSource = '#include <iostream>\nint main() { return 0; }';
const invalidSource = '#include </etc/passwd>';
// For valid source, checkSource should return null
expect(compiler.checkSource(validSource)).toBeNull();
// For invalid source with absolute path in include, it should return an error message
const result = compiler.checkSource(invalidSource);
expect(result).not.toBeNull();
expect(result).toContain('no absolute or relative includes');
});
it('should handle compiler failures with memory safety errors', async () => {
execSpy.mockResolvedValue({
code: 139, // SIGSEGV exit code
stdout: '',
stderr: 'Segmentation fault',
okToCache: true,
filenameTransform: (x: string) => x,
execTime: 0,
timedOut: false,
truncated: false,
});
const source = 'int main() { return 0; }';
const options = [''];
const filters: ParseFiltersAndOutputOptions = makeFakeParseFiltersAndOutputOptions({});
const result = await compiler.compile(
source,
options,
{},
filters,
false as any,
[],
{},
[],
[] as FiledataPair[],
);
expect(result.code).toBe(139);
expect(result.asm).toEqual([{text: '<Compilation failed>', source: null, labels: []}]);
expect(result.stderr).toEqual([{text: 'Segmentation fault'}]);
});
});
describe('BaseCompiler include handling', () => {
let ce: CompilationEnvironment;
let compiler: BaseCompiler;
let outputFileSpy: any;
beforeEach(async () => {
ce = makeCompilationEnvironment({
languages,
props: {
compileTimeoutMs: 7000,
binaryExecTimeoutMs: 2000,
},
});
ce.findBadOptions = vi.fn().mockReturnValue([]);
const compilationInfo = makeFakeCompilerInfo({
exe: '/fake/compiler/path',
remote: undefined,
lang: 'c++',
options: '-Wall -O2',
});
compiler = new BaseCompiler(compilationInfo, ce);
// Create a temporary directory for testing
await newTempDir();
// Mock filesystem operations
vi.spyOn(fs, 'writeFile').mockImplementation(async () => {});
vi.spyOn(fs, 'readFile').mockResolvedValue('Assembly output');
outputFileSpy = vi.spyOn(utils, 'outputTextFile').mockResolvedValue();
// Mock the exec method with a fully typed result
vi.spyOn(compiler, 'exec').mockImplementation(async () => {
return {
code: 0,
stdout: 'Compilation successful',
stderr: '',
okToCache: true,
filenameTransform: (x: string) => x,
execTime: 0,
timedOut: false,
truncated: false,
};
});
// Mock check source method to prevent validation issues
vi.spyOn(compiler, 'checkSource').mockReturnValue(null);
});
afterEach(async () => {
vi.restoreAllMocks();
});
it('should properly prepare input with additional files', async () => {
// Access the protected method directly to test it
const writeAllFiles = async (dirPath: string, source: string, files: any[]) => {
return await (compiler as any).writeAllFiles(dirPath, source, files, {});
};
const source = '#include "header.h"\nint main() { return TEST_VALUE; }';
const additionalFiles = [
{
filename: 'header.h',
contents: '#define TEST_VALUE 42',
},
];
// Mock the utility functions
outputFileSpy.mockClear();
// Call the method directly
await writeAllFiles('/tmp/test', source, additionalFiles);
// Verify the main source file was written
expect(fs.writeFile).toHaveBeenCalled();
// Verify the output file utility was called for the header
expect(outputFileSpy).toHaveBeenCalledWith(expect.stringContaining('header.h'), '#define TEST_VALUE 42');
});
it('should correctly handle paths in additional files', async () => {
// Test getExtraFilepath directly for path validation
const getExtraFilepath = (dirPath: string, filename: string) => {
return (compiler as any).getExtraFilepath(dirPath, filename);
};
// Valid paths
expect(getExtraFilepath('/tmp/test', 'header.h')).toBe(path.join('/tmp/test', 'header.h'));
expect(getExtraFilepath('/tmp/test', 'subdir/header.h')).toBe(path.join('/tmp/test', 'subdir', 'header.h'));
// Invalid paths with directory traversal
expect(() => getExtraFilepath('/tmp/test', '../header.h')).toThrow();
expect(() => getExtraFilepath('/tmp/test', 'subdir/../../header.h')).toThrow();
});
});
-459
View File
@@ -1,459 +0,0 @@
// Copyright (c) 2025, Compiler Explorer Authors
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
import fs from 'node:fs/promises';
import {type Mock, afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {BaseCompiler} from '../lib/base-compiler.js';
import {CompilationEnvironment} from '../lib/compilation-env.js';
import * as exec from '../lib/exec.js';
import type {CompilationResult} from '../types/compilation/compilation.interfaces.js';
import type {FiledataPair} from '../types/compilation/compilation.interfaces.js';
import {ParseFiltersAndOutputOptions} from '../types/features/filters.interfaces.js';
import {createMockExecutor} from './mock/mock-utils.js';
import {makeCompilationEnvironment, makeFakeCompilerInfo, makeFakeParseFiltersAndOutputOptions} from './utils.js';
// Import the BypassCache enum
import {BypassCache} from '../types/compilation/compilation.interfaces.js';
const languages = {
'c++': {id: 'c++'},
rust: {id: 'rust'},
} as const;
describe('BaseCompiler core functionality', () => {
let ce: CompilationEnvironment;
let compiler: BaseCompiler;
let mockExec: ReturnType<typeof createMockExecutor>;
beforeEach(async () => {
ce = makeCompilationEnvironment({
languages,
props: {
compileTimeoutMs: 7000,
binaryExecTimeoutMs: 2000,
},
});
// Mock the findBadOptions function
ce.findBadOptions = vi.fn().mockReturnValue([]);
const compilationInfo = makeFakeCompilerInfo({
exe: '/fake/compiler/path',
remote: undefined,
lang: 'c++',
options: '-Wall -O2',
supportsExecute: true,
supportsBinary: true,
});
compiler = new BaseCompiler(compilationInfo, ce);
// Set up our mocks
mockExec = createMockExecutor(
new Map([
[
'/fake/compiler/path -Wall -O2 -g -o output.s -S input.cpp',
{
code: 0,
stdout: 'Compilation successful',
stderr: '',
},
],
[
'/fake/compiler/path -Wall -O2 -g input.cpp -o a.out',
{
code: 0,
stdout: 'Binary compilation successful',
stderr: '',
},
],
]),
);
vi.spyOn(exec, 'execute').mockImplementation(mockExec);
// Mock the exec method with a fully typed result
vi.spyOn(compiler, 'exec').mockImplementation(async () => {
return {
code: 0,
stdout: 'Compilation successful',
stderr: '',
okToCache: true,
filenameTransform: (x: string) => x,
execTime: 0,
timedOut: false,
truncated: false,
};
});
// Mock filesystem operations
vi.spyOn(fs, 'writeFile').mockImplementation(async () => {});
vi.spyOn(fs, 'readFile').mockResolvedValue('Assembly output');
// Mock check source method to prevent validation issues
vi.spyOn(compiler, 'checkSource').mockReturnValue(null);
});
afterEach(async () => {
vi.restoreAllMocks();
});
it('should compile code successfully', async () => {
const source = 'int main() { return 42; }';
const options = ['']; // Array of strings
const filters: ParseFiltersAndOutputOptions = makeFakeParseFiltersAndOutputOptions({});
const result = await compiler.compile(
source,
options,
{},
filters,
BypassCache.None, // bypassCache
[], // backendOptions
{}, // filters
[], // tools
[] as FiledataPair[], // executionParams
);
expect(result.code).toBe(0);
expect(result.asm.length).toBeGreaterThan(0);
});
it('should handle compilation failures', async () => {
// Override the exec mock to simulate a compilation failure
vi.spyOn(compiler, 'exec').mockResolvedValueOnce({
code: 1,
stdout: '',
stderr: "error: unknown type name 'foo'",
okToCache: true,
filenameTransform: (x: string) => x,
execTime: 0,
timedOut: false,
truncated: false,
});
const source = 'foo bar() { return 42; }';
const options = ['']; // Array of strings
const filters: ParseFiltersAndOutputOptions = makeFakeParseFiltersAndOutputOptions({});
const result = await compiler.compile(
source,
options,
{},
filters,
BypassCache.None, // bypassCache
[], // backendOptions
{}, // filters
[], // tools
[] as FiledataPair[], // executionParams
);
expect(result.code).toBe(1);
expect(result.asm).toEqual([{text: '<Compilation failed>', source: null, labels: []}]);
});
});
describe('BaseCompiler caching', () => {
let ce: CompilationEnvironment;
let compiler: BaseCompiler;
let cacheGetSpy: Mock;
let cachePutSpy: Mock;
beforeEach(async () => {
ce = makeCompilationEnvironment({
languages,
doCache: true,
props: {
compileTimeoutMs: 7000,
binaryExecTimeoutMs: 2000,
},
});
// Completely mock the cache methods directly rather than through spies
ce.cacheGet = vi.fn().mockResolvedValue(null);
ce.cachePut = vi.fn().mockResolvedValue(null);
ce.findBadOptions = vi.fn().mockReturnValue([]);
cacheGetSpy = ce.cacheGet as Mock;
cachePutSpy = ce.cachePut as Mock;
const compilationInfo = makeFakeCompilerInfo({
exe: '/fake/compiler/path',
remote: undefined,
lang: 'c++',
options: '-Wall -O2',
});
compiler = new BaseCompiler(compilationInfo, ce);
// Mock compiler execution
vi.spyOn(compiler, 'exec').mockResolvedValue({
code: 0,
stdout: 'Compilation successful',
stderr: '',
okToCache: true,
filenameTransform: (x: string) => x,
execTime: 0,
timedOut: false,
truncated: false,
});
vi.spyOn(fs, 'writeFile').mockImplementation(async () => {});
vi.spyOn(fs, 'readFile').mockResolvedValue('Assembly output');
// Mock check source method to prevent validation issues
vi.spyOn(compiler, 'checkSource').mockReturnValue(null);
});
afterEach(async () => {
vi.restoreAllMocks();
});
it('should try to fetch from cache when caching is enabled', async () => {
const source = 'int main() { return 42; }';
const options = ['']; // Array of strings
const filters: ParseFiltersAndOutputOptions = makeFakeParseFiltersAndOutputOptions({});
await compiler.compile(
source,
options,
{},
filters,
BypassCache.None, // NOT bypassing cache
[], // backendOptions
{}, // filters
[], // tools
[] as FiledataPair[], // executionParams
);
expect(cacheGetSpy).toHaveBeenCalled();
});
it('should store results in cache when compilation succeeds with okToCache', async () => {
const source = 'int main() { return 42; }';
const options = ['']; // Array of strings
const filters: ParseFiltersAndOutputOptions = makeFakeParseFiltersAndOutputOptions({});
await compiler.compile(
source,
options,
{},
filters,
BypassCache.None, // NOT bypassing cache
[], // backendOptions
{}, // filters
[], // tools
[] as FiledataPair[], // executionParams
);
expect(cachePutSpy).toHaveBeenCalled();
});
it('should not store results in cache when okToCache is false', async () => {
vi.spyOn(compiler, 'exec').mockResolvedValue({
code: 0,
stdout: 'Compilation successful',
stderr: '',
okToCache: false, // Setting okToCache to false
filenameTransform: (x: string) => x,
execTime: 0,
timedOut: false,
truncated: false,
});
const source = 'int main() { return 42; }';
const options = ['']; // Array of strings
const filters: ParseFiltersAndOutputOptions = makeFakeParseFiltersAndOutputOptions({});
await compiler.compile(
source,
options,
{},
filters,
BypassCache.None, // NOT bypassing cache
[], // backendOptions
{}, // filters
[], // tools
[] as FiledataPair[], // executionParams
);
expect(cachePutSpy).not.toHaveBeenCalled();
});
it('should return cached results when found in cache', async () => {
const cachedResult: CompilationResult = {
code: 0,
stdout: [{text: 'Cached stdout'}],
stderr: [{text: 'Cached stderr'}],
asm: [{text: 'Cached assembly', source: null, labels: []}],
timedOut: false,
compilationOptions: ['cached', 'options'],
inputFilename: 'cached.cpp',
// outputFilename is removed as it's not in CompilationResult type
executableFilename: 'cached.out',
// packagedFiles removed as it's not in CompilationResult type
optOutput: undefined,
tools: [],
popularArguments: {},
okToCache: true,
};
cacheGetSpy.mockResolvedValueOnce(cachedResult);
const source = 'int main() { return 42; }';
const options = ['']; // Array of strings
const filters: ParseFiltersAndOutputOptions = makeFakeParseFiltersAndOutputOptions({});
const result = await compiler.compile(
source,
options,
{},
filters,
BypassCache.None, // NOT bypassing cache
[], // backendOptions
{}, // filters
[], // tools
[] as FiledataPair[], // executionParams
);
expect(result).toBe(cachedResult);
// exec should not be called as we got a cache hit
expect(compiler.exec).not.toHaveBeenCalled();
});
});
describe('BaseCompiler demangle', () => {
let ce: CompilationEnvironment;
let compiler: BaseCompiler;
let execSpy: any; // Use any type to avoid Mock type issues
beforeEach(async () => {
ce = makeCompilationEnvironment({
languages,
props: {
compileTimeoutMs: 7000,
binaryExecTimeoutMs: 2000,
},
});
// Mock the findBadOptions function
ce.findBadOptions = vi.fn().mockReturnValue([]);
const compilationInfo = makeFakeCompilerInfo({
exe: '/fake/compiler/path',
remote: undefined,
lang: 'c++',
options: '-Wall -O2',
demangler: '/fake/demangler',
demanglerType: 'cpp',
demanglerArgs: ['-n'], // Add demanglerArgs property
});
compiler = new BaseCompiler(compilationInfo, ce);
// Set up our mocks
execSpy = vi.spyOn(compiler, 'exec');
// Mock compiler assembly compilation
execSpy.mockResolvedValueOnce({
code: 0,
stdout: 'Assembly compilation successful',
stderr: '',
okToCache: true,
filenameTransform: (x: string) => x,
execTime: 0,
timedOut: false,
truncated: false,
});
vi.spyOn(fs, 'writeFile').mockImplementation(async () => {});
vi.spyOn(fs, 'readFile').mockResolvedValue('_Z3foov:\n ret\n');
// Mock check source method to prevent validation issues
vi.spyOn(compiler, 'checkSource').mockReturnValue(null);
// Mock the postProcessAsm to simulate demangling
vi.spyOn(compiler, 'postProcessAsm').mockImplementation(async result => {
if (result) {
// Just create a simple demangled output
result.asm = [{text: 'foo():\n ret\n', source: null, labels: []}];
}
return result;
});
});
afterEach(async () => {
vi.restoreAllMocks();
});
it('should demangle symbols when requested', async () => {
// Mock demangler execution
execSpy.mockResolvedValueOnce({
code: 0,
stdout: 'foo():\n',
stderr: '',
filenameTransform: (x: string) => x,
execTime: 0,
timedOut: false,
truncated: false,
});
const source = 'int main() { return 42; }';
const options = ['']; // Array of strings
const filters: ParseFiltersAndOutputOptions = makeFakeParseFiltersAndOutputOptions({
demangle: true, // Request demangling
});
const result = await compiler.compile(
source,
options,
{},
filters,
BypassCache.None,
[],
{},
[],
[] as FiledataPair[],
);
// Result should have demangled output from our mock
expect(result.asm[0].text).toContain('foo():');
});
it('should not demangle when not requested', async () => {
const source = 'int main() { return 42; }';
const options = ['']; // Array of strings
const filters: ParseFiltersAndOutputOptions = makeFakeParseFiltersAndOutputOptions({
demangle: false, // Do not request demangling
});
await compiler.compile(source, options, {}, filters, BypassCache.None, [], {}, [], [] as FiledataPair[]);
// Check only one call to exec was made (for compilation, not demangling)
expect(execSpy).toHaveBeenCalledTimes(1);
});
});
+1182 -339
View File
File diff suppressed because it is too large Load Diff
-220
View File
@@ -1,220 +0,0 @@
// Copyright (c) 2025, Compiler Explorer Authors
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
import fs from 'node:fs/promises';
import path from 'node:path';
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {BaseCompiler} from '../lib/base-compiler.js';
import {CompilationEnvironment} from '../lib/compilation-env.js';
import * as utils from '../lib/utils.js';
import {makeCompilationEnvironment, makeFakeCompilerInfo, newTempDir} from './utils.js';
describe('BaseCompiler utilities', () => {
let ce: CompilationEnvironment;
let compiler: BaseCompiler;
let tempDir: string;
beforeEach(async () => {
ce = makeCompilationEnvironment({
props: {
compileTimeoutMs: 7000,
binaryExecTimeoutMs: 2000,
},
});
ce.findBadOptions = vi.fn().mockReturnValue([]);
tempDir = await newTempDir();
const compilationInfo = makeFakeCompilerInfo({
exe: '/fake/compiler/path',
remote: undefined,
lang: 'c++',
options: '-Wall -O2',
});
compiler = new BaseCompiler(compilationInfo, ce);
});
afterEach(async () => {
vi.restoreAllMocks();
});
describe('getExtraFilepath', () => {
it('should join paths correctly', () => {
// Skip this test on Windows as paths are handled differently
if (process.platform === 'win32') {
return;
}
// Access the protected method using a type assertion
const extraFilepath = (compiler as any).getExtraFilepath('/tmp/base/dir', 'file.txt');
expect(extraFilepath).toBe('/tmp/base/dir/file.txt');
});
it('should normalize paths', () => {
// Skip this test on Windows as paths are handled differently
if (process.platform === 'win32') {
return;
}
// Access the protected method using a type assertion
const extraFilepath = (compiler as any).getExtraFilepath('/tmp/base/dir', './subdir/../file.txt');
expect(extraFilepath).toBe('/tmp/base/dir/file.txt');
});
it('should reject paths with parent directory traversal', () => {
// Access the protected method using a type assertion
expect(() => (compiler as any).getExtraFilepath('/tmp/base/dir', '../file.txt')).toThrow(Error);
expect(() => (compiler as any).getExtraFilepath('/tmp/base/dir', 'subdir/../../file.txt')).toThrow(Error);
});
});
describe('optionsForFilter', () => {
// Using TypeScript's "any" assertion to access protected methods
const getOptions = (filter: any, output: string, userOptions?: string[]) => {
return (compiler as any).optionsForFilter(filter, output, userOptions);
};
it('should handle binary output option', () => {
const options = getOptions({binary: true}, 'output.out', []);
// Should include -o output.out but not -S
expect(options).toContain('-o');
expect(options).toContain('output.out');
expect(options).not.toContain('-S');
});
it('should handle assembly output option', () => {
const options = getOptions({binary: false}, 'output.s', []);
// Should include -o output.s and -S
expect(options).toContain('-o');
expect(options).toContain('output.s');
expect(options).toContain('-S');
});
it('should handle debug info option', () => {
const options = getOptions({binary: false}, 'output.s', []);
// Should include -g
expect(options).toContain('-g');
});
it('should accept user options but not include them directly', () => {
// The optionsForFilter method doesn't directly add userOptions to the return value
// That's handled later in prepareArguments and orderArguments methods
const options = getOptions({binary: false}, 'output.s', ['-O3', '-march=native']);
// Should not contain user options yet - they're processed later in the compile chain
expect(options).not.toContain('-O3');
expect(options).not.toContain('-march=native');
// Basic options should still be present
expect(options).toContain('-S');
expect(options).toContain('-o');
expect(options).toContain('output.s');
});
});
describe('writeAllFiles', () => {
it('should write source file to directory', async () => {
const fsWriteSpy = vi.spyOn(fs, 'writeFile').mockResolvedValue();
const source = 'int main() { return 0; }';
// Access the protected method using a type assertion
await (compiler as any).writeAllFiles(tempDir, source, [], {});
// Should have written the source file
// Access the protected compileFilename using a type assertion
expect(fsWriteSpy).toHaveBeenCalledWith(path.join(tempDir, (compiler as any).compileFilename), source);
});
it('should write multiple files', async () => {
const fsWriteSpy = vi.spyOn(fs, 'writeFile').mockResolvedValue();
const outputFileSpy = vi.spyOn(utils, 'outputTextFile').mockResolvedValue();
const source = 'int main() { return 0; }';
const extraFiles = [
{filename: 'header.h', contents: '#pragma once'},
{filename: 'impl.cpp', contents: '#include "header.h"'},
];
// Access the protected method using a type assertion
await (compiler as any).writeAllFiles(tempDir, source, extraFiles, {});
// Should have written the source file
// Access the protected compileFilename using a type assertion
expect(fsWriteSpy).toHaveBeenCalledWith(path.join(tempDir, (compiler as any).compileFilename), source);
// Should have called outputTextFile for each extra file
expect(outputFileSpy).toHaveBeenCalledTimes(2);
if (process.platform === 'win32') {
// On Windows, just check that both calls were made with the correct contents
// and don't check the exact paths (since they'll use backslashes)
expect(outputFileSpy.mock.calls[0][1]).toBe('#pragma once');
expect(outputFileSpy.mock.calls[1][1]).toBe('#include "header.h"');
// Verify that the first call has header.h in the path
expect(outputFileSpy.mock.calls[0][0]).toContain('header.h');
// Verify that the second call has impl.cpp in the path
expect(outputFileSpy.mock.calls[1][0]).toContain('impl.cpp');
} else {
// On non-Windows, check the exact paths with forward slashes
expect(outputFileSpy).toHaveBeenCalledWith(`${tempDir}/header.h`, '#pragma once');
expect(outputFileSpy).toHaveBeenCalledWith(`${tempDir}/impl.cpp`, '#include "header.h"');
}
});
});
describe('findBadOptions', () => {
// We'll temporarily override the findBadOptions mock to test the real method
beforeEach(() => {
vi.restoreAllMocks();
});
it('should check options against compiler environment', () => {
const ceSpy = vi.spyOn(ce, 'findBadOptions').mockReturnValue([]);
const result = compiler.checkOptions(['-Wall', '-O2']);
expect(ceSpy).toHaveBeenCalledWith(['-Wall', '-O2']);
expect(result).toBeNull();
});
it('should return error message for bad options', () => {
vi.spyOn(ce, 'findBadOptions').mockReturnValue(['-badoption']);
const result = compiler.checkOptions(['-Wall', '-badoption']);
expect(result).toBe('Bad options: -badoption');
});
});
});