From f596a6171440004089e2a890511e523c4d72bf2e Mon Sep 17 00:00:00 2001 From: Mykola Mokhnach Date: Mon, 28 Oct 2024 18:11:40 +0100 Subject: [PATCH] fix: Support non-strict XPath queries (#318) --- .../IntegrationTests/AMFindElementTests.m | 2 +- .../WebDriverAgentLib/Utilities/FBXPath.m | 28 ++++++++++++++++++- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/WebDriverAgentMac/IntegrationTests/AMFindElementTests.m b/WebDriverAgentMac/IntegrationTests/AMFindElementTests.m index 25e6961..5f8b09c 100644 --- a/WebDriverAgentMac/IntegrationTests/AMFindElementTests.m +++ b/WebDriverAgentMac/IntegrationTests/AMFindElementTests.m @@ -78,7 +78,7 @@ - (void)testMultipleDescendantsWithPredicate - (void)testSingleDescendantWithXPath { - NSString *query = @"*//XCUIElementTypeButton[starts-with(@identifier, \"_XCUI:\")]"; + NSString *query = @"//XCUIElementTypeButton[starts-with(@identifier, \"_XCUI:\")]"; NSArray *matches = [self.testedApplication fb_descendantsMatchingXPathQuery:query shouldReturnAfterFirstMatch:YES]; XCTAssertEqual(matches.count, 1); diff --git a/WebDriverAgentMac/WebDriverAgentLib/Utilities/FBXPath.m b/WebDriverAgentMac/WebDriverAgentLib/Utilities/FBXPath.m index 0e74265..24c1e96 100644 --- a/WebDriverAgentMac/WebDriverAgentLib/Utilities/FBXPath.m +++ b/WebDriverAgentMac/WebDriverAgentLib/Utilities/FBXPath.m @@ -93,6 +93,31 @@ + (void)recordWithNode:(NSXMLElement *)node forValue:(NSString *)value; @end +@interface NSString (FBXPathFixes) + +/** + https://discuss.appium.io/t/cannot-find-element-with-mac2/44959 + */ +- (NSString *)fb_toFixedXPathQuery; + +@end + +@implementation NSString (FBXPathFixes) + +- (NSString *)fb_toFixedXPathQuery +{ + NSString *replacePattern = @"^([(]*)(/)"; + NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:replacePattern + options:NSRegularExpressionCaseInsensitive + error:nil]; + return [regex stringByReplacingMatchesInString:self + options:0 + range:NSMakeRange(0, [self length]) + withTemplate:@"$1.$2"]; +} + +@end + static NSString *const kXMLIndexPathKey = @"private_indexPath"; @@ -132,7 +157,8 @@ + (nullable NSString *)xmlStringWithRootElement:(XCUIElement *)root NSXMLElement *rootElement = [self makeXmlWithRootSnapshot:snapshot indexPath:[AMSnapshotUtils hashWithSnapshot:snapshot]]; - NSArray<__kindof NSXMLNode *> *matches = [rootElement nodesForXPath:xpathQuery error:&error]; + NSArray<__kindof NSXMLNode *> *matches = [rootElement nodesForXPath:[xpathQuery fb_toFixedXPathQuery] + error:&error]; if (nil == matches) { @throw [NSException exceptionWithName:FBInvalidXPathException reason:error.description