SPB Git

Repository Public MIT

TestSupport.swift 1.7 KB 52 lines swift

1// ORIX Calc2// File: Packages/ORIXUnits/Tests/ORIXUnitsTests/TestSupport.swift3// Description: Shared helpers for the ORIXUnits test suite.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai78import Foundation9import Testing1011@testable import ORIXUnits1213let catalog = UnitCatalog.standard1415/// Exact decimal from a string literal.16func dec(_ text: String) -> Decimal {17    guard let value = Decimal(string: text, locale: Locale(identifier: "en_US_POSIX")) else {18        fatalError("bad decimal literal \(text)")19    }20    return value21}2223/// Unit by id; a missing id is recorded as a test failure by the caller's `#require`.24func unit(_ id: String) throws -> UnitDefinition {25    try #require(catalog.unit(id: id), "missing unit \(id)")26}2728func convert(_ value: String, _ from: String, _ to: String, mode: ConversionMode = .absolute) throws -> Decimal {29    try UnitConverter.convert(dec(value), from: try unit(from), to: try unit(to), mode: mode)30}3132func magnitude(_ value: Decimal) -> Decimal { value < 0 ? -value : value }3334/// |a − b| ≤ tolerance × |b| (absolute when b is zero).35func isClose(_ a: Decimal, _ b: Decimal, relative tolerance: Decimal) -> Bool {36    if b == 0 { return magnitude(a) <= tolerance }37    return magnitude(a - b) <= tolerance * magnitude(b)38}3940func isClose(_ a: Double, _ b: Double, relative tolerance: Double) -> Bool {41    if b == 0 { return abs(a) <= tolerance }42    return abs(a - b) <= tolerance * abs(b)43}4445/// Number of significant decimal digits of a value.46func significantDigits(_ value: Decimal) -> Int {47    var digits = Array(value.description.filter(\.isNumber))48    while digits.first == "0" { digits.removeFirst() }49    while digits.last == "0" { digits.removeLast() }50    return digits.count51}52
Files main
Menu

Theme