Commit 7401a4eb authored by Peter K. Lee's avatar Peter K. Lee Committed by Commit Bot

Adds TranslateAppInterface to prepare for EG2 conversion

Use TranslateAppInterface to migrate EG1 tests to be EG2 compatible

Bug: None
Change-Id: Ide249041d5e35567f184df89b430a3c29f1e5bc7
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1967763
Commit-Queue: Peter Lee <pkl@chromium.org>
Reviewed-by: default avatarEugene But <eugenebut@chromium.org>
Cr-Commit-Position: refs/heads/master@{#726715}
parent 35ac419d
...@@ -108,12 +108,14 @@ source_set("unit_tests") { ...@@ -108,12 +108,14 @@ source_set("unit_tests") {
} }
source_set("eg_tests") { source_set("eg_tests") {
defines = [ "CHROME_EARL_GREY_1" ]
configs += [ "//build/config/compiler:enable_arc" ] configs += [ "//build/config/compiler:enable_arc" ]
testonly = true testonly = true
sources = [ sources = [
"translate_egtest.mm", "translate_egtest.mm",
] ]
deps = [ deps = [
":test_support",
":translate", ":translate",
"//base", "//base",
"//base/test:test_support", "//base/test:test_support",
...@@ -132,6 +134,7 @@ source_set("eg_tests") { ...@@ -132,6 +134,7 @@ source_set("eg_tests") {
"//ios/chrome/test/app:test_support", "//ios/chrome/test/app:test_support",
"//ios/chrome/test/earl_grey:test_support", "//ios/chrome/test/earl_grey:test_support",
"//ios/chrome/test/fakes", "//ios/chrome/test/fakes",
"//ios/testing/earl_grey:earl_grey_support",
"//ios/third_party/earl_grey:earl_grey+link", "//ios/third_party/earl_grey:earl_grey+link",
"//ios/web:earl_grey_test_support", "//ios/web:earl_grey_test_support",
"//ios/web/public/test", "//ios/web/public/test",
...@@ -141,3 +144,57 @@ source_set("eg_tests") { ...@@ -141,3 +144,57 @@ source_set("eg_tests") {
] ]
libs = [ "XCTest.framework" ] libs = [ "XCTest.framework" ]
} }
source_set("eg2_tests") {
defines = [ "CHROME_EARL_GREY_2" ]
configs += [
"//build/config/compiler:enable_arc",
"//build/config/ios:xctest_config",
]
testonly = true
sources = []
deps = []
libs = [ "UIKit.framework" ]
}
source_set("test_support") {
defines = [ "CHROME_EARL_GREY_1" ]
testonly = true
sources = [
"translate_app_interface.h",
"translate_app_interface.mm",
]
deps = [
"//components/translate/core/browser:browser",
"//components/translate/core/common:common",
"//components/translate/ios/browser:browser",
"//ios/chrome/browser/browser_state:browser_state",
"//ios/chrome/browser/translate",
"//ios/chrome/test/app:test_support",
"//ios/chrome/test/fakes:fakes",
]
configs += [ "//build/config/compiler:enable_arc" ]
}
source_set("eg_app_support+eg2") {
defines = [ "CHROME_EARL_GREY_2" ]
configs += [
"//build/config/compiler:enable_arc",
"//build/config/ios:xctest_config",
]
testonly = true
sources = []
}
source_set("eg_test_support+eg2") {
defines = [ "CHROME_EARL_GREY_2" ]
configs += [
"//build/config/compiler:enable_arc",
"//build/config/ios:xctest_config",
]
testonly = true
sources = []
deps = [
"//ios/testing/earl_grey:eg_test_support+eg2",
]
}
// 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.
#ifndef IOS_CHROME_BROWSER_TRANSLATE_TRANSLATE_APP_INTERFACE_H_
#define IOS_CHROME_BROWSER_TRANSLATE_TRANSLATE_APP_INTERFACE_H_
#import <Foundation/Foundation.h>
@interface TranslateAppInterface : NSObject
// Sets up the app for testing.
+ (void)setUp;
// Tears down the testing set up for the app.
+ (void)tearDown;
// Registers an observer of the IOSLanguageDetectionTabHelper to capture
// the details of webpage language detection. The captured details can be
// used for test verification.
+ (void)setUpLanguageDetectionTabHelperObserver;
// Deallocates the observer for IOSLanguageDetectionTabHelper.
+ (void)tearDownLanguageDetectionTabHelperObserver;
// Resets the language detection state kept in the observer of
// IOSLanguageDetectionTabHelper.
+ (void)resetLanguageDetectionTabHelperObserver;
// Returns whether a language information was detected on the webpage.
+ (BOOL)isLanguageDetected;
// Returns the language code of the webpage indicated in the Content-Language
// HTTP header.
+ (NSString*)contentLanguage;
// Returns the language code indicated in the language attribute of the HTML
// element.
+ (NSString*)htmlRootLanguage;
// Returns the language code for the language determined from the webpage.
+ (NSString*)adoptedLanguage;
// Sets up a fake translation manager for the current WebState. This translation
// manager fakes the translation and does not depend on the real JavaScript.
+ (void)setUpFakeJSTranslateManagerInCurrentTab;
/// Whether user has set a preference to translate from |source| language to
// |target| language.
+ (BOOL)shouldAutoTranslateFromLanguage:(NSString*)source
toLanguage:(NSString*)target;
// Whether user has set a preference to block the translation of |language|.
+ (BOOL)isBlockedLanguage:(NSString*)language;
// Whether user has set a preference to translate any pages on |hostName|.
+ (BOOL)isBlockedSite:(NSString*)hostName;
@end
#endif // IOS_CHROME_BROWSER_TRANSLATE_TRANSLATE_APP_INTERFACE_H_
// 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/chrome/browser/translate/translate_app_interface.h"
#include "base/memory/singleton.h"
#include "base/strings/sys_string_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "components/translate/core/browser/translate_manager.h"
#include "components/translate/core/browser/translate_prefs.h"
#include "components/translate/core/common/language_detection_details.h"
#import "components/translate/ios/browser/js_translate_manager.h"
#include "ios/chrome/browser/browser_state/chrome_browser_state.h"
#include "ios/chrome/browser/translate/chrome_ios_translate_client.h"
#import "ios/chrome/test/app/chrome_test_util.h"
#import "ios/chrome/test/app/tab_test_util.h"
#import "ios/chrome/test/fakes/fake_language_detection_tab_helper_observer.h"
#include "net/base/network_change_notifier.h"
#if !defined(__has_feature) || !__has_feature(objc_arc)
#error "This file requires ARC support."
#endif
namespace {
// Simulates a given network connection type for tests.
// TODO(crbug.com/938598): Refactor this and similar net::NetworkChangeNotifier
// subclasses for testing into a separate file.
class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier {
public:
FakeNetworkChangeNotifier(
net::NetworkChangeNotifier::ConnectionType connection_type_to_return)
: connection_type_to_return_(connection_type_to_return) {}
private:
ConnectionType GetCurrentConnectionType() const override {
return connection_type_to_return_;
}
// The currently simulated network connection type. If this is set to
// CONNECTION_NONE, then NetworkChangeNotifier::IsOffline will return true.
net::NetworkChangeNotifier::ConnectionType connection_type_to_return_ =
net::NetworkChangeNotifier::CONNECTION_UNKNOWN;
DISALLOW_COPY_AND_ASSIGN(FakeNetworkChangeNotifier);
};
// Helper singleton object to hold states for fake objects to facility testing.
class TranslateAppInterfaceHelper {
public:
static TranslateAppInterfaceHelper* GetInstance() {
return base::Singleton<TranslateAppInterfaceHelper>::get();
}
FakeLanguageDetectionTabHelperObserver& tab_helper_observer() const {
return *tab_helper_observer_;
}
void set_tab_helper_observer(
std::unique_ptr<FakeLanguageDetectionTabHelperObserver> observer) {
tab_helper_observer_ = std::move(observer);
}
void SetUpFakeWiFiConnection() {
// Disables the net::NetworkChangeNotifier singleton and replace it with a
// FakeNetworkChangeNotifier to simulate a WIFI network connection.
network_change_notifier_disabler_ =
std::make_unique<net::NetworkChangeNotifier::DisableForTest>();
network_change_notifier_ = std::make_unique<FakeNetworkChangeNotifier>(
net::NetworkChangeNotifier::CONNECTION_WIFI);
}
void TearDownFakeWiFiConnection() {
// Note: Tears down in the opposite order of construction.
network_change_notifier_.reset();
network_change_notifier_disabler_.reset();
}
private:
TranslateAppInterfaceHelper() {}
~TranslateAppInterfaceHelper() = default;
friend struct base::DefaultSingletonTraits<TranslateAppInterfaceHelper>;
// Observes the language detection tab helper and captures the translation
// details for inspection by tests.
std::unique_ptr<FakeLanguageDetectionTabHelperObserver> tab_helper_observer_;
// Helps fake the network condition for tests.
std::unique_ptr<net::NetworkChangeNotifier::DisableForTest>
network_change_notifier_disabler_;
std::unique_ptr<FakeNetworkChangeNotifier> network_change_notifier_;
};
} // namespace
#pragma mark - FakeJSTranslateManager
// Fake translate manager to be used in tests so no network is needed.
// Translating the page just adds a 'Translated' button to the page, without
// changing the text.
@interface FakeJSTranslateManager : JsTranslateManager {
web::WebState* _webState;
}
- (instancetype)initWithWebState:(web::WebState*)webState;
@end
@implementation FakeJSTranslateManager
- (instancetype)initWithWebState:(web::WebState*)webState {
if ((self = [super init])) {
_webState = webState;
}
return self;
}
- (void)setScript:(NSString*)script {
// No need to set the JavaScript since it will never be used by this fake
// object.
}
- (void)startTranslationFrom:(const std::string&)source
to:(const std::string&)target {
// Add a button with the 'Translated' label to the web page.
// The test can check it to determine if this method has been called.
_webState->ExecuteJavaScript(base::UTF8ToUTF16(
"myButton = document.createElement('button');"
"myButton.setAttribute('id', 'translated-button');"
"myButton.appendChild(document.createTextNode('Translated'));"
"document.body.prepend(myButton);"));
}
- (void)revertTranslation {
// Removes the button with 'translated-button' id from the web page, if any.
_webState->ExecuteJavaScript(base::UTF8ToUTF16(
"myButton = document.getElementById('translated-button');"
"myButton.remove();"));
}
- (void)inject {
// Prevent the actual script from being injected and instead just invoke host
// with 'translate.ready' followed by 'translate.status'.
_webState->ExecuteJavaScript(
base::UTF8ToUTF16("__gCrWeb.message.invokeOnHost({"
" 'command': 'translate.ready',"
" 'errorCode': 0,"
" 'loadTime': 0,"
" 'readyTime': 0});"));
_webState->ExecuteJavaScript(
base::UTF8ToUTF16("__gCrWeb.message.invokeOnHost({"
" 'command': 'translate.status',"
" 'errorCode': 0,"
" 'originalPageLanguage': 'fr',"
" 'translationTime': 0});"));
}
@end
#pragma mark - TranslateAppInterface
@implementation TranslateAppInterface
#pragma mark public methods
+ (void)setUp {
// Allows the offering of translate in builds without an API key.
translate::TranslateManager::SetIgnoreMissingKeyForTesting(true);
[self setUpLanguageDetectionTabHelperObserver];
[self setDefaultTranslatePrefs];
// Sets up a fake JsTranslateManager that does not use the translate script.
[self setUpFakeJSTranslateManagerInCurrentTab];
TranslateAppInterfaceHelper::GetInstance()->SetUpFakeWiFiConnection();
}
+ (void)tearDown {
TranslateAppInterfaceHelper::GetInstance()->TearDownFakeWiFiConnection();
[self setDefaultTranslatePrefs];
[TranslateAppInterface tearDownLanguageDetectionTabHelperObserver];
// Stops allowing the offering of translate in builds without an API key.
translate::TranslateManager::SetIgnoreMissingKeyForTesting(false);
}
+ (void)setUpLanguageDetectionTabHelperObserver {
TranslateAppInterfaceHelper::GetInstance()->set_tab_helper_observer(
std::make_unique<FakeLanguageDetectionTabHelperObserver>(
chrome_test_util::GetCurrentWebState()));
}
+ (void)tearDownLanguageDetectionTabHelperObserver {
TranslateAppInterfaceHelper::GetInstance()->set_tab_helper_observer(nullptr);
}
+ (void)resetLanguageDetectionTabHelperObserver {
TranslateAppInterfaceHelper::GetInstance()
->tab_helper_observer()
.ResetLanguageDetectionDetails();
}
+ (BOOL)isLanguageDetected {
return TranslateAppInterfaceHelper::GetInstance()
->tab_helper_observer()
.GetLanguageDetectionDetails() != nullptr;
}
+ (NSString*)contentLanguage {
translate::LanguageDetectionDetails* details =
TranslateAppInterfaceHelper::GetInstance()
->tab_helper_observer()
.GetLanguageDetectionDetails();
return base::SysUTF8ToNSString(details->content_language);
}
+ (NSString*)htmlRootLanguage {
translate::LanguageDetectionDetails* details =
TranslateAppInterfaceHelper::GetInstance()
->tab_helper_observer()
.GetLanguageDetectionDetails();
return base::SysUTF8ToNSString(details->html_root_language);
}
+ (NSString*)adoptedLanguage {
translate::LanguageDetectionDetails* details =
TranslateAppInterfaceHelper::GetInstance()
->tab_helper_observer()
.GetLanguageDetectionDetails();
return base::SysUTF8ToNSString(details->adopted_language);
}
+ (void)setUpFakeJSTranslateManagerInCurrentTab {
ChromeIOSTranslateClient* client = ChromeIOSTranslateClient::FromWebState(
chrome_test_util::GetCurrentWebState());
translate::IOSTranslateDriver* driver =
static_cast<translate::IOSTranslateDriver*>(client->GetTranslateDriver());
FakeJSTranslateManager* fakeJSTranslateManager =
[[FakeJSTranslateManager alloc]
initWithWebState:chrome_test_util::GetCurrentWebState()];
driver->translate_controller()->SetJsTranslateManagerForTesting(
fakeJSTranslateManager);
}
+ (BOOL)shouldAutoTranslateFromLanguage:(NSString*)source
toLanguage:(NSString*)target {
std::unique_ptr<translate::TranslatePrefs> prefs(
ChromeIOSTranslateClient::CreateTranslatePrefs(
chrome_test_util::GetOriginalBrowserState()->GetPrefs()));
return prefs->IsLanguagePairWhitelisted(base::SysNSStringToUTF8(source),
base::SysNSStringToUTF8(target));
}
+ (BOOL)isBlockedLanguage:(NSString*)language {
std::unique_ptr<translate::TranslatePrefs> prefs(
ChromeIOSTranslateClient::CreateTranslatePrefs(
chrome_test_util::GetOriginalBrowserState()->GetPrefs()));
return prefs->IsBlockedLanguage(base::SysNSStringToUTF8(language));
}
+ (BOOL)isBlockedSite:(NSString*)hostName {
std::unique_ptr<translate::TranslatePrefs> prefs(
ChromeIOSTranslateClient::CreateTranslatePrefs(
chrome_test_util::GetOriginalBrowserState()->GetPrefs()));
return prefs->IsSiteBlacklisted(base::SysNSStringToUTF8(hostName));
}
#pragma mark private methods
// Reset translate prefs to default.
+ (void)setDefaultTranslatePrefs {
std::unique_ptr<translate::TranslatePrefs> prefs(
ChromeIOSTranslateClient::CreateTranslatePrefs(
chrome_test_util::GetOriginalBrowserState()->GetPrefs()));
prefs->ResetToDefaults();
}
@end
// 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/chrome/browser/translate/translate_app_interface.h"
#import "ios/testing/earl_grey/earl_grey_test.h"
#if !defined(__has_feature) || !__has_feature(objc_arc)
#error "This file requires ARC support."
#endif
#if defined(CHROME_EARL_GREY_2)
// TODO(crbug.com/1015113): The EG2 macro is breaking indexing for some reason
// without the trailing semicolon. For now, disable the extra semi warning
// so Xcode indexing works for the egtest.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wc++98-compat-extra-semi"
GREY_STUB_CLASS_IN_APP_MAIN_QUEUE(TranslateAppInterface);
#pragma clang diagnostic pop
#endif // defined(CHROME_EARL_GREY_2)
...@@ -2,52 +2,44 @@ ...@@ -2,52 +2,44 @@
// Use of this source code is governed by a BSD-style license that can be // Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. // found in the LICENSE file.
#import <EarlGrey/EarlGrey.h>
#import <XCTest/XCTest.h> #import <XCTest/XCTest.h>
#include <memory> #include <memory>
#include <string> #include <string>
#include "base/bind.h"
#include "base/command_line.h"
#include "base/ios/ios_util.h"
#include "base/strings/stringprintf.h" #include "base/strings/stringprintf.h"
#include "base/strings/sys_string_conversions.h" #include "base/strings/sys_string_conversions.h"
#include "base/strings/utf_string_conversions.h" #include "base/strings/utf_string_conversions.h"
#import "base/test/ios/wait_util.h" #import "base/test/ios/wait_util.h"
#include "components/strings/grit/components_strings.h" #include "components/strings/grit/components_strings.h"
#include "components/translate/core/browser/translate_download_manager.h"
#include "components/translate/core/browser/translate_infobar_delegate.h" #include "components/translate/core/browser/translate_infobar_delegate.h"
#include "components/translate/core/browser/translate_manager.h"
#include "components/translate/core/browser/translate_pref_names.h" #include "components/translate/core/browser/translate_pref_names.h"
#include "components/translate/core/browser/translate_prefs.h"
#include "components/translate/core/common/language_detection_details.h" #include "components/translate/core/common/language_detection_details.h"
#include "components/translate/core/common/translate_constants.h" #include "components/translate/core/common/translate_constants.h"
#include "components/translate/core/common/translate_switches.h" #include "components/translate/core/common/translate_switches.h"
#include "components/translate/ios/browser/ios_translate_driver.h"
#import "components/translate/ios/browser/js_translate_manager.h" #import "components/translate/ios/browser/js_translate_manager.h"
#include "ios/chrome/browser/browser_state/chrome_browser_state.h" #include "ios/chrome/browser/browser_state/chrome_browser_state.h"
#import "ios/chrome/browser/chrome_url_util.h" #import "ios/chrome/browser/chrome_url_util.h"
#include "ios/chrome/browser/translate/chrome_ios_translate_client.h" #include "ios/chrome/browser/translate/chrome_ios_translate_client.h"
#import "ios/chrome/browser/translate/translate_app_interface.h"
#import "ios/chrome/browser/ui/popup_menu/popup_menu_constants.h" #import "ios/chrome/browser/ui/popup_menu/popup_menu_constants.h"
#import "ios/chrome/browser/ui/translate/legacy_translate_infobar_coordinator.h" #import "ios/chrome/browser/ui/translate/legacy_translate_infobar_coordinator.h"
#import "ios/chrome/browser/ui/translate/translate_infobar_view.h" #import "ios/chrome/browser/ui/translate/translate_infobar_view.h"
#import "ios/chrome/browser/ui/util/ui_util.h"
#include "ios/chrome/grit/ios_strings.h" #include "ios/chrome/grit/ios_strings.h"
#import "ios/chrome/test/app/chrome_test_util.h"
#import "ios/chrome/test/app/tab_test_util.h"
#import "ios/chrome/test/earl_grey/chrome_earl_grey.h" #import "ios/chrome/test/earl_grey/chrome_earl_grey.h"
#import "ios/chrome/test/earl_grey/chrome_earl_grey_app_interface.h"
#import "ios/chrome/test/earl_grey/chrome_earl_grey_ui.h" #import "ios/chrome/test/earl_grey/chrome_earl_grey_ui.h"
#import "ios/chrome/test/earl_grey/chrome_matchers.h" #import "ios/chrome/test/earl_grey/chrome_matchers.h"
#import "ios/chrome/test/earl_grey/chrome_test_case.h" #import "ios/chrome/test/earl_grey/chrome_test_case.h"
#import "ios/chrome/test/fakes/fake_language_detection_tab_helper_observer.h" #import "ios/testing/earl_grey/earl_grey_test.h"
#import "ios/web/public/test/earl_grey/web_view_matchers.h"
#include "ios/web/public/test/http_server/data_response_provider.h" #include "ios/web/public/test/http_server/data_response_provider.h"
#import "ios/web/public/test/http_server/http_server.h" #import "ios/web/public/test/http_server/http_server.h"
#include "ios/web/public/test/http_server/http_server_util.h" #include "ios/web/public/test/http_server/http_server_util.h"
#include "net/base/network_change_notifier.h" #import "ios/web/public/web_state.h"
#include "net/base/url_util.h" #include "net/base/url_util.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/l10n/l10n_util_mac.h" #include "ui/base/l10n/l10n_util_mac.h"
#include "url/gurl.h"
#if !defined(__has_feature) || !__has_feature(objc_arc) #if !defined(__has_feature) || !__has_feature(objc_arc)
#error "This file requires ARC support." #error "This file requires ARC support."
...@@ -55,7 +47,6 @@ ...@@ -55,7 +47,6 @@
using base::test::ios::WaitUntilConditionOrTimeout; using base::test::ios::WaitUntilConditionOrTimeout;
using base::test::ios::kWaitForJSCompletionTimeout; using base::test::ios::kWaitForJSCompletionTimeout;
using base::test::ios::kWaitForPageLoadTimeout;
using base::test::ios::kWaitForUIElementTimeout; using base::test::ios::kWaitForUIElementTimeout;
using chrome_test_util::ButtonWithAccessibilityLabel; using chrome_test_util::ButtonWithAccessibilityLabel;
using chrome_test_util::ButtonWithAccessibilityLabelId; using chrome_test_util::ButtonWithAccessibilityLabelId;
...@@ -335,159 +326,19 @@ void TestResponseProvider::GetLanguageResponse( ...@@ -335,159 +326,19 @@ void TestResponseProvider::GetLanguageResponse(
base::StringPrintf("<html><body>%s</body></html>", kLanguagePathText); base::StringPrintf("<html><body>%s</body></html>", kLanguagePathText);
} }
// Simulates a given network connection type for tests.
// TODO(crbug.com/938598): Refactor this and similar net::NetworkChangeNotifier
// subclasses for testing into a separate file.
class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier {
public:
FakeNetworkChangeNotifier(
net::NetworkChangeNotifier::ConnectionType connection_type_to_return)
: connection_type_to_return_(connection_type_to_return) {}
private:
ConnectionType GetCurrentConnectionType() const override {
return connection_type_to_return_;
}
// The currently simulated network connection type. If this is set to
// CONNECTION_NONE, then NetworkChangeNotifier::IsOffline will return true.
net::NetworkChangeNotifier::ConnectionType connection_type_to_return_ =
net::NetworkChangeNotifier::CONNECTION_UNKNOWN;
DISALLOW_COPY_AND_ASSIGN(FakeNetworkChangeNotifier);
};
} // namespace } // namespace
#pragma mark - MockTranslateScriptManager
// Mock javascript translate manager that does not use the translate servers.
// Translating the page just adds a 'Translated' button to the page, without
// changing the text.
@interface MockTranslateScriptManager : JsTranslateManager {
web::WebState* _webState; // weak
}
- (instancetype)initWithWebState:(web::WebState*)webState;
@end
@implementation MockTranslateScriptManager
- (instancetype)initWithWebState:(web::WebState*)webState {
if ((self = [super init])) {
_webState = webState;
}
return self;
}
- (void)setScript:(NSString*)script {
}
- (void)startTranslationFrom:(const std::string&)source
to:(const std::string&)target {
// Add a button with the 'Translated' label to the web page.
// The test can check it to determine if this method has been called.
_webState->ExecuteJavaScript(base::UTF8ToUTF16(
"myButton = document.createElement('button');"
"myButton.setAttribute('id', 'translated-button');"
"myButton.appendChild(document.createTextNode('Translated'));"
"document.body.prepend(myButton);"));
}
- (void)revertTranslation {
// Removes the button with 'translated-button' id from the web page, if any.
_webState->ExecuteJavaScript(base::UTF8ToUTF16(
"myButton = document.getElementById('translated-button');"
"myButton.remove();"));
}
- (void)inject {
// Prevent the actual script from being injected and instead just invoke host
// with 'translate.ready' followed by 'translate.status'.
_webState->ExecuteJavaScript(
base::UTF8ToUTF16("__gCrWeb.message.invokeOnHost({"
" 'command': 'translate.ready',"
" 'errorCode': 0,"
" 'loadTime': 0,"
" 'readyTime': 0});"));
_webState->ExecuteJavaScript(
base::UTF8ToUTF16("__gCrWeb.message.invokeOnHost({"
" 'command': 'translate.status',"
" 'errorCode': 0,"
" 'originalPageLanguage': 'fr',"
" 'translationTime': 0});"));
}
@end
#pragma mark - TranslateTestCase #pragma mark - TranslateTestCase
// Tests for translate. // Tests for translate.
@interface TranslateTestCase : ChromeTestCase { @interface TranslateTestCase : ChromeTestCase
std::unique_ptr<FakeLanguageDetectionTabHelperObserver>
_language_detection_tab_helper_observer;
std::unique_ptr<net::NetworkChangeNotifier::DisableForTest>
_network_change_notifier_disabler;
std::unique_ptr<FakeNetworkChangeNotifier> _network_change_notifier;
}
@end @end
@implementation TranslateTestCase @implementation TranslateTestCase
- (void)setUp { - (void)setUp {
[super setUp]; [super setUp];
[TranslateAppInterface setUp];
// Allow offering translate in builds without an API key.
translate::TranslateManager::SetIgnoreMissingKeyForTesting(true);
_language_detection_tab_helper_observer =
std::make_unique<FakeLanguageDetectionTabHelperObserver>(
chrome_test_util::GetCurrentWebState());
// Reset translate prefs to default.
std::unique_ptr<translate::TranslatePrefs> translatePrefs(
ChromeIOSTranslateClient::CreateTranslatePrefs(
chrome_test_util::GetOriginalBrowserState()->GetPrefs()));
translatePrefs->ResetToDefaults();
[self setUpMockScriptManager];
// Disable the net::NetworkChangeNotifier singleton and replace it with a
// FakeNetworkChangeNotifier to simulate a WIFI network connection.
_network_change_notifier_disabler =
std::make_unique<net::NetworkChangeNotifier::DisableForTest>();
_network_change_notifier = std::make_unique<FakeNetworkChangeNotifier>(
net::NetworkChangeNotifier::CONNECTION_WIFI);
}
- (void)tearDown {
_language_detection_tab_helper_observer.reset();
// Reset translate prefs to default.
std::unique_ptr<translate::TranslatePrefs> translatePrefs(
ChromeIOSTranslateClient::CreateTranslatePrefs(
chrome_test_util::GetOriginalBrowserState()->GetPrefs()));
translatePrefs->ResetToDefaults();
// Do not allow offering translate in builds without an API key.
translate::TranslateManager::SetIgnoreMissingKeyForTesting(false);
[super tearDown];
}
// Sets up MockTranslateScriptManager that does not use the translate script.
- (void)setUpMockScriptManager {
// Set up the mock translate script manager.
ChromeIOSTranslateClient* client = ChromeIOSTranslateClient::FromWebState(
chrome_test_util::GetCurrentWebState());
translate::IOSTranslateDriver* driver =
static_cast<translate::IOSTranslateDriver*>(client->GetTranslateDriver());
MockTranslateScriptManager* jsTranslateManager =
[[MockTranslateScriptManager alloc]
initWithWebState:chrome_test_util::GetCurrentWebState()];
driver->translate_controller()->SetJsTranslateManagerForTesting(
jsTranslateManager);
// Set up a fake URL for the translate script to hit the mock HTTP server. // Set up a fake URL for the translate script to hit the mock HTTP server.
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
...@@ -497,6 +348,11 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier { ...@@ -497,6 +348,11 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier {
translateScriptURL.spec().c_str()); translateScriptURL.spec().c_str());
} }
- (void)tearDown {
[TranslateAppInterface tearDown];
[super tearDown];
}
#pragma mark - Test Cases #pragma mark - Test Cases
// Tests that different language signals are detected correcty. // Tests that different language signals are detected correcty.
...@@ -552,16 +408,14 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier { ...@@ -552,16 +408,14 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier {
[ChromeEarlGrey loadURL:noTranslateContentURL]; [ChromeEarlGrey loadURL:noTranslateContentURL];
// Check that no language has been detected. // Check that no language has been detected.
GREYAssert( GREYAssertFalse([self waitForLanguageDetection],
!_language_detection_tab_helper_observer->GetLanguageDetectionDetails(),
@"A language has been detected"); @"A language has been detected");
// Load some french page with |value="notranslate"| meta tag. // Load some french page with |value="notranslate"| meta tag.
[ChromeEarlGrey loadURL:noTranslateValueURL]; [ChromeEarlGrey loadURL:noTranslateValueURL];
// Check that no language has been detected. // Check that no language has been detected.
GREYAssert( GREYAssertFalse([self waitForLanguageDetection],
!_language_detection_tab_helper_observer->GetLanguageDetectionDetails(),
@"A language has been detected"); @"A language has been detected");
} }
...@@ -579,6 +433,9 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier { ...@@ -579,6 +433,9 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier {
translate::LanguageDetectionDetails expectedLanguageDetails; translate::LanguageDetectionDetails expectedLanguageDetails;
expectedLanguageDetails.adopted_language = "und"; expectedLanguageDetails.adopted_language = "und";
[self assertLanguageDetails:expectedLanguageDetails]; [self assertLanguageDetails:expectedLanguageDetails];
// Resets state before triggering a new round of language detection.
[TranslateAppInterface resetLanguageDetectionTabHelperObserver];
// Change the text of the page. // Change the text of the page.
chrome_test_util::ExecuteJavaScript( chrome_test_util::ExecuteJavaScript(
[NSString stringWithFormat:@"document.write('%s');", kEnglishText], nil); [NSString stringWithFormat:@"document.write('%s');", kEnglishText], nil);
...@@ -618,6 +475,9 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier { ...@@ -618,6 +475,9 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier {
translate::LanguageDetectionDetails expectedLanguageDetails; translate::LanguageDetectionDetails expectedLanguageDetails;
expectedLanguageDetails.adopted_language = "fr"; expectedLanguageDetails.adopted_language = "fr";
[self assertLanguageDetails:expectedLanguageDetails]; [self assertLanguageDetails:expectedLanguageDetails];
// Resets state before triggering a new round of language detection.
[TranslateAppInterface resetLanguageDetectionTabHelperObserver];
// Trigger the hash change. // Trigger the hash change.
[ChromeEarlGrey tapWebStateElementWithID:@"Hash"]; [ChromeEarlGrey tapWebStateElementWithID:@"Hash"];
// Check that language detection has been re-run. // Check that language detection has been re-run.
...@@ -640,6 +500,8 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier { ...@@ -640,6 +500,8 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier {
expectedLanguageDetails.adopted_language = "fr"; expectedLanguageDetails.adopted_language = "fr";
[self assertLanguageDetails:expectedLanguageDetails]; [self assertLanguageDetails:expectedLanguageDetails];
// Resets state before triggering a new round of language detection.
[TranslateAppInterface resetLanguageDetectionTabHelperObserver];
// Everything after the comma is truncated. // Everything after the comma is truncated.
URL = web::test::HttpServer::MakeUrl(std::string("http://") + kLanguagePath + URL = web::test::HttpServer::MakeUrl(std::string("http://") + kLanguagePath +
"?http=fr,ornot"); "?http=fr,ornot");
...@@ -648,6 +510,8 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier { ...@@ -648,6 +510,8 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier {
expectedLanguageDetails.adopted_language = "fr"; expectedLanguageDetails.adopted_language = "fr";
[self assertLanguageDetails:expectedLanguageDetails]; [self assertLanguageDetails:expectedLanguageDetails];
// Resets state before triggering a new round of language detection.
[TranslateAppInterface resetLanguageDetectionTabHelperObserver];
// The HTTP header is overriden by meta tag. // The HTTP header is overriden by meta tag.
URL = web::test::HttpServer::MakeUrl(std::string("http://") + kLanguagePath + URL = web::test::HttpServer::MakeUrl(std::string("http://") + kLanguagePath +
"?http=fr&meta=it"); "?http=fr&meta=it");
...@@ -656,6 +520,8 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier { ...@@ -656,6 +520,8 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier {
expectedLanguageDetails.adopted_language = "it"; expectedLanguageDetails.adopted_language = "it";
[self assertLanguageDetails:expectedLanguageDetails]; [self assertLanguageDetails:expectedLanguageDetails];
// Resets state before triggering a new round of language detection.
[TranslateAppInterface resetLanguageDetectionTabHelperObserver];
// Only the header of the main page is detected. // Only the header of the main page is detected.
URL = URL =
web::test::HttpServer::MakeUrl(std::string("http://") + kSubresourcePath); web::test::HttpServer::MakeUrl(std::string("http://") + kSubresourcePath);
...@@ -724,21 +590,20 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier { ...@@ -724,21 +590,20 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier {
web::test::SetUpSimpleHttpServer(responses); web::test::SetUpSimpleHttpServer(responses);
// Disable translate. // Disable translate.
chrome_test_util::SetBooleanUserPref( [ChromeEarlGreyAppInterface
chrome_test_util::GetOriginalBrowserState(), setBoolValue:NO
prefs::kOfferTranslateEnabled, NO); forUserPref:base::SysUTF8ToNSString(prefs::kOfferTranslateEnabled)];
// Open some webpage. // Open some webpage.
[ChromeEarlGrey loadURL:URL]; [ChromeEarlGrey loadURL:URL];
// Check that no language has been detected. // Check that no language has been detected.
GREYAssert( GREYAssertFalse([self waitForLanguageDetection],
!_language_detection_tab_helper_observer->GetLanguageDetectionDetails(),
@"A language has been detected"); @"A language has been detected");
// Enable translate. // Enable translate.
chrome_test_util::SetBooleanUserPref( [ChromeEarlGreyAppInterface
chrome_test_util::GetOriginalBrowserState(), setBoolValue:YES
prefs::kOfferTranslateEnabled, YES); forUserPref:base::SysUTF8ToNSString(prefs::kOfferTranslateEnabled)];
} }
// Tests that the infobar hides/shows as the browser enters/exits the fullscreen // Tests that the infobar hides/shows as the browser enters/exits the fullscreen
...@@ -843,12 +708,13 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier { ...@@ -843,12 +708,13 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier {
base::StringPrintf("http://%s", kFrenchPagePath)); base::StringPrintf("http://%s", kFrenchPagePath));
// Stop observing the current IOSLanguageDetectionTabHelper before opening the // Stop observing the current IOSLanguageDetectionTabHelper before opening the
// incognito tab. // incognito tab.
_language_detection_tab_helper_observer.reset(); [TranslateAppInterface tearDownLanguageDetectionTabHelperObserver];
[ChromeEarlGrey openNewIncognitoTab]; [ChromeEarlGrey openNewIncognitoTab];
[ChromeEarlGrey loadURL:URL]; [ChromeEarlGrey loadURL:URL];
// Needed for the incognito WebState. // Since current web state has changed to Incognito, a new fake translation
[self setUpMockScriptManager]; // manager has to be set up for the rest of this test.
[TranslateAppInterface setUpFakeJSTranslateManagerInCurrentTab];
[self translateThenRevert]; [self translateThenRevert];
} }
...@@ -1037,10 +903,8 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier { ...@@ -1037,10 +903,8 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier {
[self assertTranslateInfobarIsVisible]; [self assertTranslateInfobarIsVisible];
// Make sure that French to English translation is not automatic. // Make sure that French to English translation is not automatic.
std::unique_ptr<translate::TranslatePrefs> translatePrefs( GREYAssert(![TranslateAppInterface shouldAutoTranslateFromLanguage:@"fr"
ChromeIOSTranslateClient::CreateTranslatePrefs( toLanguage:@"en"],
chrome_test_util::GetOriginalBrowserState()->GetPrefs()));
GREYAssert(!translatePrefs->IsLanguagePairWhitelisted("fr", "en"),
@"French to English translation is automatic"); @"French to English translation is automatic");
// Open the translate options menu. // Open the translate options menu.
...@@ -1059,7 +923,8 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier { ...@@ -1059,7 +923,8 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier {
[ChromeEarlGrey waitForWebStateNotContainingText:"Translated"]; [ChromeEarlGrey waitForWebStateNotContainingText:"Translated"];
// Make sure that French to English translation is not automatic yet. // Make sure that French to English translation is not automatic yet.
GREYAssert(!translatePrefs->IsLanguagePairWhitelisted("fr", "en"), GREYAssert(![TranslateAppInterface shouldAutoTranslateFromLanguage:@"fr"
toLanguage:@"en"],
@"French to English translation is automatic"); @"French to English translation is automatic");
// Tap the notification snackbar to dismiss it. // Tap the notification snackbar to dismiss it.
...@@ -1075,7 +940,8 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier { ...@@ -1075,7 +940,8 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier {
// Make sure that French to English translation is automatic after the // Make sure that French to English translation is automatic after the
// snackbar is dismissed. // snackbar is dismissed.
GREYAssert(translatePrefs->IsLanguagePairWhitelisted("fr", "en"), GREYAssert([TranslateAppInterface shouldAutoTranslateFromLanguage:@"fr"
toLanguage:@"en"],
@"French to English translation is not automatic"); @"French to English translation is not automatic");
// Reload the page. // Reload the page.
...@@ -1102,7 +968,8 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier { ...@@ -1102,7 +968,8 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier {
assertWithMatcher:ElementIsSelected(YES)] performAction:grey_tap()]; assertWithMatcher:ElementIsSelected(YES)] performAction:grey_tap()];
// Make sure that French to English translation is no longer automatic. // Make sure that French to English translation is no longer automatic.
GREYAssert(!translatePrefs->IsLanguagePairWhitelisted("fr", "en"), GREYAssert(![TranslateAppInterface shouldAutoTranslateFromLanguage:@"fr"
toLanguage:@"en"],
@"French to English translation is automatic"); @"French to English translation is automatic");
// Open the translate options menu. // Open the translate options menu.
...@@ -1125,7 +992,8 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier { ...@@ -1125,7 +992,8 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier {
assertWithMatcher:ElementIsSelected(NO)]; assertWithMatcher:ElementIsSelected(NO)];
// Make sure that French to English translation is not automatic. // Make sure that French to English translation is not automatic.
GREYAssert(!translatePrefs->IsLanguagePairWhitelisted("fr", "en"), GREYAssert(![TranslateAppInterface shouldAutoTranslateFromLanguage:@"fr"
toLanguage:@"en"],
@"French to English translation is automatic"); @"French to English translation is automatic");
} }
...@@ -1144,10 +1012,8 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier { ...@@ -1144,10 +1012,8 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier {
[self assertTranslateInfobarIsVisible]; [self assertTranslateInfobarIsVisible];
// Make sure that French to English translation is not automatic. // Make sure that French to English translation is not automatic.
std::unique_ptr<translate::TranslatePrefs> translatePrefs( GREYAssert(![TranslateAppInterface shouldAutoTranslateFromLanguage:@"fr"
ChromeIOSTranslateClient::CreateTranslatePrefs( toLanguage:@"en"],
chrome_test_util::GetOriginalBrowserState()->GetPrefs()));
GREYAssert(!translatePrefs->IsLanguagePairWhitelisted("fr", "en"),
@"French to English translation is automatic"); @"French to English translation is automatic");
// Translate the page by tapping the target language tab until // Translate the page by tapping the target language tab until
...@@ -1163,7 +1029,8 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier { ...@@ -1163,7 +1029,8 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier {
} }
// Make sure that French to English translation is not automatic yet. // Make sure that French to English translation is not automatic yet.
GREYAssert(!translatePrefs->IsLanguagePairWhitelisted("fr", "en"), GREYAssert(![TranslateAppInterface shouldAutoTranslateFromLanguage:@"fr"
toLanguage:@"en"],
@"French to English translation is automatic"); @"French to English translation is automatic");
// Tap the notification snackbar to dismiss it. // Tap the notification snackbar to dismiss it.
...@@ -1176,7 +1043,8 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier { ...@@ -1176,7 +1043,8 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier {
// Make sure that French to English translation is automatic after the // Make sure that French to English translation is automatic after the
// snackbar is dismissed. // snackbar is dismissed.
GREYAssert(translatePrefs->IsLanguagePairWhitelisted("fr", "en"), GREYAssert([TranslateAppInterface shouldAutoTranslateFromLanguage:@"fr"
toLanguage:@"en"],
@"French to English translation is not automatic"); @"French to English translation is not automatic");
} }
...@@ -1195,10 +1063,8 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier { ...@@ -1195,10 +1063,8 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier {
[self assertTranslateInfobarIsVisible]; [self assertTranslateInfobarIsVisible];
// Make sure that French to English translation is not automatic. // Make sure that French to English translation is not automatic.
std::unique_ptr<translate::TranslatePrefs> translatePrefs( GREYAssert(![TranslateAppInterface shouldAutoTranslateFromLanguage:@"fr"
ChromeIOSTranslateClient::CreateTranslatePrefs( toLanguage:@"en"],
chrome_test_util::GetOriginalBrowserState()->GetPrefs()));
GREYAssert(!translatePrefs->IsLanguagePairWhitelisted("fr", "en"),
@"French to English translation is automatic"); @"French to English translation is automatic");
// Trigger and refuse the auto "Always Translate". // Trigger and refuse the auto "Always Translate".
...@@ -1256,10 +1122,7 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier { ...@@ -1256,10 +1122,7 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier {
[self assertTranslateInfobarIsVisible]; [self assertTranslateInfobarIsVisible];
// Make sure that translation from French is not blocked. // Make sure that translation from French is not blocked.
std::unique_ptr<translate::TranslatePrefs> translatePrefs( GREYAssert(![TranslateAppInterface isBlockedLanguage:@"fr"],
ChromeIOSTranslateClient::CreateTranslatePrefs(
chrome_test_util::GetOriginalBrowserState()->GetPrefs()));
GREYAssert(!translatePrefs->IsBlockedLanguage("fr"),
@"Translation from French is blocked"); @"Translation from French is blocked");
// Open the translate options menu. // Open the translate options menu.
...@@ -1278,7 +1141,7 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier { ...@@ -1278,7 +1141,7 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier {
[[EarlGrey selectElementWithMatcher:UndoButton()] performAction:grey_tap()]; [[EarlGrey selectElementWithMatcher:UndoButton()] performAction:grey_tap()];
// Make sure that translation from French is still not blocked. // Make sure that translation from French is still not blocked.
GREYAssert(!translatePrefs->IsBlockedLanguage("fr"), GREYAssert(![TranslateAppInterface isBlockedLanguage:@"fr"],
@"Translation from French is blocked"); @"Translation from French is blocked");
// Open the translate options menu. // Open the translate options menu.
...@@ -1290,7 +1153,7 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier { ...@@ -1290,7 +1153,7 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier {
performAction:grey_tap()]; performAction:grey_tap()];
// Make sure that translation from French is not blocked yet. // Make sure that translation from French is not blocked yet.
GREYAssert(!translatePrefs->IsBlockedLanguage("fr"), GREYAssert(![TranslateAppInterface isBlockedLanguage:@"fr"],
@"Translation from French is blocked"); @"Translation from French is blocked");
// Tap the notification snackbar to dismiss it. // Tap the notification snackbar to dismiss it.
...@@ -1306,7 +1169,7 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier { ...@@ -1306,7 +1169,7 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier {
// Make sure that translation from French is blocked after the snackbar is // Make sure that translation from French is blocked after the snackbar is
// dismissed. // dismissed.
GREYAssert(translatePrefs->IsBlockedLanguage("fr"), GREYAssert([TranslateAppInterface isBlockedLanguage:@"fr"],
@"Translation from French is not blocked"); @"Translation from French is not blocked");
// Reload the page. // Reload the page.
...@@ -1332,10 +1195,7 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier { ...@@ -1332,10 +1195,7 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier {
[self assertTranslateInfobarIsVisible]; [self assertTranslateInfobarIsVisible];
// Make sure that translation from French is not blocked. // Make sure that translation from French is not blocked.
std::unique_ptr<translate::TranslatePrefs> translatePrefs( GREYAssert(![TranslateAppInterface isBlockedLanguage:@"fr"],
ChromeIOSTranslateClient::CreateTranslatePrefs(
chrome_test_util::GetOriginalBrowserState()->GetPrefs()));
GREYAssert(!translatePrefs->IsBlockedLanguage("fr"),
@"Translation from French is blocked"); @"Translation from French is blocked");
// Dismiss the translate infobar until "Never Translate ..." is automatically // Dismiss the translate infobar until "Never Translate ..." is automatically
...@@ -1353,7 +1213,7 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier { ...@@ -1353,7 +1213,7 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier {
} }
// Make sure that translation from French is not blocked yet. // Make sure that translation from French is not blocked yet.
GREYAssert(!translatePrefs->IsBlockedLanguage("fr"), GREYAssert(![TranslateAppInterface isBlockedLanguage:@"fr"],
@"Translation from French is blocked"); @"Translation from French is blocked");
// Tap the notification snackbar to dismiss it. // Tap the notification snackbar to dismiss it.
...@@ -1369,7 +1229,7 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier { ...@@ -1369,7 +1229,7 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier {
// Make sure that translation from French is blocked after the snackbar is // Make sure that translation from French is blocked after the snackbar is
// dismissed. // dismissed.
GREYAssert(translatePrefs->IsBlockedLanguage("fr"), GREYAssert([TranslateAppInterface isBlockedLanguage:@"fr"],
@"Translation from French is not blocked"); @"Translation from French is not blocked");
} }
...@@ -1391,10 +1251,7 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier { ...@@ -1391,10 +1251,7 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier {
[self assertTranslateInfobarIsVisible]; [self assertTranslateInfobarIsVisible];
// Make sure that translation from French is not blocked. // Make sure that translation from French is not blocked.
std::unique_ptr<translate::TranslatePrefs> translatePrefs( GREYAssert(![TranslateAppInterface isBlockedLanguage:@"fr"],
ChromeIOSTranslateClient::CreateTranslatePrefs(
chrome_test_util::GetOriginalBrowserState()->GetPrefs()));
GREYAssert(!translatePrefs->IsBlockedLanguage("fr"),
@"Translation from French is blocked"); @"Translation from French is blocked");
// Trigger and refuse the auto "Never Translate ...". // Trigger and refuse the auto "Never Translate ...".
...@@ -1460,11 +1317,9 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier { ...@@ -1460,11 +1317,9 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier {
[self assertTranslateInfobarIsVisible]; [self assertTranslateInfobarIsVisible];
NSString* URLHost = base::SysUTF8ToNSString(URL.HostNoBrackets());
// Make sure that translation for the site is not blocked. // Make sure that translation for the site is not blocked.
std::unique_ptr<translate::TranslatePrefs> translatePrefs( GREYAssert(![TranslateAppInterface isBlockedSite:URLHost],
ChromeIOSTranslateClient::CreateTranslatePrefs(
chrome_test_util::GetOriginalBrowserState()->GetPrefs()));
GREYAssert(!translatePrefs->IsSiteBlacklisted(URL.HostNoBrackets()),
@"Translation is blocked for the site"); @"Translation is blocked for the site");
// Open the translate options menu. // Open the translate options menu.
...@@ -1483,7 +1338,7 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier { ...@@ -1483,7 +1338,7 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier {
[[EarlGrey selectElementWithMatcher:UndoButton()] performAction:grey_tap()]; [[EarlGrey selectElementWithMatcher:UndoButton()] performAction:grey_tap()];
// Make sure that translation for the site is still not blocked. // Make sure that translation for the site is still not blocked.
GREYAssert(!translatePrefs->IsSiteBlacklisted(URL.HostNoBrackets()), GREYAssert(![TranslateAppInterface isBlockedSite:URLHost],
@"Translation is blocked for the site"); @"Translation is blocked for the site");
// Open the translate options menu. // Open the translate options menu.
...@@ -1495,7 +1350,7 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier { ...@@ -1495,7 +1350,7 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier {
performAction:grey_tap()]; performAction:grey_tap()];
// Make sure that translation for the site is not blocked yet. // Make sure that translation for the site is not blocked yet.
GREYAssert(!translatePrefs->IsSiteBlacklisted(URL.HostNoBrackets()), GREYAssert(![TranslateAppInterface isBlockedSite:URLHost],
@"Translation is blocked for the site"); @"Translation is blocked for the site");
// Tap the notification snackbar to dismiss it. // Tap the notification snackbar to dismiss it.
...@@ -1506,7 +1361,7 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier { ...@@ -1506,7 +1361,7 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier {
// Make sure that translation for the site is blocked after the snackbar is // Make sure that translation for the site is blocked after the snackbar is
// dismissed. // dismissed.
GREYAssert(translatePrefs->IsSiteBlacklisted(URL.HostNoBrackets()), GREYAssert([TranslateAppInterface isBlockedSite:URLHost],
@"Translation is not blocked for the site"); @"Translation is not blocked for the site");
// Wait until the translate infobar disappears. // Wait until the translate infobar disappears.
...@@ -1717,8 +1572,7 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier { ...@@ -1717,8 +1572,7 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier {
[ChromeEarlGrey loadURL:noTranslateContentURL]; [ChromeEarlGrey loadURL:noTranslateContentURL];
// Make sure no language has been detected. // Make sure no language has been detected.
GREYAssert( GREYAssertFalse([self waitForLanguageDetection],
!_language_detection_tab_helper_observer->GetLanguageDetectionDetails(),
@"A language has been detected"); @"A language has been detected");
// Make sure the Translate manual trigger button is not enabled. // Make sure the Translate manual trigger button is not enabled.
...@@ -1737,8 +1591,7 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier { ...@@ -1737,8 +1591,7 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier {
[ChromeEarlGrey loadURL:noTranslateValueURL]; [ChromeEarlGrey loadURL:noTranslateValueURL];
// Make sure no language has been detected. // Make sure no language has been detected.
GREYAssert( GREYAssertFalse([self waitForLanguageDetection],
!_language_detection_tab_helper_observer->GetLanguageDetectionDetails(),
@"A language has been detected"); @"A language has been detected");
// Make sure the Translate manual trigger button is not enabled. // Make sure the Translate manual trigger button is not enabled.
...@@ -1804,42 +1657,48 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier { ...@@ -1804,42 +1657,48 @@ class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier {
return WaitUntilConditionOrTimeout(kWaitForUIElementTimeout, condition); return WaitUntilConditionOrTimeout(kWaitForUIElementTimeout, condition);
} }
// Returns whether a language has been detected on the current page. Returns
// false if a timeout was detected while waiting for language detection.
- (BOOL)waitForLanguageDetection {
bool detected = WaitUntilConditionOrTimeout(kWaitForJSCompletionTimeout, ^{
return [TranslateAppInterface isLanguageDetected];
});
return detected;
}
// Waits until language details have been detected then verifies them. Resets // Waits until language details have been detected then verifies them. Resets
// language details in order to wait for new detection in the next call. // language details in order to wait for new detection in the next call.
- (void)assertLanguageDetails: - (void)assertLanguageDetails:
(const translate::LanguageDetectionDetails&)expectedDetails { (const translate::LanguageDetectionDetails&)expectedDetails {
GREYAssert(WaitUntilConditionOrTimeout( GREYAssert([self waitForLanguageDetection],
kWaitForJSCompletionTimeout,
^{
return _language_detection_tab_helper_observer
->GetLanguageDetectionDetails() != nullptr;
}),
@"Language not detected"); @"Language not detected");
translate::LanguageDetectionDetails* details =
_language_detection_tab_helper_observer->GetLanguageDetectionDetails();
std::string contentLanguage =
base::SysNSStringToUTF8([TranslateAppInterface contentLanguage]);
NSString* contentLanguageError = NSString* contentLanguageError =
[NSString stringWithFormat:@"Wrong content-language: %s (expected %s)", [NSString stringWithFormat:@"Wrong content-language: %s (expected %s)",
details->content_language.c_str(), contentLanguage.c_str(),
expectedDetails.content_language.c_str()]; expectedDetails.content_language.c_str()];
GREYAssert(expectedDetails.content_language == details->content_language, GREYAssertEqual(expectedDetails.content_language, contentLanguage,
contentLanguageError); contentLanguageError);
std::string htmlRootLanguage =
base::SysNSStringToUTF8([TranslateAppInterface htmlRootLanguage]);
NSString* htmlRootLanguageError = NSString* htmlRootLanguageError =
[NSString stringWithFormat:@"Wrong html root language: %s (expected %s)", [NSString stringWithFormat:@"Wrong html root language: %s (expected %s)",
details->html_root_language.c_str(), htmlRootLanguage.c_str(),
expectedDetails.html_root_language.c_str()]; expectedDetails.html_root_language.c_str()];
GREYAssert(expectedDetails.html_root_language == details->html_root_language, GREYAssertEqual(expectedDetails.html_root_language, htmlRootLanguage,
htmlRootLanguageError); htmlRootLanguageError);
std::string adoptedLanguage =
base::SysNSStringToUTF8([TranslateAppInterface adoptedLanguage]);
NSString* adoptedLanguageError = NSString* adoptedLanguageError =
[NSString stringWithFormat:@"Wrong adopted language: %s (expected %s)", [NSString stringWithFormat:@"Wrong adopted language: %s (expected %s)",
details->adopted_language.c_str(), adoptedLanguage.c_str(),
expectedDetails.adopted_language.c_str()]; expectedDetails.adopted_language.c_str()];
GREYAssert(expectedDetails.adopted_language == details->adopted_language, GREYAssertEqual(expectedDetails.adopted_language, adoptedLanguage,
adoptedLanguageError); adoptedLanguageError);
_language_detection_tab_helper_observer->ResetLanguageDetectionDetails();
} }
@end @end
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment