Files
oai-swift/oAITests/OllamaProviderTests.swift
T
rune a053d4a983 Phase 2: tests for the provider layer and other exposed pure helpers
66 new tests across 8 files (93 total in the suite now):

- GitSyncServiceTests: convertToSSH/injectCredentials/sanitizeFilename/
  detectSecretsInText, including a below-threshold false-positive check
  on the secret regex.
- ChatViewModelPureLogicTests: detectGoodbyePhrase, inferProvider,
  calculateCost -- including the cache-read (0.1x) / cache-write (1.25x)
  pricing multipliers, which is real billing-affecting logic.
- EmbeddingServiceTests / ContextSelectionServiceTests: embedding
  (de)serialization round-trip, importance-score weighting, and the
  token-estimate fallback (content.count / 4) when no real count exists.
- OpenRouterProviderTests / OllamaProviderTests / OpenAIProviderTests /
  AnthropicProviderTests: request-building (attachments, online mode,
  cache_control breakpoints, o1/o3 temperature omission, tool schema
  conversion) and response-parsing (text, tool_use blocks, empty-choices
  fallback behavior) for all four providers, with no network involved.

Also marks calculateCost/inferProvider/detectGoodbyePhrase (ChatViewModel)
and serializeEmbedding/deserializeEmbedding (EmbeddingService) as
`nonisolated` -- discovered via the actual test failures, not
speculation: the project's `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor`
setting isolates the classes that carry an explicit `@MainActor`
(ChatViewModel), so calling their static members from a plain
synchronous @Test needs the pure ones marked `nonisolated`. Matches
the existing convention already used elsewhere in EmbeddingService
(cosineSimilarity was already nonisolated before this change).

Phase 2 of the test-suite rollout plan (peaceful-baking-kurzweil).
2026-07-23 14:11:50 +02:00

80 lines
3.3 KiB
Swift

//
// OllamaProviderTests.swift
// oAITests
//
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
// Copyright (C) 2026 Rune Olsen
import Testing
import Foundation
@testable import oAI
@Suite("OllamaProvider request/response conversion")
struct OllamaProviderTests {
private var provider: OllamaProvider { OllamaProvider() }
// MARK: - buildRequestBody
@Test("Builds a basic request body with model, messages, and stream flag")
func basicRequestBody() {
let request = ChatRequest(messages: [Message(role: .user, content: "hi")], model: "llama3.2")
let body = provider.buildRequestBody(from: request, stream: true)
#expect(body["model"] as? String == "llama3.2")
#expect(body["stream"] as? Bool == true)
let messages = body["messages"] as? [[String: Any]]
#expect(messages?.count == 1)
#expect(messages?.first?["role"] as? String == "user")
#expect(messages?.first?["content"] as? String == "hi")
}
@Test("System prompt is prepended as its own system-role message")
func systemPromptPrepended() {
let request = ChatRequest(messages: [Message(role: .user, content: "hi")], model: "llama3.2", systemPrompt: "be concise")
let body = provider.buildRequestBody(from: request, stream: false)
let messages = body["messages"] as? [[String: Any]]
#expect(messages?.count == 2)
#expect(messages?.first?["role"] as? String == "system")
#expect(messages?.first?["content"] as? String == "be concise")
}
@Test("maxTokens and temperature are nested under options only when present")
func optionsOnlyWhenPresent() {
let withOptions = ChatRequest(messages: [Message(role: .user, content: "hi")], model: "llama3.2", maxTokens: 500, temperature: 0.7)
let bodyWithOptions = provider.buildRequestBody(from: withOptions, stream: false)
let options = bodyWithOptions["options"] as? [String: Any]
#expect(options?["num_predict"] as? Int == 500)
#expect(options?["temperature"] as? Double == 0.7)
let withoutOptions = ChatRequest(messages: [Message(role: .user, content: "hi")], model: "llama3.2")
let bodyWithoutOptions = provider.buildRequestBody(from: withoutOptions, stream: false)
#expect(bodyWithoutOptions["options"] == nil)
}
// MARK: - parseOllamaResponse
@Test("Parses content and token counts from a well-formed response")
func parsesWellFormedResponse() {
let json: [String: Any] = [
"message": ["content": "the answer"],
"prompt_eval_count": 10,
"eval_count": 20
]
let response = provider.parseOllamaResponse(json, model: "llama3.2")
#expect(response.content == "the answer")
#expect(response.role == "assistant")
#expect(response.finishReason == "stop")
#expect(response.usage?.promptTokens == 10)
#expect(response.usage?.completionTokens == 20)
#expect(response.usage?.totalTokens == 30)
}
@Test("Missing fields default to empty content and zero token counts")
func missingFieldsDefaultGracefully() {
let response = provider.parseOllamaResponse([:], model: "llama3.2")
#expect(response.content == "")
#expect(response.usage?.promptTokens == 0)
#expect(response.usage?.completionTokens == 0)
}
}