1#!/usr/bin/env python3
2#
3#   Copyright 2016 - The Android Open Source Project
4#
5#   Licensed under the Apache License, Version 2.0 (the "License");
6#   you may not use this file except in compliance with the License.
7#   You may obtain a copy of the License at
8#
9#       http://www.apache.org/licenses/LICENSE-2.0
10#
11#   Unless required by applicable law or agreed to in writing, software
12#   distributed under the License is distributed on an "AS IS" BASIS,
13#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14#   See the License for the specific language governing permissions and
15#   limitations under the License.
16"""
17Fi Switching Methods
18"""
19import time
20from acts.libs.utils.multithread import multithread_func
21from acts.controllers.anritsu_lib._anritsu_utils import AnritsuError
22from acts.controllers.anritsu_lib.md8475a import MD8475A
23from acts_contrib.test_utils.tel.anritsu_utils import cb_serial_number
24from acts_contrib.test_utils.tel.anritsu_utils import set_system_model_lte
25from acts_contrib.test_utils.tel.anritsu_utils import set_usim_parameters
26from acts_contrib.test_utils.tel.anritsu_utils import set_post_sim_params
27from acts_contrib.test_utils.tel.TelephonyBaseTest import TelephonyBaseTest
28from acts_contrib.test_utils.tel.tel_defines import NETWORK_MODE_LTE_GSM_WCDMA
29from acts_contrib.test_utils.tel.tel_defines import RAT_FAMILY_LTE
30from acts.test_decorators import test_tracker_info
31from acts_contrib.test_utils.tel.tel_defines import RAT_LTE
32from acts_contrib.test_utils.tel.tel_defines import CARRIER_SPT
33from acts_contrib.test_utils.tel.tel_defines import CARRIER_TMO
34from acts_contrib.test_utils.tel.tel_defines import CARRIER_USCC
35from acts_contrib.test_utils.tel.tel_logging_utils import log_screen_shot
36from acts_contrib.test_utils.tel.tel_logging_utils import start_qxdm_loggers
37from acts_contrib.test_utils.tel.tel_lookup_tables import operator_name_from_plmn_id
38from acts_contrib.test_utils.tel.tel_phone_setup_utils import ensure_phone_subscription
39from acts_contrib.test_utils.tel.tel_phone_setup_utils import ensure_phones_idle
40from acts_contrib.test_utils.tel.tel_phone_setup_utils import ensure_preferred_network_type_for_subscription
41from acts_contrib.test_utils.tel.tel_test_utils import abort_all_tests
42from acts_contrib.test_utils.tel.tel_test_utils import is_sim_ready
43from acts_contrib.test_utils.tel.tel_test_utils import reboot_device
44from acts_contrib.test_utils.tel.tel_test_utils import refresh_droid_config
45from acts_contrib.test_utils.tel.tel_test_utils import send_dialer_secret_code
46from acts_contrib.test_utils.tel.tel_test_utils import toggle_airplane_mode
47from acts_contrib.test_utils.tel.tel_test_utils import toggle_airplane_mode_by_adb
48from acts_contrib.test_utils.tel.tel_test_utils import wait_for_state
49from acts_contrib.test_utils.tel.tel_test_utils import add_google_account
50from acts_contrib.test_utils.tel.tel_test_utils import remove_google_account
51from acts_contrib.test_utils.tel.tel_wifi_utils import ensure_wifi_connected
52
53WAIT_TIME_BETWEEN_REG_AND_MSG = 15  # default 15 sec
54CARRIER = None
55CARRIER_AUTO = "auto"
56
57_CARRIER_DIALER_CODE_LOOKUP = {
58    CARRIER_AUTO: '342886',
59    CARRIER_SPT: '34777',
60    CARRIER_TMO: '34866',
61    CARRIER_USCC: '34872'
62}
63
64_SWITCHING_PREF_FILE = (
65    '/data/data/com.google.android.apps.tycho/shared_prefs/switching.xml')
66
67_INTENT_FLAGS = int(0x00008000 | 0x10000000 | 0x00080000 | 0x00020000)
68_TYCHO_PKG = 'com.google.android.apps.tycho'
69_MAX_WAIT_TIME = 120
70_TYCHO_VERBOSE_LOGGING_CMDS = [
71    "setprop log.tag.Tycho VERBOSE",
72    "CLASSPATH=/system/framework/am.jar su root app_process "
73    "/system/bin com.android.commands.am.Am broadcast -a "
74    "com.google.gservices.intent.action.GSERVICES_OVERRIDE "
75    "-e tycho.enable_request_logging true",
76    "CLASSPATH=/system/framework/am.jar su root app_process "
77    "/system/bin com.android.commands.am.Am broadcast -a "
78    "com.google.gservices.intent.action.GSERVICES_OVERRIDE "
79    "-e tycho.enable_sensitive_logging true",
80    "CLASSPATH=/system/framework/am.jar su root app_process "
81    "/system/bin com.android.commands.am.Am broadcast -a "
82    "com.google.gservices.intent.action.GSERVICES_OVERRIDE "
83    "-e tycho.enable_ample_logging true"
84]
85
86_TYCHO_SERVER_LAB_OVERRIDE_CMD = (
87    "am broadcast -a com.google.gservices.intent.action.GSERVICES_OVERRIDE -e "
88    "url:tycho_server_endpoint https://android.googleapis.com/nova/nfe/ rewrite"
89    " https://android.googleapis.com/lab/nova/nfe/")
90
91
92class TychoClassId(object):
93    """Tycho Activity/Service Classnames."""
94    # Activities
95    CARRIER_SETUP = 'CarrierSetupEntryPointTrampoline'
96    INIT_ACTIVITY = 'InitActivity'
97    # Services
98    SYNC_SERVICE = 'services.SyncService'
99    ACTIVATE_SUPER_NETWORK_SERVICE = 'services.SuperNetworkConfigurationService'
100
101
102class ActionTypeId(object):
103    """Andorid Action Type to trigger events."""
104    MAIN = 'android.intent.action.MAIN'
105    MASTER_CLEAR_NOTIFICATION = 'android.intent.action.MASTER_CLEAR_NOTIFICATION'
106    TYCHO_ACTIVATE_SUPER_NETWORK = (
107        'com.google.android.apps.tycho.ActionType.ACTIVATE_SUPER_NETWORK')
108
109
110class TelLabProjectFiTest(TelephonyBaseTest):
111    SERIAL_NO = cb_serial_number()
112
113    def setup_class(self):
114        super().setup_class()
115        self.ad = self.android_devices[0]
116        self.ad.sim_card = getattr(self.ad, "sim_card", None)
117        self.md8475a_ip_address = self.user_params[
118            "anritsu_md8475a_ip_address"]
119        self.wlan_option = self.user_params.get("anritsu_wlan_option", False)
120        self.md8475_version = self.user_params.get("md8475", "A")
121        self.ad.adb.shell("settings put secure cmas_additional_broadcast_pkg "
122                          "com.googlecode.android_scripting")
123        self.wait_time_between_reg_and_msg = self.user_params.get(
124            "wait_time_between_reg_and_msg", WAIT_TIME_BETWEEN_REG_AND_MSG)
125
126        try:
127            self.anritsu = MD8475A(self.md8475a_ip_address, self.wlan_option,
128                                   self.md8475_version)
129        except AnritsuError:
130            self.log.error("Error in connecting to Anritsu Simulator")
131            return False
132        self.activation_attemps = self.user_params.get("activation_attemps", 3)
133        return True
134
135    def setup_test(self):
136        if getattr(self, "qxdm_log", True):
137            start_qxdm_loggers(self.log, self.android_devices)
138        ensure_phones_idle(self.log, self.android_devices)
139        toggle_airplane_mode(self.log, self.ad, True)
140        return True
141
142    def teardown_test(self):
143        self.log.info("Stopping Simulation")
144        self.anritsu.stop_simulation()
145        toggle_airplane_mode(self.log, self.ad, True)
146
147    def teardown_class(self):
148        self.anritsu.disconnect()
149        return True
150
151    def _bring_up_callbox(self, set_simulation_func, rat):
152        try:
153            [self.bts1] = set_simulation_func(self.anritsu, self.user_params,
154                                              self.ad.sim_card)
155            set_usim_parameters(self.anritsu, self.ad.sim_card)
156            if rat == RAT_LTE:
157                set_post_sim_params(self.anritsu, self.user_params,
158                                    self.ad.sim_card)
159            self.anritsu.start_simulation()
160
161            if rat == RAT_LTE:
162                preferred_network_setting = NETWORK_MODE_LTE_GSM_WCDMA
163                rat_family = RAT_FAMILY_LTE
164            else:
165                self.log.error("No valid RAT provided to bring up callbox.")
166                return False
167
168            if not ensure_preferred_network_type_for_subscription(
169                    self.ad, preferred_network_setting):
170                self.log.error(
171                    "Failed to set rat family {}, preferred network:{}".format(
172                        rat_family, preferred_network_setting))
173                return False
174
175            if self.ad.droid.connectivityCheckAirplaneMode():
176                toggle_airplane_mode(self.log, self.ad, False)
177        except AnritsuError as e:
178            self.log.error("Error in connection with Anritsu Simulator: " +
179                           str(e))
180            return False
181        return True
182
183    def pre_switching_callbox_setup(self):
184        """ Setup environment to enable carrier switching
185        Returns:
186            True if pass; False if fail
187        """
188        return self._bring_up_callbox(set_system_model_lte, RAT_LTE)
189
190    def _install_account_util(self, ad):
191        account_util = self.user_params["account_util"]
192        if isinstance(account_util, list):
193            account_util = account_util[0]
194        ad.log.info("Install account_util %s", account_util)
195        ad.ensure_screen_on()
196        ad.adb.install("-r %s" % account_util, timeout=300, ignore_status=True)
197        time.sleep(3)
198        if not ad.is_apk_installed("com.google.android.tradefed.account"):
199            ad.log.info("com.google.android.tradefed.account is not installed")
200            return False
201        return True
202
203    def _account_registration(self, ad):
204        toggle_airplane_mode_by_adb(self.log, ad, new_state=False)
205        for cmd in _TYCHO_VERBOSE_LOGGING_CMDS:
206            ad.adb.shell(cmd)
207        if hasattr(ad, "user_account"):
208            ad.exit_setup_wizard()
209            if not ad.is_apk_installed("com.google.android.tradefed.account"
210                                       ) and \
211                    self.user_params.get("account_util"):
212                for _ in range(2):
213                    if self._install_account_util(ad):
214                        break
215                else:
216                    ad.log.error(
217                        "Fail to install com.google.android.tradefed.account")
218                    return False
219            ad.force_stop_apk(_TYCHO_PKG)
220            if not ensure_wifi_connected(self.log, ad, self.wifi_network_ssid,
221                                         self.wifi_network_pass):
222                ad.log.error("Failed to connect to wifi")
223                return False
224            ad.log.info("Add google account")
225            if not add_google_account(ad):
226                ad.log.error("Failed to add google account")
227                return False
228            ad.adb.shell(
229                'am instrument -w -e account "%s@gmail.com" -e password '
230                '"%s" -e sync true -e wait-for-checkin false '
231                'com.google.android.tradefed.account/.AddAccount' %
232                (ad.user_account, ad.user_password))
233            ad.log.info("Enable and activate tycho apk")
234            if not ad.is_apk_installed(_TYCHO_PKG):
235                ad.log.info("%s is not installed", _TYCHO_PKG)
236                return False
237            ad.adb.shell('pm enable %s' % _TYCHO_PKG)
238            # ad.adb.shell(_TYCHO_SERVER_LAB_OVERRIDE_CMD)
239            for i in range(1, self.activation_attemps + 1):
240                if i == self.activation_attemps:
241                    ad.log.info("Reboot and try Fi activation again")
242                    reboot_device(ad)
243                self.activate_fi_account(ad)
244                if not self.check_project_fi_activated(ad):
245                    ad.log.error("Fail to activate Fi account on attempt-%s",
246                                 i)
247                    if i == self.activation_attemps:
248                        return False
249                else:
250                    ad.log.info("Fi account is activated successfully")
251                    break
252        elif "Fi Network" in ad.adb.getprop("gsm.sim.operator.alpha"):
253            ad.log.error("Google account is not provided for Fi Network")
254            return False
255        if not ensure_phone_subscription(self.log, ad):
256            ad.log.error("Unable to find a valid subscription!")
257            return False
258        refresh_droid_config(self.log, ad)
259        return True
260
261    def start_service(self, ad, package, service_id, extras, action_type):
262        """Starts the specified service.
263
264        Args:
265          ad: (android_device.AndroidDevice) device to start activity on
266          package: (str) the package to start the service from
267          service_id: (str) service to start
268          extras: (dict) extras needed to specify with the activity id
269          action_type: The action type id to create the intent
270        """
271        ad.log.info('Starting service %s/.%s.', package, service_id)
272        intent = ad.droid.makeIntent(action_type, None, None, extras,
273                                     ['android.intent.category.DEFAULT'],
274                                     package, package + '.' + service_id,
275                                     _INTENT_FLAGS)
276        ad.droid.startServiceIntent(intent)
277
278    def start_activity(self, ad, package, activity_id, extras=None):
279        """Starts the specified activity.
280
281        Args:
282          ad: (android_device.AndroidDevice) device to start activity on
283          package: (str) the package to start
284          activity_id: (str) activity to start
285          extras: (dict) extras needed to specify with the activity id
286        """
287        ad.log.info('Starting activity %s/.%s.', package, activity_id)
288        intent = ad.droid.makeIntent(ActionTypeId.MAIN, None, None, extras,
289                                     ['android.intent.category.LAUNCHER'],
290                                     package, package + '.' + activity_id,
291                                     _INTENT_FLAGS)
292        ad.droid.startActivityIntent(intent, False)
293
294    def activate_fi_account(self, ad):
295        """Start Tycho InitActivity.
296
297        For in-app Tycho activition (post-SUW tests), Tycho does not
298        automatically trigger OMADM process. This method is used to start
299        Tycho InitActivity before launching super network activation.
300
301        The device will finally stay on Sprint network if everything goes well.
302
303        Args:
304          ad: Android device need to start Tycho InitActivity.
305        """
306        ad.force_stop_apk(_TYCHO_PKG)
307        ad.send_keycode("HOME")
308        extra = {'in_setup_wizard': False, 'force_show_account_chooser': False}
309        self.start_activity(ad, _TYCHO_PKG, TychoClassId.INIT_ACTIVITY, extra)
310        for _ in range(30):
311            ad.send_keycode("WAKEUP")
312            time.sleep(1)
313            current_window = ad.get_my_current_focus_window()
314            log_screen_shot(ad, self.test_name)
315            if ad.adb.shell(
316                    "settings get global device_provisioning_mobile_data"
317            ) != "1":
318                ad.adb.shell(
319                    "settings put global device_provisioning_mobile_data 1")
320            if 'SwitchConfirmDialogActivity' in current_window:
321                ad.log.info("In Switch Confirmation Dialog")
322                if ad.adb.getprop("ro.build.version.release")[0] not in ("8",
323                                                                         "O"):
324                    ad.send_keycode("TAB")
325                ad.send_keycode("TAB")
326                ad.send_keycode("ENTER")
327                time.sleep(10)
328            elif 'tycho.InitActivity' in current_window:
329                ad.log.info("In Tycho InitActivity")
330                ad.send_keycode("TAB")
331                ad.send_keycode("TAB")
332                ad.send_keycode("ENTER")
333                time.sleep(10)
334
335            elif 'tycho.AccountChooserActivity' in current_window:
336                ad.send_keycode("ENTER")
337            else:
338                ad.log.info("Finished activation process")
339                return
340
341    def check_project_fi_activated(self, ad, retries=20):
342        for _ in range(retries):
343            if is_sim_ready(self.log, ad) and (
344                    ad.droid.telephonyGetSimOperatorName() == "Fi Network"):
345                ad.log.info("SIM state is READY, SIM operator is Fi")
346                return True
347            time.sleep(5)
348
349    def start_tycho_activation(self, ad):
350        """Start the Tycho client and register to cellular network.
351
352        Starts Tycho within SUW:
353         - Tycho is expected to follow the in-SUW work flow:
354          - Tycho will perform TychoInit, handshake to server,
355            account configuration, etc
356          - If successful, Tycho will trigger a switch to Sprint Network
357          - If successful, Tycho will start OMA-DM activation sessions
358
359        The device will finally stay on Sprint network if everything goes well.
360
361        Args:
362          ad: Android device need to start Tycho activation.
363        """
364        extra = {'device_setup': True, 'has_account': True}
365        self.start_activity(ad, _TYCHO_PKG, TychoClassId.CARRIER_SETUP, extra)
366
367    def start_super_network_activation(self, ad):
368        """Start the Super-Network activation.
369
370        For in-app Tycho activition (post-SUW tests), this method starts
371        super-network activation after Tycho is initialized.
372
373        The device will finally stay on Sprint network if everything goes well.
374
375        Args:
376          ad: Android device need to start Tycho super network activation.
377        """
378        extra = {'in_setup_wizard': False, 'is_interactive': True}
379        self.start_service(ad, _TYCHO_PKG,
380                           TychoClassId.ACTIVATE_SUPER_NETWORK_SERVICE, extra,
381                           ActionTypeId.TYCHO_ACTIVATE_SUPER_NETWORK)
382
383    def get_active_carrier(self, ad):
384        """Gets the active carrier profile value from the device.
385
386        Args:
387            ad: An AndroidDevice Object.
388
389        Returns:
390            (string) A key from the CARRIER_TO_MCC_MNC map representing the
391            active carrier.
392
393        Raises:
394            KeyError: when an mcc_mnc code reported by the device is not a
395            recognized Fi partner carrier.
396        """
397        mcc_mnc = ad.droid.telephonyGetSimOperator()
398        if not mcc_mnc:
399            return "UNKNOWN"
400        try:
401            return operator_name_from_plmn_id(mcc_mnc)
402        except KeyError:
403            ad.log.error('Unknown Mobile Country Code/Mobile Network Code %s',
404                         mcc_mnc)
405            raise
406
407    def switch_sim(self, ad):
408        """Requests switch between physical sim and esim.
409
410        Args:
411            ad: An AndroidDevice Object.
412            timeout: (optional -- integer) the number of seconds in which a
413                     switch should be completed.
414
415        Raises:
416            Error: whenever a device is not set to the desired carrier within
417                   the timeout window.
418        """
419        old_sim_operator = ad.droid.telephonyGetSimOperatorName()
420        ad.log.info("Before SIM switch, SIM operator = %s", old_sim_operator)
421        send_dialer_secret_code(ad, "794824746")
422        time.sleep(10)
423        new_sim_operator = ad.droid.telephonyGetSimOperatorName()
424        ad.log.info("After SIM switch, SIM operator = %s", new_sim_operator)
425        refresh_droid_config(self.log, ad)
426        return old_sim_operator != new_sim_operator
427
428    def set_active_carrier(self,
429                           ad,
430                           carrier,
431                           timeout=_MAX_WAIT_TIME,
432                           check_interval=10):
433        """Requests an active carrier to be set on the device sim.
434
435        If switching to a different carrier, after the switch is completed
436        auto-switching will be disabled. To re-enable, call
437        enable_auto_switching.
438
439        Args:
440            ad: An AndroidDevice Object.
441            carrier: (carrier_constants.Carrier) Which carrier to switch to.
442            timeout: (optional -- integer) the number of seconds in which a
443                     switch should be completed.
444
445        Raises:
446            Error: whenever a device is not set to the desired carrier within
447                   the timeout window.
448        """
449        # If there's no need to switch, then don't.
450
451        if self.pre_switching_callbox_setup():
452            self.log.info("Turned ON Anritsu for Switching")
453        else:
454            self.log.error("Failed to Camp to Anritsu")
455            return False
456
457        max_time = timeout
458        while max_time >= 0:
459            if self.is_ready_to_make_carrier_switch(ad):
460                break
461            time.sleep(check_interval)
462            max_time -= check_interval
463        else:
464            ad.log.error("Device stays in carrier switch lock state")
465            return False
466        if carrier == CARRIER_AUTO:
467            send_dialer_secret_code(ad, _CARRIER_DIALER_CODE_LOOKUP[carrier])
468            return True
469        old_carrier = self.get_active_carrier(ad)
470        if carrier == old_carrier:
471            ad.log.info('Already on %s, so no need to switch', carrier)
472            return True
473
474        # Start switch on device, using events to verify that the switch starts.
475        ad.log.info('Initiating unsolicited switch from %s to %s.',
476                    old_carrier, carrier)
477        send_dialer_secret_code(ad, _CARRIER_DIALER_CODE_LOOKUP[carrier])
478        return self.wait_for_carrier_switch_completed(
479            ad, carrier, timeout=timeout, check_interval=check_interval)
480
481    def is_switching_silent(self, ad):
482        """Checks if Tycho switching controller is in silent mode.
483
484        Note that silent mode is a sign of airplane mode, not of a switching \
485        lock.
486
487        Args: ad: An AndroidDevice Object.
488
489        Returns:
490            A Boolean True if the preferences file reports True, False
491            otherwise.
492        """
493        return "isInSilentMode\" value=\"true" in ad.adb.shell(
494            "cat %s | grep isInSilentMode" % _SWITCHING_PREF_FILE,
495            ignore_status=True)
496
497    def is_switching_locked(self, ad):
498        """Checks if Tycho switching controller is locked.
499
500        Args: ad: An AndroidDevice Object.
501
502        Returns:
503            A Boolean True if the switching controller is locked for any reason,
504            False otherwise.
505        """
506        return "switchingInProgress\" value=\"true" in ad.adb.shell(
507            "cat %s | grep switchingInProgress" % _SWITCHING_PREF_FILE)
508
509    def is_ready_to_make_carrier_switch(self, ad):
510        """Checks if device is ready to make carrier switch.
511
512        Args:
513            ad: An AndroidDevice Object.
514
515        Returns:
516             A Boolean True if it is ready to make switch, False otherwise.
517        """
518        # Check Tycho switching controller states.
519        if self.is_switching_silent(ad):
520            ad.log.info(
521                "Cannot make carrier switch: SwitchingController is in silent "
522                "mode!")
523            return False
524        if self.is_switching_locked(ad):
525            ad.log.info(
526                "Cannot make carrier switch: SwitchingController is locked!")
527            return False
528        if self.is_carrier_switch_in_progress(ad):
529            ad.log.info("Cannot make carrier switch: Switch in progress!")
530            return False
531        return True
532
533    def is_carrier_switch_in_progress(self, ad):
534        """Checks if Tycho says that a switch is currently in progress.
535
536        Args:
537            ad: An AndroidDevice Object.
538
539        Returns:
540             A Boolean True if the preferences file reports True, False
541             otherwise.
542        """
543        switching_preferences = ad.adb.shell("cat %s" % _SWITCHING_PREF_FILE)
544        return 'InProgress\" value=\"true' in switching_preferences
545
546    def check_network_carrier(self, ad, carrier):
547        current_carrier = self.get_active_carrier(ad)
548        ad.log.info("Current network carrier is %s", current_carrier)
549        is_in_switch = self.is_carrier_switch_in_progress(ad)
550        ad.log.info("Device in carrier switch progress mode")
551        return current_carrier == carrier and is_in_switch
552
553    def wait_for_carrier_switch_completed(self,
554                                          ad,
555                                          carrier,
556                                          timeout=_MAX_WAIT_TIME,
557                                          check_interval=10):
558        """Wait for carrier switch to complete.
559
560        This function waits for a carrier switch to complete by monitoring the
561        Tycho switching controller preference file.
562
563        Args:
564            ad: An Android device object.
565            carrier: The target carrier network to switch to.
566            timeout: (integer) Time wait for switch to complete.
567
568        Return:
569            True or False for successful/unsuccessful switch.
570        """
571        check_args = [ad, carrier]
572        if wait_for_state(self.check_network_carrier, True, check_interval,
573                          timeout, *check_args):
574            ad.log.info("Switched to %s successfully", carrier)
575            ad.send_keycode("ENTER")
576            return True
577        else:
578            active_carrier = self.get_active_carrier(ad)
579            if active_carrier == carrier:
580                ad.log.info("Switched to %s successfully", carrier)
581                return True
582            ad.log.error("Carrier is %s. Fail to switch to %s", active_carrier,
583                         carrier)
584            return False
585
586    def operator_network_switch(self, ad, carrier):
587        if ad.droid.telephonyGetSimOperatorName() == "Google Fi":
588            for i in range(3):
589                if self.set_active_carrier(ad, carrier):
590                    break
591                elif i == 2:
592                    ad.log.error("Failed to switch to %s", carrier)
593                    return False
594        if not ensure_phone_subscription(self.log, ad):
595            ad.log.error("Unable to find a valid subscription!")
596            return False
597        refresh_droid_config(self.log, ad)
598        return True
599
600    def network_switch_test(self, carrier):
601        tasks = [(self.operator_network_switch, [ad, carrier])
602                 for ad in self.android_devices]
603        if not multithread_func(self.log, tasks):
604            abort_all_tests(self.log,
605                            "Unable to switch to network %s" % carrier)
606        return True
607
608    """ Tests Begin """
609
610    @test_tracker_info(uuid="4d92318e-4980-471a-882b-3136c5dda384")
611    @TelephonyBaseTest.tel_test_wrap
612    def test_project_fi_account_activation(self):
613        """Test activate Fi account.
614
615        Returns:
616            True if success.
617            False if failed.
618        """
619        tasks = [(self._account_registration, [ad])
620                 for ad in self.android_devices]
621        try:
622            if not multithread_func(self.log, tasks):
623                abort_all_tests(self.log, "Unable to activate Fi account!")
624        except Exception as e:
625            self.log.error(e)
626            abort_all_tests(self.log, "Unable to activate Fi account!")
627        return True
628
629    @test_tracker_info(uuid="6bfbcc1d-e318-4964-bf36-5b82f086860d")
630    @TelephonyBaseTest.tel_test_wrap
631    def test_switch_to_tmobile_network(self):
632        """Test switch to tmobile network.
633
634        Returns:
635            True if success.
636            False if failed.
637        """
638        setattr(self.ad, "sim_card", "FiTMO")
639        return self.network_switch_test(CARRIER_TMO)
640
641    @test_tracker_info(uuid="4f27944d-f3c5-423d-b0c5-5c66dbb98376")
642    @TelephonyBaseTest.tel_test_wrap
643    def test_switch_to_sprint_network(self):
644        """Test switch to sprint network.
645
646        Returns:
647            True if success.
648            False if failed.
649        """
650        setattr(self.ad, "sim_card", "FiSPR")
651        return self.network_switch_test(CARRIER_SPT)
652
653    @test_tracker_info(uuid="5f30c9bd-b79e-4805-aa46-7855ed9023f0")
654    @TelephonyBaseTest.tel_test_wrap
655    def test_switch_to_uscc_network(self):
656        """Test switch to uscc network.
657
658        Returns:
659            True if success.
660            False if failed.
661        """
662        setattr(self.ad, "sim_card", "FiUSCC")
663        return self.network_switch_test(CARRIER_USCC)
664
665    @test_tracker_info(uuid="0b062751-d59d-420e-941e-3ffa02aea0d5")
666    @TelephonyBaseTest.tel_test_wrap
667    def test_switch_to_auto_network(self):
668        """Test switch to auto network selection.
669
670        Returns:
671            True if success.
672            False if failed.
673        """
674        return self.network_switch_test(CARRIER_AUTO)
675
676    @test_tracker_info(uuid="13c5f080-69bf-42fd-86ed-c67b1984c347")
677    @TelephonyBaseTest.tel_test_wrap
678    def test_switch_between_sim(self):
679        """Test switch between physical sim and esim.
680
681        Returns:
682            True if success.
683            False if failed.
684        """
685        for ad in self.android_devices:
686            self.switch_sim(ad)
687
688    @test_tracker_info(uuid="")
689    @TelephonyBaseTest.tel_test_wrap
690    def test_remove_google_account(self):
691        for ad in self.android_devices:
692            remove_google_account(ad)
693
694
695""" Tests End """
696