SPB Git

Repository Public MIT

CalculatorTests.swift 13.7 KB 245 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Astra9// File             : Tests/AstraAgentsTests/CalculatorTests.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 CalculatorTests {94    static let table: [(String, String)] = [95        ("1 + 2 * 3", "7"), ("(1 + 2) * 3", "9"), ("2 ^ 3 ^ 2", "512"), ("-2 ^ 2", "-4"), ("(-2) ^ 2", "4"), ("2 ^ -1", "0.5"),96        ("10 / 4", "2.5"), ("10 / 5", "2"), ("7 % 3", "1"), ("-7 % 3", "-1"), ("mod(-7, 3)", "2"), ("mod(7, -3)", "-2"),97        ("1 - 2 - 3", "-4"), ("2 * 3 % 4", "2"), ("100 / 10 / 5", "2"), ("0.1 + 0.2", "0.3"), ("1e3", "1000"), ("1.5e-3 * 2", "0.003"),98        ("2.5E2", "250"), ("sqrt(16)", "4"), ("sqrt(2)", "1.4142135623731"), ("cbrt(27)", "3"), ("cbrt(-8)", "-2"), ("abs(-5)", "5"),99        ("abs(-2.5)", "2.5"), ("ln(e)", "1"), ("log10(1000)", "3"), ("log2(8)", "3"), ("log(8, 2)", "3"), ("log(100)", "2"), ("exp(0)", "1"),100        ("sin(0)", "0"), ("sin(pi)", "0"), ("cos(pi)", "-1"), ("tan(pi / 4)", "1"), ("asin(1)", "1.5707963267949"), ("acos(1)", "0"),101        ("sinh(0)", "0"), ("cosh(0)", "1"), ("tanh(0)", "0"), ("floor(2.7)", "2"), ("floor(-2.7)", "-3"), ("ceil(2.1)", "3"),102        ("ceil(-2.1)", "-2"), ("round(2.5)", "3"), ("round(-2.5)", "-3"), ("round(3.14159, 2)", "3.14"), ("round(1234.5, -2)", "1200"),103        ("trunc(-2.7)", "-2"), ("min(3, 1, 2)", "1"), ("max(3, 1, 2)", "3"), ("max(1.5, 2)", "2"), ("factorial(5)", "120"), ("5!", "120"),104        ("3!!", "720"), ("20!", "2432902008176640000"), ("factorial(0)", "1"), ("nCr(5, 2)", "10"), ("nCr(52, 5)", "2598960"),105        ("nPr(5, 2)", "20"), ("nPr(10, 3)", "720"), ("nCr(5, 7)", "0"), ("gcd(12, 18)", "6"), ("gcd(12, 18, 8)", "2"), ("lcm(4, 6)", "12"),106        ("lcm(2, 3, 4)", "12"), ("pi", "3.14159265358979"), ("e", "2.71828182845905"), ("tau / 2 - pi", "0"), ("2 × 3", "6"), ("8 ÷ 2", "4"),107        ("5 − 3", "2"), ("2 ** 10", "1024"), ("2 ^ 62", "4611686018427387904"), ("1 / 3", "0.333333333333333"), ("2 / 3", "0.666666666666667"),108        ("--5", "5"), ("-(-5)", "5"), ("+5", "5"), ("2 * -3", "-6"), ("(((((1)))))", "1"), ("3 * (2 + 4) / 2 - 1", "8"), (".5 + .5", "1"),109        ("1e2 + 1", "101"), ("1000000 * 1000000", "1000000000000"), ("sqrt(1e10)", "100000"), ("2 ^ 0.5 * 2 ^ 0.5", "2"), ("10 % 4 + 1", "3"),110        ("25 ^ 0.5", "5"), ("0 ^ 0", "1"), ("12345678 * 87654321", "1082152022374638"), ("7 / 2 * 2", "7"), ("  42  ", "42"),111        ("PI * 2 - TAU", "0"), ("Sqrt(9) + ABS(-1)", "4"), ("π", "3.14159265358979"), ("2^10 - 1", "1023"), ("5.5 % 2", "1.5"),112    ]113114    @Test(arguments: table.indices)115    func evaluatesTable(_ index: Int) throws {116        let (expression, expected) = Self.table[index]117        #expect(try Calculator.compute(expression) == expected, "\(expression)")118    }119120    @Test func tableIsLargeEnough() { #expect(Self.table.count >= 60) }121122    @Test func precedenceAndAssociativity() throws {123        #expect(try Calculator.compute("2 + 3 * 4 ^ 2") == "50")124        #expect(try Calculator.compute("2 ^ 2 ^ 3") == "256")          // right associative: 2^(2^3)125        #expect(try Calculator.compute("8 - 3 - 2") == "3")            // left associative126        #expect(try Calculator.compute("16 / 4 / 2") == "2")127        #expect(try Calculator.compute("-3 ^ 2") == "-9")              // power binds tighter than unary minus128        #expect(try Calculator.compute("2 ^ -2") == "0.25")129        #expect(try Calculator.compute("-2 * -2") == "4")130        #expect(try Calculator.compute("3! ^ 2") == "36")              // postfix binds tighter than power131        #expect(try Calculator.compute("2 * (3 + 4) * 5") == "70")132    }133134    @Test func exactIntegersWhileTheyFit() throws {135        #expect(try Calculator.evaluate("9223372036854775806 + 1") == .integer(9_223_372_036_854_775_807))136        #expect(try Calculator.evaluate("3037000499 * 3037000499") == .integer(9_223_372_030_926_249_001))137        #expect(try Calculator.evaluate("7 * 6") == .integer(42))138        #expect(try Calculator.evaluate("6 / 3") == .integer(2))139        #expect(try Calculator.evaluate("7 / 2") == .real(3.5))140        #expect(try Calculator.evaluate("3 ^ 39") == .integer(4_052_555_153_018_976_267))141        #expect(try Calculator.evaluate("nCr(60, 30)") == .integer(118_264_581_564_861_424))142    }143144    @Test func largeValuesFallBackToFloatingPoint() throws {145        #expect(try Calculator.compute("9223372036854775807 + 1") == "9.22337203685478e+18")146        #expect(try Calculator.compute("2 ^ 64") == "1.84467440737096e+19")147        #expect(try Calculator.compute("170!") == "7.25741561530799e+306")148        #expect(try Calculator.compute("nCr(100, 50)") == "1.00891344545564e+29")149        #expect(try Calculator.compute("99999999999999999999") == "1e+20")150        #expect(try Calculator.compute("1e300 * 1e5") == "1e+305")151        #expect(try Calculator.compute("-9223372036854775807 - 2") == "-9.22337203685478e+18")152    }153154    @Test func degrees() throws {155        let cases = [("sin(30)", "0.5"), ("cos(60)", "0.5"), ("tan(45)", "1"), ("sin(180)", "0"), ("cos(90)", "0"), ("asin(1)", "90"),156                     ("acos(0)", "90"), ("atan(1)", "45"), ("atan2(1, 1)", "45"), ("sin(90) + cos(0)", "2")]157        for (expression, expected) in cases { #expect(try Calculator.compute(expression, angle: .degrees) == expected, "\(expression)") }158        #expect(try Calculator.compute("atan2(1, 1)") == "0.785398163397448")159    }160161    @Test func divisionByZero() {162        for expression in ["1 / 0", "5 % 0", "1 / (2 - 2)", "0 ^ -1", "mod(3, 0)", "1.5 / 0.0"] {163            #expect(throws: CalculatorError.divisionByZero, "\(expression)") { try Calculator.evaluate(expression) }164        }165    }166167    @Test func domainErrors() {168        for expression in ["sqrt(-1)", "ln(0)", "log10(-5)", "log(8, 1)", "asin(2)", "acos(-1.5)", "tan(pi / 2)", "(-8) ^ 0.5", "factorial(-1)",169                           "factorial(2.5)", "nCr(-1, 2)", "gcd(1.5, 2)"] {170            do { _ = try Calculator.evaluate(expression); Issue.record("\(expression) should fail") }171            catch let error as CalculatorError {172                guard case .domain = error else { Issue.record("\(expression): \(error)"); continue }173                #expect(error.errorDescription?.hasPrefix("Math error") == true)174            } catch { Issue.record("\(expression): \(error)") }175        }176        #expect(throws: CalculatorError.self) { try Calculator.evaluate("tan(90)", angle: .degrees) }177    }178179    @Test func overflow() {180        for expression in ["171!", "1e308 * 10", "10 ^ 400", "exp(1000)", "nCr(5000, 2500)"] {181            #expect(throws: CalculatorError.overflow, "\(expression)") { try Calculator.evaluate(expression) }182        }183    }184185    @Test func syntaxErrors() {186        for expression in ["", "   ", "1 +", "(1 + 2", "1 2", "1 $ 2", "2 * * 3", ")", "1 + 2)", "sqrt(4", "1,2", "3 +* 4", "1..2", "."] {187            do { _ = try Calculator.evaluate(expression); Issue.record("“\(expression)” should fail") }188            catch let error as CalculatorError {189                guard case .syntax = error else { Issue.record("“\(expression)”: \(error)"); continue }190            } catch { Issue.record("\(error)") }191        }192    }193194    @Test func unknownNamesAndArity() {195        #expect(throws: CalculatorError.unknownName("foo")) { try Calculator.evaluate("foo(1)") }196        #expect(throws: CalculatorError.unknownName("x")) { try Calculator.evaluate("x + 1") }197        #expect(throws: CalculatorError.unknownName("import")) { try Calculator.evaluate("import os") }198        #expect(throws: CalculatorError.unknownName("system")) { try Calculator.evaluate("system(1)") }199        for expression in ["sqrt()", "sqrt(1, 2)", "atan2(1)", "nCr(5)", "min()", "gcd(4)", "round(1, 2, 3)"] {200            do { _ = try Calculator.evaluate(expression); Issue.record("\(expression) should fail") }201            catch let error as CalculatorError {202                guard case .arity = error else { Issue.record("\(expression): \(error)"); continue }203            } catch { Issue.record("\(error)") }204        }205    }206207    @Test func limits() {208        let long = String(repeating: "1+", count: 600) + "1"209        #expect(throws: CalculatorError.self) { try Calculator.evaluate(long) }210        let deep = String(repeating: "(", count: 200) + "1" + String(repeating: ")", count: 200)211        do { _ = try Calculator.evaluate(deep); Issue.record("deep nesting should fail") }212        catch let error as CalculatorError { if case .tooComplex = error {} else { Issue.record("\(error)") } }213        catch { Issue.record("\(error)") }214        let minuses = String(repeating: "-", count: 300) + "1"215        #expect(throws: CalculatorError.self) { try Calculator.evaluate(minuses) }216        let powers = Array(repeating: "2", count: 200).joined(separator: "^")217        #expect(throws: CalculatorError.self) { try Calculator.evaluate(powers) }218        // Inside the limits, long flat expressions are fine.219        let flat = Array(repeating: "1", count: 400).joined(separator: "+")220        #expect((try? Calculator.compute(flat)) == "400")221        let nested = String(repeating: "(", count: 20) + "7" + String(repeating: ")", count: 20)222        #expect((try? Calculator.compute(nested)) == "7")223    }224225    @Test func formatting() {226        #expect(Calculator.format(.real(-0.0)) == "0")227        #expect(Calculator.format(.real(1e15)) == "1e+15")228        #expect(Calculator.format(.real(123456789.125)) == "123456789.125")229        #expect(Calculator.format(.real(0.000001234)) == "1.234e-06")230        #expect(Calculator.format(.integer(.min)) == "-9223372036854775808")231        #expect(Calculator.format(.real(5)) == "5")232    }233234    @Test func toolRunsAndReportsErrorsReadably() async throws {235        let tool = CalculatorTool()236        #expect(tool.risk == .safe)237        #expect(try await runTool(tool, ["expression": "nCr(52, 5) / 4"]) == "649740")238        #expect(try await runTool(tool, ["expression": "sin(90)", "angle_unit": "degrees"]) == "1")239        #expect(await toolError(tool, ["expression": "1 / 0"]) == "Math error: division by zero.")240        #expect(await toolError(tool, ["expression": "frobnicate(2)"])?.contains("Unknown name “frobnicate”") == true)241        #expect(await toolError(tool, ["expression": "1", "angle_unit": "gradians"])?.contains("must be one of") == true)242        #expect(await toolError(tool, ["expr": "1"])?.contains("expression: this required property is missing") == true)243    }244}245
Files main
Menu

Theme