您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發基礎

為 UIAutomation 自動生成測試標籤的實踐探索

編輯:iOS 開發基礎

提到 iOS 上的自動化測試,蘋果官方的 UIAutomation 框架是繞不開的一環。不過和 Android 相比,它有一個頗令人頭疼的差異:Android 可以在 xml 佈局裡自動生成唯一的 id 當作標籤,而 iOS 卻要求開發者手動為每個控件掛上可訪問性(Accessibility)標識。那麼,怎樣才能讓一個控件的可訪問標籤在同一頁面內保持唯一且穩定不變呢?

純手動在代碼裡逐個插入打標籤的邏輯當然行得通,但既費時又費力。於是本文嘗試探索一條更省事的路徑——用程序來自動完成標籤的生成。

Github 傳送門:TBUIAutoTest

分析與方案

先回顧一下生成標籤必須滿足的兩個前提(下文將"自動化測試標籤"簡稱為"標籤"):

  1. 頁面內唯一:同一頁面中不同視圖的標籤不能重複。

  2. 運行時恆定:每次啟動應用的同一頁面,視圖標籤都保持一致,無需改動測試腳本。

要滿足這兩點,一個自然的想法是拿某個類的屬性名稱來當標籤。原因很簡單:同一個類裡不可能出現兩個同名屬性,而且屬性名是寫死在代碼中的,天然恆定。由此可以歸納出標籤策略的整體思路:

  1. 若某變量是某個類的屬性,它就能滿足標籤條件。只要代碼不改,標籤就不會變;即便代碼有變動,通常也是業務邏輯調整帶來的界面變化,那時測試腳本本來就得跟著改,因此不必過度擔心這種情況。

  2. 若是臨時創建的局部變量,同一頁面裡很可能出現同名局部變量,而 Objective-C Runtime 又拿不到局部變量的名稱,所以這類情況要另尋標籤來源。

  3. 設法取得代碼中局部變量的名字,並將它與對象綁定起來(所謂綁定,就是把標籤賦給 accessibilityIdentifier 之類的屬性)。

局部變量標籤的難點

編譯器在詞法分析、語法分析和語義分析之後,局部變量名早已煙消雲散。運行時它只是內存裡一個冷冰冰的對象,不像實例變量或屬性那樣還保留著名稱。既然編譯之後就取不到局部變量名,那唯一的辦法就是直接對源代碼做文字處理。

比如可以用宏定義,在 addSubview: 調用時把參數名傳進來,再將參數表與參數實例綁定。遺憾的是,這招對語法規整的 Swift 或許管用,對語法"古怪"的 Objective-C 卻行不通。

既然沒法從方法外傳入參數,那就試著從方法內部去拿函數調用堆棧:查上一層函數在源碼中的位置,再用正則表達式抓取 addSubview: 的參數名。獲取調用棧對應的源碼位置可以借助 backtrace_symbols 或 [NSThread callStackSymbols] 等,但這些操作都發生在 iOS 系統環境之外,沒法把標籤綁定到 iOS 運行時中的實例上。

當然,也可以寫腳本在源碼指定位置插入打標籤的邏輯代碼,但弊端有二:

  1. 維護成本高。腳本插入代碼前得判斷是否已經插入過,容易出錯。

  2. 對代碼變化的魯棒性差。重構等行為很可能打亂原有代碼順序,腳本要兼顧各種情況,每次新增代碼都得重跑一遍。

另闢蹊徑:用內容作標籤

既然局部變量的名字既可能重名、又難以綁定,不妨換個思路。這裡提出一個假設:程序員之所以把某個視圖變量聲明為類的屬性,往往是因為後續還會反覆用到它;而被聲明為局部變量的,多半只用一次就丟了。這種用臨時變量創建、加進視圖層級的視圖,內容往後基本不會再變,而且大多是 UILabel、UIButton、UIImageView,以及充當容器用的 UIView 實例。

針對這類情況,可以把視圖自身的內容當作標籤,比如 UILabel 的文本、UIButton 的背景圖片資源名與文本、UIImageView 的圖片資源名。基於這個邏輯,最終選擇用基礎控件的內容作為局部變量的標籤。

一句話總結:視圖若是某個類的屬性,就用屬性名作標籤;否則用它的內容作標籤。

實踐與探索

我採用 hook 的方式在運行時生成標籤。之所以 hook UIView 的 accessibilityIdentifier,是因為此時視圖層級更完整,而且能惰性生成標籤。用 accessibilityLabel 其實也行,但它會影響 VoiceOver 的體驗——畢竟變量名不像視圖文字那樣有實際語義。

PS:這裡不 hook addSubview:,是因為添加 subview 時視圖層級樹還不完整。雖然調用 accessibilityIdentifier 時視圖層級偶爾也不完整(比如在 addSubview: 之前就調用),但這種概率遠小於前者。很多時候是 [a addSubview:b] 這種寫法,此時 a 還沒有 superview,若 hook addSubview:,就只能保留 a 以下的視圖層級,這並不是我們想要的。因此在 UIView 的 accessibilityIdentifier 裡生成標籤,能盡可能保留完整層級,同時以 lazy load 的方式降低 CPU 峰值。

@implementation UIView (TBUIAutoTest) + (void)load { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{   [self swizzleSelector:@selector(accessibilityIdentifier) withAnotherSelector:@selector(tb_accessibilityIdentifier)];   [self swizzleSelector:@selector(accessibilityLabel) withAnotherSelector:@selector(tb_accessibilityLabel)]; }); } + (void)swizzleSelector:(SEL)originalSelector withAnotherSelector:(SEL)swizzledSelector {     Class aClass = [self class];          Method originalMethod = class_getInstanceMethod(aClass, originalSelector);     Method swizzledMethod = class_getInstanceMethod(aClass, swizzledSelector);          BOOL didAddMethod =     class_addMethod(aClass,                     originalSelector,                     method_getImplementation(swizzledMethod),                     method_getTypeEncoding(swizzledMethod));          if (didAddMethod) {         class_replaceMethod(aClass,                             swizzledSelector,                             method_getImplementation(originalMethod),                             method_getTypeEncoding(originalMethod));     } else {         method_exchangeImplementations(originalMethod, swizzledMethod);     } } #pragma mark - Method Swizzling - (NSString *)tb_accessibilityIdentifier {     NSString *accessibilityIdentifier = [self tb_accessibilityIdentifier];     if (accessibilityIdentifier.length > 0 && [[accessibilityIdentifier substringToIndex:1] isEqualToString:@"("]) {         return accessibilityIdentifier;     }     else if ([accessibilityIdentifier isEqualToString:@"null"]) {         accessibilityIdentifier = @"";     }          NSString *labelStr = [self.superview findNameWithInstance:self];          if (labelStr && ![labelStr isEqualToString:@""]) {         labelStr = [NSString stringWithFormat:@"(%@)",labelStr];     }     else {         if ([self isKindOfClass:[UILabel class]]) {//UILabel 使用 text             labelStr = [NSString stringWithFormat:@"(%@)",((UILabel *)self).text?:@""];         }         else if ([self isKindOfClass:[UIImageView class]]) {//UIImageView 使用 image 的 imageName             labelStr = [NSString stringWithFormat:@"(%@)",((UIImageView *)self).image.accessibilityIdentifier?:[NSString stringWithFormat:@"image%ld",(long)((UIImageView *)self).tag]];         }         else if ([self isKindOfClass:[UIButton class]]) {//UIButton 使用 button 的 text 和 image             labelStr = [NSString stringWithFormat:@"(%@%@)",((UIButton *)self).titleLabel.text?:@"",((UIButton *)self).imageView.image.accessibilityIdentifier?:@""];         }         else if (accessibilityIdentifier) {// 已有 label,則在此基礎上再次添加更多信息             labelStr = [NSString stringWithFormat:@"(%@)",accessibilityIdentifier];         }         if ([self isKindOfClass:[UIButton class]]) {             self.accessibilityValue = [NSString stringWithFormat:@"(%@)",((UIButton *)self).currentBackgroundImage.accessibilityIdentifier?:@""];         }     }     if ([labelStr isEqualToString:@"()"] || [labelStr isEqualToString:@"(null)"] || [labelStr isEqualToString:@"null"]) {         labelStr = @"";     }     [self setAccessibilityIdentifier:labelStr];     return labelStr; } - (NSString *)tb_accessibilityLabel {     if ([self isKindOfClass:[UIImageView class]]) {//UIImageView 特殊處理         NSString *name = [self.superview findNameWithInstance:self];         if (name) {             self.accessibilityIdentifier = [NSString stringWithFormat:@"(%@)",name];         }         else {             self.accessibilityIdentifier = [NSString stringWithFormat:@"(%@)",((UIImageView *)self).image.accessibilityIdentifier?:[NSString stringWithFormat:@"image%ld",(long)((UIImageView *)self).tag]];         }     }     if ([self isKindOfClass:[UITableViewCell class]]) {//UITableViewCell 特殊處理         self.accessibilityIdentifier = [NSString stringWithFormat:@"(%@)",((UITableViewCell *)self).reuseIdentifier];     }     return [self tb_accessibilityLabel]; } @end

拿到變量名之後,還要加工一番才能當標籤用。首先在變量名外層套一對括號,用來區分它是程序生成的而非手動添加的;方法末尾的 [self setAccessibilityIdentifier:subLabelStr] 則把生成好的標籤寫回 _accessibilityIdentifier。對於拿不到名字的臨時變量,以及視圖層級裡一些系統私有視圖,就按前面分析的方案特殊處理。一長串 if-else 寫下來,為了應對這些特例堆了一坨髒代碼,也是頗為無奈。最後別忘了清理 "null" 這類無意義字符串。

在 UIAutomation 生成控件樹時,大部分 UIImageView 和 UITableViewCell 無法通過 hook accessibilityIdentifier 拿到標籤,或者拿到的只是圖片資源名而非屬性名。的解決辦法是 hook accessibilityLabel,在其中為 UIImageView 和 UITableViewCell 補上標籤。

為了把 UIImage 的圖片資源名與實例綁定,我還 hook 了 UIImage 的 imageNamed: 類方法:

+ (UIImage *)tb_imageNamed:(NSString *)imageName{     UIImage *image = [UIImage tb_imageNamed:imageName];     image.accessibilityIdentifier = imageName;     return image; }

下面是獲取變量名的 findNameWithInstance: 方法實現:

@implementation UIResponder (TBUIAutoTest) -(NSString *)nameWithInstance:(id)instance {     unsigned int numIvars = 0;     NSString *key=nil;     Ivar * ivars = class_copyIvarList([self class], &numIvars);     for(int i = 0; i < numIvars; i++) {         Ivar thisIvar = ivars[i];         const char *type = ivar_getTypeEncoding(thisIvar);         NSString *stringType =  [NSString stringWithCString:type encoding:NSUTF8StringEncoding];         if (!stringType hasPrefix:@"@"]) {             continue;         }         if ((object_getIvar(self, thisIvar) == instance)) {//此處 crash 不要慌!             key = [NSString stringWithUTF8String:ivar_getName(thisIvar)];             break;         }     }     free(ivars);     return key; } - (NSString *)findNameWithInstance:(UIView *) instance {     id nextResponder = [self nextResponder];     NSString *name = [self nameWithInstance:instance];     if (!name) {         return [nextResponder findNameWithInstance:instance];     }     if ([name hasPrefix:@"_"]) {  //去掉變量名的下劃線前綴         name = [name substringFromIndex:1];     }     return name; }

由於我們無從得知某個視圖對象在哪個類裡充當了屬性或成員變量,findNameWithInstance: 便沿著響應鏈向上遞歸查找,範圍不只覆蓋 UIView,連 UIViewController 也不放過。每往上找一層,就調用 nameWithInstance: 用 Objective-C Runtime 遍歷成員變量列表來匹配變量名。

別忘了去掉開頭的下劃線——Runtime 裡保存的其實是成員變量的名稱,默認都帶下劃線前綴。

因為 hook 的方法不是 accessibilityLabel,所以沒法通過 Xcode 的 View Debug 頁面查看效果。最靠譜的方式還是用 UIAutomation 抓取控件樹,這樣的結果最真實。為了方便在真機上查看標籤內容,我給所有視圖加了長按手勢,長按後彈出警告框顯示自動化測試標籤。

hook addSubview: 方法,在其中添加長按手勢。longPress: 方法主要負責讓長按的視圖高亮並彈出 Alert 顯示標籤內容,代碼就不貼了。

- (void)tb_addSubview:(UIView *)view {     if (!view) {         return;     }     [self tb_addSubview:view];     UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];     longPress.delegate = [TBUIAutoTest sharedInstance];     [self addGestureRecognizer:longPress]; }

創建 TBUIAutoTest 單例作為所有手勢的委托,並在其中實現手勢捕獲優先級的邏輯,以化解手勢衝突:

@implementation TBUIAutoTest + (instancetype)sharedInstance {     static dispatch_once_t onceToken;     static TBUIAutoTest *_instance;     dispatch_once(&onceToken, ^{         _instance = [TBUIAutoTest new];     });     return _instance; } - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {          return YES; } - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRequireFailureOfGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {     if ([otherGestureRecognizer.view isDescendantOfView:gestureRecognizer.view]) {         return YES;     }     if (!([otherGestureRecognizer isKindOfClass:[UILongPressGestureRecognizer class]]) {         return YES;     }     return NO; } @end

最後聊幾句感受。這套方案的由來,說到底是測試同學提出加自動化標籤的訴求,團隊討論後一致認為手動添加太費力,於是自動化生成的任務就落到了我頭上。經歷了方案反覆打磨、同事的實力參謀,甚至連本該放空思考人生的時間都貢獻給了改進方案。這個月實在不知道寫點啥,眼看月底再不更新怕以後就懶得寫了,所以這篇水文你就湊合看吧。

後來發現好多人看不太懂,但這套方案是真的好用!如果你有更妙的思路,或者手上已經有現成的、免手動打標籤的超強 iOS 自動化測試框架,歡迎告訴我。據說整個團隊都是靠手動添加標籤,而做點有挑戰的事情,向來更有意思。

歡迎給 TBUIAutoTest 提 PR 和 Issue。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved