示例工程 38-gestures

38-gestures/Tests/Ch38KitTests/GestureTests.swift

swift · 2.7 KB

import SwiftUI
import Testing
 
@testable import Ch38Kit
 
@Suite("拖拽计算")
struct DragMathTests {
    private let limit = CGSize(width: 80, height: 40)
 
    @Test func clampKeepsInsideBounds() {
        let result = DragMath.clamped(CGSize(width: 120, height: -70), limit: limit)
        #expect(result == CGSize(width: 80, height: -40))
    }
 
    @Test func clampKeepsSmallValues() {
        let result = DragMath.clamped(CGSize(width: 12, height: -8), limit: limit)
        #expect(result == CGSize(width: 12, height: -8))
    }
 
    @Test func projectionAddsVelocityAndClamps() {
        let result = DragMath.projected(
            CGSize(width: 10, height: 10),
            velocity: CGSize(width: 200, height: -100),
            limit: limit
        )
        #expect(result == CGSize(width: 40, height: -5))
    }
 
    @Test func snappingRoundsToGrid() {
        let result = DragMath.snapped(CGSize(width: 34, height: -26), grid: 20)
        #expect(result == CGSize(width: 40, height: -20))
    }
 
    @Test func snappingIsIdempotent() {
        let once = DragMath.snapped(CGSize(width: 39, height: 4), grid: 20)
        let twice = DragMath.snapped(once, grid: 20)
        #expect(once == twice)
    }
}
 
@Suite("组合")
struct CompositionTests {
    @Test func allCompositionsHaveSummaries() {
        for item in GestureComposition.allCases {
            #expect(!item.summary.isEmpty)
        }
    }
 
    @Test func simultaneouslyIsFirst() {
        #expect(GestureComposition.allCases.first == .simultaneously)
    }
}
 
@Suite("视图")
struct GestureViewTests {
    @Test @MainActor func boardRendersAtFixedSize() throws {
        let image = try #require(ImageRenderer(content: GestureBoard()).cgImage)
        #expect(image.width == 420)
        #expect(image.height > 200)
    }
}
 
@Suite("截图")
struct ScreenshotTests {
    @Test @MainActor func shotMatchesExpectedWidth() throws {
        let renderer = ImageRenderer(content: GestureBoard())
        renderer.scale = 2
        let image = try #require(renderer.cgImage)
        #expect(image.width == 840)
 
        let url = URL(fileURLWithPath: #filePath)
            .deletingLastPathComponent()
            .deletingLastPathComponent()
            .deletingLastPathComponent()
            .appendingPathComponent("shots/gesture-board.png")
        guard !FileManager.default.fileExists(atPath: url.path) else { return }
        let data = try #require(
            NSBitmapImageRep(cgImage: image).representation(using: .png, properties: [:])
        )
        try FileManager.default.createDirectory(
            at: url.deletingLastPathComponent(),
            withIntermediateDirectories: true
        )
        try data.write(to: url)
    }
}