示例工程 13-error-handling

13-error-handling/Tests/Ch13KitTests/CleanupTests.swift

swift · 1.2 KB

import Testing
 
@testable import Ch13Kit
 
@Suite("清理与 rethrows")
struct CleanupTests {
    @Test func deferRunsAfterSuccess() {
        #expect(CleanupLab.loadWithCleanup("ok.md") == ["open", "read", "close", "success"])
    }
 
    @Test func deferRunsBeforeCatch() {
        #expect(CleanupLab.loadWithCleanup("/root/x") == ["open", "close", "failure"])
    }
 
    @Test func rethrowsMapsWhenTransformDoesNotThrow() {
        let values = CleanupLab.mapValues([1, 2, 3]) { $0 * 2 }
        #expect(values == [2, 4, 6])
    }
 
    @Test func rethrowsPropagatesTransformError() {
        #expect(throws: LoadError.corrupted(line: 0)) {
            _ = try CleanupLab.mapValues(["1", "x"], CleanupLab.parseInt)
        }
    }
}
 
@Suite("类型化抛错")
struct TypedThrowsTests {
    @Test func typedErrorsKeepReason() {
        #expect(TypedParser.reason("") == "empty")
        #expect(TypedParser.reason("x") == "notANumber(x)")
        #expect(TypedParser.reason("3") == "ok")
    }
 
    @Test func tryQuestionStillLosesReason() {
        #expect(TypedParser.parseOrZero("x") == 0)
        #expect(TypedParser.parseOrZero("3") == 3)
    }
 
    @Test func parseAcceptsValidInput() throws {
        #expect(try TypedParser.parse("42") == 42)
    }
}