Cotton code
228 lines · 13.2 KB · SwiftRaw
// Several pictures to WhatsApp, one grid (owner, FEEDBACK-4 B3 on Comms 26:// several photos sent with words stood as a bubble each, with no preview// before or after sending; CONTRACT.md "Several pictures to WhatsApp, one// grid"). Over Chat Dev's invented chats (-chat-warm-seed YES: the core's own// answers on a copy linked through an invented Mac, written by// write_chat_warm_fixture), Photos and videos hands over an invented picture// each time (-chat-warm-pick YES), each a shade of its own. Three picked wait// in Tara's writing box with the caption; Send stands them as one grid at// once, each tile drawn from the phone's own file; they land a few seconds// later (-chat-warm-wa-land <s>), a message each, and still stand as one grid;// a tap on the third tile opens that picture, before and after they land. At// the default text size and the largest. Shots wa-grid-*.import XCTestfinal class ChatWhatsAppGridTests: XCTestCase {    private let tara = "11111111-1111-4111-8111-0000000000f1"    private static let largestText = ["-UIPreferredContentSizeCategoryName", "UICTContentSizeCategoryAccessibilityXXXL"]    private let caption = "From the invented train"    /// One tile's side in the grid (ChatAlbumView: 248 points, two to a row, 2 apart).    private let side: CGFloat = 123    override func setUp() {        continueAfterFailure = false        XCUIDevice.shared.orientation = .portrait    }    private func keep(_ name: String) {        let shot = XCTAttachment(screenshot: XCUIScreen.main.screenshot())        shot.name = name        shot.lifetime = .keepAlways        add(shot)    }    // MARK: the screen's own colours    private struct Screen {        let bytes: [UInt8]        let width: Int        let height: Int        let scale: CGFloat        init() {            let image = XCUIScreen.main.screenshot().image            let cg = image.cgImage!            width = cg.width            height = cg.height            scale = CGFloat(cg.width) / image.size.width            var bytes = [UInt8](repeating: 0, count: cg.width * cg.height * 4)            let context = CGContext(data: &bytes, width: cg.width, height: cg.height, bitsPerComponent: 8, bytesPerRow: cg.width * 4,                                    space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!            context.draw(cg, in: CGRect(x: 0, y: 0, width: cg.width, height: cg.height))            self.bytes = bytes        }        func ink(_ point: CGPoint) -> [Int] {            let x = min(width - 1, max(0, Int(point.x * scale))), y = min(height - 1, max(0, Int(point.y * scale)))            let i = (y * width + x) * 4            return [Int(bytes[i]), Int(bytes[i + 1]), Int(bytes[i + 2])]        }        /// The invented pictures picked are cool blue-greens (their previews too); the chat's own grounds are warm.        func picture(_ point: CGPoint) -> Bool {            let c = ink(point)            return c[1] > c[0] + 10 && c[2] > c[0] + 4        }    }    /// The grid's top-left in `bubble`: in its second row (the third tile, at the left), the first picture ink from    /// the left, then that column's last picture ink from the bottom, two tiles up.    private func gridOrigin(_ bubble: XCUIElement, _ screen: Screen) -> CGPoint? {        let f = bubble.frame        let width = XCUIApplication().windows.firstMatch.frame.width        for y in stride(from: f.minY + side + 40, through: f.minY + side + 110, by: 10) {            guard let x = stride(from: CGFloat(0), to: width, by: 1).first(where: { screen.picture(CGPoint(x: $0, y: y)) }) else { continue }            let column = x + 30            guard let bottom = stride(from: f.maxY, to: y, by: -1).first(where: { screen.picture(CGPoint(x: column, y: $0)) }) else { continue }            return CGPoint(x: x, y: bottom + 1 - (side * 2 + 2))        }        return nil    }    /// The keyboard put away (the thread's own interactive drag, past the keyboard's top) and the chat back at its    /// newest, then the thread dragged by what is measured (held at the end so nothing flings) until `bubble`'s top    /// stands just below the chat's header, its grid clear of the writing box.    @MainActor private func inView(_ bubble: XCUIElement, _ app: XCUIApplication) {        if app.keyboards.firstMatch.exists {            let from = app.windows.firstMatch.coordinate(withNormalizedOffset: CGVector(dx: 0.3, dy: 0.3))            from.press(forDuration: 0.05, thenDragTo: app.windows.firstMatch.coordinate(withNormalizedOffset: CGVector(dx: 0.3, dy: 0.99)))            XCTAssertTrue(app.keyboards.firstMatch.waitForNonExistence(timeout: 5), "the keyboard went down")            let jump = app.buttons["chat-jump"]            if jump.waitForExistence(timeout: 2), jump.isHittable { jump.tap() }            Thread.sleep(forTimeInterval: 0.8)        }        let target = app.buttons["chat-person"].frame.maxY + 12        for _ in 0..<6 {            let was = bubble.frame.minY            let off = target - was            if abs(off) < 16 { break }            let dy = max(-300, min(300, off))            let start = app.windows.firstMatch.coordinate(withNormalizedOffset: CGVector(dx: 0.3, dy: dy > 0 ? 0.3 : 0.6))            start.press(forDuration: 0.05, thenDragTo: start.withOffset(CGVector(dx: 0, dy: dy)), withVelocity: .slow, thenHoldForDuration: 0.4)            // The newest message cannot be drawn higher than the chat's end allows (at the default size the grid fits            // above the box as it stands): once a drag moves it no more, it is as far into view as it goes.            if abs(bubble.frame.minY - was) < 2 { break }        }        Thread.sleep(forTimeInterval: 0.4)    }    /// Each tile's centre: two to a row, the second clipped at the bubble's edge.    private func centres(_ origin: CGPoint) -> [CGPoint] {        let half = side / 2        return [CGPoint(x: origin.x + half, y: origin.y + half), CGPoint(x: origin.x + side + 2 + half * 0.9, y: origin.y + half),                CGPoint(x: origin.x + half, y: origin.y + side + 2 + half), CGPoint(x: origin.x + side + 2 + half * 0.9, y: origin.y + side + 2 + half)]    }    /// Three tiles, each a picture now (never a blank box), and no fourth.    @MainActor private func threeTiles(_ bubble: XCUIElement, _ said: String) -> [CGPoint] {        inView(bubble, XCUIApplication())        let screen = Screen()        guard let origin = gridOrigin(bubble, screen) else {            keep("wa-grid-failed-\(said)")            XCTFail("\(said): no picture drawn in \(bubble.frame)")            return []        }        let at = centres(origin)        for (i, point) in at.prefix(3).enumerated() {            if !screen.picture(point) { keep("wa-grid-failed-\(said)-\(i)") }            XCTAssertTrue(screen.picture(point), "\(said): tile \(i + 1) is its picture, never a blank box: \(screen.ink(point)) at \(point), grid at \(origin)")        }        XCTAssertFalse(screen.picture(at[3]), "\(said): three tiles, no fourth: \(screen.ink(at[3])) at \(at[3])")        return Array(at.prefix(3))    }    // MARK: the walk    @MainActor private func open(_ extra: [String]) -> XCUIApplication {        let app = XCUIApplication()        app.launchArguments += ["-chat-warm-seed", "YES", "-chat-warm-pick", "YES", "-chat-warm-wa-land", "12", "-chat-warm-open", tara] + extra        app.launch()        XCTAssertTrue(app.descendants(matching: .any)["chat-composer"].firstMatch.waitForExistence(timeout: 30), "Tara's chat opened with a writing box")        // The card of a device asking to be let in can come down a few seconds in and move things: wait for it.        _ = ShellCard.refuse(app).waitForExistence(timeout: 6)        return app    }    /// The plus, then Photos and videos: one invented picture more waits in the box.    @MainActor private func pickOne(_ app: XCUIApplication) {        let plus = app.buttons["chat-attach"]        XCTAssertTrue(plus.waitForExistence(timeout: 5), "the plus: the core's writing box takes pictures here")        plus.tap()        let photos = app.buttons["chat-attach-photo"]        XCTAssertTrue(photos.waitForExistence(timeout: 5))        photos.tap()    }    /// Taps the third tile at `point`: the viewer opens on that picture, by the message it opens through.    @MainActor private func opensThird(_ app: XCUIApplication, at point: CGPoint, key: String, shot: String) {        app.windows.firstMatch.coordinate(withNormalizedOffset: .zero).withOffset(CGVector(dx: point.x, dy: point.y)).tap()        XCTAssertTrue(app.descendants(matching: .any)["chat-viewer"].firstMatch.waitForExistence(timeout: 5), "the viewer opened")        let picture = app.images["chat-viewer-picture-\(key)"]        XCTAssertTrue(picture.waitForExistence(timeout: 8), "the third tile opens the third picture (\(key))")        let window = app.windows.firstMatch.frame        XCTAssertLessThan(abs(picture.frame.midX - window.midX), 40, "it is the page shown: \(picture.frame)")        Thread.sleep(forTimeInterval: 0.5)        keep(shot)        app.buttons["chat-viewer-close"].tap()        XCTAssertTrue(app.descendants(matching: .any)["chat-viewer"].firstMatch.waitForNonExistence(timeout: 5), "the viewer closed")    }    @MainActor private func walk(_ extra: [String], _ shots: String) {        let app = open(extra)        XCTAssertEqual(app.descendants(matching: .any)["chat-composer-place"].firstMatch.label, "via WhatsApp", "the box says where it goes")        // Before Send: the three picked stand in the writing box with the caption.        for _ in 0..<3 { pickOne(app) }        let box = app.descendants(matching: .any)["chat-attached"].firstMatch        XCTAssertTrue(box.waitForExistence(timeout: 10), "the picked pictures wait in the writing box")        let waiting = box.descendants(matching: .any).matching(NSPredicate(format: "label == %@", "Photo"))        XCTAssertEqual(XCTWaiter().wait(for: [XCTNSPredicateExpectation(predicate: NSPredicate(format: "count == 3"), object: waiting)], timeout: 5), .completed,                       "all three wait in the box: \(waiting.count)")        XCTAssertTrue(app.keyboards.firstMatch.waitForExistence(timeout: 10), "the field takes the keyboard for the caption")        app.textViews["chat-composer-text"].typeText(caption)        let screen = Screen()        let tiles = waiting.allElementsBoundByIndex        for (i, tile) in tiles.enumerated() {            let c = CGPoint(x: tile.frame.midX, y: tile.frame.midY)            XCTAssertTrue(screen.picture(c), "picked picture \(i + 1) is drawn in the box, not its mark: \(screen.ink(c))")        }        keep("wa-grid-\(shots)-picked")        // After Send: one bubble with the three, at once, from the phone's own files, waiting for the Mac.        app.buttons["chat-composer-send"].tap()        let grid = app.descendants(matching: .any)["chat-bubble-outbox:seed-sent-1"].firstMatch        XCTAssertTrue(grid.waitForExistence(timeout: 3), "the grid stands at once")        XCTAssertFalse(box.exists, "nothing waits in the box after Send")        let said = grid.label        XCTAssertTrue(said.contains("Photo"), "pictures: \(said)")        XCTAssertTrue(said.contains(caption), "headed by the words: \(said)")        XCTAssertTrue(said.contains("Waiting to send"), "waiting for the Mac, never sent: \(said)")        let others = app.descendants(matching: .any).matching(NSPredicate(format: "identifier BEGINSWITH 'chat-bubble-outbox:seed-sent-1-'"))        XCTAssertEqual(others.count, 0, "one bubble, not one a picture")        Thread.sleep(forTimeInterval: 0.4)        let pending = threeTiles(grid, "sent")        keep("wa-grid-\(shots)-sent")        if pending.count == 3 { opensThird(app, at: pending[2], key: "outbox:seed-sent-1-2#0", shot: "wa-grid-\(shots)-viewer-waiting") }        // Landed, a message each: still one grid, headed by the words, each tile its picture.        let landed = app.descendants(matching: .any)["chat-bubble-seed-landed-1"].firstMatch        XCTAssertTrue(landed.waitForExistence(timeout: 20), "the pictures landed")        XCTAssertTrue(grid.waitForNonExistence(timeout: 5), "nothing still waits")        XCTAssertTrue(landed.label.contains(caption), "still headed by the words: \(landed.label)")        XCTAssertFalse(landed.label.contains("Waiting to send"), landed.label)        let apart = app.descendants(matching: .any).matching(NSPredicate(format: "identifier BEGINSWITH 'chat-bubble-seed-landed-1-'"))        XCTAssertEqual(apart.count, 0, "still one grid, not a bubble each")        Thread.sleep(forTimeInterval: 0.4)        let after = threeTiles(landed, "landed")        keep("wa-grid-\(shots)-landed")        if after.count == 3 { opensThird(app, at: after[2], key: "seed-landed-1-2#0", shot: "wa-grid-\(shots)-viewer-landed") }    }    // RULE (owner, FEEDBACK-4 B3): three pictures picked wait in the box with the caption; Send stands them as one grid    // at once with no blank tile; landed, still one grid; the third tile opens the third picture.    @MainActor func testThreePicturesStandAsOneGridBeforeAndAfterTheyLand() { walk([], "default") }    // RULE: the same at the largest text.    @MainActor func testThreePicturesStandAsOneGridAtTheLargestText() { walk(Self.largestText, "largest") }}