SPB Git

Repository Public

RulesTests.swift 8.6 KB 166 lines swift

1import Foundation2import Testing3import SheetCore4import SheetUI5@testable import FeatureAudit67@MainActor @Suite struct RuleEditorTests {8    nonisolated static let ranges = [RangeRef(a1: "A1:B10")!, RangeRef(a1: "D2:D5")!]9    static let style: DiffStyle = { var s = DiffStyle(bold: true, italic: nil, textColor: RGBA(hex: 0x9C0006), fill: RGBA(hex: 0xFFC7CE)); s.strikethrough = true; return s }()1011    nonisolated static var everyKind: [ConditionalRuleKind] {12        [13            .cellIs(op: "greaterThan", formulas: ["100"]),14            .cellIs(op: "between", formulas: ["1", "$C$1*2"]),15            .cellIs(op: "notEqual", formulas: ["\"done\""]),16            .formula("$C1>AVERAGE($C:$C)"),17            .colorScale(points: [ScalePoint(kind: "min", color: RGBA(hex: 0xFFFFFF)), ScalePoint(kind: "max", color: RGBA(hex: 0x0891B2))]),18            .colorScale(points: [ScalePoint(kind: "num", value: "0", color: RGBA(hex: 0xF8696B)), ScalePoint(kind: "percentile", value: "50", color: RGBA(hex: 0xFFEB84)), ScalePoint(kind: "formula", value: "MAX($A:$A)", color: RGBA(hex: 0x63BE7B))]),19            .dataBar(min: ScalePoint(kind: "min"), max: ScalePoint(kind: "percent", value: "90"), color: RGBA(hex: 0x5B5BF0)),20            .iconSet(name: "3Arrows", thresholds: [ScalePoint(kind: "percent", value: "33"), ScalePoint(kind: "percent", value: "67")], reversed: false),21            .iconSet(name: "5Rating", thresholds: [ScalePoint(kind: "num", value: "10"), ScalePoint(kind: "num", value: "20"), ScalePoint(kind: "num", value: "30"), ScalePoint(kind: "num", value: "40")], reversed: true),22            .duplicates(unique: false), .duplicates(unique: true),23            .top(rank: 10, percent: false, bottom: false), .top(rank: 25, percent: true, bottom: true),24            .aboveAverage(above: true, equal: false), .aboveAverage(above: false, equal: true),25            .containsText("late"), .blanks(true), .blanks(false), .errors(true), .errors(false),26        ]27    }2829    @Test(arguments: everyKind) func roundTrip(kind: ConditionalRuleKind) throws {30        var rule = ConditionalFormat(ranges: Self.ranges, kind: kind, style: Self.style, priority: 4)31        rule.stopIfTrue = true32        let model = RuleEditorModel(rule: rule)33        if !model.type.usesStyle { rule.style = DiffStyle() }       // scales, bars and icons carry no differential style34        #expect(try model.build() == rule)35        #expect(model.problem == nil)36        #expect(model.rangeText == "A1:B10, D2:D5")37        #expect(RuleEditorModel(rule: try model.build()) == RuleEditorModel(rule: rule))38        #expect(!RuleDescriber.describe(rule).isEmpty)39    }4041    @Test func onePointPerIconFormIsReadAsCutPoints() throws {42        let stored = ConditionalFormat(ranges: Self.ranges, kind: .iconSet(name: "3TrafficLights1", thresholds: [43            ScalePoint(kind: "percent", value: "0"), ScalePoint(kind: "percent", value: "33"), ScalePoint(kind: "percent", value: "67")], reversed: false))44        let m = RuleEditorModel(rule: stored)45        #expect(m.iconThresholds.map(\.value) == ["33", "67"])46        guard case .iconSet(_, let t, _) = try m.build().kind else { Issue.record("icon set expected"); return }47        #expect(t.count == 2)48    }4950    @Test func problemsAreReported() {51        var m = RuleEditorModel(type: .cellValue, ranges: Self.ranges)52        #expect(m.problem == .missingValue)53        m.value1 = "=5"; m.op = "between"54        #expect(m.problem == .missingSecondValue)55        m.value2 = "SUM("56        #expect(m.problem == .invalidFormula("SUM("))57        m.value2 = "9"58        #expect(m.problem == nil)59        #expect((try? m.build())?.kind == .cellIs(op: "between", formulas: ["5", "9"]))60        m.rangeText = "not a range"61        #expect(m.problem == .invalidRange)62        m.rangeText = ""63        #expect(m.problem == .invalidRange)6465        var top = RuleEditorModel(type: .topBottom, ranges: Self.ranges)66        top.rank = 067        #expect(top.problem == .invalidRank)68        top.rank = 150; top.rankPercent = true69        #expect(top.problem == .invalidRank)70        var text = RuleEditorModel(type: .containsText, ranges: Self.ranges)71        #expect(text.problem == .missingText)72        text.text = "x"73        #expect(text.problem == nil)74        var scale = RuleEditorModel(type: .colorScale3, ranges: Self.ranges)75        #expect(scale.problem == nil)76        scale.points[1].value = "abc"77        #expect(scale.problem == .invalidThreshold)78        var icons = RuleEditorModel(type: .iconSet, ranges: Self.ranges)79        icons.setIconSet("5Arrows")80        #expect(icons.iconThresholds.map(\.value) == ["20", "40", "60", "80"] && icons.problem == nil)81    }8283    @Test func presetsBuildValidRules() throws {84        for p in RulePresets.Preset.allCases {85            let rule = RulePresets.rule(p, ranges: Self.ranges, priority: 2)86            #expect(rule.ranges == Self.ranges && rule.priority == 2)87            var expected = rule88            if !RuleEditorModel(rule: rule).type.usesStyle { expected.style = DiffStyle() }89            #expect(try RuleEditorModel(rule: rule).build() == expected, "\(p)")90        }91    }92}9394@MainActor @Suite struct RuleActionsTests {95    func session() -> WorkbookSession {96        let s = Fixture.session()97        Fixture.fill(s, (1...10).map { [String($0), String($0 * 2)] })98        return s99    }100    func kinds(_ s: WorkbookSession) -> [String] {101        let rules = s.sheet.meta.conditionalFormats102        return RuleActions.order(rules).map { RuleDescriber.describe(rules[$0]) }103    }104105    @Test func addReorderEditDeleteAreUndoable() {106        let s = session()107        s.select(Fixture.rg("A1:A10"))108        RuleActions.applyPreset(.duplicates, to: s)109        RuleActions.applyPreset(.dataBars, to: s)110        RuleActions.add(RulePresets.rule(.top10, ranges: [Fixture.rg("B1:B10")]), to: s)111        #expect(kinds(s) == ["Top 10", "Data bar", "Duplicate values"])            // newest first112        #expect(s.sheet.meta.conditionalFormats.map(\.priority).sorted() == [1, 2, 3])113        #expect(s.sheet.meta.conditionalFormats.allSatisfy { $0.ranges == [Fixture.rg("A1:A10")] || $0.ranges == [Fixture.rg("B1:B10")] })114115        RuleActions.move(from: 0, to: 2, in: s)116        #expect(kinds(s) == ["Data bar", "Duplicate values", "Top 10"])117        RuleActions.move(from: 2, to: 1, in: s)118        #expect(kinds(s) == ["Data bar", "Top 10", "Duplicate values"])119        s.undo()120        #expect(kinds(s) == ["Data bar", "Duplicate values", "Top 10"])121122        let idx = RuleActions.order(s.sheet.meta.conditionalFormats)[1]123        var edited = RuleEditorModel(rule: s.sheet.meta.conditionalFormats[idx])124        edited.type = .unique125        RuleActions.replace(at: idx, with: try! edited.build(), in: s)126        #expect(kinds(s) == ["Data bar", "Unique values", "Top 10"])                // keeps its place127        RuleActions.delete(at: idx, in: s)128        #expect(kinds(s) == ["Data bar", "Top 10"])129        #expect(s.sheet.meta.conditionalFormats.map(\.priority).sorted() == [1, 2])130        s.undo()131        #expect(kinds(s).count == 3)132        for _ in 0..<5 { s.undo() }133        #expect(s.sheet.meta.conditionalFormats.isEmpty)134    }135136    @Test func singleCellSelectionTargetsTheCurrentRegion() {137        let s = session()138        s.select(cell: CellRef(a1: "B4")!)139        #expect(RuleActions.targetRanges(s) == [Fixture.rg("A1:B10")])140        s.select(Fixture.rg("B:B"))141        #expect(RuleActions.targetRanges(s) == [Fixture.rg("B1:B10")])142    }143144    @Test func disableAndEnableSurviveUndo() {145        let s = session()146        s.select(Fixture.rg("A1:A10"))147        RuleActions.applyPreset(.top10, to: s)148        RuleActions.applyPreset(.dataBars, to: s)149        let top = s.sheet.meta.conditionalFormats.firstIndex { if case .top = $0.kind { true } else { false } }!150        RuleActions.disable(at: top, in: s)151        #expect(kinds(s) == ["Data bar"])152        #expect(RuleActions.disabledRules(in: s).map(RuleDescriber.describe) == ["Top 10"])153        #expect(s.workbook.attachments[DisabledRules.attachmentKey] != nil)154        s.undo()                                                    // the rule is active again: not listed as disabled155        #expect(kinds(s).count == 2 && RuleActions.disabledRules(in: s).isEmpty)156        s.redo()157        #expect(RuleActions.disabledRules(in: s).count == 1)158        RuleActions.enable(RuleActions.disabledRules(in: s)[0], in: s)159        #expect(kinds(s) == ["Data bar", "Top 10"] && RuleActions.disabledRules(in: s).isEmpty)160        s.undo()161        #expect(RuleActions.disabledRules(in: s).count == 1)162        RuleActions.deleteDisabled(RuleActions.disabledRules(in: s)[0], in: s)163        #expect(RuleActions.disabledRules(in: s).isEmpty && s.workbook.attachments[DisabledRules.attachmentKey] == nil)164    }165}166
Files main
Menu

Theme