Files

313 lines
9.6 KiB
TypeScript
Raw Permalink Normal View History

2025-07-24 19:11:15 +10:00
import {vi, describe, expect, it, beforeEach, type MockedFunction} from 'vitest'
2025-04-04 07:27:58 +11:00
import * as core from '../__fixtures__/core.js'
2025-04-06 23:21:29 +00:00
// Default to throwing errors to catch unexpected calls
2025-07-24 18:08:26 +10:00
const mockExistsSync = vi.fn().mockImplementation(() => {
2025-07-24 19:11:15 +10:00
throw new Error('Unexpected call to existsSync - test should override this implementation')
})
2025-07-24 18:08:26 +10:00
const mockReadFileSync = vi.fn().mockImplementation(() => {
2025-07-24 19:11:15 +10:00
throw new Error('Unexpected call to readFileSync - test should override this implementation')
})
2025-07-24 18:08:26 +10:00
const mockWriteFileSync = vi.fn()
2025-04-17 20:13:47 +00:00
2025-05-24 04:07:29 +02:00
/**
* Helper function to mock file system operations for one or more files
* @param fileContents - Object mapping file paths to their contents
* @param nonExistentFiles - Array of file paths that should be treated as non-existent
*/
2025-07-24 19:11:15 +10:00
function mockFileContent(fileContents: Record<string, string> = {}, nonExistentFiles: string[] = []): void {
2025-05-24 04:07:29 +02:00
// Mock existsSync to return true for files that exist, false for those that don't
2025-05-26 04:03:09 +02:00
mockExistsSync.mockImplementation((...args: unknown[]): boolean => {
const [path] = args as [string]
2025-05-24 04:07:29 +02:00
if (nonExistentFiles.includes(path)) {
return false
}
return path in fileContents || true
})
2025-05-26 03:46:39 +02:00
2025-05-24 04:07:29 +02:00
// Mock readFileSync to return the content for known files
2025-05-26 04:03:09 +02:00
mockReadFileSync.mockImplementation((...args: unknown[]): string => {
const [path, options] = args as [string, BufferEncoding]
if (options === 'utf-8' && path in fileContents) {
2025-05-24 04:07:29 +02:00
return fileContents[path]
}
throw new Error(`Unexpected file read: ${path}`)
})
}
/**
* Helper function to mock action inputs
* @param inputs - Object mapping input names to their values
*/
function mockInputs(inputs: Record<string, string> = {}): void {
// Default values that are applied unless overridden
const defaultInputs: Record<string, string> = {
2025-07-16 00:12:41 +00:00
token: 'fake-token',
model: 'gpt-4',
'max-tokens': '100',
2025-07-24 19:11:15 +10:00
endpoint: 'https://api.test.com',
2025-05-24 04:07:29 +02:00
}
2025-05-26 03:46:39 +02:00
2025-05-24 04:07:29 +02:00
// Combine defaults with user-provided inputs
2025-07-24 19:11:15 +10:00
const allInputs: Record<string, string> = {...defaultInputs, ...inputs}
2025-05-26 03:46:39 +02:00
2025-05-24 04:07:29 +02:00
core.getInput.mockImplementation((name: string) => {
return allInputs[name] || ''
})
2025-07-16 00:12:41 +00:00
core.getBooleanInput.mockImplementation((name: string) => {
const value = allInputs[name]
return value === 'true'
})
2025-05-24 04:07:29 +02:00
}
/**
* Helper function to verify common response assertions
*/
function verifyStandardResponse(): void {
2025-05-26 03:46:39 +02:00
expect(core.setOutput).toHaveBeenNthCalledWith(1, 'response', 'Hello, user!')
expect(core.setOutput).toHaveBeenNthCalledWith(2, 'response-file', expect.stringContaining('modelResponse-'))
2025-05-24 04:07:29 +02:00
}
2025-07-24 18:08:26 +10:00
vi.mock('fs', () => ({
2025-04-17 20:13:47 +00:00
existsSync: mockExistsSync,
2025-07-16 00:12:41 +00:00
readFileSync: mockReadFileSync,
2025-07-24 19:11:15 +10:00
writeFileSync: mockWriteFileSync,
2025-07-16 00:12:41 +00:00
}))
// Mocks for tmp module to control temporary file creation
2025-08-12 14:25:08 -07:00
const mockFileSync = vi.fn().mockReturnValue({
name: '/secure/temp/dir/modelResponse-abc123.txt',
})
vi.mock('tmp', () => ({
fileSync: mockFileSync,
}))
2025-07-16 00:12:41 +00:00
// Mock MCP and inference modules
2025-07-16 02:19:49 +00:00
// eslint-disable-next-line @typescript-eslint/no-explicit-any
2025-07-24 18:08:26 +10:00
const mockConnectToGitHubMCP = vi.fn() as MockedFunction<any>
2025-07-16 02:19:49 +00:00
// eslint-disable-next-line @typescript-eslint/no-explicit-any
2025-07-24 18:08:26 +10:00
const mockSimpleInference = vi.fn() as MockedFunction<any>
2025-07-16 02:19:49 +00:00
// eslint-disable-next-line @typescript-eslint/no-explicit-any
2025-07-24 18:08:26 +10:00
const mockMcpInference = vi.fn() as MockedFunction<any>
2025-07-16 00:12:41 +00:00
2025-07-24 18:08:26 +10:00
vi.mock('../src/mcp.js', () => ({
2025-07-24 19:11:15 +10:00
connectToGitHubMCP: mockConnectToGitHubMCP,
2025-07-16 00:12:41 +00:00
}))
2025-07-24 18:08:26 +10:00
vi.mock('../src/inference.js', () => ({
2025-07-16 00:12:41 +00:00
simpleInference: mockSimpleInference,
2025-07-24 19:11:15 +10:00
mcpInference: mockMcpInference,
2025-04-17 20:13:47 +00:00
}))
2025-07-24 18:08:26 +10:00
vi.mock('@actions/core', () => core)
2025-04-04 07:27:58 +11:00
2025-08-04 22:44:17 +00:00
// Mock process.exit to prevent it from actually exiting during tests
const mockProcessExit = vi.spyOn(process, 'exit').mockImplementation(() => {
// Prevent actual exit, but don't throw - just return
return undefined as never
2025-08-04 22:44:17 +00:00
})
2025-04-04 07:27:58 +11:00
// The module being tested should be imported dynamically. This ensures that the
// mocks are used in place of any actual dependencies.
2025-07-24 19:11:15 +10:00
const {run} = await import('../src/main.js')
2025-04-04 07:27:58 +11:00
describe('main.ts', () => {
// Reset all mocks before each test
beforeEach(() => {
2025-07-24 18:08:26 +10:00
vi.clearAllMocks()
2025-08-04 22:44:17 +00:00
mockProcessExit.mockClear()
2025-07-16 00:12:41 +00:00
// Remove any existing GITHUB_TOKEN
delete process.env.GITHUB_TOKEN
// Set up default mock responses
mockSimpleInference.mockResolvedValue('Hello, user!')
mockMcpInference.mockResolvedValue('Hello, user!')
2025-05-26 03:46:39 +02:00
})
2025-04-17 20:13:47 +00:00
it('Sets the response output', async () => {
2025-05-24 04:07:29 +02:00
mockInputs({
2025-05-26 03:46:39 +02:00
prompt: 'Hello, AI!',
2025-07-24 19:11:15 +10:00
'system-prompt': 'You are a test assistant.',
2025-04-06 23:21:29 +00:00
})
2025-04-04 07:27:58 +11:00
await run()
2025-05-26 04:03:09 +02:00
expect(core.setOutput).toHaveBeenCalled()
expect(core.setSecret).toHaveBeenCalledWith('fake-token')
2025-05-24 04:07:29 +02:00
verifyStandardResponse()
expect(mockProcessExit).toHaveBeenCalledWith(0)
2025-04-04 07:27:58 +11:00
})
it('Sets a failed status when no prompt is set', async () => {
2025-05-24 04:07:29 +02:00
mockInputs({
2025-05-26 03:46:39 +02:00
prompt: '',
2025-07-24 19:11:15 +10:00
'prompt-file': '',
})
2025-04-04 07:27:58 +11:00
await run()
2025-04-04 07:27:58 +11:00
2025-08-04 22:44:17 +00:00
expect(core.setFailed).toHaveBeenCalledWith('Neither prompt-file nor prompt was set')
expect(mockProcessExit).toHaveBeenCalledWith(1)
2025-04-04 07:27:58 +11:00
})
2025-04-17 20:13:47 +00:00
2025-07-16 00:12:41 +00:00
it('uses simple inference when MCP is disabled', async () => {
2025-05-24 04:07:29 +02:00
mockInputs({
2025-07-16 00:12:41 +00:00
prompt: 'Hello, AI!',
'system-prompt': 'You are a test assistant.',
2025-07-24 19:11:15 +10:00
'enable-github-mcp': 'false',
2025-04-17 20:13:47 +00:00
})
await run()
2025-07-16 00:12:41 +00:00
expect(mockSimpleInference).toHaveBeenCalledWith({
2025-07-21 00:11:26 +00:00
messages: [
2025-07-24 19:11:15 +10:00
{role: 'system', content: 'You are a test assistant.'},
{role: 'user', content: 'Hello, AI!'},
2025-07-21 00:11:26 +00:00
],
2025-07-16 00:12:41 +00:00
modelName: 'gpt-4',
maxTokens: 100,
maxCompletionTokens: undefined,
2025-07-16 00:12:41 +00:00
endpoint: 'https://api.test.com',
2025-07-21 00:11:26 +00:00
token: 'fake-token',
2025-07-24 19:11:15 +10:00
responseFormat: undefined,
temperature: undefined,
topP: undefined,
customHeaders: {},
2025-07-16 00:12:41 +00:00
})
2025-07-16 02:19:49 +00:00
expect(mockConnectToGitHubMCP).not.toHaveBeenCalled()
2025-07-16 00:12:41 +00:00
expect(mockMcpInference).not.toHaveBeenCalled()
verifyStandardResponse()
expect(mockProcessExit).toHaveBeenCalledWith(0)
2025-07-16 00:12:41 +00:00
})
it('uses MCP inference when enabled and connection succeeds', async () => {
const mockMcpClient = {
2025-07-16 02:19:49 +00:00
// eslint-disable-next-line @typescript-eslint/no-explicit-any
2025-07-16 00:12:41 +00:00
client: {} as any,
2025-07-24 19:11:15 +10:00
tools: [{type: 'function', function: {name: 'test-tool'}}],
2025-07-16 00:12:41 +00:00
}
mockInputs({
prompt: 'Hello, AI!',
'system-prompt': 'You are a test assistant.',
2025-07-24 19:11:15 +10:00
'enable-github-mcp': 'true',
2025-07-16 00:12:41 +00:00
})
2025-07-16 02:19:49 +00:00
mockConnectToGitHubMCP.mockResolvedValue(mockMcpClient)
2025-07-16 00:12:41 +00:00
await run()
expect(core.setSecret).toHaveBeenCalledWith('fake-token')
2025-11-30 22:20:19 +01:00
expect(mockConnectToGitHubMCP).toHaveBeenCalledWith('fake-token', '')
2025-07-16 00:12:41 +00:00
expect(mockMcpInference).toHaveBeenCalledWith(
expect.objectContaining({
2025-07-21 00:11:26 +00:00
messages: [
2025-07-24 19:11:15 +10:00
{role: 'system', content: 'You are a test assistant.'},
{role: 'user', content: 'Hello, AI!'},
2025-07-21 00:11:26 +00:00
],
2025-07-24 19:11:15 +10:00
token: 'fake-token',
2025-07-16 00:12:41 +00:00
}),
2025-07-24 19:11:15 +10:00
mockMcpClient,
2025-07-16 00:12:41 +00:00
)
expect(mockSimpleInference).not.toHaveBeenCalled()
verifyStandardResponse()
expect(mockProcessExit).toHaveBeenCalledWith(0)
2025-07-16 00:12:41 +00:00
})
it('falls back to simple inference when MCP connection fails', async () => {
mockInputs({
prompt: 'Hello, AI!',
'system-prompt': 'You are a test assistant.',
2025-07-24 19:11:15 +10:00
'enable-github-mcp': 'true',
2025-07-16 00:12:41 +00:00
})
2025-07-16 02:19:49 +00:00
mockConnectToGitHubMCP.mockResolvedValue(null)
2025-07-16 00:12:41 +00:00
await run()
2025-11-30 22:20:19 +01:00
expect(mockConnectToGitHubMCP).toHaveBeenCalledWith('fake-token', '')
2025-07-16 00:12:41 +00:00
expect(mockSimpleInference).toHaveBeenCalled()
expect(mockMcpInference).not.toHaveBeenCalled()
2025-07-24 19:11:15 +10:00
expect(core.warning).toHaveBeenCalledWith('MCP connection failed, falling back to simple inference')
2025-07-16 00:12:41 +00:00
verifyStandardResponse()
expect(mockProcessExit).toHaveBeenCalledWith(0)
2025-07-16 00:12:41 +00:00
})
it('properly integrates with loadContentFromFileOrInput', async () => {
const promptFile = 'prompt.txt'
const systemPromptFile = 'system-prompt.txt'
const promptContent = 'File-based prompt'
const systemPromptContent = 'File-based system prompt'
mockFileContent({
[promptFile]: promptContent,
2025-07-24 19:11:15 +10:00
[systemPromptFile]: systemPromptContent,
2025-07-16 00:12:41 +00:00
})
mockInputs({
'prompt-file': promptFile,
'system-prompt-file': systemPromptFile,
2025-07-24 19:11:15 +10:00
'enable-github-mcp': 'false',
2025-07-16 00:12:41 +00:00
})
await run()
expect(mockSimpleInference).toHaveBeenCalledWith({
2025-07-21 00:11:26 +00:00
messages: [
2025-07-24 19:11:15 +10:00
{role: 'system', content: systemPromptContent},
{role: 'user', content: promptContent},
2025-07-21 00:11:26 +00:00
],
2025-07-16 00:12:41 +00:00
modelName: 'gpt-4',
maxTokens: 100,
maxCompletionTokens: undefined,
2025-07-16 00:12:41 +00:00
endpoint: 'https://api.test.com',
2025-07-21 00:11:26 +00:00
token: 'fake-token',
2025-07-24 19:11:15 +10:00
responseFormat: undefined,
temperature: undefined,
topP: undefined,
customHeaders: {},
2025-07-16 00:12:41 +00:00
})
2025-05-24 04:07:29 +02:00
verifyStandardResponse()
expect(mockProcessExit).toHaveBeenCalledWith(0)
2025-04-17 20:13:47 +00:00
})
it('handles non-existent prompt-file with an error', async () => {
const promptFile = 'non-existent-prompt.txt'
2025-05-26 03:46:39 +02:00
2025-05-24 04:07:29 +02:00
mockFileContent({}, [promptFile])
2025-05-26 03:46:39 +02:00
2025-05-24 04:07:29 +02:00
mockInputs({
2025-07-24 19:11:15 +10:00
'prompt-file': promptFile,
})
await run()
2025-07-24 19:11:15 +10:00
expect(core.setFailed).toHaveBeenCalledWith(`File for prompt-file was not found: ${promptFile}`)
2025-08-04 22:44:17 +00:00
expect(mockProcessExit).toHaveBeenCalledWith(1)
})
2025-08-12 14:25:08 -07:00
it('creates temporary files that persist for downstream steps', async () => {
2025-08-12 14:25:08 -07:00
mockInputs({
prompt: 'Test prompt',
'system-prompt': 'You are a test assistant.',
})
await run()
// Verify temp file is created with keep: true so it persists
2025-08-12 14:25:08 -07:00
expect(mockFileSync).toHaveBeenCalledWith({
prefix: 'modelResponse-',
postfix: '.txt',
keep: true,
2025-08-12 14:25:08 -07:00
})
expect(core.setOutput).toHaveBeenNthCalledWith(2, 'response-file', '/secure/temp/dir/modelResponse-abc123.txt')
expect(mockWriteFileSync).toHaveBeenCalledWith('/secure/temp/dir/modelResponse-abc123.txt', 'Hello, user!', 'utf-8')
expect(mockProcessExit).toHaveBeenCalledWith(0)
})
2025-04-04 07:27:58 +11:00
})