Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 72 additions & 0 deletions __mocks__/obsidian.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,80 @@
export const requestUrl = jest.fn();

// Obsidian API functions
export const getFrontMatterInfo = jest.fn((content: string) => {
const match = content.match(/^---\n[\s\S]*?\n---\n/);
if (match) {
return {
exists: true,
frontmatter: match[0],
contentStart: match[0].length,
};
}
return {
exists: false,
frontmatter: '',
contentStart: 0,
};
});

export const parseFrontMatterStringArray = jest.fn((frontmatter: any, key: string) => {
if (!frontmatter || !frontmatter[key]) {
return null;
}
const value = frontmatter[key];
if (Array.isArray(value)) {
return value;
}
return [value];
});

export const getAllTags = jest.fn((cache: any) => {
if (!cache) return null;
const tags = new Set<string>();

// Add frontmatter tags
if (cache.frontmatter && cache.frontmatter.tags) {
const frontmatterTags = Array.isArray(cache.frontmatter.tags)
? cache.frontmatter.tags
: [cache.frontmatter.tags];
frontmatterTags.forEach((tag: string) => tags.add(tag));
}

// Add inline tags (simulated)
if (cache.tags) {
cache.tags.forEach((tag: any) => tags.add(tag.tag));
}

return tags.size > 0 ? Array.from(tags) : null;
});

// MetadataCache mock
export class MetadataCache {
private fileCaches = new Map<any, any>();

getFileCache = jest.fn((file: any) => {
return this.fileCaches.get(file) || null;
});

// Helper for testing
setFileCache(file: any, cache: any) {
this.fileCaches.set(file, cache);
}

clearCache() {
this.fileCaches.clear();
}
}

// TFile mock
export class TFile {
constructor(public path: string, public basename: string) {}
}

// Basic App mock for components relying on Obsidian's App
export class App {
vault = { getMarkdownFiles: jest.fn().mockReturnValue([]) } as any;
metadataCache = new MetadataCache();
}

export class FuzzySuggestModal<T> {
Expand Down
203 changes: 203 additions & 0 deletions __tests__/api/UnifiedProvider.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,203 @@
import { UnifiedProvider } from 'api';
import { ProviderConfig } from 'api/types';
import { requestUrl } from 'obsidian';
import { PROVIDER_NAMES } from 'utils';

jest.mock('obsidian');

describe('UnifiedProvider Tests', () => {
const unifiedProvider = new UnifiedProvider();

const mockConfig: ProviderConfig = {
name: '',
apiKey: 'test-key',
baseUrl: 'https://api.test.com',
models: [{ id: 'test-model', name: 'Test Model' }],
temperature: 0.7
};

beforeEach(() => {
jest.clearAllMocks();
});

describe('Response parsing', () => {
it('should parse OpenAI format with nested JSON content', () => {
const openAIResponse = {
choices: [{
message: {
content: '{"output":["tag1"],"reliability":0.9}'
}
}]
};
expect(unifiedProvider.processApiResponse(openAIResponse)).toEqual({
output: ['tag1'],
reliability: 0.9
});
});

it('should parse Anthropic tool_use format', () => {
const anthropicResponse = {
content: [{
type: 'tool_use',
input: { output: ['tag2'], reliability: 0.8 }
}]
};
expect(unifiedProvider.processApiResponse(anthropicResponse, PROVIDER_NAMES.ANTHROPIC)).toEqual({
output: ['tag2'],
reliability: 0.8
});
});

it('should parse Gemini nested content format', () => {
const geminiResponse = {
candidates: [{
content: {
parts: [{
text: '{"output":["tag3"],"reliability":0.7}'
}]
}
}]
};
expect(unifiedProvider.processApiResponse(geminiResponse, PROVIDER_NAMES.GEMINI)).toEqual({
output: ['tag3'],
reliability: 0.7
});
});

it('should parse Ollama message format', () => {
const ollamaResponse = {
message: {
content: '{"output":["tag4"],"reliability":0.6}'
}
};
expect(unifiedProvider.processApiResponse(ollamaResponse, PROVIDER_NAMES.OLLAMA)).toEqual({
output: ['tag4'],
reliability: 0.6
});
});

it('should throw error for missing content in Gemini response', () => {
const invalidResponse = { candidates: [] };
expect(() => unifiedProvider.processApiResponse(invalidResponse, PROVIDER_NAMES.GEMINI))
.toThrow('Gemini response missing content');
});

it('should throw error for missing content in Ollama response', () => {
const invalidResponse = { message: {} };
expect(() => unifiedProvider.processApiResponse(invalidResponse, PROVIDER_NAMES.OLLAMA))
.toThrow('Ollama response missing content');
});

it('should throw error for invalid JSON structure in response', () => {
const invalidJsonResponse = {
choices: [{
message: {
content: '{"invalid":"structure"}'
}
}]
};
expect(() => unifiedProvider.processApiResponse(invalidJsonResponse))
.toThrow('Invalid response structure: missing output array or reliability number');
});

it('should throw error for malformed JSON in response', () => {
const malformedJsonResponse = {
choices: [{
message: {
content: 'not valid json'
}
}]
};
expect(() => unifiedProvider.processApiResponse(malformedJsonResponse))
.toThrow(/Failed to parse API response/);
});
});

describe('API routing integration', () => {
it('should handle Anthropic provider end-to-end', async () => {
const config: ProviderConfig = {
...mockConfig,
name: PROVIDER_NAMES.ANTHROPIC
};

const mockResponse = {
status: 200,
json: {
content: [{
type: 'tool_use',
input: { output: ['test'], reliability: 1.0 }
}]
}
};

(requestUrl as jest.Mock).mockResolvedValueOnce(mockResponse);

const result = await unifiedProvider.callAPI('system', 'user', config, 'model');

expect(requestUrl).toHaveBeenCalledWith(
expect.objectContaining({
headers: expect.objectContaining({
'x-api-key': 'test-key',
'anthropic-version': '2023-06-01'
})
})
);
expect(result).toEqual({ output: ['test'], reliability: 1.0 });
});

it('should handle Gemini provider with API key in URL', async () => {
const config: ProviderConfig = {
...mockConfig,
name: PROVIDER_NAMES.GEMINI
};

const mockResponse = {
status: 200,
json: {
candidates: [{
content: {
parts: [{
text: '{"output":["test"],"reliability":0.95}'
}]
}
}]
}
};

(requestUrl as jest.Mock).mockResolvedValueOnce(mockResponse);

await unifiedProvider.callAPI('system', 'user', config, 'gemini-pro');

expect(requestUrl).toHaveBeenCalledWith(
expect.objectContaining({
url: expect.stringContaining('models/gemini-pro:generateContent?key=test-key')
})
);
});

it('should handle temperature override in provider config', async () => {
const config: ProviderConfig = {
...mockConfig,
name: PROVIDER_NAMES.OPENAI,
temperature: 0.3
};

const mockResponse = {
status: 200,
json: {
choices: [{
message: { content: '{"output":["test"],"reliability":1.0}' }
}]
}
};

(requestUrl as jest.Mock).mockResolvedValueOnce(mockResponse);

await unifiedProvider.callAPI('system', 'user', config, 'model', 0.9);

const callArgs = (requestUrl as jest.Mock).mock.calls[0][0];
const bodyData = JSON.parse(callArgs.body);
expect(bodyData.temperature).toBe(0.3);
});
});
});
Loading