Cotton code
107 lines · 5.9 KB · SwiftRaw
// Comms Dev over invented people (-chat-warm-seed YES): on every place// (Chats, Calls, You), at the default text size and the largest, the// content scrolled to its end stands clear of the floating pill and below the// status bar (owner's iPhone, Comms build 19: words under the clock, the last// row cut by the pill).import UIKitimport XCTestfinal class ChatEdgesTests: XCTestCase {    private static let largest = "UICTContentSizeCategoryAccessibilityXXXL"    private func launched(_ place: String, size: String?) -> XCUIApplication {        let app = XCUIApplication()        app.launchArguments += ["-chat-warm-seed", "YES", "-chat-warm-place", place]        if let size { app.launchArguments += ["-UIPreferredContentSizeCategoryName", size] }        app.launch()        return app    }    /// The bottom of the status bar, from SpringBoard; the usual 54 points when it cannot be read.    private var statusBarFoot: CGFloat {        let bar = XCUIApplication(bundleIdentifier: "com.apple.springboard").statusBars.firstMatch        return bar.exists && bar.frame.maxY > 0 ? bar.frame.maxY : 54    }    /// Scrolled to its end, `place`'s lowest element ends above the pill and starts below the status bar.    private func clearsTheEdges(_ place: String, container: (XCUIApplication) -> XCUIElement, rows: (XCUIElement) -> XCUIElementQuery, size: String?) {        let app = launched(place, size: size)        let pill = app.otherElements["chat-places"]        XCTAssertTrue(pill.waitForExistence(timeout: 30), "the pill floats")        let page = container(app)        XCTAssertTrue(page.waitForExistence(timeout: 30), "\(place) stands")        XCTAssertTrue(rows(page).firstMatch.waitForExistence(timeout: 15), "\(place) has rows")        // Part way: whatever has scrolled up under the status bar is not drawn there.        page.swipeUp(velocity: .slow)        sleep(1)        nothingUnderTheClock(app, "\(place) at \(size ?? "default")")        for _ in 0..<8 { page.swipeUp(velocity: .fast) }        sleep(1)        keepShot("fb-edges-\(place)-\(size == nil ? "default" : "largest")-end")        let shown = rows(page).allElementsBoundByIndex.map { $0.frame }.filter { !$0.isEmpty && $0.minY < app.frame.maxY }        guard let last = shown.max(by: { $0.maxY < $1.maxY }) else { return XCTFail("\(place): no row") }        XCTAssertLessThanOrEqual(last.maxY, pill.frame.minY + 0.5, "\(place) at \(size ?? "default"): the last row \(last) ends above the pill \(pill.frame)")        XCTAssertGreaterThanOrEqual(last.minY, statusBarFoot, "\(place) at \(size ?? "default"): the last row \(last) is below the status bar")    }    /// The band under the clock, left of it (where the page's words start), holds no ink: only the ground.    private func nothingUnderTheClock(_ app: XCUIApplication, _ what: String) {        let screen = XCUIScreen.main.screenshot()        keepShot(screen, "fb-edges-\(what.replacingOccurrences(of: " at ", with: "-"))-scrolled")        guard let image = screen.image.cgImage else { return XCTFail("no screenshot") }        let scale = CGFloat(image.width) / app.frame.width        let (w, h) = (image.width, image.height)        var pixels = [UInt8](repeating: 0, count: w * h * 4)        let drawn = pixels.withUnsafeMutableBytes { raw -> Bool in            guard let context = CGContext(data: raw.baseAddress, width: w, height: h, bitsPerComponent: 8, bytesPerRow: w * 4,                                          space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { return false }            context.draw(image, in: CGRect(x: 0, y: 0, width: w, height: h))            return true        }        guard drawn else { return XCTFail("the screenshot did not draw") }        var inked = 0        for y in stride(from: Int(6 * scale), to: Int((statusBarFoot - 4) * scale), by: 2) {            for x in stride(from: Int(18 * scale), to: Int(44 * scale), by: 2) {                let at = (y * w + x) * 4                let light = (Int(pixels[at]) + Int(pixels[at + 1]) + Int(pixels[at + 2])) / 3                if light < 140 { inked += 1 }            }        }        XCTAssertEqual(inked, 0, "\(what): words drawn under the status bar")    }    private func chats(_ size: String?) {        clearsTheEdges("chats", container: { $0.tables["chat-list"] }, rows: { $0.cells }, size: size)    }    private func calls(_ size: String?) {        clearsTheEdges("calls", container: { $0.scrollViews["chat-calls"] }, rows: { $0.buttons.matching(identifier: "chat-call-row") }, size: size)    }    private func you(_ size: String?) {        clearsTheEdges("you", container: { $0.scrollViews["you"] }, rows: { $0.descendants(matching: .any).matching(NSPredicate(format: "elementType IN %@", [XCUIElement.ElementType.staticText.rawValue, XCUIElement.ElementType.button.rawValue, XCUIElement.ElementType.switch.rawValue])) }, size: size)    }    // RULE: Chats' last conversation scrolls clear of the pill.    func testChatsClearThePill() { chats(nil) }    func testChatsClearThePillAtTheLargestText() { chats(Self.largest) }    // RULE: Calls' last call scrolls clear of the pill.    func testCallsClearThePill() { calls(nil) }    func testCallsClearThePillAtTheLargestText() { calls(Self.largest) }    // RULE: You's last row (About, the last of the seven) scrolls clear of the pill.    func testYouClearsThePill() { you(nil) }    func testYouClearsThePillAtTheLargestText() { you(Self.largest) }}/// Shots for the record, written where `COMMS_SHOTS` (TEST_RUNNER_COMMS_SHOTS) names, when it does.extension XCTestCase {    func keepShot(_ name: String) { keepShot(XCUIScreen.main.screenshot(), name) }    func keepShot(_ screen: XCUIScreenshot, _ name: String) {        guard let dir = ProcessInfo.processInfo.environment["COMMS_SHOTS"], !dir.isEmpty else { return }        try? screen.pngRepresentation.write(to: URL(fileURLWithPath: dir).appendingPathComponent(name + ".png"))    }}