SPB Git

Repository Public MIT

TextToolsTests.swift 10.2 KB 196 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Astra9// File             : Tests/AstraAgentsTests/TextToolsTests.swift10// Module           : AstraAgentsTests11// Repository       : https://git.spboucher.ai/orix-astra12// Created          : 2026-11-2113// Last Modified    : 2026-11-2114//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author           : Simon-Pierre Boucher20// Position         : Professor of Finance21// Institution      : Université du Québec en Outaouais (UQO)22// Department       : Département des sciences administratives23// Organization     : SP Boucher24//25// Website          : https://spboucher.ai26// Git              : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General          : info@spboucher.ai33// Professional     : contact@spboucher.ai34// Direct           : simon@spboucher.ai35// Research         : research@spboucher.ai36// Development      : dev@spboucher.ai37// Support          : support@spboucher.ai38// Security/Admin   : admin@spboucher.ai39// Notifications    : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification   : Public66// Distribution     : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License          : Proprietary, all rights reserved (see license file)80// License File     : LICENSE81// Maintainer       : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import Foundation89import Testing90import AstraCore91@testable import AstraAgents9293@Suite struct TextToolsTests {94    @Test func statistics() {95        let s = TextStatistics("Hello, world! This is a test.\nSecond line here…\n\nNew paragraph — done?")96        #expect(s.words == 12)97        #expect(s.lines == 4)98        #expect(s.paragraphs == 2)99        #expect(s.sentences == 4)100        #expect(s.characters == 70)101        #expect(s.bytes == 74)102        let empty = TextStatistics("")103        #expect(empty.words == 0 && empty.lines == 0 && empty.sentences == 0 && empty.paragraphs == 0 && empty.characters == 0)104        #expect(TextStatistics("one\ntwo\n").lines == 2)105        #expect(TextStatistics("one\ntwo\n\n").lines == 3)106        #expect(TextStatistics("no terminator").sentences == 1)107        #expect(TextStatistics("Wait... what?!").sentences == 2)108        #expect(TextStatistics("  spaced   out  ").charactersWithoutSpaces == 9)109        #expect(TextStatistics("👨‍👩‍👧 café").characters == 6)110        #expect(TextStatistics("a - b").words == 2)111    }112113    @Test func statsTool() async throws {114        let out = try await runTool(TextStatsTool(), ["text": "One two three.\nFour."])115        #expect(out.contains("words: 4") && out.contains("lines: 2") && out.contains("characters: 20") && out.contains("sentences: 2"))116    }117118    @Test func regexExtraction() async throws {119        let tool = RegexExtractTool()120        let text = "Contact ana@example.com or BOB@Example.org; invoice INV-2026-0042 and INV-2025-0007."121        #expect(try await runTool(tool, ["text": .string(text), "pattern": #"[A-Za-z0-9._]+@[A-Za-z0-9.]+\.[a-z]{2,}"#]) == "matches: 2\n1. ana@example.com\n2. BOB@Example.org")122        #expect(try await runTool(tool, ["text": .string(text), "pattern": #"INV-(\d{4})-(\d+)"#, "group": 2]) == "matches: 2\n1. 0042\n2. 0007")123        #expect(try await runTool(tool, ["text": .string(text), "pattern": "bob", "case_insensitive": true]) == "matches: 1\n1. BOB")124        #expect(try await runTool(tool, ["text": .string(text), "pattern": "zzz"]) == "No match.")125        #expect(try await runTool(tool, ["text": "a1b2c3d4", "pattern": #"\d"#, "max_matches": 2]) == "matches: 2 (stopped at the limit)\n1. 1\n2. 2")126        #expect(await toolError(tool, ["text": .string(text), "pattern": #"INV-(\d+)"#, "group": 3])?.contains("group 3 does not exist") == true)127        #expect(await toolError(tool, ["text": "x", "pattern": "(unclosed"])?.contains("not a valid regular expression") == true)128        #expect(await toolError(tool, ["text": "x", "pattern": ""])?.contains("must not be empty") == true)129    }130131    @Test func riskyPatternsAreRefused() {132        for pattern in [#"(a+)+$"#, #"(a*)*b"#, #"(\w+\s?)+$"#, #"([a-z]+)*x"#, #"((ab)+)+"#, #"(a{2,})+"#, #"(.*a){20,}"#] {133            #expect(BoundedRegex.looksCatastrophic(pattern), "\(pattern)")134            #expect(throws: ToolError.self, "\(pattern)") { try BoundedRegex.matches(pattern: pattern, in: "aaaa") }135        }136        for pattern in [#"\d+(\.\d+)?"#, #"(\w+)@(\w+)\.com"#, #"(ab)+"#, #"[a-z]+\s*=\s*\d+"#, #"(?:INV|PO)-\d{4}"#, #"a{2,5}"#, #"\(\d+\)+"#, #"[(+*]+"#] {137            #expect(!BoundedRegex.looksCatastrophic(pattern), "\(pattern)")138        }139    }140141    @Test func timeLimitStopsACatastrophicMatch() {142        // With the static refusal switched off, the wall-clock limit is what protects the app.143        let text = String(repeating: "a", count: 40) + "b"144        let start = Date()145        do {146            _ = try BoundedRegex.matches(pattern: "(a+)+$", in: text, timeLimit: 0.1, refuseRiskyPatterns: false)147            Issue.record("the match should have been stopped")148        } catch { #expect((error as? ToolError)?.message.contains("was stopped") == true) }149        #expect(Date().timeIntervalSince(start) < 3)150        // An alternation the static check does not recognise is caught the same way.151        let start2 = Date()152        #expect(throws: ToolError.self) { try BoundedRegex.matches(pattern: "(a|aa|a?a)+$", in: text, timeLimit: 0.1, refuseRiskyPatterns: false) }153        #expect(Date().timeIntervalSince(start2) < 3)154    }155156    @Test func regexInputLimits() {157        #expect(throws: ToolError.self) { try BoundedRegex.matches(pattern: "a", in: String(repeating: "a", count: BoundedRegex.maxInputCharacters + 1)) }158        #expect(throws: ToolError.self) { try BoundedRegex.matches(pattern: String(repeating: "a", count: BoundedRegex.maxPatternLength + 1), in: "a") }159        #expect((try? BoundedRegex.matches(pattern: "a", in: String(repeating: "a", count: 1000), maxMatches: 7))?.count == 7)160    }161162    @Test func unitConversion() throws {163        func convert(_ value: Double, _ from: String, _ to: String) throws -> String { UnitConverter.format(try UnitConverter.convert(value, from: from, to: to)) }164        #expect(try convert(5, "km", "mi") == "3.10685596119")165        #expect(try convert(1, "mile", "km") == "1.609344")166        #expect(try convert(12, "in", "cm") == "30.48")167        #expect(try convert(6, "ft", "m") == "1.8288")168        #expect(try convert(100, "F", "C") == "37.7777777778")169        #expect(try convert(-40, "celsius", "fahrenheit") == "-40")170        #expect(try convert(0, "C", "K") == "273.15")171        #expect(try convert(300, "K", "C") == "26.85")172        #expect(try convert(10, "lb", "kg") == "4.5359237")173        #expect(try convert(1, "kg", "oz") == "35.2739619496")174        #expect(try convert(1, "GiB", "MB") == "1073.741824")175        #expect(try convert(1, "GB", "MiB") == "953.674316406")176        #expect(try convert(8, "bit", "B") == "1")177        #expect(try convert(2.5, "h", "min") == "150")178        #expect(try convert(1, "week", "hours") == "168")179        #expect(try convert(1, "cup", "ml") == "236.5882365")180        #expect(try convert(1, "gal", "l") == "3.785411784")181        #expect(try convert(0, "m", "ft") == "0")182        #expect(throws: ToolError.self) { try convert(1, "km", "kg") }183        #expect(throws: ToolError.self) { try convert(1, "parsec", "km") }184        #expect(throws: ToolError.self) { try convert(-300, "C", "K") }185        #expect(throws: ToolError.self) { try convert(-1, "K", "C") }186    }187188    @Test func unitTool() async throws {189        let tool = UnitConvertTool()190        #expect(try await runTool(tool, ["value": 26.2, "from": "miles", "to": "km"]) == "26.2 mi = 42.1648128 km")191        #expect(await toolError(tool, ["value": "26", "from": "mi", "to": "km"])?.contains("“value” must be of type number, got string") == true)192        #expect(await toolError(tool, ["value": 1, "from": "km", "to": "s"])?.contains("cannot be converted") == true)193        #expect(await toolError(tool, ["value": 1, "from": "cubits", "to": "m"])?.contains("Supported units") == true)194    }195}196
Files main
Menu

Theme