SPB Git

Repository Public License

EndpointAndModelTests.swift 10.9 KB 173 lines swift

1import Foundation2import Testing3@testable import ProviderKit45@Suite struct EndpointPolicyTests {6    @Test(arguments: ["https://api.example.com/v1", "https://10.0.0.5:8443/v1", " https://example.com/v1 "])7    func httpsIsAlwaysAccepted(_ url: String) throws {8        #expect(try EndpointPolicy.validate(url).scheme == "https")9    }1011    @Test(arguments: ["http://localhost:11434/v1", "http://127.0.0.1:1234/v1", "http://192.168.2.103:8000/v1", "http://10.67.0.33/v1",12                      "http://172.16.4.1/v1", "http://172.31.255.254/v1", "http://100.125.225.117:8080/v1", "http://studio.local:8080/v1",13                      "http://[::1]:8080/v1", "http://[fd12:3456::1]/v1", "http://169.254.10.10/v1"])14    func plainHTTPIsAcceptedForLocalAndPrivateHostsWithoutOptIn(_ url: String) throws {15        #expect(try EndpointPolicy.validate(url, allowInsecureHTTP: false).scheme == "http")16    }1718    @Test(arguments: ["http://api.example.com/v1", "http://8.8.8.8/v1", "http://172.32.0.1/v1", "http://100.128.0.1/v1", "http://192.169.1.1/v1",19                      "http://10.0.0.1.evil.com/v1", "http://010.0.0.1/v1", "http://localhost.evil.com/v1", "http://[2001:db8::1]/v1"])20    func plainHTTPToAPublicHostNeedsExplicitOptIn(_ url: String) throws {21        #expect { try EndpointPolicy.validate(url, allowInsecureHTTP: false) } throws: { error in22            if case ProviderError.insecureEndpoint = error { true } else { false }23        }24        #expect(try EndpointPolicy.validate(url, allowInsecureHTTP: true).scheme == "http")25    }2627    @Test(arguments: ["", "example.com/v1", "ftp://example.com/v1", "file:///etc/passwd", "https://user:pass@example.com/v1",28                      "https://example.com/v1?key=abc", "https:///v1"])29    func unusableURLsAreRefused(_ url: String) {30        #expect(throws: ProviderError.self) { try EndpointPolicy.validate(url, allowInsecureHTTP: true) }31    }3233    @Test func credentialAndControlHeadersAreRefused() throws {34        try EndpointPolicy.validate(headers: ["X-Team": "browser", "x_trace": "1"])35        for name in ["Authorization", "x-api-key", "Cookie", "Host", "api-key", "Bad Name", ""] {36            #expect(throws: ProviderError.self) { try EndpointPolicy.validate(headers: [name: "v"]) }37        }38        #expect(throws: ProviderError.self) { try EndpointPolicy.validate(headers: ["X-Team": "a\r\nAuthorization: Bearer x"]) }39    }4041    @Test func compatibleProviderRefusesAnInsecureEndpointBeforeSendingAnything() async {42        let test = TestEnvironment([.sse(HTTPFamily.compatible.textStream)])43        let provider = CompatibleProvider(endpoint: .init(baseURL: "http://api.example.com/v1"), apiKey: { testKey }, environment: test.environment)44        let (_, error) = await collect(provider.stream(sampleRequest()))45        guard case .insecureEndpoint = error else { Issue.record("expected insecureEndpoint, got \(String(describing: error))"); return }46        await #expect(throws: ProviderError.self) { try await provider.listModels() }47        #expect(test.transport.requests.isEmpty)48    }4950    @Test func compatibleProviderSendsOverHTTPAfterOptIn() async {51        let test = TestEnvironment([.sse(HTTPFamily.compatible.textStream)])52        let provider = CompatibleProvider(endpoint: .init(baseURL: "http://api.example.com/v1", allowInsecureHTTP: true), environment: test.environment)53        let (events, error) = await collect(provider.stream(sampleRequest()))54        #expect(error == nil)55        #expect(text(events) == "Hello, wörld")56        #expect(test.transport.requests[0].url?.absoluteString == "http://api.example.com/v1/chat/completions")57    }58}5960@Suite struct ModelListTests {61    @Test func anthropicModelListIsPaginatedAndParsed() async throws {62        let first = #"{"data":[{"id":"claude-a","display_name":"Claude A","created_at":"2026-01-02T00:00:00Z","max_input_tokens":1000000,"max_tokens":128000,"capabilities":{"image_input":{"supported":true}}}],"has_more":true,"last_id":"claude-a"}"#63        let second = #"{"data":[{"id":"claude-b"}],"has_more":false,"last_id":"claude-b"}"#64        let test = TestEnvironment([.json(first), .json(second)])65        let models = try await HTTPFamily.anthropic.provider(test).listModels()66        #expect(models.map(\.id) == ["claude-a", "claude-b"])67        #expect(models[0].displayName == "Claude A")68        #expect(models[0].contextLength == 1_000_000)69        #expect(models[0].maxOutputTokens == 128_000)70        #expect(models[0].supportsImages == true)71        #expect(models[1].supportsImages == nil)   // not stated: unknown, not "no"72        #expect(models[1].displayName == "claude-b")73        let requests = test.transport.requests74        #expect(requests[0].url?.absoluteString == "https://api.anthropic.com/v1/models?limit=1000")75        #expect(requests[1].url?.absoluteString == "https://api.anthropic.com/v1/models?limit=1000&after_id=claude-a")76        #expect(requests[0].value(forHTTPHeaderField: "x-api-key") == testKey)77        #expect(requests[0].httpMethod == "GET")78    }7980    @Test func openAIModelListKeepsChatModelsNewestFirst() async throws {81        let body = #"{"data":[{"id":"gpt-old","created":100},{"id":"text-embedding-3-large","created":300},{"id":"gpt-new","created":200},{"id":"whisper-1","created":50},{"id":"gpt-realtime","created":400}]}"#82        let test = TestEnvironment([.json(body)])83        let models = try await HTTPFamily.openAI.provider(test).listModels()84        #expect(models.map(\.id) == ["gpt-new", "gpt-old"])85        #expect(models[0].price == nil)86        #expect(test.transport.requests[0].url?.absoluteString == "https://api.openai.com/v1/models")87        #expect(test.transport.requests[0].value(forHTTPHeaderField: "Authorization") == "Bearer \(testKey)")88    }8990    @Test func openRouterModelListCarriesLivePrices() async throws {91        let body = #"{"data":[{"id":"vendor/model-a","name":"Model A","context_length":200000,"architecture":{"input_modalities":["text","image"],"output_modalities":["text"]},"supported_parameters":["tools","temperature"],"pricing":{"prompt":"0.000003","completion":"0.000015","input_cache_read":"0.0000003"},"top_provider":{"max_completion_tokens":64000}},{"id":"openrouter/auto","pricing":{"prompt":"-1","completion":"-1"}},{"id":"vendor/image-only","architecture":{"output_modalities":["image"]}}]}"#92        let test = TestEnvironment([.json(body)])93        let models = try await HTTPFamily.openRouter.provider(test, key: nil).listModels()   // the catalogue is public94        #expect(models.map(\.id) == ["vendor/model-a", "openrouter/auto"])95        let price = try #require(models[0].price)96        #expect(price.inputPerMillion == 3)97        #expect(price.outputPerMillion == 15)98        #expect(price.cacheReadPerMillion == 0.3)99        #expect(price.cacheWritePerMillion == nil)100        if case .providerList(let url, _) = price.source { #expect(url == "https://openrouter.ai/api/v1/models") } else { Issue.record("wrong price source") }101        #expect(models[0].supportsTools == true)102        #expect(models[0].supportsImages == true)103        #expect(models[0].maxOutputTokens == 64_000)104        #expect(models[1].price == nil)             // a router's price depends on the model it picks105        #expect(models[1].supportsTools == nil)106        #expect(test.transport.requests[0].value(forHTTPHeaderField: "Authorization") == nil)107    }108109    @Test func openRouterConnectionTestReportsRemainingCredit() async throws {110        let test = TestEnvironment([.json(#"{"data":{"label":"k","limit_remaining":4.25,"is_free_tier":false}}"#)])111        let report = try await HTTPFamily.openRouter.provider(test).testConnection()112        #expect(report.remainingCreditUSD == 4.25)113        #expect(report.family == .openRouter)114        #expect(test.transport.requests[0].url?.absoluteString == "https://openrouter.ai/api/v1/key")115    }116117    @Test(arguments: [#"{"data":[{"id":"llama3.2"},{"id":"qwen3"}]}"#, #"{"models":[{"name":"llama3.2"},{"name":"qwen3"}]}"#, #"["llama3.2","qwen3"]"#])118    func compatibleModelListAcceptsCommonShapes(_ body: String) async throws {119        let test = TestEnvironment([.json(body)])120        let models = try await HTTPFamily.compatible.provider(test, key: nil).listModels()121        #expect(models.map(\.id) == ["llama3.2", "qwen3"])122        #expect(models[0].supportsTools == nil)123        #expect(test.transport.requests[0].url?.absoluteString == "http://localhost:11434/v1/models")124    }125126    @Test(arguments: [HTTPFamily.anthropic, .openAI, .compatible])127    func connectionTestCountsModelsAndFailsHonestly(_ family: HTTPFamily) async throws {128        let ok = TestEnvironment([.json(#"{"data":[{"id":"gpt-a"},{"id":"gpt-b"}],"has_more":false}"#)])129        let report = try await family.provider(ok).testConnection()130        #expect(report.modelCount == 2)131        #expect(report.family.rawValue.lowercased() == family.rawValue.lowercased())132        let bad = TestEnvironment([.json(family.errorBody("bad key", type: "authentication_error"), status: 401)])133        await #expect(throws: ProviderError.invalidKey("bad key")) { try await family.provider(bad).testConnection() }134    }135136    @Test func suggestedModelsAreSuggestionsOnly() {137        #expect(ProviderFamily.anthropic.suggestedModels.contains("claude-opus-5-5"))138        #expect(ProviderFamily.compatible.suggestedModels.isEmpty)139        #expect(ProviderFamily.compatible.defaultBaseURL == nil)140        #expect(!ProviderFamily.compatible.requiresKey && !ProviderFamily.local.requiresKey)141        #expect(ProviderFamily.anthropic.requiresKey && ProviderFamily.openAI.requiresKey && ProviderFamily.openRouter.requiresKey)142    }143}144145@Suite struct JSONValueTests {146    @Test func roundTripAndStableSerialisation() throws {147        let value: JSONValue = ["b": [1, 2.5, true, nil, "x"], "a": ["nested": "é/"]]148        #expect(value.serialized() == #"{"a":{"nested":"é/"},"b":[1,2.5,true,null,"x"]}"#)149        #expect(JSONValue.parse(value.serialized()) == value)150        #expect(try JSONDecoder().decode(JSONValue.self, from: JSONEncoder().encode(value)) == value)151    }152153    @Test func accessors() {154        let value = JSONValue.parse(#"{"n":3,"f":3.5,"s":"0.25","t":true,"l":[1],"big":1e30}"#)!155        #expect(value["n"]?.intValue == 3)156        #expect(value["f"]?.intValue == nil)157        #expect(value["big"]?.intValue == nil)158        #expect(value["s"]?.doubleValue == 0.25)159        #expect(value["t"]?.boolValue == true)160        #expect(value["n"]?.boolValue == nil)   // 1/0 are numbers, not booleans161        #expect(value["l"]?[0] == 1)162        #expect(value["l"]?[5] == nil)163        #expect(JSONValue.parse("not json") == nil)164    }165166    @Test func toolCallArgumentParsing() {167        #expect(ToolCall(id: "1", name: "t", streamedArguments: "").arguments == .object([:]))168        #expect(ToolCall(id: "1", name: "t", streamedArguments: " {\"a\":1} ").arguments == ["a": 1])169        #expect(!ToolCall(id: "1", name: "t", streamedArguments: "[1,2]").hasValidArguments)170        #expect(!ToolCall(id: "1", name: "t", streamedArguments: "{\"a\":").hasValidArguments)171    }172}173
Files main
Menu

Theme