blob: 3d6cc2912990126429aff1b2c0bffbaeb59cb3fd [file] [log] [blame]
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import "ios/testing/earl_grey/base_earl_grey_test_case.h"
#import <UIKit/UIKit.h>
#import <objc/runtime.h>
#include "base/feature_list.h"
#include "base/logging.h"
#include "base/strings/sys_string_conversions.h"
#import "ios/testing/earl_grey/app_launch_configuration.h"
#import "ios/testing/earl_grey/app_launch_manager.h"
#import "ios/testing/earl_grey/base_earl_grey_test_case_app_interface.h"
#import "ios/testing/earl_grey/coverage_utils.h"
#import "ios/testing/earl_grey/earl_grey_test.h"
#if !defined(__has_feature) || !__has_feature(objc_arc)
#error "This file requires ARC support."
#if defined(CHROME_EARL_GREY_2)
#endif // defined(CHROME_EARL_GREY_2)
namespace {
// If true, +setUpForTestCase will be called from -setUp. This flag is used to
// ensure that +setUpForTestCase is called exactly once per unique XCTestCase
// and is reset in +tearDown.
bool g_needs_set_up_for_test_case = true;
} // namespace
@implementation BaseEarlGreyTestCase
+ (void)setUpForTestCase {
// Invoked upon starting each test method in a test case.
// Launches the app under test if necessary.
- (void)setUp {
[super setUp];
#if defined(CHROME_EARL_GREY_2)
[[AppLaunchManager sharedManager]
ensureAppLaunchedWithConfiguration:[self appConfigurationForTestCase]];
[self handleSystemAlertIfVisible];
NSString* logFormat = @"*********************************\nStarting test: %@";
logMessage:[NSString stringWithFormat:logFormat,]];
// Calling XCTFail before the application is launched does not assert
// properly, so failing upon detection of overriding +setUp is delayed until
// here. See +setUp below for details on why overriding +setUp causes a
// failure.
[self failIfSetUpIsOverridden];
if (g_needs_set_up_for_test_case) {
g_needs_set_up_for_test_case = false;
#if defined(CHROME_EARL_GREY_1)
[CoverageUtils configureCoverageReportPath];
[[self class] setUpForTestCase];
+ (void)tearDown {
[CoverageUtils writeClangCoverageProfile];
[CoverageUtils resetCoverageProfileCounters];
g_needs_set_up_for_test_case = true;
[super tearDown];
// Handles system alerts if any are present, closing them to unblock the UI.
- (void)handleSystemAlertIfVisible {
#if defined(CHROME_EARL_GREY_2)
NSError* systemAlertFoundError = nil;
[[EarlGrey selectElementWithMatcher:grey_systemAlertViewShown()]
if (systemAlertFoundError) {
NSError* alertGetTextError = nil;
NSString* alertText =
[self grey_systemAlertTextWithError:&alertGetTextError];
GREYAssertNil(alertGetTextError, @"Error getting alert text.\n%@",
@try {
// TODO( Style guide does not allow throwing
// exceptions. This call throws an NSInternalInconsistencyException when
// the system alert is unknown in EG2 framework. The exception will be
// handled in @catch. Otherwise the system alert is of a known type,
// accept it.
[self grey_systemAlertType];
DLOG(WARNING) << "Accepting iOS system alert: "
<< base::SysNSStringToUTF8(alertText);
NSError* acceptAlertError = nil;
[self grey_acceptSystemDialogWithError:&acceptAlertError];
GREYAssertNil(acceptAlertError, @"Error accepting system alert.\n%@",
} @catch (NSException* exception) {
( == NSInternalInconsistencyException &&
[exception.reason rangeOfString:@"Invalid System Alert."].location !=
@"Unknown error caught when handling unknown system alert: %@",
// If the unsupported alert is iOS upgrade or carrier settings alert,
// handle it. Otherwise, fail the test.
if ([alertText isEqualToString:@"Software Update"]) {
DLOG(WARNING) << "Denying iOS system alert of Software Update!";
// Software Update alert usually has two consecutive alerts, handle them
// one by one.
NSError* error = nil;
// Choose "Later" for the first alert.
[self tapAlertButtonWithText:@"Later" error:&error];
// If an error with code |GREYSystemAlertCustomButtonNotFound| happens,
// probably the second alert is already there. Try to handle it in
// following steps.
error == nil || error.code == GREYSystemAlertCustomButtonNotFound,
@"Error denying first Software Update alert.\n%@", error);
// A second alert promoting to update tonight will appear. Wait for it.
[self grey_waitForAlertVisibility:YES
error = nil;
// Choose "Remind Me Later" for the second alert.
[self tapAlertButtonWithText:@"Remind Me Later" error:&error];
GREYAssertNil(error, @"Error denying second Software Update alert.\n%@",
} else if ([alertText
containsString:@"A new iOS update is now available."]) {
<< "Denying iOS system alert of new iOS update is now available!";
// This is another format of Software Update dialog. Need to choose
// "Close".
NSError* error = nil;
[self tapAlertButtonWithText:@"Close" error:&error];
GREYAssertNil(error, @"Error closing Software Update alert.\n%@",
} else if ([alertText isEqualToString:@"Carrier Settings Update"]) {
DLOG(WARNING) << "Denying iOS system alert of Carrier Settings Update!";
NSError* error = nil;
[self tapAlertButtonWithText:@"Not Now" error:&error];
error, @"Error closing Carrier Settings Update alert.\n%@", error);
} else if ([alertText containsString:@"would like to find and connect to "
@"devices on your local network."]) {
DLOG(WARNING) << "Denying iOS system alert of connecting to local "
"network devices!";
NSError* error = nil;
[self tapAlertButtonWithText:@"OK" error:&error];
@"Error closing connecting to local network devices.\n%@",
} else {
XCTFail("An unsupported system alert is present on device. Failing "
"this test. Alert label: %@",
// Ensures no visible alert after handling.
[self grey_waitForAlertVisibility:NO
#endif // CHROME_EARL_GREY_2
- (AppLaunchConfiguration)appConfigurationForTestCase {
return AppLaunchConfiguration();
#pragma mark - Private
// Prevents tests inheriting from this class from putting logic in +setUp.
// +setUp will be called before the application is launched,
// and thus is not suitable for most test case setup. Inheriting tests should
// migrate their +setUp logic to use the equivalent -setUpForTestCase.
- (void)failIfSetUpIsOverridden {
if ([[BaseEarlGreyTestCase class] methodForSelector:@selector(setUp)] !=
[[self class] methodForSelector:@selector(setUp)]) {
XCTFail(@"EG2 test class %@ inheriting from BaseEarlGreyTestCase "
@"should not override +setUp, as it is called before the "
@"test application is launched. Please convert your "
@"+setUp method to +setUpForTestCase.",
NSStringFromClass([self class]));
// Taps button with |text| in the system alert on screen. If an alert or the
// button doesn't exist, note it in |error| accordingly. In EG1, this method is
// no-op.
- (void)tapAlertButtonWithText:(NSString*)text error:(NSError**)error {
#if defined(CHROME_EARL_GREY_2)
XCUIApplication* springboardApp = [[XCUIApplication alloc]
XCUIElement* alert = [[springboardApp
descendantsMatchingType:XCUIElementTypeAlert] firstMatch];
if (![alert waitForExistenceWithTimeout:kSystemAlertVisibilityTimeout]) {
*error = [NSError errorWithDomain:kGREYSystemAlertDismissalErrorDomain
XCUIElement* button = alert.buttons[text];
if (![alert.buttons[text] exists]) {
*error = [NSError errorWithDomain:kGREYSystemAlertDismissalErrorDomain
[button tap];
#endif // CHROME_EARL_GREY_2