Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -280,23 +280,14 @@ extension RunnerTests {
return (wasVisible: wasVisible, pressed: true, visible: isKeyboardVisible(app: app))
}

var typed = false
let exceptionMessage = RunnerObjCExceptionCatcher.catchException({
app.typeText(XCUIKeyboardKey.return.rawValue)
typed = true
})
if let exceptionMessage {
NSLog(
"AGENT_DEVICE_RUNNER_KEYBOARD_RETURN_IGNORED_EXCEPTION=%@",
exceptionMessage
)
guard typeKeyboardReturn({ app.typeText(XCUIKeyboardKey.return.rawValue) }) else {
if let singleTarget = singleTextEntryElement(app: app) {
return pressKeyboardReturn(on: singleTarget, app: app, wasVisible: wasVisible)
}
return (wasVisible: wasVisible, pressed: false, visible: isKeyboardVisible(app: app))
}
sleepFor(0.2)
return (wasVisible: wasVisible, pressed: typed, visible: isKeyboardVisible(app: app))
return (wasVisible: wasVisible, pressed: true, visible: isKeyboardVisible(app: app))
#else
return (wasVisible: false, pressed: false, visible: false)
#endif
Expand All @@ -322,15 +313,13 @@ extension RunnerTests {
wasVisible: Bool
) -> (wasVisible: Bool, pressed: Bool, visible: Bool) {
#if os(iOS)
let exceptionMessage = RunnerObjCExceptionCatcher.catchException({
// `element` is bound by index, and the keyboard the tap raises shifts those indices, so the
// return goes to whatever the tap focused rather than to a re-resolved `element`.
let typed = typeKeyboardReturn({
element.tap()
element.typeText(XCUIKeyboardKey.return.rawValue)
app.typeText(XCUIKeyboardKey.return.rawValue)
})
if let exceptionMessage {
NSLog(
"AGENT_DEVICE_RUNNER_KEYBOARD_RETURN_TARGET_IGNORED_EXCEPTION=%@",
exceptionMessage
)
guard typed else {
return (wasVisible: wasVisible, pressed: false, visible: isKeyboardVisible(app: app))
}
sleepFor(0.2)
Expand All @@ -340,6 +329,26 @@ extension RunnerTests {
#endif
}

/// Types a return, false when nothing was typed: an ObjC exception, or XCTest's refusal to type
/// with nothing focused. XCTest records that refusal as an issue, which would invalidate the runner
/// session, so it alone is dropped; every other issue is recorded as usual.
private func typeKeyboardReturn(_ type: () -> Void) -> Bool {
let (issues, exceptionMessage) = holdingRecordedIssues(type)
let noFocus = issues.filter { Self.isNoKeyboardFocusIssue($0.compactDescription) }
issues.filter { !Self.isNoKeyboardFocusIssue($0.compactDescription) }.forEach { record($0) }
if !noFocus.isEmpty { NSLog("AGENT_DEVICE_RUNNER_KEYBOARD_RETURN_NO_FOCUS") }
if let exceptionMessage {
NSLog("AGENT_DEVICE_RUNNER_KEYBOARD_RETURN_IGNORED_EXCEPTION=%@", exceptionMessage)
}
return noFocus.isEmpty && exceptionMessage == nil
}

/// XCTest names this refusal only in its English issue text, as it does the AX failures that
/// `isSuppressedAxSnapshotIssueDescription` matches.
static func isNoKeyboardFocusIssue(_ description: String) -> Bool {
description.contains("Neither element nor any descendant has keyboard focus")
}

private func singleTextEntryElement(app: XCUIApplication) -> XCUIElement? {
#if os(iOS)
let matches = safely("KEYBOARD_RETURN_TEXT_ENTRY_QUERY", []) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import AgentDeviceSnapshotPresentation
final class TextInputProbeIssues {
let thread = Thread.current
var count = 0
var held: [XCTIssue] = []
}

enum TextInputProbeFailure: String, Error {
Expand Down Expand Up @@ -117,6 +118,28 @@ extension RunnerTests {
fallback: T,
_ probe: (_ shouldStop: () -> Bool) -> T
) -> Result<T, TextInputProbeFailure> {
withIssueScope { issues in
let (value, exception) = catchingObjCException(fallback: fallback) {
probe({ self.hasTextInputProbeIssues(issues) })
}
if hasTextInputProbeIssues(issues) { return .failure(.recordedIssue) }
if exception != nil { return .failure(.exception) }
return .success(value)
}
}

/// Runs `body` with its XCTest issues held back instead of recorded, and hands them to the caller,
/// which records the ones it does not explain.
func holdingRecordedIssues(_ body: () -> Void) -> (issues: [XCTIssue], exceptionMessage: String?) {
withIssueScope { issues in
let (_, exceptionMessage) = catchingObjCException(fallback: ()) { body() }
suppressedIssueLock.lock()
defer { suppressedIssueLock.unlock() }
return (issues.held, exceptionMessage)
}
}

private func withIssueScope<T>(_ body: (TextInputProbeIssues) -> T) -> T {
precondition(Thread.isMainThread)
let issues = TextInputProbeIssues()
suppressedIssueLock.lock()
Expand All @@ -128,12 +151,7 @@ extension RunnerTests {
textInputProbeIssues = previous
suppressedIssueLock.unlock()
}
let (value, exception) = catchingObjCException(fallback: fallback) {
probe({ self.hasTextInputProbeIssues(issues) })
}
if hasTextInputProbeIssues(issues) { return .failure(.recordedIssue) }
if exception != nil { return .failure(.exception) }
return .success(value)
return body(issues)
}

private func hasTextInputProbeIssues(_ scope: TextInputProbeIssues) -> Bool {
Expand All @@ -149,8 +167,9 @@ extension RunnerTests {
return false
}
scope.count += 1
scope.held.append(issue)
suppressedIssueLock.unlock()
NSLog("AGENT_DEVICE_RUNNER_TEXT_INPUT_PROBE_UNAVAILABLE issue=%@", issue.compactDescription)
NSLog("AGENT_DEVICE_RUNNER_RECORDED_ISSUE_HELD issue=%@", issue.compactDescription)
return true
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -243,5 +243,71 @@ extension RunnerTests {
runnerScreenshotStabilitySettled([Data([1])], requiredConsecutiveMatches: 1)
)
}

func testNoKeyboardFocusIssueIsOnlyXCTestsRefusalToTypeUnfocused() {
XCTAssertTrue(Self.isNoKeyboardFocusIssue(
"Failed to synthesize event: Neither element nor any descendant has keyboard focus. Event dispatch snapshot: Application"
))
XCTAssertFalse(Self.isNoKeyboardFocusIssue("Timed out while evaluating UI query."))
}

#if os(iOS)
@MainActor
func testKeyboardReturnWithNothingFocusedSubmitsTheSoleTextInput() throws {
app.launchArguments = [
"--agent-device-text-entry-regression",
"--agent-device-text-entry-soft-keyboard",
"--agent-device-text-entry-submit-clears",
"--agent-device-text-entry-long-prefill",
]
let (response, recordedFailures) = try keyboardReturnOnLaunchedFixture(
waitingForTextInput: "agent-device-hardware-keyboard-input"
)
let field = app.textFields["agent-device-hardware-keyboard-input"]

XCTAssertEqual(textEntryInputCount(), 1)
XCTAssertEqual(recordedFailures, 0)
XCTAssertTrue(response.ok, String(describing: response.error))
XCTAssertEqual(field.value as? String, "", "the field's submit clears it")
}

@MainActor
func testKeyboardReturnWithNothingFocusedAndNoTextInputFailsWithoutInvalidatingTheRunnerSession() throws {
app.launchArguments = []
let (response, recordedFailures) = try keyboardReturnOnLaunchedFixture()

XCTAssertEqual(textEntryInputCount(), 0)
XCTAssertEqual(recordedFailures, 0)
XCTAssertEqual(response.error?.code, "UNSUPPORTED_OPERATION")
}

@MainActor
private func keyboardReturnOnLaunchedFixture(
waitingForTextInput identifier: String? = nil
) throws -> (response: Response, recordedFailures: Int) {
app.launch()
addTeardownBlock { @MainActor in
self.invalidateCachedTarget(reason: "unit_test_cleanup")
self.app.terminate()
}
XCTAssertTrue(app.wait(for: .runningForeground, timeout: appExistenceTimeout))
Comment thread
thymikee marked this conversation as resolved.
Resolved
if let identifier {
XCTAssertTrue(app.textFields[identifier].waitForFixtureExistence(timeout: appExistenceTimeout))
}
mainOwned.app = app
mainOwned.bundleId = "com.callstack.agentdevice.runner"
mainOwned.processIdentifier = try XCTUnwrap(Self.processIdentifier(of: app))
let failures = currentXCTestFailureCount()
let command = try runnerCommandFixture(
#"{"appBundleId":"com.callstack.agentdevice.runner","command":"keyboardReturn","commandId":"return-unfocused"}"#
)
let response = try execute(command: command)
return (response, currentXCTestFailureCount() - failures)
}

private func textEntryInputCount() -> Int {
app.textFields.count + app.secureTextFields.count + app.searchFields.count + app.textViews.count
}
#endif
}
#endif
Loading