1#!/usr/bin/env python3.4
2#
3#   Copyright 2016 - Google
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"""
17    Test Script for Telephony Pre Check In Sanity
18"""
19
20import collections
21import random
22import time
23import os
24
25from acts import signals
26from acts.test_decorators import test_tracker_info
27from acts.test_utils.tel.tel_subscription_utils import \
28    get_subid_from_slot_index
29from acts.test_utils.bt.bt_test_utils import bluetooth_enabled_check
30from acts.test_utils.bt.bt_test_utils import disable_bluetooth
31from acts.test_utils.bt.bt_test_utils import pair_pri_to_sec
32from acts.test_utils.tel.tel_subscription_utils import set_subid_for_data
33from acts.test_utils.tel.TelephonyBaseTest import TelephonyBaseTest
34from acts.test_utils.tel.tel_defines import DIRECTION_MOBILE_ORIGINATED
35from acts.test_utils.tel.tel_defines import DIRECTION_MOBILE_TERMINATED
36from acts.test_utils.tel.tel_defines import DATA_STATE_CONNECTED
37from acts.test_utils.tel.tel_defines import GEN_2G
38from acts.test_utils.tel.tel_defines import GEN_3G
39from acts.test_utils.tel.tel_defines import GEN_4G
40from acts.test_utils.tel.tel_defines import NETWORK_SERVICE_DATA
41from acts.test_utils.tel.tel_defines import NETWORK_SERVICE_VOICE
42from acts.test_utils.tel.tel_defines import RAT_2G
43from acts.test_utils.tel.tel_defines import RAT_3G
44from acts.test_utils.tel.tel_defines import RAT_4G
45from acts.test_utils.tel.tel_defines import RAT_FAMILY_LTE
46from acts.test_utils.tel.tel_defines import SIM1_SLOT_INDEX
47from acts.test_utils.tel.tel_defines import SIM2_SLOT_INDEX
48from acts.test_utils.tel.tel_defines import MAX_WAIT_TIME_NW_SELECTION
49from acts.test_utils.tel.tel_defines import MAX_WAIT_TIME_TETHERING_ENTITLEMENT_CHECK
50from acts.test_utils.tel.tel_defines import MAX_WAIT_TIME_WIFI_CONNECTION
51from acts.test_utils.tel.tel_defines import TETHERING_MODE_WIFI
52from acts.test_utils.tel.tel_defines import WAIT_TIME_AFTER_REBOOT
53from acts.test_utils.tel.tel_defines import WAIT_TIME_ANDROID_STATE_SETTLING
54from acts.test_utils.tel.tel_defines import WAIT_TIME_BETWEEN_REG_AND_CALL
55from acts.test_utils.tel.tel_defines import \
56    WAIT_TIME_DATA_STATUS_CHANGE_DURING_WIFI_TETHERING
57from acts.test_utils.tel.tel_defines import WAIT_TIME_TETHERING_AFTER_REBOOT
58from acts.test_utils.tel.tel_data_utils import airplane_mode_test
59from acts.test_utils.tel.tel_data_utils import browsing_test
60from acts.test_utils.tel.tel_data_utils import change_data_sim_and_verify_data
61from acts.test_utils.tel.tel_data_utils import data_connectivity_single_bearer
62from acts.test_utils.tel.tel_data_utils import tethering_check_internet_connection
63from acts.test_utils.tel.tel_data_utils import wifi_cell_switching
64from acts.test_utils.tel.tel_data_utils import wifi_tethering_cleanup
65from acts.test_utils.tel.tel_data_utils import wifi_tethering_setup_teardown
66from acts.test_utils.tel.tel_test_utils import active_file_download_test
67from acts.test_utils.tel.tel_test_utils import call_setup_teardown
68from acts.test_utils.tel.tel_test_utils import check_is_wifi_connected
69from acts.test_utils.tel.tel_test_utils import ensure_phones_default_state
70from acts.test_utils.tel.tel_test_utils import ensure_phones_idle
71from acts.test_utils.tel.tel_test_utils import ensure_network_generation
72from acts.test_utils.tel.tel_test_utils import \
73    ensure_network_generation_for_subscription
74from acts.test_utils.tel.tel_test_utils import ensure_wifi_connected
75from acts.test_utils.tel.tel_test_utils import get_mobile_data_usage
76from acts.test_utils.tel.tel_test_utils import get_slot_index_from_subid
77from acts.test_utils.tel.tel_test_utils import get_network_rat_for_subscription
78from acts.test_utils.tel.tel_test_utils import hangup_call
79from acts.test_utils.tel.tel_test_utils import multithread_func
80from acts.test_utils.tel.tel_test_utils import remove_mobile_data_usage_limit
81from acts.test_utils.tel.tel_test_utils import set_call_state_listen_level
82from acts.test_utils.tel.tel_test_utils import set_mobile_data_usage_limit
83from acts.test_utils.tel.tel_test_utils import setup_sim
84from acts.test_utils.tel.tel_test_utils import stop_wifi_tethering
85from acts.test_utils.tel.tel_test_utils import start_wifi_tethering
86from acts.test_utils.tel.tel_test_utils import toggle_airplane_mode
87from acts.test_utils.tel.tel_test_utils import toggle_airplane_mode_by_adb
88from acts.test_utils.tel.tel_test_utils import toggle_volte
89from acts.test_utils.tel.tel_test_utils import verify_internet_connection
90from acts.test_utils.tel.tel_test_utils import verify_http_connection
91from acts.test_utils.tel.tel_test_utils import verify_incall_state
92from acts.test_utils.tel.tel_test_utils import wait_for_cell_data_connection
93from acts.test_utils.tel.tel_test_utils import wait_for_network_rat
94from acts.test_utils.tel.tel_test_utils import \
95    wait_for_voice_attach_for_subscription
96from acts.test_utils.tel.tel_test_utils import \
97    wait_for_data_attach_for_subscription
98from acts.test_utils.tel.tel_test_utils import wait_for_wifi_data_connection
99from acts.test_utils.tel.tel_test_utils import wifi_reset
100from acts.test_utils.tel.tel_test_utils import wait_for_state
101from acts.test_utils.tel.tel_test_utils import wifi_toggle_state
102from acts.test_utils.tel.tel_test_utils import WIFI_CONFIG_APBAND_2G
103from acts.test_utils.tel.tel_test_utils import WIFI_CONFIG_APBAND_5G
104from acts.test_utils.tel.tel_test_utils import WIFI_SSID_KEY
105from acts.test_utils.tel.tel_test_utils import bring_up_sl4a
106from acts.test_utils.tel.tel_test_utils import check_data_stall_detection
107from acts.test_utils.tel.tel_test_utils import check_network_validation_fail
108from acts.test_utils.tel.tel_test_utils import break_internet_except_sl4a_port
109from acts.test_utils.tel.tel_test_utils import resume_internet_with_sl4a_port
110from acts.test_utils.tel.tel_test_utils import get_device_epoch_time
111from acts.test_utils.tel.tel_test_utils import check_data_stall_recovery
112from acts.test_utils.tel.tel_test_utils import \
113    test_data_browsing_success_using_sl4a
114from acts.test_utils.tel.tel_test_utils import \
115    test_data_browsing_failure_using_sl4a
116from acts.test_utils.tel.tel_voice_utils import is_phone_in_call_3g
117from acts.test_utils.tel.tel_voice_utils import is_phone_in_call_csfb
118from acts.test_utils.tel.tel_voice_utils import is_phone_in_call_volte
119from acts.test_utils.tel.tel_voice_utils import phone_setup_voice_3g
120from acts.test_utils.tel.tel_voice_utils import phone_setup_csfb
121from acts.test_utils.tel.tel_voice_utils import phone_setup_voice_general
122from acts.test_utils.tel.tel_voice_utils import phone_setup_volte
123from acts.test_utils.tel.tel_voice_utils import phone_setup_4g
124from acts.utils import disable_doze
125from acts.utils import enable_doze
126from acts.utils import rand_ascii_str
127from acts.utils import adb_shell_ping
128
129
130class TelLiveDataTest(TelephonyBaseTest):
131    def setup_class(self):
132        super().setup_class()
133
134        self.stress_test_number = self.get_stress_test_number()
135        self.provider = self.android_devices[0]
136        self.clients = self.android_devices[1:]
137
138    def setup_test(self):
139        TelephonyBaseTest.setup_test(self)
140        self.number_of_devices = 1
141
142    def teardown_class(self):
143        TelephonyBaseTest.teardown_class(self)
144
145
146    """ Tests Begin """
147
148
149    @test_tracker_info(uuid="ba24f9a3-0126-436c-8a5c-9f88859c273c")
150    @TelephonyBaseTest.tel_test_wrap
151    def test_data_browsing_for_single_phone(self):
152        """ Browsing websites on cellular.
153
154        Ensure phone attach, data on, WiFi off
155        Verify 5 websites on cellular.
156
157        Returns:
158            True if pass; False if fail.
159        """
160        ad = self.android_devices[0]
161        wifi_toggle_state(ad.log, ad, False)
162        for iteration in range(3):
163            ad.log.info("Attempt %d", iteration + 1)
164            if test_data_browsing_success_using_sl4a(ad.log, ad):
165                ad.log.info("Call test PASS in iteration %d", iteration + 1)
166                return True
167            time.sleep(WAIT_TIME_ANDROID_STATE_SETTLING)
168        ad.log.info("Data Browsing test FAIL for all 3 iterations")
169        return False
170
171
172    @test_tracker_info(uuid="0679214b-9002-476d-83a7-3532b3cca209")
173    @TelephonyBaseTest.tel_test_wrap
174    def test_wifi_browsing_for_single_phone(self):
175        """ Browsing websites on wifi.
176
177        Ensure phone attach, data on, WiFi On, WiFi Connected.
178        Verify 5 websites on WiFi.
179
180        Returns:
181            True if pass; False if fail.
182        """
183        ad = self.android_devices[0]
184        wifi_toggle_state(ad.log, ad, True)
185        if not ensure_wifi_connected(ad.log, ad, self.wifi_network_ssid,
186                                     self.wifi_network_pass):
187            ad.log.error("WiFi connect fail.")
188            return False
189        for iteration in range(3):
190            ad.log.info("Attempt %d", iteration + 1)
191            if test_data_browsing_success_using_sl4a(ad.log, ad):
192                ad.log.info("Call test PASS in iteration %d", iteration + 1)
193                wifi_toggle_state(ad.log, ad, False)
194                return True
195            time.sleep(WAIT_TIME_ANDROID_STATE_SETTLING)
196        ad.log.info("Data Browsing test FAIL for all 3 iterations")
197        wifi_toggle_state(ad.log, ad, False)
198        return False
199
200
201    @test_tracker_info(uuid="1b0354f3-8668-4a28-90a5-3b3d2b2756d3")
202    @TelephonyBaseTest.tel_test_wrap
203    def test_airplane_mode(self):
204        """ Test airplane mode basic on Phone and Live SIM.
205
206        Ensure phone attach, data on, WiFi off and verify Internet.
207        Turn on airplane mode to make sure detach.
208        Turn off airplane mode to make sure attach.
209        Verify Internet connection.
210
211        Returns:
212            True if pass; False if fail.
213        """
214        return airplane_mode_test(self.log, self.android_devices[0])
215
216    @test_tracker_info(uuid="47430f01-583f-4efb-923a-285a51b75d50")
217    @TelephonyBaseTest.tel_test_wrap
218    def test_lte_wifi_switching(self):
219        """Test data connection network switching when phone camped on LTE.
220
221        Ensure phone is camped on LTE
222        Ensure WiFi can connect to live network,
223        Airplane mode is off, data connection is on, WiFi is on.
224        Turn off WiFi, verify data is on cell and browse to google.com is OK.
225        Turn on WiFi, verify data is on WiFi and browse to google.com is OK.
226        Turn off WiFi, verify data is on cell and browse to google.com is OK.
227
228        Returns:
229            True if pass.
230        """
231        return wifi_cell_switching(self.log, self.android_devices[0],
232                                   self.wifi_network_ssid,
233                                   self.wifi_network_pass, GEN_4G)
234
235    @test_tracker_info(uuid="98d9f8c9-0532-49b6-85a3-5246b8314755")
236    @TelephonyBaseTest.tel_test_wrap
237    def test_lte_wifi_switching_stress(self):
238        """LTE WiFi Switching Data Connection Check
239
240        Same steps as test_lte_wifi_switching with stress testing
241
242        Returns:
243            True if pass.
244        """
245        MINIMUM_SUCCESS_RATE = .95
246        success_count = 0
247        fail_count = 0
248        self.stress_test_number = 10
249
250        for i in range(1, self.stress_test_number + 1):
251            ensure_phones_default_state(
252                self.log, [self.android_devices[0]])
253
254            if wifi_cell_switching(self.log, self.android_devices[0],
255                                   self.wifi_network_ssid,
256                                   self.wifi_network_pass, GEN_4G):
257                success_count += 1
258                result_str = "Succeeded"
259            else:
260                fail_count += 1
261                result_str = "Failed"
262            self.log.info("Iteration {} {}. Current: {} / {} passed.".format(
263                i, result_str, success_count, self.stress_test_number))
264
265        self.log.info("Final Count - Success: {}, Failure: {} - {}%".format(
266            success_count, fail_count,
267            str(100 * success_count / (success_count + fail_count))))
268        if success_count / (
269                success_count + fail_count) >= MINIMUM_SUCCESS_RATE:
270            return True
271        else:
272            return False
273
274    @test_tracker_info(uuid="8a836cf1-600b-4cf3-abfe-2e3da5c11396")
275    @TelephonyBaseTest.tel_test_wrap
276    def test_wcdma_wifi_switching(self):
277        """Test data connection network switching when phone camped on WCDMA.
278
279        Ensure phone is camped on WCDMA
280        Ensure WiFi can connect to live network,
281        Airplane mode is off, data connection is on, WiFi is on.
282        Turn off WiFi, verify data is on cell and browse to google.com is OK.
283        Turn on WiFi, verify data is on WiFi and browse to google.com is OK.
284        Turn off WiFi, verify data is on cell and browse to google.com is OK.
285
286        Returns:
287            True if pass.
288        """
289        return wifi_cell_switching(self.log, self.android_devices[0],
290                                   self.wifi_network_ssid,
291                                   self.wifi_network_pass, GEN_3G)
292
293    @test_tracker_info(uuid="c016f2e8-0af6-42e4-a3cb-a2b7d8b564d0")
294    @TelephonyBaseTest.tel_test_wrap
295    def test_gsm_wifi_switching(self):
296        """Test data connection network switching when phone camped on GSM.
297
298        Ensure phone is camped on GSM
299        Ensure WiFi can connect to live network,,
300        Airplane mode is off, data connection is on, WiFi is on.
301        Turn off WiFi, verify data is on cell and browse to google.com is OK.
302        Turn on WiFi, verify data is on WiFi and browse to google.com is OK.
303        Turn off WiFi, verify data is on cell and browse to google.com is OK.
304
305        Returns:
306            True if pass.
307        """
308        return wifi_cell_switching(self.log, self.android_devices[0],
309                                   self.wifi_network_ssid,
310                                   self.wifi_network_pass, GEN_2G)
311
312    @test_tracker_info(uuid="78d6b258-82d4-47b4-8723-3b3a15412d2d")
313    @TelephonyBaseTest.tel_test_wrap
314    def test_lte_multi_bearer(self):
315        """Test LTE data connection before call and in call. (VoLTE call)
316
317
318        Turn off airplane mode, disable WiFi, enable Cellular Data.
319        Make sure phone in LTE, verify Internet.
320        Initiate a voice call. verify Internet.
321        Disable Cellular Data, verify Internet is inaccessible.
322        Enable Cellular Data, verify Internet.
323        Hangup Voice Call, verify Internet.
324
325        Returns:
326            True if success.
327            False if failed.
328        """
329        if not phone_setup_volte(self.log, self.android_devices[0]):
330            self.log.error("Failed to setup VoLTE")
331            return False
332        return self._test_data_connectivity_multi_bearer(GEN_4G)
333
334    @test_tracker_info(uuid="5c9cb076-0c26-4517-95dc-2ec4974e8ce3")
335    @TelephonyBaseTest.tel_test_wrap
336    def test_wcdma_multi_bearer(self):
337        """Test WCDMA data connection before call and in call.
338
339        Turn off airplane mode, disable WiFi, enable Cellular Data.
340        Make sure phone in WCDMA, verify Internet.
341        Initiate a voice call. verify Internet.
342        Disable Cellular Data, verify Internet is inaccessible.
343        Enable Cellular Data, verify Internet.
344        Hangup Voice Call, verify Internet.
345
346        Returns:
347            True if success.
348            False if failed.
349        """
350
351        return self._test_data_connectivity_multi_bearer(GEN_3G)
352
353    @test_tracker_info(uuid="314bbf1c-073f-4d48-9817-a6e14f96f3c0")
354    @TelephonyBaseTest.tel_test_wrap
355    def test_gsm_multi_bearer_mo(self):
356        """Test gsm data connection before call and in call.
357
358        Turn off airplane mode, disable WiFi, enable Cellular Data.
359        Make sure phone in GSM, verify Internet.
360        Initiate a MO voice call. Verify there is no Internet during call.
361        Hangup Voice Call, verify Internet.
362
363        Returns:
364            True if success.
365            False if failed.
366        """
367
368        return self._test_data_connectivity_multi_bearer(
369            GEN_2G, False, DIRECTION_MOBILE_ORIGINATED)
370
371    @test_tracker_info(uuid="549271ff-1034-4d02-8d92-b9d1b2bb912e")
372    @TelephonyBaseTest.tel_test_wrap
373    def test_gsm_multi_bearer_mt(self):
374        """Test gsm data connection before call and in call.
375
376        Turn off airplane mode, disable WiFi, enable Cellular Data.
377        Make sure phone in GSM, verify Internet.
378        Initiate a MT voice call. Verify there is no Internet during call.
379        Hangup Voice Call, verify Internet.
380
381        Returns:
382            True if success.
383            False if failed.
384        """
385
386        return self._test_data_connectivity_multi_bearer(
387            GEN_2G, False, DIRECTION_MOBILE_TERMINATED)
388
389    @test_tracker_info(uuid="111de471-559a-4bc3-9d3e-de18f098c162")
390    @TelephonyBaseTest.tel_test_wrap
391    def test_wcdma_multi_bearer_stress(self):
392        """Stress Test WCDMA data connection before call and in call.
393
394        This is a stress test for "test_wcdma_multi_bearer".
395        Default MINIMUM_SUCCESS_RATE is set to 95%.
396
397        Returns:
398            True stress pass rate is higher than MINIMUM_SUCCESS_RATE.
399            False otherwise.
400        """
401        MINIMUM_SUCCESS_RATE = .95
402        success_count = 0
403        fail_count = 0
404        self.number_of_devices = 2
405
406        for i in range(1, self.stress_test_number + 1):
407
408            ensure_phones_default_state(
409                self.log, [self.android_devices[0], self.android_devices[1]])
410
411            if self.test_wcdma_multi_bearer():
412                success_count += 1
413                result_str = "Succeeded"
414            else:
415                fail_count += 1
416                result_str = "Failed"
417            self.log.info("Iteration {} {}. Current: {} / {} passed.".format(
418                i, result_str, success_count, self.stress_test_number))
419
420        self.log.info("Final Count - Success: {}, Failure: {} - {}%".format(
421            success_count, fail_count,
422            str(100 * success_count / (success_count + fail_count))))
423        if success_count / (
424                success_count + fail_count) >= MINIMUM_SUCCESS_RATE:
425            return True
426        else:
427            return False
428
429    @test_tracker_info(uuid="c7f14ba7-7ac3-45d2-b391-5ed5c4b0e70b")
430    @TelephonyBaseTest.tel_test_wrap
431    def test_lte_multi_bearer_stress(self):
432        """Stress Test LTE data connection before call and in call. (VoLTE call)
433
434        This is a stress test for "test_lte_multi_bearer".
435        Default MINIMUM_SUCCESS_RATE is set to 95%.
436
437        Returns:
438            True stress pass rate is higher than MINIMUM_SUCCESS_RATE.
439            False otherwise.
440        """
441        ads = self.android_devices
442        MINIMUM_SUCCESS_RATE = .95
443        success_count = 0
444        fail_count = 0
445
446        for i in range(1, self.stress_test_number + 1):
447
448            ensure_phones_default_state(
449                self.log, [self.android_devices[0], self.android_devices[1]])
450
451            if self.test_lte_multi_bearer():
452                success_count += 1
453                result_str = "Succeeded"
454            else:
455                fail_count += 1
456                result_str = "Failed"
457            self.log.info("Iteration {} {}. Current: {} / {} passed.".format(
458                i, result_str, success_count, self.stress_test_number))
459
460        self.log.info("Final Count - Success: {}, Failure: {} - {}%".format(
461            success_count, fail_count,
462            str(100 * success_count / (success_count + fail_count))))
463        if success_count / (
464                success_count + fail_count) >= MINIMUM_SUCCESS_RATE:
465            return True
466        else:
467            return False
468
469    def _test_data_connectivity_multi_bearer(
470            self,
471            nw_gen,
472            simultaneous_voice_data=True,
473            call_direction=DIRECTION_MOBILE_ORIGINATED):
474        """Test data connection before call and in call.
475
476        Turn off airplane mode, disable WiFi, enable Cellular Data.
477        Make sure phone in <nw_gen>, verify Internet.
478        Initiate a voice call.
479        if simultaneous_voice_data is True, then:
480            Verify Internet.
481            Disable Cellular Data, verify Internet is inaccessible.
482            Enable Cellular Data, verify Internet.
483        if simultaneous_voice_data is False, then:
484            Verify Internet is not available during voice call.
485        Hangup Voice Call, verify Internet.
486
487        Returns:
488            True if success.
489            False if failed.
490        """
491
492        class _LocalException(Exception):
493            pass
494
495        self.number_of_devices = 2
496        ad_list = [self.android_devices[0], self.android_devices[1]]
497        ensure_phones_idle(self.log, ad_list)
498
499        if not ensure_network_generation_for_subscription(
500                self.log, self.android_devices[0], self.android_devices[0]
501                .droid.subscriptionGetDefaultDataSubId(), nw_gen,
502                MAX_WAIT_TIME_NW_SELECTION, NETWORK_SERVICE_DATA):
503            self.log.error("Device failed to reselect in {}s.".format(
504                MAX_WAIT_TIME_NW_SELECTION))
505            return False
506
507        if not wait_for_voice_attach_for_subscription(
508                self.log, self.android_devices[0], self.android_devices[0]
509                .droid.subscriptionGetDefaultVoiceSubId(),
510                MAX_WAIT_TIME_NW_SELECTION):
511            return False
512
513        self.log.info("Step1 WiFi is Off, Data is on Cell.")
514        toggle_airplane_mode(self.log, self.android_devices[0], False)
515        wifi_toggle_state(self.log, self.android_devices[0], False)
516        self.android_devices[0].droid.telephonyToggleDataConnection(True)
517        if (not wait_for_cell_data_connection(self.log,
518                                              self.android_devices[0], True)
519                or not verify_internet_connection(self.log,
520                                                  self.android_devices[0])):
521            self.log.error("Data not available on cell")
522            return False
523
524        self.log.info(
525            "b/69431819, sending data to increase NW threshold limit")
526        adb_shell_ping(
527            self.android_devices[0], count=30, timeout=60, loss_tolerance=100)
528
529        try:
530            self.log.info("Step2 Initiate call and accept.")
531            if call_direction == DIRECTION_MOBILE_ORIGINATED:
532                ad_caller = self.android_devices[0]
533                ad_callee = self.android_devices[1]
534            else:
535                ad_caller = self.android_devices[1]
536                ad_callee = self.android_devices[0]
537            if not call_setup_teardown(self.log, ad_caller, ad_callee, None,
538                                       None, None):
539                self.log.error(
540                    "Failed to Establish {} Voice Call".format(call_direction))
541                return False
542            if simultaneous_voice_data:
543                self.log.info("Step3 Verify internet.")
544                time.sleep(WAIT_TIME_ANDROID_STATE_SETTLING)
545                if not verify_internet_connection(
546                        self.log, self.android_devices[0], retries=3):
547                    raise _LocalException("Internet Inaccessible when Enabled")
548
549                self.log.info("Step4 Turn off data and verify not connected.")
550                self.android_devices[0].droid.telephonyToggleDataConnection(
551                    False)
552                if not wait_for_cell_data_connection(
553                        self.log, self.android_devices[0], False):
554                    raise _LocalException("Failed to Disable Cellular Data")
555
556                if not verify_internet_connection(self.log,
557                                              self.android_devices[0], expected_state=False):
558                    raise _LocalException("Internet Accessible when Disabled")
559
560                self.log.info("Step5 Re-enable data.")
561                self.android_devices[0].droid.telephonyToggleDataConnection(
562                    True)
563                if not wait_for_cell_data_connection(
564                        self.log, self.android_devices[0], True):
565                    raise _LocalException("Failed to Re-Enable Cellular Data")
566                if not verify_internet_connection(
567                        self.log, self.android_devices[0], retries=3):
568                    raise _LocalException("Internet Inaccessible when Enabled")
569            else:
570                self.log.info("Step3 Verify no Internet and skip step 4-5.")
571                if verify_internet_connection(
572                        self.log, self.android_devices[0], retries=0):
573                    raise _LocalException("Internet Accessible.")
574
575            self.log.info("Step6 Verify phones still in call and Hang up.")
576            if not verify_incall_state(
577                    self.log,
578                [self.android_devices[0], self.android_devices[1]], True):
579                return False
580            if not hangup_call(self.log, self.android_devices[0]):
581                self.log.error("Failed to hang up call")
582                return False
583            if not verify_internet_connection(
584                    self.log, self.android_devices[0], retries=3):
585                raise _LocalException("Internet Inaccessible when Enabled")
586
587        except _LocalException as e:
588            self.log.error(str(e))
589            try:
590                hangup_call(self.log, self.android_devices[0])
591                self.android_devices[0].droid.telephonyToggleDataConnection(
592                    True)
593            except Exception:
594                pass
595            return False
596
597        return True
598
599    @test_tracker_info(uuid="dcb9bdc6-dbe2-47e1-9c2d-6f37c529d366")
600    @TelephonyBaseTest.tel_test_wrap
601    def test_2g(self):
602        """Test data connection in 2G.
603
604        Turn off airplane mode, disable WiFi, enable Cellular Data.
605        Ensure phone data generation is 2G.
606        Verify Internet.
607        Disable Cellular Data, verify Internet is inaccessible.
608        Enable Cellular Data, verify Internet.
609
610        Returns:
611            True if success.
612            False if failed.
613        """
614        wifi_reset(self.log, self.android_devices[0])
615        wifi_toggle_state(self.log, self.android_devices[0], False)
616        return data_connectivity_single_bearer(self.log,
617                                               self.android_devices[0], RAT_2G)
618
619    @test_tracker_info(uuid="84197a49-d73f-44ce-8b9e-9479e5c4dfdc")
620    @TelephonyBaseTest.tel_test_wrap
621    def test_2g_wifi_not_associated(self):
622        """Test data connection in 2G.
623
624        Turn off airplane mode, enable WiFi (but not connected), enable Cellular Data.
625        Ensure phone data generation is 2G.
626        Verify Internet.
627        Disable Cellular Data, verify Internet is inaccessible.
628        Enable Cellular Data, verify Internet.
629
630        Returns:
631            True if success.
632            False if failed.
633        """
634        wifi_reset(self.log, self.android_devices[0])
635        wifi_toggle_state(self.log, self.android_devices[0], False)
636        wifi_toggle_state(self.log, self.android_devices[0], True)
637        return data_connectivity_single_bearer(self.log,
638                                               self.android_devices[0], RAT_2G)
639
640    @test_tracker_info(uuid="97067ebb-130a-4fcb-8e6b-f4ec5874828f")
641    @TelephonyBaseTest.tel_test_wrap
642    def test_3g(self):
643        """Test data connection in 3G.
644
645        Turn off airplane mode, disable WiFi, enable Cellular Data.
646        Ensure phone data generation is 3G.
647        Verify Internet.
648        Disable Cellular Data, verify Internet is inaccessible.
649        Enable Cellular Data, verify Internet.
650
651        Returns:
652            True if success.
653            False if failed.
654        """
655        wifi_reset(self.log, self.android_devices[0])
656        wifi_toggle_state(self.log, self.android_devices[0], False)
657        return data_connectivity_single_bearer(self.log,
658                                               self.android_devices[0], RAT_3G)
659
660    @test_tracker_info(uuid="ffe2a392-95b8-4a4d-8a6f-bfa846c3462f")
661    @TelephonyBaseTest.tel_test_wrap
662    def test_3g_wifi_not_associated(self):
663        """Test data connection in 3G.
664
665        Turn off airplane mode, enable WiFi (but not connected), enable Cellular Data.
666        Ensure phone data generation is 3G.
667        Verify Internet.
668        Disable Cellular Data, verify Internet is inaccessible.
669        Enable Cellular Data, verify Internet.
670
671        Returns:
672            True if success.
673            False if failed.
674        """
675        wifi_reset(self.log, self.android_devices[0])
676        wifi_toggle_state(self.log, self.android_devices[0], False)
677        wifi_toggle_state(self.log, self.android_devices[0], True)
678        return data_connectivity_single_bearer(self.log,
679                                               self.android_devices[0], RAT_3G)
680
681    @test_tracker_info(uuid="9c2f459f-1aac-4c68-818b-8698e8124c8b")
682    @TelephonyBaseTest.tel_test_wrap
683    def test_4g(self):
684        """Test data connection in 4g.
685
686        Turn off airplane mode, disable WiFi, enable Cellular Data.
687        Ensure phone data generation is 4g.
688        Verify Internet.
689        Disable Cellular Data, verify Internet is inaccessible.
690        Enable Cellular Data, verify Internet.
691
692        Returns:
693            True if success.
694            False if failed.
695        """
696        wifi_reset(self.log, self.android_devices[0])
697        wifi_toggle_state(self.log, self.android_devices[0], False)
698        return data_connectivity_single_bearer(self.log,
699                                               self.android_devices[0], RAT_4G)
700
701    @test_tracker_info(uuid="015a39a1-15ac-4b76-962b-d7d82d52d425")
702    @TelephonyBaseTest.tel_test_wrap
703    def test_4g_wifi_not_associated(self):
704        """Test data connection in 4g.
705
706        Turn off airplane mode, enable WiFi (but not connected), enable Cellular Data.
707        Ensure phone data generation is 4g.
708        Verify Internet.
709        Disable Cellular Data, verify Internet is inaccessible.
710        Enable Cellular Data, verify Internet.
711
712        Returns:
713            True if success.
714            False if failed.
715        """
716        wifi_reset(self.log, self.android_devices[0])
717        wifi_toggle_state(self.log, self.android_devices[0], False)
718        wifi_toggle_state(self.log, self.android_devices[0], True)
719        return data_connectivity_single_bearer(self.log,
720                                               self.android_devices[0], RAT_4G)
721
722    @test_tracker_info(uuid="44f47b64-f8bc-4a17-9195-42dcca0806bb")
723    @TelephonyBaseTest.tel_test_wrap
724    def test_3g_stress(self):
725        """Stress Test data connection in 3G.
726
727        This is a stress test for "test_3g".
728        Default MINIMUM_SUCCESS_RATE is set to 95%.
729
730        Returns:
731            True stress pass rate is higher than MINIMUM_SUCCESS_RATE.
732            False otherwise.
733        """
734        MINIMUM_SUCCESS_RATE = .95
735        success_count = 0
736        fail_count = 0
737
738        for i in range(1, self.stress_test_number + 1):
739
740            ensure_phones_default_state(self.log, [self.android_devices[0]])
741            wifi_reset(self.log, self.android_devices[0])
742            wifi_toggle_state(self.log, self.android_devices[0], False)
743
744            if data_connectivity_single_bearer(
745                    self.log, self.android_devices[0], RAT_3G):
746                success_count += 1
747                result_str = "Succeeded"
748            else:
749                fail_count += 1
750                result_str = "Failed"
751            self.log.info("Iteration {} {}. Current: {} / {} passed.".format(
752                i, result_str, success_count, self.stress_test_number))
753
754        self.log.info("Final Count - Success: {}, Failure: {} - {}%".format(
755            success_count, fail_count,
756            str(100 * success_count / (success_count + fail_count))))
757        if success_count / (
758                success_count + fail_count) >= MINIMUM_SUCCESS_RATE:
759            return True
760        else:
761            return False
762
763    @test_tracker_info(uuid="c8876388-0441-4a51-81e6-ac2cb358a531")
764    @TelephonyBaseTest.tel_test_wrap
765    def test_4g_stress(self):
766        """Stress Test data connection in 4g.
767
768        This is a stress test for "test_4g".
769        Default MINIMUM_SUCCESS_RATE is set to 95%.
770
771        Returns:
772            True stress pass rate is higher than MINIMUM_SUCCESS_RATE.
773            False otherwise.
774        """
775        MINIMUM_SUCCESS_RATE = .95
776        success_count = 0
777        fail_count = 0
778        self.number_of_devices = 1
779
780        for i in range(1, self.stress_test_number + 1):
781
782            ensure_phones_default_state(self.log, [self.android_devices[0]])
783            wifi_reset(self.log, self.android_devices[0])
784            wifi_toggle_state(self.log, self.android_devices[0], False)
785
786            if data_connectivity_single_bearer(
787                    self.log, self.android_devices[0], RAT_4G):
788                success_count += 1
789                result_str = "Succeeded"
790            else:
791                fail_count += 1
792                result_str = "Failed"
793            self.log.info("Iteration {} {}. Current: {} / {} passed.".format(
794                i, result_str, success_count, self.stress_test_number))
795
796        self.log.info("Final Count - Success: {}, Failure: {} - {}%".format(
797            success_count, fail_count,
798            str(100 * success_count / (success_count + fail_count))))
799        if success_count / (
800                success_count + fail_count) >= MINIMUM_SUCCESS_RATE:
801            return True
802        else:
803            return False
804
805    def _test_setup_tethering(self, network_generation=None):
806        """Pre setup steps for WiFi tethering test.
807
808        Ensure all ads are idle.
809        Ensure tethering provider:
810            turn off APM, turn off WiFI, turn on Data.
811            have Internet connection, no active ongoing WiFi tethering.
812
813        Returns:
814            True if success.
815            False if failed.
816        """
817        self.number_of_devices = None
818        ensure_phones_idle(self.log, self.android_devices)
819        wifi_toggle_state(self.log, self.provider, False)
820        if network_generation:
821            if not ensure_network_generation(
822                    self.log, self.provider, network_generation,
823                    MAX_WAIT_TIME_NW_SELECTION, NETWORK_SERVICE_DATA):
824                self.provider.log.error("Provider failed to connect to %s.",
825                                        network_generation)
826                return False
827
828        self.provider.log.info(
829            "Set provider Airplane Off, Wifi Off, Bluetooth Off, Data On.")
830        toggle_airplane_mode(self.log, self.provider, False)
831        self.provider.droid.telephonyToggleDataConnection(True)
832        self.provider.log.info("Provider disable wifi")
833        wifi_toggle_state(self.log, self.provider, False)
834        # Turn off active SoftAP if any.
835        if self.provider.droid.wifiIsApEnabled():
836            self.provider.log.info("Disable provider wifi tethering")
837            stop_wifi_tethering(self.log, self.provider)
838        self.provider.log.info("Provider disable bluetooth")
839        disable_bluetooth(self.provider.droid)
840        time.sleep(10)
841
842        for ad in self.clients:
843            ad.log.info(
844                "Set client Airplane Off, Wifi Off, Bluetooth Off, Data Off.")
845            toggle_airplane_mode(self.log, ad, False)
846            ad.log.info("Client disable data")
847            ad.droid.telephonyToggleDataConnection(False)
848            ad.log.info("Client disable bluetooth")
849            disable_bluetooth(ad.droid)
850            ad.log.info("Client disable wifi")
851            wifi_toggle_state(self.log, ad, False)
852        if not wait_for_cell_data_connection(self.log, self.provider, True):
853            self.provider.log.error(
854                "Provider failed to enable data connection.")
855            return False
856
857        time.sleep(10)
858        self.log.info("Verify internet")
859        if not self._test_internet_connection(
860                client_status=False, provider_status=True):
861            self.log.error("Internet connection check failed before tethering")
862            return False
863
864        return True
865
866    def _enable_bluetooth_tethering_connection(self, provider, clients):
867        for ad in [self.provider] + self.clients:
868            if not bluetooth_enabled_check(ad):
869                ad.log.info("Bluetooth is not enabled")
870                return False
871            else:
872                ad.log.info("Bluetooth is enabled")
873
874        for client in self.clients:
875            if not (pair_pri_to_sec(self.provider, client)):
876                client.log.error("Client failed to pair with provider")
877                return False
878            else:
879                client.log.info("Client paired with provider")
880        self.provider.log.info("Provider enabling bluetooth tethering")
881        try:
882            provider.droid.bluetoothPanSetBluetoothTethering(True)
883        except Exception as e:
884            provider.log.error(
885                "Faile to enable provider Bluetooth tethering with %s", e)
886            return False
887
888        if wait_for_state(provider.droid.bluetoothPanIsTetheringOn, True):
889            provider.log.info("Provider Bluetooth tethering is enabled.")
890        else:
891            provider.log.error(
892                "Failed to enable provider Bluetooth tethering.")
893            provider.log.error("bluetoothPanIsTetheringOn = %s",
894                               provider.droid.bluetoothPanIsTetheringOn())
895            return False
896        time.sleep(5)
897        for client in clients:
898            client.droid.bluetoothConnectBonded(
899                provider.droid.bluetoothGetLocalAddress())
900        time.sleep(20)
901        return True
902
903    def _test_internet_connection(self,
904                                  client_status=True,
905                                  provider_status=True):
906        client_retry = 10 if client_status else 1
907        for client in self.clients:
908            if not verify_internet_connection(
909                    self.log,
910                    client,
911                    retries=client_retry,
912                    expected_state=client_status):
913                client.log.error("client internet connection state is not %s",
914                                 client_status)
915                return False
916            else:
917                client.log.info("client internet connection state is %s",
918                                client_status)
919        if not verify_internet_connection(
920                self.log, self.provider, retries=3,
921                expected_state=provider_status):
922            self.provider.log.error(
923                "provider internet connection is not %s" % provider_status)
924            return False
925        else:
926            self.provider.log.info(
927                "provider internet connection is %s" % provider_status)
928        return True
929
930    def _verify_bluetooth_tethering_connection(self,
931                                               change_rat=None,
932                                               toggle_data=False,
933                                               toggle_tethering=False,
934                                               voice_call=False,
935                                               toggle_bluetooth=True):
936        """Setups up a bluetooth tethering conenction between two android devices.
937
938        Returns:
939            True if PAN connection and verification is successful,
940            false if unsuccessful.
941        """
942        if not self._enable_bluetooth_tethering_connection(
943                self.provider, self.clients):
944            return False
945        if not self._test_internet_connection():
946            self.log.error("Internet connection check failed")
947            return False
948        if voice_call:
949            self.log.info("====== Voice call test =====")
950            for caller, callee in [(self.provider, self.clients[0]),
951                                   (self.clients[0], self.provider)]:
952                if not call_setup_teardown(
953                        self.log, caller, callee, ad_hangup=None):
954                    self.log.error("Setup Call Failed.")
955                    hangup_call(self.log, caller)
956                    return False
957                self.log.info("Verify data.")
958                if not verify_internet_connection(
959                        self.log, self.clients[0], retries=1):
960                    self.clients[0].log.warning(
961                        "client internet connection state is not on")
962                else:
963                    self.clients[0].log.info(
964                        "client internet connection state is on")
965                hangup_call(self.log, caller)
966                if not verify_internet_connection(
967                        self.log, self.clients[0], retries=1):
968                    self.clients[0].log.warning(
969                        "client internet connection state is not on")
970                    return False
971                else:
972                    self.clients[0].log.info(
973                        "client internet connection state is on")
974        if toggle_tethering:
975            self.log.info("====== Toggling provider bluetooth tethering =====")
976            self.provider.log.info("Disable bluetooth tethering")
977            self.provider.droid.bluetoothPanSetBluetoothTethering(False)
978            if not self._test_internet_connection(False, True):
979                self.log.error(
980                    "Internet connection check failed after disable tethering")
981                return False
982            self.provider.log.info("Enable bluetooth tethering")
983            if not self._enable_bluetooth_tethering_connection(
984                    self.provider, self.clients):
985                self.provider.log.error(
986                    "Fail to re-enable bluetooth tethering")
987                return False
988            if not self._test_internet_connection(True, True):
989                self.log.error(
990                    "Internet connection check failed after enable tethering")
991                return False
992        if toggle_bluetooth:
993            self.log.info("====== Toggling provider bluetooth =====")
994            self.provider.log.info("Disable provider bluetooth")
995            disable_bluetooth(self.provider.droid)
996            time.sleep(10)
997            if not self._test_internet_connection(False, True):
998                self.log.error(
999                    "Internet connection check failed after disable bluetooth")
1000                return False
1001            if not self._enable_bluetooth_tethering_connection(
1002                    self.provider, self.clients):
1003                self.provider.log.error(
1004                    "Fail to re-enable bluetooth tethering")
1005                return False
1006            if not self._test_internet_connection(True, True):
1007                self.log.error(
1008                    "Internet connection check failed after enable bluetooth")
1009                return False
1010        if toggle_data:
1011            self.log.info("===== Toggling provider data connection =====")
1012            self.provider.log.info("Disable provider data connection")
1013            self.provider.droid.telephonyToggleDataConnection(False)
1014            time.sleep(10)
1015            if not self._test_internet_connection(False, False):
1016                return False
1017            self.provider.log.info("Enable provider data connection")
1018            self.provider.droid.telephonyToggleDataConnection(True)
1019            if not wait_for_cell_data_connection(self.log, self.provider,
1020                                                 True):
1021                self.provider.log.error(
1022                    "Provider failed to enable data connection.")
1023                return False
1024            if not self._test_internet_connection(True, True):
1025                self.log.error(
1026                    "Internet connection check failed after enable data")
1027                return False
1028        if change_rat:
1029            self.log.info("===== Change provider RAT to %s =====", change_rat)
1030            if not ensure_network_generation(
1031                    self.log,
1032                    self.provider,
1033                    change_rat,
1034                    voice_or_data=NETWORK_SERVICE_DATA,
1035                    toggle_apm_after_setting=False):
1036                self.provider.log.error("Provider failed to reselect to %s.",
1037                                        change_rat)
1038                return False
1039            if not self._test_internet_connection(True, True):
1040                self.log.error(
1041                    "Internet connection check failed after RAT change to %s",
1042                    change_rat)
1043                return False
1044        return True
1045
1046    @test_tracker_info(uuid="2d945656-22f7-4610-9a84-40ce04d603a4")
1047    @TelephonyBaseTest.tel_test_wrap
1048    def test_tethering_4g_to_bluetooth(self):
1049        """Bluetooth Tethering test: LTE to Bluetooth Tethering
1050
1051        1. DUT in LTE mode, idle.
1052        2. DUT start Bluetooth Tethering
1053        3. PhoneB disable data, connect to DUT's softAP
1054        4. Verify Internet access on DUT and PhoneB
1055        5. Toggle provider bluetooth connection
1056        6. Verify Internet access on DUT and PhoneB
1057
1058        Returns:
1059            True if success.
1060            False if failed.
1061        """
1062        if not self._test_setup_tethering(RAT_4G):
1063            self.log.error("Verify 4G Internet access failed.")
1064            return False
1065
1066        return self._verify_bluetooth_tethering_connection()
1067
1068    @test_tracker_info(uuid="8d2ae56b-c2c1-4c32-9b8e-5044007b5b90")
1069    @TelephonyBaseTest.tel_test_wrap
1070    def test_tethering_4g_to_bluetooth_with_voice_call(self):
1071        """Bluetooth Tethering test: LTE to Bluetooth Tethering
1072
1073        1. DUT in LTE mode, idle.
1074        2. DUT start Bluetooth Tethering
1075        3. PhoneB disable data, connect to DUT's softAP
1076        4. Verify Internet access on DUT and PhoneB
1077        5. Verify provider and client are able to make or receive phone call
1078        6. Verify Internet access on DUT and PhoneB
1079
1080        Returns:
1081            True if success.
1082            False if failed.
1083        """
1084        if not self._test_setup_tethering(RAT_4G):
1085            self.log.error("Verify 4G Internet access failed.")
1086            return False
1087
1088        return self._verify_bluetooth_tethering_connection(
1089            toggle_tethering=False, toggle_bluetooth=False, voice_call=True)
1090
1091    @test_tracker_info(uuid="b4617727-fa83-4451-89d7-7e574c0a0938")
1092    @TelephonyBaseTest.tel_test_wrap
1093    def test_tethering_4g_to_bluetooth_toggle_data(self):
1094        """Bluetooth Tethering test: LTE to Bluetooth Tethering
1095
1096        1. DUT in LTE mode, idle.
1097        2. DUT start Bluetooth Tethering
1098        3. PhoneB disable data, connect to DUT's softAP
1099        4. Verify Internet access on DUT and PhoneB
1100        5. Toggle provider data connection
1101        6. Verify Internet access on DUT and PhoneB
1102
1103        Returns:
1104            True if success.
1105            False if failed.
1106        """
1107        if not self._test_setup_tethering(RAT_4G):
1108            self.log.error("Verify 4G Internet access failed.")
1109            return False
1110
1111        return self._verify_bluetooth_tethering_connection(
1112            toggle_tethering=False, toggle_bluetooth=False, toggle_data=True)
1113
1114    @test_tracker_info(uuid="6a0f6001-609d-41f2-ad09-c8ae19f73ac8")
1115    @TelephonyBaseTest.tel_test_wrap
1116    def test_tethering_4g_to_bluetooth_toggle_tethering(self):
1117        """Bluetooth Tethering test: LTE to Bluetooth Tethering
1118
1119        1. DUT in LTE mode, idle.
1120        2. DUT start Bluetooth Tethering
1121        3. PhoneB disable data, connect to DUT's softAP
1122        4. Verify Internet access on DUT and PhoneB
1123        5. Toggle provider bluetooth tethering
1124        6. Verify Internet access on DUT and PhoneB
1125
1126        Returns:
1127            True if success.
1128            False if failed.
1129        """
1130        if not self._test_setup_tethering(RAT_4G):
1131            self.log.error("Verify 4G Internet access failed.")
1132            return False
1133
1134        return self._verify_bluetooth_tethering_connection(
1135            toggle_tethering=True, toggle_bluetooth=False, toggle_data=False)
1136
1137    @test_tracker_info(uuid="b1abc1ac-8018-4956-a17e-bf2ceaf264ea")
1138    @TelephonyBaseTest.tel_test_wrap
1139    def test_tethering_3g_to_bluetooth(self):
1140        """Bluetooth Tethering test: 3G to Bluetoothing Tethering
1141
1142        1. DUT in 3G mode, idle.
1143        2. DUT start bluetooth Tethering
1144        3. PhoneB disable data, connect to DUT's softAP
1145        4. Verify Internet access on DUT and PhoneB
1146        5. Toggle provider bluetooth connection
1147        6. Verify Internet access on DUT and PhoneB
1148
1149        Returns:
1150            True if success.
1151            False if failed.
1152        """
1153        if not self._test_setup_tethering(RAT_3G):
1154            self.log.error("Verify 3G Internet access failed.")
1155            return False
1156
1157        return self._verify_bluetooth_tethering_connection()
1158
1159    @test_tracker_info(uuid="69793745-0c49-4cef-9879-d372e3a3f4c7")
1160    @TelephonyBaseTest.tel_test_wrap
1161    def test_tethering_3g_to_bluetooth_with_voice_call(self):
1162        """Bluetooth Tethering test: 3G to Bluetooth Tethering
1163
1164        1. DUT in 3G mode, idle.
1165        2. DUT start Bluetooth Tethering
1166        3. PhoneB disable data, connect to DUT's softAP
1167        4. Verify Internet access on DUT and PhoneB
1168        5. Verify provider and client are able to make or receive phone call
1169        6. Verify Internet access on DUT and PhoneB
1170
1171        Returns:
1172            True if success.
1173            False if failed.
1174        """
1175        if not self._test_setup_tethering(RAT_3G):
1176            self.log.error("Verify 3G Internet access failed.")
1177            return False
1178
1179        return self._verify_bluetooth_tethering_connection(
1180            toggle_tethering=False, toggle_bluetooth=False, voice_call=True)
1181
1182    @test_tracker_info(uuid="4275ee69-dfdf-4f47-82c5-4224fceee761")
1183    @TelephonyBaseTest.tel_test_wrap
1184    def test_tethering_3g_to_bluetooth_toggle_data(self):
1185        """Bluetooth Tethering test: 3G to Bluetoothing Tethering
1186
1187        1. DUT in 3G mode, idle.
1188        2. DUT start bluetooth Tethering
1189        3. PhoneB disable data, connect to DUT's softAP
1190        4. Verify Internet access on DUT and PhoneB
1191        5. Toggle provider data connection
1192        6. Verify Internet access on DUT and PhoneB
1193
1194        Returns:
1195            True if success.
1196            False if failed.
1197        """
1198        if not self._test_setup_tethering(RAT_3G):
1199            self.log.error("Verify 3G Internet access failed.")
1200            return False
1201
1202        return self._verify_bluetooth_tethering_connection(
1203            toggle_tethering=False, toggle_bluetooth=False, toggle_data=True)
1204
1205    @test_tracker_info(uuid="db0e0f27-1a4f-4301-832d-b66415e289f3")
1206    @TelephonyBaseTest.tel_test_wrap
1207    def test_tethering_2g_to_bluetooth(self):
1208        """Bluetooth Tethering test: 2G to Bluetooth Tethering
1209
1210        1. DUT in 2G mode, idle.
1211        2. DUT start bluetooth Tethering
1212        3. PhoneB disable data, connect to DUT's softAP
1213        4. Verify Internet access on DUT and PhoneB
1214        5. Toggle provider bluetooth connection
1215        6. Verify Internet access on DUT and PhoneB
1216
1217        Returns:
1218            True if success.
1219            False if failed.
1220        """
1221        for a in self.android_devices:
1222            a.adb.shell("setprop persist.bluetooth.btsnoopenable true")
1223            if not toggle_airplane_mode_by_adb(self.log, a, True):
1224                self.log.error("Failed to toggle airplane mode on")
1225                return False
1226            if not toggle_airplane_mode_by_adb(self.log, a, False):
1227                self.log.error("Failed to toggle airplane mode off")
1228                return False
1229
1230        if not self._test_setup_tethering(RAT_2G):
1231            self.log.error("Verify 3G Internet access failed.")
1232            return False
1233
1234        return self._verify_bluetooth_tethering_connection()
1235
1236    @test_tracker_info(uuid="584e9fa5-a38e-47cd-aa33-fcf8d72c423e")
1237    @TelephonyBaseTest.tel_test_wrap
1238    def test_tethering_2g_to_bluetooth_with_voice_call(self):
1239        """Bluetooth Tethering test: 2G to Bluetooth Tethering
1240
1241        1. DUT in 2G mode, idle.
1242        2. DUT start Bluetooth Tethering
1243        3. PhoneB disable data, connect to DUT's softAP
1244        4. Verify Internet access on DUT and PhoneB
1245        5. Verify provider and client are able to make or receive phone call
1246        6. Verify Internet access on DUT and PhoneB
1247
1248        Returns:
1249            True if success.
1250            False if failed.
1251        """
1252        if not self._test_setup_tethering(RAT_2G):
1253            self.log.error("Verify 2G Internet access failed.")
1254            return False
1255
1256        return self._verify_bluetooth_tethering_connection(
1257            toggle_tethering=False, toggle_bluetooth=False, voice_call=True)
1258
1259    @test_tracker_info(uuid="be3e74f9-3dc8-4b72-8a33-32bff0868a44")
1260    @TelephonyBaseTest.tel_test_wrap
1261    def test_tethering_2g_to_bluetooth_toggle_data(self):
1262        """Bluetooth Tethering test: 2G to Bluetooth Tethering
1263
1264        1. DUT in 2G mode, idle.
1265        2. DUT start Bluetooth Tethering
1266        3. PhoneB disable data, connect to DUT's softAP
1267        4. Verify Internet access on DUT and PhoneB
1268        5. Toggle provider data connection
1269        6. Verify Internet access on DUT and PhoneB
1270
1271        Returns:
1272            True if success.
1273            False if failed.
1274        """
1275        if not self._test_setup_tethering(RAT_2G):
1276            self.log.error("Verify 4G Internet access failed.")
1277            return False
1278
1279        return self._verify_bluetooth_tethering_connection(
1280            toggle_tethering=False, toggle_bluetooth=False, toggle_data=True)
1281
1282    @test_tracker_info(uuid="4a106549-0bfa-4c8f-8e66-edec93fabadf")
1283    @TelephonyBaseTest.tel_test_wrap
1284    def test_tethering_rat_from_4g_to_3g_bluetooth(self):
1285        """Bluetooth Tethering test: 2G to Bluetooth Tethering
1286
1287        1. DUT in 4G mode, idle.
1288        2. DUT start bluetooth Tethering
1289        3. PhoneB disable data, connect to DUT's softAP
1290        4. Verify Internet access on DUT and PhoneB
1291        5. Change provider RAT to 3G
1292        6. Verify Internet access on DUT and PhoneB
1293
1294        Returns:
1295            True if success.
1296            False if failed.
1297        """
1298        if not self._test_setup_tethering(RAT_4G):
1299            self.log.error("Verify 3G Internet access failed.")
1300            return False
1301
1302        return self._verify_bluetooth_tethering_connection(
1303            toggle_tethering=False,
1304            toggle_bluetooth=False,
1305            toggle_data=False,
1306            change_rat=RAT_3G)
1307
1308    @test_tracker_info(uuid="eaa5b61b-f054-437f-ae82-8d80f6487785")
1309    @TelephonyBaseTest.tel_test_wrap
1310    def test_tethering_rat_from_4g_to_2g_bluetooth(self):
1311        """Bluetooth Tethering test: 2G to Bluetooth Tethering
1312
1313        1. DUT in 4G mode, idle.
1314        2. DUT start bluetooth Tethering
1315        3. PhoneB disable data, connect to DUT's softAP
1316        4. Verify Internet access on DUT and PhoneB
1317        5. Change provider RAT to 2G
1318        6. Verify Internet access on DUT and PhoneB
1319
1320        Returns:
1321            True if success.
1322            False if failed.
1323        """
1324        if not self._test_setup_tethering(RAT_4G):
1325            self.log.error("Verify 3G Internet access failed.")
1326            return False
1327
1328        return self._verify_bluetooth_tethering_connection(
1329            toggle_tethering=False,
1330            toggle_bluetooth=False,
1331            toggle_data=False,
1332            change_rat=RAT_2G)
1333
1334    @test_tracker_info(uuid="912a11a3-14b3-4928-885f-cea69f14a571")
1335    @TelephonyBaseTest.tel_test_wrap
1336    def test_tethering_4g_to_2gwifi(self):
1337        """WiFi Tethering test: LTE to WiFI 2.4G Tethering
1338
1339        1. DUT in LTE mode, idle.
1340        2. DUT start 2.4G WiFi Tethering
1341        3. PhoneB disable data, connect to DUT's softAP
1342        4. Verify Internet access on DUT and PhoneB
1343
1344        Returns:
1345            True if success.
1346            False if failed.
1347        """
1348        if not self._test_setup_tethering(RAT_4G):
1349            self.log.error("Verify 4G Internet access failed.")
1350            return False
1351
1352        return wifi_tethering_setup_teardown(
1353            self.log,
1354            self.provider,
1355            self.clients,
1356            ap_band=WIFI_CONFIG_APBAND_2G,
1357            check_interval=10,
1358            check_iteration=10)
1359
1360    @test_tracker_info(uuid="743e3998-d39f-42b9-b11f-009dcee34f3f")
1361    @TelephonyBaseTest.tel_test_wrap
1362    def test_tethering_4g_to_5gwifi(self):
1363        """WiFi Tethering test: LTE to WiFI 5G Tethering
1364
1365        1. DUT in LTE mode, idle.
1366        2. DUT start 5G WiFi Tethering
1367        3. PhoneB disable data, connect to DUT's softAP
1368        4. Verify Internet access on DUT and PhoneB
1369
1370        Returns:
1371            True if success.
1372            False if failed.
1373        """
1374        if not self._test_setup_tethering(RAT_4G):
1375            self.log.error("Verify 4G Internet access failed.")
1376            return False
1377
1378        return wifi_tethering_setup_teardown(
1379            self.log,
1380            self.provider,
1381            self.clients,
1382            ap_band=WIFI_CONFIG_APBAND_5G,
1383            check_interval=10,
1384            check_iteration=10)
1385
1386    @test_tracker_info(uuid="c1a16464-3800-40d3-ba63-35db784e0383")
1387    @TelephonyBaseTest.tel_test_wrap
1388    def test_tethering_default_to_5gwifi(self):
1389        """WiFi Tethering test: Default to WiFI 5G Tethering
1390
1391        1. DUT in default mode, idle.
1392        2. DUT start 5G WiFi Tethering
1393        3. PhoneB disable data, connect to DUT's softAP
1394        4. Verify Internet access on DUT and PhoneB
1395        5. True: Stop
1396           False: Change DUT to next device and repeat until find the device
1397                  with tethering capability
1398
1399        Returns:
1400            True if success.
1401            False if no device has tethering capability.
1402        """
1403        num = len(self.android_devices)
1404        for idx, ad in enumerate(self.android_devices):
1405            self.provider = self.android_devices[idx]
1406            self.clients = self.android_devices[:
1407                                                idx] + self.android_devices[idx
1408                                                                            +
1409                                                                            1:]
1410            ensure_phones_default_state(self.log, self.android_devices)
1411            wifi_toggle_state(self.log, self.provider, False)
1412
1413            if not self._test_setup_tethering(None):
1414                self.provider.log.error("Data connection check failed.")
1415                continue
1416
1417            if not self.provider.droid.carrierConfigIsTetheringModeAllowed(
1418                    TETHERING_MODE_WIFI,
1419                    MAX_WAIT_TIME_TETHERING_ENTITLEMENT_CHECK):
1420                self.provider.log.info("Tethering is not entitled")
1421                continue
1422
1423            if wifi_tethering_setup_teardown(
1424                    self.log,
1425                    self.provider, [self.clients[0]],
1426                    ap_band=WIFI_CONFIG_APBAND_5G,
1427                    check_interval=10,
1428                    check_iteration=10):
1429                self.android_devices = [self.provider] + self.clients
1430                return True
1431            elif idx == num - 1:
1432                self.log.error("Tethering is not working on all devices")
1433                return False
1434        self.log.error(
1435            "Failed to enable tethering on any device in this testbed")
1436        raise signals.TestAbortClass(
1437            "Tethering is not available on all devices in this testbed")
1438
1439    @test_tracker_info(uuid="c9a570b0-838c-44ba-991c-f1ddeee21f3c")
1440    @TelephonyBaseTest.tel_test_wrap
1441    def test_tethering_default_to_2gwifi(self):
1442        """WiFi Tethering test: Default to WiFI 2G Tethering
1443
1444        1. DUT in default mode, idle.
1445        2. DUT start 2G WiFi Tethering
1446        3. PhoneB disable data, connect to DUT's softAP
1447        4. Verify Internet access on DUT and PhoneB
1448        5. True: Stop
1449           False: Change DUT to next device and repeat until find the device
1450                  with tethering capability
1451
1452        Returns:
1453            True if success.
1454            False if no device has tethering capability.
1455        """
1456        num = len(self.android_devices)
1457        for idx, ad in enumerate(self.android_devices):
1458            self.provider = self.android_devices[idx]
1459            self.clients = self.android_devices[:
1460                                                idx] + self.android_devices[idx
1461                                                                            +
1462                                                                            1:]
1463            ensure_phones_default_state(self.log, self.android_devices)
1464            wifi_toggle_state(self.log, self.provider, False)
1465
1466            if not self._test_setup_tethering(None):
1467                self.provider.log.error("Data connection check failed.")
1468                continue
1469
1470            if not self.provider.droid.carrierConfigIsTetheringModeAllowed(
1471                    TETHERING_MODE_WIFI,
1472                    MAX_WAIT_TIME_TETHERING_ENTITLEMENT_CHECK):
1473                self.provider.log.info("Tethering is not entitled")
1474                continue
1475
1476            if wifi_tethering_setup_teardown(
1477                    self.log,
1478                    self.provider, [self.clients[0]],
1479                    ap_band=WIFI_CONFIG_APBAND_2G,
1480                    check_interval=10,
1481                    check_iteration=10):
1482                self.android_devices = [self.provider] + self.clients
1483                return True
1484            elif idx == num - 1:
1485                self.log.error("Tethering is not working on all devices")
1486                return False
1487        self.log.error(
1488            "Failed to enable tethering on any device in this testbed")
1489        raise signals.TestAbortClass(
1490            "Tethering is not available on all devices in this testbed")
1491
1492    @test_tracker_info(uuid="59be8d68-f05b-4448-8584-de971174fd81")
1493    @TelephonyBaseTest.tel_test_wrap
1494    def test_tethering_3g_to_2gwifi(self):
1495        """WiFi Tethering test: 3G to WiFI 2.4G Tethering
1496
1497        1. DUT in 3G mode, idle.
1498        2. DUT start 2.4G WiFi Tethering
1499        3. PhoneB disable data, connect to DUT's softAP
1500        4. Verify Internet access on DUT and PhoneB
1501
1502        Returns:
1503            True if success.
1504            False if failed.
1505        """
1506        if not self._test_setup_tethering(RAT_3G):
1507            self.log.error("Verify 3G Internet access failed.")
1508            return False
1509
1510        return wifi_tethering_setup_teardown(
1511            self.log,
1512            self.provider,
1513            self.clients,
1514            ap_band=WIFI_CONFIG_APBAND_2G,
1515            check_interval=10,
1516            check_iteration=10)
1517
1518    @test_tracker_info(uuid="1be6b741-92e8-4ee1-9f59-e7f9f369b065")
1519    @TelephonyBaseTest.tel_test_wrap
1520    def test_tethering_3g_to_5gwifi(self):
1521        """WiFi Tethering test: 3G to WiFI 5G Tethering
1522
1523        1. DUT in 3G mode, idle.
1524        2. DUT start 5G WiFi Tethering
1525        3. PhoneB disable data, connect to DUT's softAP
1526        4. Verify Internet access on DUT and PhoneB
1527
1528        Returns:
1529            True if success.
1530            False if failed.
1531        """
1532        if not self._test_setup_tethering(RAT_3G):
1533            self.log.error("Verify 3G Internet access failed.")
1534            return False
1535
1536        return wifi_tethering_setup_teardown(
1537            self.log,
1538            self.provider,
1539            self.clients,
1540            ap_band=WIFI_CONFIG_APBAND_5G,
1541            check_interval=10,
1542            check_iteration=10)
1543
1544    @test_tracker_info(uuid="89fe6321-4c0d-40c0-89b2-54008ecca68f")
1545    @TelephonyBaseTest.tel_test_wrap
1546    def test_tethering_2g_to_2gwifi(self):
1547        """WiFi Tethering test: 2G to WiFI 2.4G Tethering
1548
1549        1. DUT in 2G mode, idle.
1550        2. DUT start 2.4G WiFi Tethering
1551        3. PhoneB disable data, connect to DUT's softAP
1552        4. Verify Internet access on DUT and PhoneB
1553
1554        Returns:
1555            True if success.
1556            False if failed.
1557        """
1558        if not self._test_setup_tethering(RAT_2G):
1559            self.log.error("Verify 2G Internet access failed.")
1560            return False
1561
1562        return wifi_tethering_setup_teardown(
1563            self.log,
1564            self.provider, [self.clients[0]],
1565            ap_band=WIFI_CONFIG_APBAND_2G,
1566            check_interval=10,
1567            check_iteration=10)
1568
1569    @test_tracker_info(uuid="b8258d51-9581-4d52-80b6-501941ec1191")
1570    @TelephonyBaseTest.tel_test_wrap
1571    def test_tethering_2g_to_5gwifi(self):
1572        """WiFi Tethering test: 2G to WiFI 5G Tethering
1573
1574        1. DUT in 2G mode, idle.
1575        2. DUT start 5G WiFi Tethering
1576        3. PhoneB disable data, connect to DUT's softAP
1577        4. Verify Internet access on DUT and PhoneB
1578
1579        Returns:
1580            True if success.
1581            False if failed.
1582        """
1583        if not self._test_setup_tethering(RAT_2G):
1584            self.log.error("Verify 2G Internet access failed.")
1585            return False
1586
1587        return wifi_tethering_setup_teardown(
1588            self.log,
1589            self.provider, [self.clients[0]],
1590            ap_band=WIFI_CONFIG_APBAND_5G,
1591            check_interval=10,
1592            check_iteration=10)
1593
1594    @test_tracker_info(uuid="8ed766a6-71c5-4b3b-8897-a4e796c75619")
1595    @TelephonyBaseTest.tel_test_wrap
1596    def test_disable_wifi_tethering_resume_connected_wifi(self):
1597        """WiFi Tethering test: WiFI connected to 2.4G network,
1598        start (LTE) 2.4G WiFi tethering, then stop tethering
1599
1600        1. DUT in data connected, idle. WiFi connected to 2.4G Network
1601        2. DUT start 2.4G WiFi Tethering
1602        3. PhoneB disable data, connect to DUT's softAP
1603        4. Verify Internet access on DUT and PhoneB
1604        5. Disable WiFi Tethering on DUT.
1605        6. Verify DUT automatically connect to previous WiFI network
1606
1607        Returns:
1608            True if success.
1609            False if failed.
1610        """
1611        if not self._test_setup_tethering():
1612            self.log.error("Verify provider Internet access failed.")
1613            return False
1614        self.log.info("Connect WiFi.")
1615        if not ensure_wifi_connected(self.log, self.provider,
1616                                     self.wifi_network_ssid,
1617                                     self.wifi_network_pass):
1618            self.log.error("WiFi connect fail.")
1619            return False
1620        self.log.info("Start WiFi Tethering.")
1621        if not wifi_tethering_setup_teardown(
1622                self.log,
1623                self.provider, [self.clients[0]],
1624                check_interval=10,
1625                check_iteration=2):
1626            self.log.error("WiFi Tethering failed.")
1627            return False
1628
1629        if (not wait_for_wifi_data_connection(self.log, self.provider, True)
1630                or not verify_internet_connection(self.log, self.provider)):
1631            self.log.error("Provider data did not return to Wifi")
1632            return False
1633        return True
1634
1635    @test_tracker_info(uuid="b879ceb2-1b80-4762-93f9-afef4d688c28")
1636    @TelephonyBaseTest.tel_test_wrap
1637    def test_toggle_data_during_active_wifi_tethering(self):
1638        """WiFi Tethering test: Toggle Data during active WiFi Tethering
1639
1640        1. DUT data connection is on and idle.
1641        2. DUT start 2.4G WiFi Tethering
1642        3. PhoneB disable data, connect to DUT's softAP
1643        4. Verify Internet access on DUT and PhoneB
1644        5. Disable Data on DUT, verify PhoneB still connected to WiFi, but no Internet access.
1645        6. Enable Data on DUT, verify PhoneB still connected to WiFi and have Internet access.
1646
1647        Returns:
1648            True if success.
1649            False if failed.
1650        """
1651        if not self._test_setup_tethering():
1652            self.log.error("Provider Internet access check failed.")
1653            return False
1654        try:
1655            ssid = rand_ascii_str(10)
1656            if not wifi_tethering_setup_teardown(
1657                    self.log,
1658                    self.provider, [self.clients[0]],
1659                    ap_band=WIFI_CONFIG_APBAND_2G,
1660                    check_interval=10,
1661                    check_iteration=2,
1662                    do_cleanup=False,
1663                    ssid=ssid):
1664                self.log.error("WiFi Tethering failed.")
1665                return False
1666
1667            if not self.provider.droid.wifiIsApEnabled():
1668                self.provider.log.error("Provider WiFi tethering stopped.")
1669                return False
1670
1671            self.provider.log.info(
1672                "Disable Data on Provider, verify no data on Client.")
1673            self.provider.droid.telephonyToggleDataConnection(False)
1674            time.sleep(WAIT_TIME_DATA_STATUS_CHANGE_DURING_WIFI_TETHERING)
1675            if not verify_internet_connection(self.log, self.provider, expected_state=False):
1676                self.provider.log.error("Disable data on provider failed.")
1677                return False
1678            if not self.provider.droid.wifiIsApEnabled():
1679                self.provider.log.error("Provider WiFi tethering stopped.")
1680                return False
1681            if not check_is_wifi_connected(self.log, self.clients[0], ssid):
1682                self.clients[0].log.error("Client WiFi is not connected")
1683                return False
1684
1685            self.log.info(
1686                "Enable Data on Provider, verify data available on Client.")
1687            self.provider.droid.telephonyToggleDataConnection(True)
1688            if not wait_for_cell_data_connection(self.log, self.provider,
1689                                                 True):
1690                self.provider.log.error(
1691                    "Provider failed to enable data connection.")
1692                return False
1693            if not verify_internet_connection(self.log, self.provider):
1694                self.provider.log.error(
1695                    "Provider internet connection check failed.")
1696                return False
1697            if not self.provider.droid.wifiIsApEnabled():
1698                self.provider.log.error("Provider WiFi tethering stopped.")
1699                return False
1700
1701            if not check_is_wifi_connected(
1702                    self.log, self.clients[0],
1703                    ssid) or (not verify_internet_connection(
1704                        self.log, self.clients[0])):
1705                self.clients[0].log.error(
1706                    "Client wifi connection check failed!")
1707                return False
1708        finally:
1709            if not wifi_tethering_cleanup(self.log, self.provider,
1710                                          self.clients):
1711                return False
1712        return True
1713
1714    # Invalid Live Test. Can't rely on the result of this test with live network.
1715    # Network may decide not to change the RAT when data conenction is active.
1716    @test_tracker_info(uuid="c92a961b-e85d-435c-8988-052928add591")
1717    @TelephonyBaseTest.tel_test_wrap
1718    def test_change_rat_during_active_wifi_tethering_lte_to_3g(self):
1719        """WiFi Tethering test: Change Cellular Data RAT generation from LTE to 3G,
1720            during active WiFi Tethering.
1721
1722        1. DUT in LTE mode, idle.
1723        2. DUT start 2.4G WiFi Tethering
1724        3. PhoneB disable data, connect to DUT's softAP
1725        4. Verily Internet access on DUT and PhoneB
1726        5. Change DUT Cellular Data RAT generation from LTE to 3G.
1727        6. Verify both DUT and PhoneB have Internet access.
1728
1729        Returns:
1730            True if success.
1731            False if failed.
1732        """
1733        if not self._test_setup_tethering(RAT_4G):
1734            self.log.error("Verify 4G Internet access failed.")
1735            return False
1736        try:
1737            if not wifi_tethering_setup_teardown(
1738                    self.log,
1739                    self.provider, [self.clients[0]],
1740                    ap_band=WIFI_CONFIG_APBAND_2G,
1741                    check_interval=10,
1742                    check_iteration=2,
1743                    do_cleanup=False):
1744                self.log.error("WiFi Tethering failed.")
1745                return False
1746
1747            if not self.provider.droid.wifiIsApEnabled():
1748                self.provider.log.error("Provider WiFi tethering stopped.")
1749                return False
1750
1751            self.log.info("Provider change RAT from LTE to 3G.")
1752            if not ensure_network_generation(
1753                    self.log,
1754                    self.provider,
1755                    RAT_3G,
1756                    voice_or_data=NETWORK_SERVICE_DATA,
1757                    toggle_apm_after_setting=False):
1758                self.provider.log.error("Provider failed to reselect to 3G.")
1759                return False
1760            time.sleep(WAIT_TIME_DATA_STATUS_CHANGE_DURING_WIFI_TETHERING)
1761            if not verify_internet_connection(self.log, self.provider):
1762                self.provider.log.error("Data not available on Provider.")
1763                return False
1764            if not self.provider.droid.wifiIsApEnabled():
1765                self.provider.log.error("Provider WiFi tethering stopped.")
1766                return False
1767            if not tethering_check_internet_connection(
1768                    self.log, self.provider, [self.clients[0]], 10, 5):
1769                return False
1770        finally:
1771            if not wifi_tethering_cleanup(self.log, self.provider,
1772                                          self.clients):
1773                return False
1774        return True
1775
1776    # Invalid Live Test. Can't rely on the result of this test with live network.
1777    # Network may decide not to change the RAT when data conenction is active.
1778    @test_tracker_info(uuid="eb5f0180-b70d-436f-8fcb-60c59307cc43")
1779    @TelephonyBaseTest.tel_test_wrap
1780    def test_change_rat_during_active_wifi_tethering_3g_to_lte(self):
1781        """WiFi Tethering test: Change Cellular Data RAT generation from 3G to LTE,
1782            during active WiFi Tethering.
1783
1784        1. DUT in 3G mode, idle.
1785        2. DUT start 2.4G WiFi Tethering
1786        3. PhoneB disable data, connect to DUT's softAP
1787        4. Verily Internet access on DUT and PhoneB
1788        5. Change DUT Cellular Data RAT generation from 3G to LTE.
1789        6. Verify both DUT and PhoneB have Internet access.
1790
1791        Returns:
1792            True if success.
1793            False if failed.
1794        """
1795        if not self._test_setup_tethering(RAT_3G):
1796            self.log.error("Verify 3G Internet access failed.")
1797            return False
1798        try:
1799            if not wifi_tethering_setup_teardown(
1800                    self.log,
1801                    self.provider, [self.clients[0]],
1802                    ap_band=WIFI_CONFIG_APBAND_2G,
1803                    check_interval=10,
1804                    check_iteration=2,
1805                    do_cleanup=False):
1806                self.log.error("WiFi Tethering failed.")
1807                return False
1808
1809            if not self.provider.droid.wifiIsApEnabled():
1810                self.log.error("Provider WiFi tethering stopped.")
1811                return False
1812
1813            self.log.info("Provider change RAT from 3G to 4G.")
1814            if not ensure_network_generation(
1815                    self.log,
1816                    self.provider,
1817                    RAT_4G,
1818                    voice_or_data=NETWORK_SERVICE_DATA,
1819                    toggle_apm_after_setting=False):
1820                self.log.error("Provider failed to reselect to 4G.")
1821                return False
1822            time.sleep(WAIT_TIME_DATA_STATUS_CHANGE_DURING_WIFI_TETHERING)
1823            if not verify_internet_connection(self.log, self.provider):
1824                self.provider.log.error("Data not available on Provider.")
1825                return False
1826            if not self.provider.droid.wifiIsApEnabled():
1827                self.provider.log.error("Provider WiFi tethering stopped.")
1828                return False
1829            if not tethering_check_internet_connection(
1830                    self.log, self.provider, [self.clients[0]], 10, 5):
1831                return False
1832        finally:
1833            if not wifi_tethering_cleanup(self.log, self.provider, [self.clients[0]]):
1834                return False
1835        return True
1836
1837    @test_tracker_info(uuid="12a6c910-fa96-4d9b-99a5-8391fea33732")
1838    @TelephonyBaseTest.tel_test_wrap
1839    def test_toggle_apm_during_active_wifi_tethering(self):
1840        """WiFi Tethering test: Toggle APM during active WiFi Tethering
1841
1842        1. DUT in LTE mode, idle.
1843        2. DUT start 2.4G WiFi Tethering
1844        3. PhoneB disable data, connect to DUT's softAP
1845        4. Verify Internet access on DUT and PhoneB
1846        5. DUT toggle APM on, verify WiFi tethering stopped, PhoneB lost WiFi connection.
1847        6. DUT toggle APM off, verify PhoneA have cellular data and Internet connection.
1848
1849        Returns:
1850            True if success.
1851            False if failed.
1852        """
1853        if not self._test_setup_tethering(RAT_4G):
1854            self.log.error("Verify 4G Internet access failed.")
1855            return False
1856        try:
1857            ssid = rand_ascii_str(10)
1858            if not wifi_tethering_setup_teardown(
1859                    self.log,
1860                    self.provider, [self.clients[0]],
1861                    ap_band=WIFI_CONFIG_APBAND_2G,
1862                    check_interval=10,
1863                    check_iteration=2,
1864                    do_cleanup=False,
1865                    ssid=ssid):
1866                self.log.error("WiFi Tethering failed.")
1867                return False
1868
1869            if not self.provider.droid.wifiIsApEnabled():
1870                self.log.error("Provider WiFi tethering stopped.")
1871                return False
1872
1873            self.log.info(
1874                "Provider turn on APM, verify no wifi/data on Client.")
1875            if not toggle_airplane_mode(self.log, self.provider, True):
1876                self.log.error("Provider turn on APM failed.")
1877                return False
1878            time.sleep(WAIT_TIME_DATA_STATUS_CHANGE_DURING_WIFI_TETHERING)
1879            if self.provider.droid.wifiIsApEnabled():
1880                self.provider.log.error("Provider WiFi tethering not stopped.")
1881                return False
1882            if not verify_internet_connection(self.log, self.clients[0], expected_state=False):
1883                self.clients[0].log.error(
1884                    "Client should not have Internet connection.")
1885                return False
1886            wifi_info = self.clients[0].droid.wifiGetConnectionInfo()
1887            self.clients[0].log.info("WiFi Info: {}".format(wifi_info))
1888            if wifi_info[WIFI_SSID_KEY] == ssid:
1889                self.clients[0].log.error(
1890                    "WiFi error. WiFi should not be connected.".format(
1891                        wifi_info))
1892                return False
1893
1894            self.log.info("Provider turn off APM.")
1895            if not toggle_airplane_mode(self.log, self.provider, False):
1896                self.provider.log.error("Provider turn on APM failed.")
1897                return False
1898            time.sleep(WAIT_TIME_DATA_STATUS_CHANGE_DURING_WIFI_TETHERING)
1899            if self.provider.droid.wifiIsApEnabled():
1900                self.provider.log.error(
1901                    "Provider WiFi tethering should not on.")
1902                return False
1903            if not verify_internet_connection(self.log, self.provider):
1904                self.provider.log.error(
1905                    "Provider should have Internet connection.")
1906                return False
1907        finally:
1908            self.clients[0].droid.telephonyToggleDataConnection(True)
1909            wifi_reset(self.log, self.clients[0])
1910        return True
1911
1912    @test_tracker_info(uuid="037e80fc-6eab-4cd1-846a-b9780a1d502d")
1913    @TelephonyBaseTest.tel_test_wrap
1914    def test_tethering_entitlement_check(self):
1915        """Tethering Entitlement Check Test
1916
1917        Get tethering entitlement check result.
1918
1919        Returns:
1920            True if entitlement check returns True.
1921        """
1922        if (not wait_for_cell_data_connection(self.log, self.provider, True)
1923                or not verify_internet_connection(self.log, self.provider)):
1924            self.log.error("Failed cell data call for entitlement check.")
1925            return False
1926
1927        result = self.provider.droid.carrierConfigIsTetheringModeAllowed(
1928            TETHERING_MODE_WIFI, MAX_WAIT_TIME_TETHERING_ENTITLEMENT_CHECK)
1929        self.provider.log.info("Tethering entitlement check result: %s",
1930                               result)
1931        return result
1932
1933    @test_tracker_info(uuid="4972826e-39ea-42f7-aae0-06fe3aa9ecc6")
1934    @TelephonyBaseTest.tel_test_wrap
1935    def test_tethering_4g_to_2gwifi_stress(self):
1936        """Stress Test LTE to WiFI 2.4G Tethering
1937
1938        This is a stress test for "test_tethering_4g_to_2gwifi".
1939        Default MINIMUM_SUCCESS_RATE is set to 95%.
1940
1941        Returns:
1942            True stress pass rate is higher than MINIMUM_SUCCESS_RATE.
1943            False otherwise.
1944        """
1945        MINIMUM_SUCCESS_RATE = .95
1946        success_count = 0
1947        fail_count = 0
1948
1949        for i in range(1, self.stress_test_number + 1):
1950
1951            ensure_phones_default_state(self.log, self.android_devices)
1952
1953            if self.test_tethering_4g_to_2gwifi():
1954                success_count += 1
1955                result_str = "Succeeded"
1956            else:
1957                fail_count += 1
1958                result_str = "Failed"
1959            self.log.info("Iteration {} {}. Current: {} / {} passed.".format(
1960                i, result_str, success_count, self.stress_test_number))
1961
1962        self.log.info("Final Count - Success: {}, Failure: {} - {}%".format(
1963            success_count, fail_count,
1964            str(100 * success_count / (success_count + fail_count))))
1965        if success_count / (
1966                success_count + fail_count) >= MINIMUM_SUCCESS_RATE:
1967            return True
1968        else:
1969            return False
1970
1971    @test_tracker_info(uuid="54e85aed-09e3-42e2-bb33-bca1005d93ab")
1972    @TelephonyBaseTest.tel_test_wrap
1973    def test_tethering_wifi_ssid_quotes(self):
1974        """WiFi Tethering test: SSID name have quotes.
1975        1. Set SSID name have double quotes.
1976        2. Start LTE to WiFi (2.4G) tethering.
1977        3. Verify tethering.
1978
1979        Returns:
1980            True if success.
1981            False if failed.
1982        """
1983        if not self._test_setup_tethering():
1984            self.log.error("Verify Internet access failed.")
1985            return False
1986        ssid = "\"" + rand_ascii_str(10) + "\""
1987        self.log.info(
1988            "Starting WiFi Tethering test with ssid: {}".format(ssid))
1989
1990        return wifi_tethering_setup_teardown(
1991            self.log,
1992            self.provider,
1993            self.clients,
1994            ap_band=WIFI_CONFIG_APBAND_2G,
1995            check_interval=10,
1996            check_iteration=10,
1997            ssid=ssid)
1998
1999    @test_tracker_info(uuid="320326da-bf32-444d-81f9-f781c55dbc99")
2000    @TelephonyBaseTest.tel_test_wrap
2001    def test_tethering_wifi_password_escaping_characters(self):
2002        """WiFi Tethering test: password have escaping characters.
2003        1. Set password have escaping characters.
2004            e.g.: '"DQ=/{Yqq;M=(^_3HzRvhOiL8S%`]w&l<Qp8qH)bs<4E9v_q=HLr^)}w$blA0Kg'
2005        2. Start LTE to WiFi (2.4G) tethering.
2006        3. Verify tethering.
2007
2008        Returns:
2009            True if success.
2010            False if failed.
2011        """
2012        if not self._test_setup_tethering():
2013            self.log.error("Verify Internet access failed.")
2014            return False
2015
2016        password = '"DQ=/{Yqq;M=(^_3HzRvhOiL8S%`]w&l<Qp8qH)bs<4E9v_q=HLr^)}w$blA0Kg'
2017        self.log.info(
2018            "Starting WiFi Tethering test with password: {}".format(password))
2019
2020        return wifi_tethering_setup_teardown(
2021            self.log,
2022            self.provider,
2023            self.clients,
2024            ap_band=WIFI_CONFIG_APBAND_2G,
2025            check_interval=10,
2026            check_iteration=10,
2027            password=password)
2028
2029    def _test_start_wifi_tethering_connect_teardown(self, ad_host, ad_client,
2030                                                    ssid, password):
2031        """Private test util for WiFi Tethering.
2032
2033        1. Host start WiFi tethering.
2034        2. Client connect to tethered WiFi.
2035        3. Host tear down WiFi tethering.
2036
2037        Args:
2038            ad_host: android device object for host
2039            ad_client: android device object for client
2040            ssid: WiFi tethering ssid
2041            password: WiFi tethering password
2042
2043        Returns:
2044            True if no error happen, otherwise False.
2045        """
2046        result = True
2047        self.number_of_devices = 2
2048        # Turn off active SoftAP if any.
2049        if ad_host.droid.wifiIsApEnabled():
2050            stop_wifi_tethering(self.log, ad_host)
2051
2052        time.sleep(WAIT_TIME_ANDROID_STATE_SETTLING)
2053        if not start_wifi_tethering(self.log, ad_host, ssid, password,
2054                                    WIFI_CONFIG_APBAND_2G):
2055            self.log.error("Start WiFi tethering failed.")
2056            result = False
2057        time.sleep(WAIT_TIME_ANDROID_STATE_SETTLING)
2058        if not ensure_wifi_connected(self.log, ad_client, ssid, password):
2059            self.log.error("Client connect to WiFi failed.")
2060            result = False
2061        if not wifi_reset(self.log, ad_client):
2062            self.log.error("Reset client WiFi failed. {}".format(
2063                ad_client.serial))
2064            result = False
2065        if not stop_wifi_tethering(self.log, ad_host):
2066            self.log.error("Stop WiFi tethering failed.")
2067            result = False
2068        return result
2069
2070    @test_tracker_info(uuid="617c7e71-f166-465f-bfd3-b5a3a40cc0d4")
2071    @TelephonyBaseTest.tel_test_wrap
2072    def test_tethering_wifi_ssid(self):
2073        """WiFi Tethering test: start WiFi tethering with all kinds of SSIDs.
2074
2075        For each listed SSID, start WiFi tethering on DUT, client connect WiFi,
2076        then tear down WiFi tethering.
2077
2078        Returns:
2079            True if WiFi tethering succeed on all SSIDs.
2080            False if failed.
2081        """
2082        if not self._test_setup_tethering(RAT_4G):
2083            self.log.error("Setup Failed.")
2084            return False
2085        ssid_list = [
2086            " !\"#$%&'()*+,-./0123456789:;<=>?",
2087            "@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_",
2088            "`abcdefghijklmnopqrstuvwxyz{|}~", " a ", "!b!", "#c#", "$d$",
2089            "%e%", "&f&", "'g'", "(h(", ")i)", "*j*", "+k+", "-l-", ".m.",
2090            "/n/", "_", " !\"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}",
2091            "\u0644\u062c\u0648\u062c", "\u8c37\u6b4c", "\uad6c\uae00"
2092            "\u30b0\u30fc\u30eb",
2093            "\u0417\u0434\u0440\u0430\u0432\u0441\u0442\u0443\u0439"
2094        ]
2095        fail_list = {}
2096
2097        for ssid in ssid_list:
2098            password = rand_ascii_str(8)
2099            self.log.info("SSID: <{}>, Password: <{}>".format(ssid, password))
2100            if not self._test_start_wifi_tethering_connect_teardown(
2101                    self.provider, self.clients[0], ssid, password):
2102                fail_list[ssid] = password
2103
2104        if (len(fail_list) > 0):
2105            self.log.error("Failed cases: {}".format(fail_list))
2106            return False
2107        else:
2108            return True
2109
2110    @test_tracker_info(uuid="9a5b5a34-b5cf-451d-94c4-8a64d456dfe5")
2111    @TelephonyBaseTest.tel_test_wrap
2112    def test_tethering_wifi_password(self):
2113        """WiFi Tethering test: start WiFi tethering with all kinds of passwords.
2114
2115        For each listed password, start WiFi tethering on DUT, client connect WiFi,
2116        then tear down WiFi tethering.
2117
2118        Returns:
2119            True if WiFi tethering succeed on all passwords.
2120            False if failed.
2121        """
2122        if not self._test_setup_tethering(RAT_4G):
2123            self.log.error("Setup Failed.")
2124            return False
2125        password_list = [
2126            " !\"#$%&'()*+,-./0123456789:;<=>?",
2127            "@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_",
2128            "`abcdefghijklmnopqrstuvwxyz{|}~",
2129            " !\"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}", "abcdefgh",
2130            "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!",
2131            " a12345 ", "!b12345!", "#c12345#", "$d12345$", "%e12345%",
2132            "&f12345&", "'g12345'", "(h12345(", ")i12345)", "*j12345*",
2133            "+k12345+", "-l12345-", ".m12345.", "/n12345/"
2134        ]
2135        fail_list = {}
2136
2137        for password in password_list:
2138            ssid = rand_ascii_str(8)
2139            self.log.info("SSID: <{}>, Password: <{}>".format(ssid, password))
2140            if not self._test_start_wifi_tethering_connect_teardown(
2141                    self.provider, self.clients[0], ssid, password):
2142                fail_list[ssid] = password
2143
2144        if (len(fail_list) > 0):
2145            self.log.error("Failed cases: {}".format(fail_list))
2146            return False
2147        else:
2148            return True
2149
2150    def _test_tethering_wifi_and_voice_call(self, provider_data_rat,
2151                                            provider_setup_func,
2152                                            provider_in_call_check_func):
2153        self.number_of_devices = 2
2154        if not self._test_setup_tethering(provider_data_rat):
2155            self.log.error("Verify 4G Internet access failed.")
2156            return False
2157
2158        tasks = [(provider_setup_func, (self.log, self.provider)),
2159                 (phone_setup_voice_general, (self.log, self.clients[0]))]
2160        if not multithread_func(self.log, tasks):
2161            self.log.error("Phone Failed to Set Up VoLTE.")
2162            return False
2163
2164        try:
2165            self.log.info("1. Setup WiFi Tethering.")
2166            if not wifi_tethering_setup_teardown(
2167                    self.log,
2168                    self.provider, [self.clients[0]],
2169                    ap_band=WIFI_CONFIG_APBAND_2G,
2170                    check_interval=10,
2171                    check_iteration=2,
2172                    do_cleanup=False):
2173                self.log.error("WiFi Tethering failed.")
2174                return False
2175            self.log.info("2. Make outgoing call.")
2176            if not call_setup_teardown(
2177                    self.log,
2178                    self.provider,
2179                    self.clients[0],
2180                    ad_hangup=None,
2181                    verify_caller_func=provider_in_call_check_func):
2182                self.log.error("Setup Call Failed.")
2183                return False
2184            self.log.info("3. Verify data.")
2185            if not verify_internet_connection(self.log, self.provider):
2186                self.provider.log.error("Provider have no Internet access.")
2187            if not verify_internet_connection(self.log, self.clients[0]):
2188                self.clients[0].log.error("Client have no Internet access.")
2189            hangup_call(self.log, self.provider)
2190
2191            time.sleep(WAIT_TIME_BETWEEN_REG_AND_CALL)
2192
2193            self.log.info("4. Make incoming call.")
2194            if not call_setup_teardown(
2195                    self.log,
2196                    self.clients[0],
2197                    self.provider,
2198                    ad_hangup=None,
2199                    verify_callee_func=provider_in_call_check_func):
2200                self.log.error("Setup Call Failed.")
2201                return False
2202            self.log.info("5. Verify data.")
2203            if not verify_internet_connection(self.log, self.provider):
2204                self.provider.log.error("Provider have no Internet access.")
2205            if not verify_internet_connection(self.log, self.clients[0]):
2206                self.clients[0].log.error("Client have no Internet access.")
2207            hangup_call(self.log, self.provider)
2208
2209        finally:
2210            if not wifi_tethering_cleanup(self.log, self.provider,
2211                                          self.clients):
2212                return False
2213        return True
2214
2215    @test_tracker_info(uuid="216bdb8c-edbf-4ff8-8750-a0861ab44df6")
2216    @TelephonyBaseTest.tel_test_wrap
2217    def test_tethering_wifi_volte_call(self):
2218        """WiFi Tethering test: VoLTE call during WiFi tethering
2219        1. Start LTE to WiFi (2.4G) tethering.
2220        2. Verify tethering.
2221        3. Make outgoing VoLTE call on tethering provider.
2222        4. Verify tethering still works.
2223        5. Make incoming VoLTE call on tethering provider.
2224        6. Verify tethering still works.
2225
2226        Returns:
2227            True if success.
2228            False if failed.
2229        """
2230        return self._test_tethering_wifi_and_voice_call(
2231            RAT_4G, phone_setup_volte, is_phone_in_call_volte)
2232
2233    @test_tracker_info(uuid="bcd430cc-6d33-47d1-825d-aae9f248addc")
2234    @TelephonyBaseTest.tel_test_wrap
2235    def test_tethering_wifi_csfb_call(self):
2236        """WiFi Tethering test: CSFB call during WiFi tethering
2237        1. Start LTE to WiFi (2.4G) tethering.
2238        2. Verify tethering.
2239        3. Make outgoing CSFB call on tethering provider.
2240        4. Verify tethering still works.
2241        5. Make incoming CSFB call on tethering provider.
2242        6. Verify tethering still works.
2243
2244        Returns:
2245            True if success.
2246            False if failed.
2247        """
2248        return self._test_tethering_wifi_and_voice_call(
2249            RAT_4G, phone_setup_csfb, is_phone_in_call_csfb)
2250
2251    @test_tracker_info(uuid="19e0df23-6819-4c69-bfda-eea9cce802d8")
2252    @TelephonyBaseTest.tel_test_wrap
2253    def test_tethering_wifi_3g_call(self):
2254        """WiFi Tethering test: 3G call during WiFi tethering
2255        1. Start 3G to WiFi (2.4G) tethering.
2256        2. Verify tethering.
2257        3. Make outgoing CS call on tethering provider.
2258        4. Verify tethering still works.
2259        5. Make incoming CS call on tethering provider.
2260        6. Verify tethering still works.
2261
2262        Returns:
2263            True if success.
2264            False if failed.
2265        """
2266        return self._test_tethering_wifi_and_voice_call(
2267            RAT_3G, phone_setup_voice_3g, is_phone_in_call_3g)
2268
2269    @test_tracker_info(uuid="4acd98b5-fdef-4736-969f-3fa953990a58")
2270    @TelephonyBaseTest.tel_test_wrap
2271    def test_tethering_wifi_no_password(self):
2272        """WiFi Tethering test: Start WiFi tethering with no password
2273
2274        1. DUT is idle.
2275        2. DUT start 2.4G WiFi Tethering, with no WiFi password.
2276        3. PhoneB disable data, connect to DUT's softAP
2277        4. Verify Internet access on DUT and PhoneB
2278
2279        Returns:
2280            True if success.
2281            False if failed.
2282        """
2283        if not self._test_setup_tethering():
2284            self.log.error("Verify Internet access failed.")
2285            return False
2286
2287        return wifi_tethering_setup_teardown(
2288            self.log,
2289            self.provider, [self.clients[0]],
2290            ap_band=WIFI_CONFIG_APBAND_2G,
2291            check_interval=10,
2292            check_iteration=10,
2293            password="")
2294
2295    @test_tracker_info(uuid="86ad1680-bfb8-457e-8b4d-23321cb3f223")
2296    @TelephonyBaseTest.tel_test_wrap
2297    def test_tethering_wifi_reboot(self):
2298        """WiFi Tethering test: Start WiFi tethering then Reboot device
2299
2300        1. DUT is idle.
2301        2. DUT start 2.4G WiFi Tethering.
2302        3. PhoneB disable data, connect to DUT's softAP
2303        4. Verify Internet access on DUT and PhoneB
2304        5. Reboot DUT
2305        6. After DUT reboot, verify tethering is stopped.
2306
2307        Returns:
2308            True if success.
2309            False if failed.
2310        """
2311        if not self._test_setup_tethering():
2312            self.log.error("Verify Internet access failed.")
2313            return False
2314        try:
2315            if not wifi_tethering_setup_teardown(
2316                    self.log,
2317                    self.provider, [self.clients[0]],
2318                    ap_band=WIFI_CONFIG_APBAND_2G,
2319                    check_interval=10,
2320                    check_iteration=2,
2321                    do_cleanup=False):
2322                self.log.error("WiFi Tethering failed.")
2323                return False
2324
2325            if not self.provider.droid.wifiIsApEnabled():
2326                self.log.error("Provider WiFi tethering stopped.")
2327                return False
2328
2329            self.provider.log.info("Reboot provider")
2330            self.provider.reboot()
2331            time.sleep(
2332                WAIT_TIME_AFTER_REBOOT + WAIT_TIME_TETHERING_AFTER_REBOOT)
2333
2334            self.log.info("After reboot check if tethering stopped.")
2335            if self.provider.droid.wifiIsApEnabled():
2336                self.log.error("Provider WiFi tethering did NOT stopped.")
2337                return False
2338        finally:
2339            self.clients[0].droid.telephonyToggleDataConnection(True)
2340            wifi_reset(self.log, self.clients[0])
2341            if self.provider.droid.wifiIsApEnabled():
2342                stop_wifi_tethering(self.log, self.provider)
2343        return True
2344
2345    @test_tracker_info(uuid="5cf04ca2-dfde-43d6-be74-78b9abdf6c26")
2346    @TelephonyBaseTest.tel_test_wrap
2347    def test_connect_wifi_start_tethering_wifi_reboot(self):
2348        """WiFi Tethering test: WiFI connected, then start WiFi tethering,
2349            then reboot device.
2350
2351        Initial Condition: DUT in 4G mode, idle, DUT connect to WiFi.
2352        1. DUT start 2.4G WiFi Tethering.
2353        2. PhoneB disable data, connect to DUT's softAP
2354        3. Verify Internet access on DUT and PhoneB
2355        4. Reboot DUT
2356        5. After DUT reboot, verify tethering is stopped. DUT is able to connect
2357            to previous WiFi AP.
2358
2359        Returns:
2360            True if success.
2361            False if failed.
2362        """
2363        if not self._test_setup_tethering():
2364            self.log.error("Verify Internet access failed.")
2365            return False
2366
2367        self.log.info("Make sure DUT can connect to live network by WIFI")
2368        if ((not ensure_wifi_connected(self.log, self.provider,
2369                                       self.wifi_network_ssid,
2370                                       self.wifi_network_pass))
2371                or (not verify_internet_connection(self.log, self.provider))):
2372            self.log.error("WiFi connect fail.")
2373            return False
2374
2375        try:
2376            if not wifi_tethering_setup_teardown(
2377                    self.log,
2378                    self.provider, [self.clients[0]],
2379                    ap_band=WIFI_CONFIG_APBAND_2G,
2380                    check_interval=10,
2381                    check_iteration=2,
2382                    do_cleanup=False):
2383                self.log.error("WiFi Tethering failed.")
2384                return False
2385
2386            if not self.provider.droid.wifiIsApEnabled():
2387                self.log.error("Provider WiFi tethering stopped.")
2388                return False
2389
2390            self.provider.log.info("Reboot Provider")
2391            self.provider.reboot()
2392            time.sleep(WAIT_TIME_AFTER_REBOOT)
2393            time.sleep(WAIT_TIME_TETHERING_AFTER_REBOOT)
2394
2395            self.log.info("After reboot check if tethering stopped.")
2396            if self.provider.droid.wifiIsApEnabled():
2397                self.provider.log.error(
2398                    "Provider WiFi tethering did NOT stopped.")
2399                return False
2400
2401            self.log.info("Make sure WiFi can connect automatically.")
2402            if (not wait_for_wifi_data_connection(self.log, self.provider,
2403                                                  True) or
2404                    not verify_internet_connection(self.log, self.provider)):
2405                self.log.error("Data did not return to WiFi")
2406                return False
2407
2408        finally:
2409            self.clients[0].droid.telephonyToggleDataConnection(True)
2410            wifi_reset(self.log, self.clients[0])
2411            if self.provider.droid.wifiIsApEnabled():
2412                stop_wifi_tethering(self.log, self.provider)
2413        return True
2414
2415    @test_tracker_info(uuid="e0621997-c5bd-4137-afa6-b43406e9c713")
2416    @TelephonyBaseTest.tel_test_wrap
2417    def test_connect_wifi_reboot_start_tethering_wifi(self):
2418        """WiFi Tethering test: DUT connected to WiFi, then reboot,
2419        After reboot, start WiFi tethering, verify tethering actually works.
2420
2421        Initial Condition: Device set to 4G mode, idle, DUT connect to WiFi.
2422        1. Verify Internet is working on DUT (by WiFi).
2423        2. Reboot DUT.
2424        3. DUT start 2.4G WiFi Tethering.
2425        4. PhoneB disable data, connect to DUT's softAP
2426        5. Verify Internet access on DUT and PhoneB
2427
2428        Returns:
2429            True if success.
2430            False if failed.
2431        """
2432        if not self._test_setup_tethering():
2433            self.log.error("Verify Internet access failed.")
2434            return False
2435
2436        self.log.info("Make sure DUT can connect to live network by WIFI")
2437        if ((not ensure_wifi_connected(self.log, self.provider,
2438                                       self.wifi_network_ssid,
2439                                       self.wifi_network_pass))
2440                or (not verify_internet_connection(self.log, self.provider))):
2441            self.log.error("WiFi connect fail.")
2442            return False
2443
2444        self.provider.log.info("Reboot provider")
2445        self.provider.reboot()
2446        time.sleep(WAIT_TIME_AFTER_REBOOT)
2447        time.sleep(WAIT_TIME_TETHERING_AFTER_REBOOT)
2448
2449        return wifi_tethering_setup_teardown(
2450            self.log,
2451            self.provider, [self.clients[0]],
2452            ap_band=WIFI_CONFIG_APBAND_2G,
2453            check_interval=10,
2454            check_iteration=10)
2455
2456    @test_tracker_info(uuid="89a849ef-e2ed-4bf2-ac31-81d34aba672a")
2457    @TelephonyBaseTest.tel_test_wrap
2458    def test_tethering_wifi_screen_off_enable_doze_mode(self):
2459        """WiFi Tethering test: Start WiFi tethering, then turn off DUT's screen,
2460            then enable doze mode.
2461
2462        1. Start WiFi tethering on DUT.
2463        2. PhoneB disable data, and connect to DUT's softAP
2464        3. Verify Internet access on DUT and PhoneB
2465        4. Turn off DUT's screen. Wait for 1 minute and
2466            verify Internet access on Client PhoneB.
2467        5. Enable doze mode on DUT. Wait for 1 minute and
2468            verify Internet access on Client PhoneB.
2469
2470        Returns:
2471            True if success.
2472            False if failed.
2473        """
2474        if not self._test_setup_tethering():
2475            self.log.error("Verify Internet access failed.")
2476            return False
2477        try:
2478            if not wifi_tethering_setup_teardown(
2479                    self.log,
2480                    self.provider, [self.clients[0]],
2481                    ap_band=WIFI_CONFIG_APBAND_2G,
2482                    check_interval=10,
2483                    check_iteration=2,
2484                    do_cleanup=False):
2485                self.log.error("WiFi Tethering failed.")
2486                return False
2487
2488            if not self.provider.droid.wifiIsApEnabled():
2489                self.provider.log.error("Provider WiFi tethering stopped.")
2490                return False
2491
2492            self.provider.log.info("Turn off screen on provider")
2493            self.provider.droid.goToSleepNow()
2494            time.sleep(60)
2495            if not verify_internet_connection(self.log, self.clients[0]):
2496                self.client.log.error("Client have no Internet access.")
2497                return False
2498
2499            self.provider.log.info("Enable doze mode on provider")
2500            if not enable_doze(self.provider):
2501                self.provider.log.error("Failed to enable doze mode.")
2502                return False
2503            time.sleep(60)
2504            if not verify_internet_connection(self.log, self.clients[0]):
2505                self.clients[0].log.error("Client have no Internet access.")
2506                return False
2507        finally:
2508            self.log.info("Disable doze mode.")
2509            if not disable_doze(self.provider):
2510                self.log.error("Failed to disable doze mode.")
2511                return False
2512            if not wifi_tethering_cleanup(self.log, self.provider,
2513                                          [self.clients[0]]):
2514                return False
2515        return True
2516
2517    @test_tracker_info(uuid="695eef18-f759-4b41-8ad3-1fb329ee4b1b")
2518    @TelephonyBaseTest.tel_test_wrap
2519    def test_msim_switch_data_sim_2g(self):
2520        """Switch Data SIM on 2G network.
2521
2522        Steps:
2523        1. Data on default Data SIM.
2524        2. Switch Data to another SIM. Make sure data is still available.
2525        3. Switch Data back to previous SIM. Make sure data is still available.
2526
2527        Expected Results:
2528        1. Verify Data on Cell
2529        2. Verify Data on Wifi
2530
2531        Returns:
2532            True if success.
2533            False if failed.
2534        """
2535        ad = self.android_devices[0]
2536        current_data_sub_id = ad.droid.subscriptionGetDefaultDataSubId()
2537        current_sim_slot_index = get_slot_index_from_subid(
2538            self.log, ad, current_data_sub_id)
2539        if current_sim_slot_index == SIM1_SLOT_INDEX:
2540            next_sim_slot_index = SIM2_SLOT_INDEX
2541        else:
2542            next_sim_slot_index = SIM1_SLOT_INDEX
2543        next_data_sub_id = get_subid_from_slot_index(self.log, ad,
2544                                                     next_sim_slot_index)
2545        self.log.info("Current Data is on subId: {}, SIM slot: {}".format(
2546            current_data_sub_id, current_sim_slot_index))
2547        if not ensure_network_generation_for_subscription(
2548                self.log,
2549                ad,
2550                ad.droid.subscriptionGetDefaultDataSubId(),
2551                GEN_2G,
2552                voice_or_data=NETWORK_SERVICE_DATA):
2553            self.log.error("Device data does not attach to 2G.")
2554            return False
2555        if not verify_internet_connection(self.log, ad):
2556            self.log.error("No Internet access on default Data SIM.")
2557            return False
2558
2559        self.log.info("Change Data to subId: {}, SIM slot: {}".format(
2560            next_data_sub_id, next_sim_slot_index))
2561        if not change_data_sim_and_verify_data(self.log, ad,
2562                                               next_sim_slot_index):
2563            self.log.error("Failed to change data SIM.")
2564            return False
2565
2566        next_data_sub_id = current_data_sub_id
2567        next_sim_slot_index = current_sim_slot_index
2568        self.log.info("Change Data back to subId: {}, SIM slot: {}".format(
2569            next_data_sub_id, next_sim_slot_index))
2570        if not change_data_sim_and_verify_data(self.log, ad,
2571                                               next_sim_slot_index):
2572            self.log.error("Failed to change data SIM.")
2573            return False
2574
2575        return True
2576
2577    def _test_wifi_connect_disconnect(self):
2578        """Perform multiple connects and disconnects from WiFi and verify that
2579            data switches between WiFi and Cell.
2580
2581        Steps:
2582        1. Reset Wifi on DUT
2583        2. Connect DUT to a WiFi AP
2584        3. Repeat steps 1-2, alternately disconnecting and disabling wifi
2585
2586        Expected Results:
2587        1. Verify Data on Cell
2588        2. Verify Data on Wifi
2589
2590        Returns:
2591            True if success.
2592            False if failed.
2593        """
2594        ad = self.android_devices[0]
2595
2596        wifi_toggles = [
2597            True, False, True, False, False, True, False, False, False, False,
2598            True, False, False, False, False, False, False, False, False
2599        ]
2600
2601        for toggle in wifi_toggles:
2602
2603            wifi_reset(self.log, ad, toggle)
2604
2605            if not wait_for_cell_data_connection(
2606                    self.log, ad, True, MAX_WAIT_TIME_WIFI_CONNECTION):
2607                self.log.error("Failed wifi connection, aborting!")
2608                return False
2609
2610            if not verify_internet_connection(self.log, ad):
2611                self.log.error("Failed to get user-plane traffic, aborting!")
2612                return False
2613
2614            if toggle:
2615                wifi_toggle_state(self.log, ad, True)
2616
2617            ensure_wifi_connected(self.log, ad, self.wifi_network_ssid,
2618                         self.wifi_network_pass)
2619
2620            if not wait_for_wifi_data_connection(
2621                    self.log, ad, True, MAX_WAIT_TIME_WIFI_CONNECTION):
2622                self.log.error("Failed wifi connection, aborting!")
2623                return False
2624
2625            if not verify_http_connection(
2626                    self.log, ad, 'http://www.google.com', 100, .1):
2627                self.log.error("Failed to get user-plane traffic, aborting!")
2628                return False
2629        return True
2630
2631    @test_tracker_info(uuid="9b8e92da-0ae1-472c-a72a-f6427e5405ce")
2632    @TelephonyBaseTest.tel_test_wrap
2633    def test_wifi_connect_disconnect_4g(self):
2634        """Perform multiple connects and disconnects from WiFi and verify that
2635            data switches between WiFi and Cell.
2636
2637        Steps:
2638        1. DUT Cellular Data is on 4G. Reset Wifi on DUT
2639        2. Connect DUT to a WiFi AP
2640        3. Repeat steps 1-2, alternately disconnecting and disabling wifi
2641
2642        Expected Results:
2643        1. Verify Data on Cell
2644        2. Verify Data on Wifi
2645
2646        Returns:
2647            True if success.
2648            False if failed.
2649        """
2650
2651        ad = self.android_devices[0]
2652        if not ensure_network_generation_for_subscription(
2653                self.log, ad, ad.droid.subscriptionGetDefaultDataSubId(),
2654                GEN_4G, MAX_WAIT_TIME_NW_SELECTION, NETWORK_SERVICE_DATA):
2655            self.log.error("Device {} failed to reselect in {}s.".format(
2656                ad.serial, MAX_WAIT_TIME_NW_SELECTION))
2657            return False
2658        return self._test_wifi_connect_disconnect()
2659
2660    @test_tracker_info(uuid="09893b1f-a4a2-49d3-8027-c2c91cb8742e")
2661    @TelephonyBaseTest.tel_test_wrap
2662    def test_wifi_connect_disconnect_3g(self):
2663        """Perform multiple connects and disconnects from WiFi and verify that
2664            data switches between WiFi and Cell.
2665
2666        Steps:
2667        1. DUT Cellular Data is on 3G. Reset Wifi on DUT
2668        2. Connect DUT to a WiFi AP
2669        3. Repeat steps 1-2, alternately disconnecting and disabling wifi
2670
2671        Expected Results:
2672        1. Verify Data on Cell
2673        2. Verify Data on Wifi
2674
2675        Returns:
2676            True if success.
2677            False if failed.
2678        """
2679
2680        ad = self.android_devices[0]
2681        if not ensure_network_generation_for_subscription(
2682                self.log, ad, ad.droid.subscriptionGetDefaultDataSubId(),
2683                GEN_3G, MAX_WAIT_TIME_NW_SELECTION, NETWORK_SERVICE_DATA):
2684            self.log.error("Device {} failed to reselect in {}s.".format(
2685                ad.serial, MAX_WAIT_TIME_NW_SELECTION))
2686            return False
2687        return self._test_wifi_connect_disconnect()
2688
2689    @test_tracker_info(uuid="0f095ca4-ce05-458f-9670-49a69f8c8270")
2690    @TelephonyBaseTest.tel_test_wrap
2691    def test_wifi_connect_disconnect_2g(self):
2692        """Perform multiple connects and disconnects from WiFi and verify that
2693            data switches between WiFi and Cell.
2694
2695        Steps:
2696        1. DUT Cellular Data is on 2G. Reset Wifi on DUT
2697        2. Connect DUT to a WiFi AP
2698        3. Repeat steps 1-2, alternately disconnecting and disabling wifi
2699
2700        Expected Results:
2701        1. Verify Data on Cell
2702        2. Verify Data on Wifi
2703
2704        Returns:
2705            True if success.
2706            False if failed.
2707        """
2708        ad = self.android_devices[0]
2709        if not ensure_network_generation_for_subscription(
2710                self.log, ad, ad.droid.subscriptionGetDefaultDataSubId(),
2711                GEN_2G, MAX_WAIT_TIME_NW_SELECTION, NETWORK_SERVICE_DATA):
2712            self.log.error("Device {} failed to reselect in {}s.".format(
2713                ad.serial, MAX_WAIT_TIME_NW_SELECTION))
2714            return False
2715        return self._test_wifi_connect_disconnect()
2716
2717    def _test_wifi_tethering_enabled_add_voice_call(
2718            self, network_generation, voice_call_direction,
2719            is_data_available_during_call):
2720        """Tethering enabled + voice call.
2721
2722        Steps:
2723        1. DUT data is on <network_generation>. Start WiFi Tethering.
2724        2. PhoneB connect to DUT's softAP
2725        3. DUT make a MO/MT (<voice_call_direction>) phone call.
2726        4. DUT end phone call.
2727
2728        Expected Results:
2729        1. DUT is able to start WiFi tethering.
2730        2. PhoneB connected to DUT's softAP and able to browse Internet.
2731        3. DUT WiFi tethering is still on. Phone call works OK.
2732            If is_data_available_during_call is True, then PhoneB still has
2733            Internet access.
2734            Else, then Data is suspend, PhoneB has no Internet access.
2735        4. WiFi Tethering still on, voice call stopped, and PhoneB have Internet
2736            access.
2737
2738        Returns:
2739            True if success.
2740            False if failed.
2741        """
2742        if not self._test_setup_tethering(network_generation):
2743            self.log.error("Verify Internet access failed.")
2744            return False
2745        try:
2746            # Start WiFi Tethering
2747            if not wifi_tethering_setup_teardown(
2748                    self.log,
2749                    self.provider, [self.clients[0]],
2750                    ap_band=WIFI_CONFIG_APBAND_2G,
2751                    check_interval=10,
2752                    check_iteration=2,
2753                    do_cleanup=False):
2754                self.log.error("WiFi Tethering failed.")
2755                return False
2756
2757            if not self.provider.droid.wifiIsApEnabled():
2758                self.log.error("Provider WiFi tethering stopped.")
2759                return False
2760
2761            # Make a voice call
2762            if voice_call_direction == DIRECTION_MOBILE_ORIGINATED:
2763                ad_caller = self.provider
2764                ad_callee = self.clients[0]
2765            else:
2766                ad_caller = self.clients[0]
2767                ad_callee = self.provider
2768            if not call_setup_teardown(self.log, ad_caller, ad_callee, None,
2769                                       None, None):
2770                self.log.error("Failed to Establish {} Voice Call".format(
2771                    voice_call_direction))
2772                return False
2773
2774            # Tethering should still be on.
2775            if not self.provider.droid.wifiIsApEnabled():
2776                self.provider.log.error("Provider WiFi tethering stopped.")
2777                return False
2778            if not is_data_available_during_call:
2779                if verify_internet_connection(
2780                        self.log, self.clients[0], retry=0):
2781                    self.clients[0].log.error(
2782                        "Client should not have Internet Access.")
2783                    return False
2784            else:
2785                if not verify_internet_connection(self.log, self.clients[0]):
2786                    self.clients[0].error(
2787                        "Client should have Internet Access.")
2788                    return False
2789
2790            # Hangup call. Client should have data.
2791            if not hangup_call(self.log, self.provider):
2792                self.provider.log.error("Failed to hang up call")
2793                return False
2794            if not self.provider.droid.wifiIsApEnabled():
2795                self.provider.log.error("Provider WiFi tethering stopped.")
2796                return False
2797            if not verify_internet_connection(self.log, self.clients[0]):
2798                self.clients[0].log.error(
2799                    "Client should have Internet Access.")
2800                return False
2801        finally:
2802            self.clients[0].droid.telephonyToggleDataConnection(True)
2803            wifi_reset(self.log, self.clients[0])
2804            if self.provider.droid.wifiIsApEnabled():
2805                stop_wifi_tethering(self.log, self.provider)
2806        return True
2807
2808    @test_tracker_info(uuid="4d7a68c6-5eae-4242-a6e6-668f830caec3")
2809    @TelephonyBaseTest.tel_test_wrap
2810    def test_wifi_tethering_enabled_add_mo_voice_call_2g_dsds(self):
2811        """Tethering enabled + voice call
2812
2813        Steps:
2814        1. DUT is DSDS device, Data on 2G. Start WiFi Tethering on <Data SIM>
2815        2. PhoneB connect to DUT's softAP
2816        3. DUT make a mo phone call on <Voice SIM>
2817        4. DUT end phone call.
2818
2819        Expected Results:
2820        1. DUT is able to start WiFi tethering.
2821        2. PhoneB connected to DUT's softAP and able to browse Internet.
2822        3. DUT WiFi tethering is still on. Phone call works OK. Data is suspend,
2823            PhoneB still connected to DUT's softAP, but no data available.
2824        4. DUT data resumes, and PhoneB have Internet access.
2825
2826        Returns:
2827            True if success.
2828            False if failed.
2829        """
2830
2831        return self._test_wifi_tethering_enabled_add_voice_call(
2832            GEN_2G, DIRECTION_MOBILE_ORIGINATED, False)
2833
2834    @test_tracker_info(uuid="de720069-a46c-4a6f-ae80-60b9349c8528")
2835    @TelephonyBaseTest.tel_test_wrap
2836    def test_wifi_tethering_enabled_add_mt_voice_call_2g_dsds(self):
2837        """Tethering enabled + voice call
2838
2839        Steps:
2840        1. DUT is DSDS device, Data on 2G. Start WiFi Tethering on <Data SIM>
2841        2. PhoneB connect to DUT's softAP
2842        3. DUT make a mt phone call on <Voice SIM>
2843        4. DUT end phone call.
2844
2845        Expected Results:
2846        1. DUT is able to start WiFi tethering.
2847        2. PhoneB connected to DUT's softAP and able to browse Internet.
2848        3. DUT WiFi tethering is still on. Phone call works OK. Data is suspend,
2849            PhoneB still connected to DUT's softAP, but no data available.
2850        4. DUT data resumes, and PhoneB have Internet access.
2851
2852        Returns:
2853            True if success.
2854            False if failed.
2855        """
2856
2857        return self._test_wifi_tethering_enabled_add_voice_call(
2858            GEN_2G, DIRECTION_MOBILE_TERMINATED, False)
2859
2860    @test_tracker_info(uuid="fad169c0-8ae6-45d2-98ba-3fb60466ff0b")
2861    @TelephonyBaseTest.tel_test_wrap
2862    def test_wifi_tethering_msim_switch_data_sim(self):
2863        """Tethering enabled + switch data SIM.
2864
2865        Steps:
2866        1. Start WiFi Tethering on <Default Data SIM>
2867        2. PhoneB connect to DUT's softAP
2868        3. DUT change Default Data SIM.
2869
2870        Expected Results:
2871        1. DUT is able to start WiFi tethering.
2872        2. PhoneB connected to DUT's softAP and able to browse Internet.
2873        3. DUT Data changed to 2nd SIM, WiFi tethering should continues,
2874            PhoneB should have Internet access.
2875
2876        Returns:
2877            True if success.
2878            False if failed.
2879        """
2880        current_data_sub_id = self.provider.droid.subscriptionGetDefaultDataSubId(
2881        )
2882        current_sim_slot_index = get_slot_index_from_subid(
2883            self.log, self.provider, current_data_sub_id)
2884        self.provider.log.info("Current Data is on subId: %s, SIM slot: %s",
2885                               current_data_sub_id, current_sim_slot_index)
2886        if not self._test_setup_tethering():
2887            self.log.error("Verify Internet access failed.")
2888            return False
2889        try:
2890            # Start WiFi Tethering
2891            if not wifi_tethering_setup_teardown(
2892                    self.log,
2893                    self.provider, [self.clients[0]],
2894                    ap_band=WIFI_CONFIG_APBAND_2G,
2895                    check_interval=10,
2896                    check_iteration=2,
2897                    do_cleanup=False):
2898                self.log.error("WiFi Tethering failed.")
2899                return False
2900            for i in range(0, 2):
2901                next_sim_slot_index = \
2902                    {SIM1_SLOT_INDEX : SIM2_SLOT_INDEX,
2903                     SIM2_SLOT_INDEX : SIM1_SLOT_INDEX}[current_sim_slot_index]
2904                self.log.info(
2905                    "Change Data to SIM slot: {}".format(next_sim_slot_index))
2906                if not change_data_sim_and_verify_data(self.log, self.provider,
2907                                                       next_sim_slot_index):
2908                    self.provider.log.error("Failed to change data SIM.")
2909                    return False
2910                current_sim_slot_index = next_sim_slot_index
2911                if not verify_internet_connection(self.log, self.clients[0]):
2912                    self.clients[0].log.error(
2913                        "Client should have Internet Access.")
2914                    return False
2915        finally:
2916            self.clients[0].droid.telephonyToggleDataConnection(True)
2917            wifi_reset(self.log, self.clients[0])
2918            if self.provider.droid.wifiIsApEnabled():
2919                stop_wifi_tethering(self.log, self.provider)
2920        return True
2921
2922    @test_tracker_info(uuid="8bb9383f-ddf9-400c-a831-c9462bae6b47")
2923    @TelephonyBaseTest.tel_test_wrap
2924    def test_msim_cell_data_switch_to_wifi_switch_data_sim_2g(self):
2925        """Switch Data SIM on 2G network.
2926
2927        Steps:
2928        1. Data on default Data SIM.
2929        2. Turn on WiFi, then data should be on WiFi.
2930        3. Switch Data to another SIM. Disable WiFi.
2931
2932        Expected Results:
2933        1. Verify Data on Cell
2934        2. Verify Data on WiFi
2935        3. After WiFi disabled, Cell Data is available on 2nd SIM.
2936
2937        Returns:
2938            True if success.
2939            False if failed.
2940        """
2941        ad = self.android_devices[0]
2942        current_data_sub_id = ad.droid.subscriptionGetDefaultDataSubId()
2943        current_sim_slot_index = get_slot_index_from_subid(
2944            self.log, ad, current_data_sub_id)
2945        if current_sim_slot_index == SIM1_SLOT_INDEX:
2946            next_sim_slot_index = SIM2_SLOT_INDEX
2947        else:
2948            next_sim_slot_index = SIM1_SLOT_INDEX
2949        next_data_sub_id = get_subid_from_slot_index(self.log, ad,
2950                                                     next_sim_slot_index)
2951        self.log.info("Current Data is on subId: {}, SIM slot: {}".format(
2952            current_data_sub_id, current_sim_slot_index))
2953        if not ensure_network_generation_for_subscription(
2954                self.log,
2955                ad,
2956                ad.droid.subscriptionGetDefaultDataSubId(),
2957                GEN_2G,
2958                voice_or_data=NETWORK_SERVICE_DATA):
2959            self.log.error("Device data does not attach to 2G.")
2960            return False
2961        if not verify_internet_connection(self.log, ad):
2962            self.log.error("No Internet access on default Data SIM.")
2963            return False
2964
2965        self.log.info("Connect to WiFi and verify Internet access.")
2966        if not ensure_wifi_connected(self.log, ad, self.wifi_network_ssid,
2967                                     self.wifi_network_pass):
2968            self.log.error("WiFi connect fail.")
2969            return False
2970        if (not wait_for_wifi_data_connection(self.log, ad, True)
2971                or not verify_internet_connection(self.log, ad)):
2972            self.log.error("Data is not on WiFi")
2973            return False
2974
2975        try:
2976            self.log.info(
2977                "Change Data SIM, Disable WiFi and verify Internet access.")
2978            set_subid_for_data(ad, next_data_sub_id)
2979            wifi_toggle_state(self.log, ad, False)
2980            if not wait_for_data_attach_for_subscription(
2981                    self.log, ad, next_data_sub_id,
2982                    MAX_WAIT_TIME_NW_SELECTION):
2983                self.log.error("Failed to attach data on subId:{}".format(
2984                    next_data_sub_id))
2985                return False
2986            if not verify_internet_connection(self.log, ad):
2987                self.log.error("No Internet access after changing Data SIM.")
2988                return False
2989
2990        finally:
2991            self.log.info("Change Data SIM back.")
2992            set_subid_for_data(ad, current_data_sub_id)
2993
2994        return True
2995
2996    @test_tracker_info(uuid="ef03eff7-ddd3-48e9-8f67-5e271e14048b")
2997    @TelephonyBaseTest.tel_test_wrap
2998    def test_vzw_embms_services(self):
2999        ad = self.android_devices[0]
3000        # Install App and Push config
3001        self.log.info("Pushing embms config and apk to the Android device.")
3002        android_embms_path = "/sdcard/mobitv"
3003        embms_path = self.user_params.get("embms_path", "embms_path")
3004        if isinstance(embms_path, list):
3005            embms_path = embms_path[0]
3006        ad.adb.shell("mkdir /sdcard/mobitv")
3007        dcafile = os.path.join(embms_path, "dca.config")
3008        apkfile = os.path.join(embms_path, "VzwDCA.apk")
3009        ad.adb.push("%s %s" % (dcafile, android_embms_path))
3010        ad.adb.install("%s" % apkfile)
3011
3012        # Co-ordinates Mapping
3013        lcd_density = ad.adb.shell("getprop ro.sf.lcd_density")
3014        ad.log.debug("lcd_density %s" % lcd_density)
3015        if lcd_density in ["420", "440"]:
3016            agree_y_axis = 1000
3017        else:
3018            agree_y_axis = 1300
3019
3020        # Screen ON needed to open the VZW App
3021        if "ON" in \
3022        ad.adb.shell(
3023               "dumpsys power | grep 'Display Power: state' | cut -d '=' -f2"):
3024            ad.log.info("Screen already ON")
3025            ad.adb.shell("input keyevent 82")
3026        else:
3027            ad.log.info("Screen OFF, turning ON")
3028            ad.adb.shell("input keyevent 26")
3029            ad.adb.shell("input keyevent 82")
3030
3031        try:
3032            # Check if app is installed
3033            if ad.is_apk_installed("com.mobitv.vzwdca"):
3034                ad.log.info("VZWDCA App is successfully installed")
3035            else:
3036                ad.log.error("VZWDCA App is not installed")
3037                return False
3038
3039            # Grant Permissions, Start, Agree, Register
3040            for cmd in ("pm grant com.mobitv.vzwdca "
3041                        "android.permission.READ_EXTERNAL_STORAGE",
3042                        "pm grant com.mobitv.vzwdca "
3043                        "android.permission.WRITE_EXTERNAL_STORAGE",
3044                        "am start -a android.intent.action.VIEW -n "
3045                        "com.mobitv.vzwdca/.DcaActivity",
3046                        "input tap 500 %d" % agree_y_axis, "input keyevent 61",
3047                        "input keyevent 61", "input keyevent 61",
3048                        "input keyevent 61", "input keyevent 61",
3049                        "input keyevent 66"):
3050                time.sleep(1)
3051                ad.log.info(cmd)
3052                ad.adb.shell(cmd)
3053
3054            # Check Reg-DeReg
3055            time.sleep(5)
3056            if ad.is_apk_running("com.qualcomm.ltebc_vzw"):
3057                ad.log.info("EMBMS Registered successfully")
3058                ad.adb.shell("input keyevent 61")
3059                time.sleep(1)
3060                ad.adb.shell("input keyevent 66")
3061                time.sleep(1)
3062                if not ad.is_apk_running("com.qualcomm.ltebc_vzw"):
3063                    ad.log.info("EMBMS De-Registered successfully")
3064                    return True
3065                else:
3066                    ad.log.error("EMBMS De-Registeration Failed")
3067                    return False
3068            else:
3069                ad.log.error("EMBMS Registeration Failed")
3070                return False
3071        finally:
3072            ad.log.info("Force Close the VZW App")
3073            ad.adb.shell("am force-stop com.mobitv.vzwdca")
3074
3075    @test_tracker_info(uuid="8a8cd773-77f5-4802-85ac-1a654bb4743c")
3076    @TelephonyBaseTest.tel_test_wrap
3077    def test_disable_data_on_non_active_data_sim(self):
3078        """Switch Data SIM on 2G network.
3079
3080        Steps:
3081        1. Data on default Data SIM.
3082        2. Disable data on non-active Data SIM.
3083
3084        Expected Results:
3085        1. Verify Data Status on Default Data SIM and non-active Data SIM.
3086        1. Verify Data Status on Default Data SIM and non-active Data SIM.
3087
3088        Returns:
3089            True if success.
3090            False if failed.
3091        """
3092        ad = self.android_devices[0]
3093        current_data_sub_id = ad.droid.subscriptionGetDefaultDataSubId()
3094        current_sim_slot_index = get_slot_index_from_subid(
3095            self.log, ad, current_data_sub_id)
3096        if current_sim_slot_index == SIM1_SLOT_INDEX:
3097            non_active_sim_slot_index = SIM2_SLOT_INDEX
3098        else:
3099            non_active_sim_slot_index = SIM1_SLOT_INDEX
3100        non_active_sub_id = get_subid_from_slot_index(
3101            self.log, ad, non_active_sim_slot_index)
3102        self.log.info("Current Data is on subId: {}, SIM slot: {}".format(
3103            current_data_sub_id, current_sim_slot_index))
3104
3105        if not ensure_network_generation_for_subscription(
3106                self.log,
3107                ad,
3108                ad.droid.subscriptionGetDefaultDataSubId(),
3109                GEN_2G,
3110                voice_or_data=NETWORK_SERVICE_DATA):
3111            self.log.error("Device data does not attach to 2G.")
3112            return False
3113        if not verify_internet_connection(self.log, ad):
3114            self.log.error("No Internet access on default Data SIM.")
3115            return False
3116
3117        if ad.droid.telephonyGetDataConnectionState() != DATA_STATE_CONNECTED:
3118            self.log.error("Data Connection State should be connected.")
3119            return False
3120        # TODO: Check Data state for non-active subId.
3121
3122        try:
3123            self.log.info("Disable Data on Non-Active Sub ID")
3124            ad.droid.telephonyToggleDataConnectionForSubscription(
3125                non_active_sub_id, False)
3126            # TODO: Check Data state for non-active subId.
3127            if ad.droid.telephonyGetDataConnectionState(
3128            ) != DATA_STATE_CONNECTED:
3129                self.log.error("Data Connection State should be connected.")
3130                return False
3131        finally:
3132            self.log.info("Enable Data on Non-Active Sub ID")
3133            ad.droid.telephonyToggleDataConnectionForSubscription(
3134                non_active_sub_id, True)
3135        return True
3136
3137    def file_download_stress(self):
3138        failure = 0
3139        total_count = 0
3140        self.result_info = collections.defaultdict(int)
3141        dut = self.android_devices[0]
3142        self.max_sleep_time = int(self.user_params.get("max_sleep_time", 1200))
3143        #file_names = ["5MB", "10MB", "20MB", "50MB", "200MB", "512MB", "1GB"]
3144        file_names = ["5MB", "10MB", "20MB", "50MB", "200MB", "512MB"]
3145        while total_count < self.stress_test_number:
3146            total_count += 1
3147            try:
3148                dut.log.info(dict(self.result_info))
3149                selection = random.randrange(0, len(file_names))
3150                file_name = file_names[selection]
3151                self.result_info["Total %s file download" % file_name] += 1
3152                if not active_file_download_test(self.log, dut, file_name):
3153                    self.result_info["%s file download failure" %
3154                                     file_name] += 1
3155                    failure += 1
3156                    dut.take_bug_report("%s_failure_%s" % (self.test_name,
3157                                                           failure),
3158                                        time.strftime("%m-%d-%Y-%H-%M-%S"))
3159                    self.dut.droid.goToSleepNow()
3160                    time.sleep(random.randrange(0, self.max_sleep_time))
3161            except Exception as e:
3162                self.log.error("Exception error %s", str(e))
3163                self.result_info["Exception Errors"] += 1
3164            dut.log.info("File download test failure: %s/%s", failure,
3165                         total_count)
3166        if failure / total_count > 0.1:
3167            dut.log.error("File download test failure: %s/%s", failure,
3168                          total_count)
3169            return False
3170        return True
3171
3172    @test_tracker_info(uuid="5381a6fa-6771-4b00-a0d6-4a3891a6dba8")
3173    @TelephonyBaseTest.tel_test_wrap
3174    def test_file_download_stress_default(self):
3175        """File download stress test
3176
3177        Steps:
3178        1. Download a file random picked.
3179        2. Device sleep for sometime and Repeat 1.
3180
3181        Expected Results:
3182        Total download failure rate is less than 10%.
3183
3184        Returns:
3185            True if success.
3186            False if failed.
3187        """
3188        return self.file_download_stress()
3189
3190    @test_tracker_info(uuid="c9970955-123b-467c-afbb-95ec8f99e9b7")
3191    def test_file_download_with_mobile_data_usage_limit_set(self):
3192        """ Steps:
3193
3194        1. Set the data usage limit to current data usage + 9MB
3195        2. Download 5MB file from internet.
3196        3. The first file download should succeed
3197        4. The second file download should fail
3198
3199        """
3200        dut = self.android_devices[0]
3201        ensure_phones_default_state(self.log, [dut])
3202        subscriber_id = dut.droid.telephonyGetSubscriberId()
3203        old_data_usage = get_mobile_data_usage(dut, subscriber_id)
3204
3205        # set data usage limit to current usage limit + 10MB
3206        data_limit = old_data_usage + 9 * 1000 * 1000
3207        set_mobile_data_usage_limit(dut, data_limit, subscriber_id)
3208
3209        # download file - size 5MB twice
3210        try:
3211            for _ in range(2):
3212                if not active_file_download_test(self.log, dut, "5MB", "curl"):
3213                    if get_mobile_data_usage(
3214                            dut, subscriber_id) + 5 * 1000 * 1000 < data_limit:
3215                        dut.log.error(
3216                            "Fail to download file when mobile data usage is"
3217                            " below data usage limit")
3218                        return False
3219                    else:
3220                        dut.log.info(
3221                            "Download fails as expected due to data limit reached"
3222                        )
3223                else:
3224                    if get_mobile_data_usage(dut, subscriber_id) < data_limit:
3225                        dut.log.info(
3226                            "Download file succeed when mobile data usage is"
3227                            " below data usage limit")
3228                    else:
3229                        dut.log.error(
3230                            "Download should fail due to data limit reached")
3231                        return False
3232            return True
3233        finally:
3234            remove_mobile_data_usage_limit(dut, subscriber_id)
3235
3236
3237    def _test_data_stall_detection_recovery(self, nw_type="cellular",
3238                                            validation_type="detection"):
3239        dut = self.android_devices[0]
3240        try:
3241            cmd = ('ss -l -p -n | grep "tcp.*droid_script" | tr -s " " '
3242                   '| cut -d " " -f 5 | sed s/.*://g')
3243            sl4a_port = dut.adb.shell(cmd)
3244            ensure_phones_default_state(self.log, [dut])
3245            if nw_type == "wifi":
3246                if not ensure_wifi_connected(self.log, dut,
3247                                self.wifi_network_ssid, self.wifi_network_pass):
3248                    return False
3249
3250            if not test_data_browsing_success_using_sl4a(self.log, dut):
3251                dut.log.error("Browsing failed before the test, aborting!")
3252                return False
3253
3254            begin_time = get_device_epoch_time(dut)
3255            break_internet_except_sl4a_port(dut, sl4a_port)
3256
3257            if not test_data_browsing_failure_using_sl4a(self.log, dut):
3258                dut.log.error("Browsing success even after breaking internet, "\
3259                              "aborting!")
3260                return False
3261
3262            if not check_data_stall_detection(dut):
3263                dut.log.error("NetworkMonitor unable to detect Data Stall")
3264
3265            if not check_network_validation_fail(dut, begin_time):
3266                dut.log.error("Unable to detect NW validation fail")
3267                return False
3268
3269            if validation_type == "recovery":
3270                if not check_data_stall_recovery(dut, begin_time):
3271                    dut.log.error("Recovery was not triggerred")
3272                    return False
3273
3274            resume_internet_with_sl4a_port(dut, sl4a_port)
3275            time.sleep(10)
3276
3277            if not test_data_browsing_success_using_sl4a(self.log, dut):
3278                dut.log.error("Browsing failed after resuming internet")
3279                return False
3280            return True
3281        finally:
3282            resume_internet_with_sl4a_port(dut, sl4a_port)
3283
3284
3285    def _test_airplane_mode_stress(self):
3286        ad = self.android_devices[0]
3287        total_iteration = self.stress_test_number
3288        fail_count = collections.defaultdict(int)
3289        current_iteration = 1
3290        for i in range(1, total_iteration + 1):
3291            msg = "Airplane mode test Iteration: <%s> / <%s>" % (i, total_iteration)
3292            self.log.info(msg)
3293            if not airplane_mode_test(self.log, ad):
3294                fail_count["apm_run"] += 1
3295                ad.log.error(">----Iteration : %d/%d failed.----<",
3296                             i, total_iteration)
3297            ad.log.info(">----Iteration : %d/%d succeeded.----<",
3298                        i, total_iteration)
3299            current_iteration += 1
3300        test_result = True
3301        for failure, count in fail_count.items():
3302            if count:
3303                ad.log.error("%s: %s %s failures in %s iterations",
3304                             self.test_name, count, failure,
3305                             total_iteration)
3306                test_result = False
3307        return test_result
3308
3309
3310    @test_tracker_info(uuid="3a82728f-18b5-4a35-9eab-4e6cf55271d9")
3311    @TelephonyBaseTest.tel_test_wrap
3312    def test_apm_toggle_stress(self):
3313        """ Test airplane mode toggle
3314
3315        1. Start with airplane mode off
3316        2. Toggle airplane mode on
3317        3. Toggle airplane mode off
3318        4. Repeat above steps
3319
3320        Returns:
3321            True if pass; False if fail.
3322        """
3323        return self._test_airplane_mode_stress()
3324
3325
3326    @test_tracker_info(uuid="fda33416-698a-408f-8ddc-b5cde13b1f83")
3327    @TelephonyBaseTest.tel_test_wrap
3328    def test_data_stall_detection_cellular(self):
3329        """ Data Stall Detection Testing
3330
3331        1. Ensure device is camped, browsing working fine
3332        2. Break Internet access, browsing should fail
3333        3. Check for Data Stall Detection
3334
3335        """
3336        return self._test_data_stall_detection_recovery(nw_type="cellular")
3337
3338
3339    @test_tracker_info(uuid="a57891d6-7892-46c7-8bca-23cd2cca8552")
3340    @TelephonyBaseTest.tel_test_wrap
3341    def test_data_stall_detection_wifi(self):
3342        """ Data Stall Detection Testing
3343
3344        1. Ensure device is connected to WiFi, browsing working fine
3345        2. Break Internet access, browsing should fail
3346        3. Check for Data Stall Detection
3347
3348        """
3349        return self._test_data_stall_detection_recovery(nw_type="wifi")
3350
3351
3352    @test_tracker_info(uuid="16d3f123-cac3-45a9-a2e5-c01bab7044d4")
3353    @TelephonyBaseTest.tel_test_wrap
3354    def test_data_stall_recovery_cellular(self):
3355        """ Data Stall Recovery Testing
3356
3357        1. Ensure device is camped, browsing working fine
3358        2. Break Internet access, browsing should fail
3359        3. Check for Data Stall Detection
3360        4. Check for Data Stall Recovery
3361
3362        """
3363        return self._test_data_stall_detection_recovery(nw_type="cellular",
3364                                                validation_type="recovery")
3365
3366    @test_tracker_info(uuid="d705d653-c810-42eb-bd07-3313f99be2fa")
3367    @TelephonyBaseTest.tel_test_wrap
3368    def test_browsing_4g(self):
3369        ad = self.android_devices[0]
3370        self.log.info("Connect to LTE and verify internet connection.")
3371        if not phone_setup_4g(self.log, ad):
3372            return False
3373        if not verify_internet_connection(self.log, ad):
3374            return False
3375
3376        return browsing_test(self.log, self.android_devices[0])
3377
3378    @test_tracker_info(uuid="71088cb1-5ccb-4d3a-8e6a-03fac9bf31cc")
3379    @TelephonyBaseTest.tel_test_wrap
3380    def test_browsing_wifi(self):
3381        ad = self.android_devices[0]
3382        self.log.info("Connect to Wi-Fi and verify internet connection.")
3383        if not ensure_wifi_connected(self.log, ad, self.wifi_network_ssid,
3384                                     self.wifi_network_pass):
3385            return False
3386        if not wait_for_wifi_data_connection(self.log, ad, True):
3387            return False
3388        if not verify_internet_connection(self.log, ad):
3389            return False
3390
3391        return browsing_test(self.log, self.android_devices[0], wifi_ssid=self.wifi_network_ssid)
3392
3393    """ Tests End """
3394