• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 time
21from acts.base_test import BaseTestClass
22from queue import Empty
23from acts.test_utils.tel.tel_subscription_utils import \
24    get_subid_from_slot_index
25from acts.test_utils.tel.tel_subscription_utils import set_subid_for_data
26from acts.test_utils.tel.TelephonyBaseTest import TelephonyBaseTest
27from acts.test_utils.tel.tel_defines import DIRECTION_MOBILE_ORIGINATED
28from acts.test_utils.tel.tel_defines import DIRECTION_MOBILE_TERMINATED
29from acts.test_utils.tel.tel_defines import DATA_STATE_CONNECTED
30from acts.test_utils.tel.tel_defines import GEN_2G
31from acts.test_utils.tel.tel_defines import GEN_3G
32from acts.test_utils.tel.tel_defines import GEN_4G
33from acts.test_utils.tel.tel_defines import NETWORK_SERVICE_DATA
34from acts.test_utils.tel.tel_defines import NETWORK_SERVICE_VOICE
35from acts.test_utils.tel.tel_defines import RAT_2G
36from acts.test_utils.tel.tel_defines import RAT_3G
37from acts.test_utils.tel.tel_defines import RAT_4G
38from acts.test_utils.tel.tel_defines import RAT_FAMILY_LTE
39from acts.test_utils.tel.tel_defines import SIM1_SLOT_INDEX
40from acts.test_utils.tel.tel_defines import SIM2_SLOT_INDEX
41from acts.test_utils.tel.tel_defines import MAX_WAIT_TIME_NW_SELECTION
42from acts.test_utils.tel.tel_defines import MAX_WAIT_TIME_TETHERING_ENTITLEMENT_CHECK
43from acts.test_utils.tel.tel_defines import MAX_WAIT_TIME_WIFI_CONNECTION
44from acts.test_utils.tel.tel_defines import TETHERING_MODE_WIFI
45from acts.test_utils.tel.tel_defines import WAIT_TIME_AFTER_REBOOT
46from acts.test_utils.tel.tel_defines import WAIT_TIME_ANDROID_STATE_SETTLING
47from acts.test_utils.tel.tel_defines import WAIT_TIME_BETWEEN_REG_AND_CALL
48from acts.test_utils.tel.tel_defines import \
49    WAIT_TIME_DATA_STATUS_CHANGE_DURING_WIFI_TETHERING
50from acts.test_utils.tel.tel_defines import WAIT_TIME_TETHERING_AFTER_REBOOT
51from acts.test_utils.tel.tel_data_utils import airplane_mode_test
52from acts.test_utils.tel.tel_data_utils import change_data_sim_and_verify_data
53from acts.test_utils.tel.tel_data_utils import data_connectivity_single_bearer
54from acts.test_utils.tel.tel_data_utils import ensure_wifi_connected
55from acts.test_utils.tel.tel_data_utils import tethering_check_internet_connection
56from acts.test_utils.tel.tel_data_utils import wifi_cell_switching
57from acts.test_utils.tel.tel_data_utils import wifi_tethering_cleanup
58from acts.test_utils.tel.tel_data_utils import wifi_tethering_setup_teardown
59from acts.test_utils.tel.tel_test_utils import WifiUtils
60from acts.test_utils.tel.tel_test_utils import call_setup_teardown
61from acts.test_utils.tel.tel_test_utils import ensure_phones_default_state
62from acts.test_utils.tel.tel_test_utils import ensure_phones_idle
63from acts.test_utils.tel.tel_test_utils import ensure_network_generation
64from acts.test_utils.tel.tel_test_utils import \
65    ensure_network_generation_for_subscription
66from acts.test_utils.tel.tel_test_utils import get_slot_index_from_subid
67from acts.test_utils.tel.tel_test_utils import get_network_rat_for_subscription
68from acts.test_utils.tel.tel_test_utils import hangup_call
69from acts.test_utils.tel.tel_test_utils import multithread_func
70from acts.test_utils.tel.tel_test_utils import set_call_state_listen_level
71from acts.test_utils.tel.tel_test_utils import setup_sim
72from acts.test_utils.tel.tel_test_utils import toggle_airplane_mode
73from acts.test_utils.tel.tel_test_utils import toggle_volte
74from acts.test_utils.tel.tel_test_utils import verify_http_connection
75from acts.test_utils.tel.tel_test_utils import verify_incall_state
76from acts.test_utils.tel.tel_test_utils import wait_for_cell_data_connection
77from acts.test_utils.tel.tel_test_utils import wait_for_network_rat
78from acts.test_utils.tel.tel_test_utils import \
79    wait_for_voice_attach_for_subscription
80from acts.test_utils.tel.tel_test_utils import \
81    wait_for_data_attach_for_subscription
82from acts.test_utils.tel.tel_test_utils import wait_for_wifi_data_connection
83from acts.test_utils.tel.tel_voice_utils import is_phone_in_call_3g
84from acts.test_utils.tel.tel_voice_utils import is_phone_in_call_csfb
85from acts.test_utils.tel.tel_voice_utils import is_phone_in_call_volte
86from acts.test_utils.tel.tel_voice_utils import phone_setup_voice_3g
87from acts.test_utils.tel.tel_voice_utils import phone_setup_csfb
88from acts.test_utils.tel.tel_voice_utils import phone_setup_voice_general
89from acts.test_utils.tel.tel_voice_utils import phone_setup_volte
90from acts.test_utils.wifi.wifi_test_utils import WifiEnums
91from acts.utils import disable_doze
92from acts.utils import enable_doze
93from acts.utils import rand_ascii_str
94
95
96class TelLiveDataTest(TelephonyBaseTest):
97    def __init__(self, controllers):
98        TelephonyBaseTest.__init__(self, controllers)
99
100        self.stress_test_number = self.get_stress_test_number()
101        self.wifi_network_ssid = self.user_params.get(
102            "wifi_network_ssid") or self.user_params.get(
103                "wifi_network_ssid_2g")
104        self.wifi_network_pass = self.user_params.get(
105            "wifi_network_pass") or self.user_params.get(
106                "wifi_network_pass_2g")
107
108    @TelephonyBaseTest.tel_test_wrap
109    def test_airplane_mode(self):
110        """ Test airplane mode basic on Phone and Live SIM.
111
112        Ensure phone attach, data on, WiFi off and verify Internet.
113        Turn on airplane mode to make sure detach.
114        Turn off airplane mode to make sure attach.
115        Verify Internet connection.
116
117        Returns:
118            True if pass; False if fail.
119        """
120        return airplane_mode_test(self.log, self.android_devices[0])
121
122    @TelephonyBaseTest.tel_test_wrap
123    def test_lte_wifi_switching(self):
124        """Test data connection network switching when phone camped on LTE.
125
126        Ensure phone is camped on LTE
127        Ensure WiFi can connect to live network,
128        Airplane mode is off, data connection is on, WiFi is on.
129        Turn off WiFi, verify data is on cell and browse to google.com is OK.
130        Turn on WiFi, verify data is on WiFi and browse to google.com is OK.
131        Turn off WiFi, verify data is on cell and browse to google.com is OK.
132
133        Returns:
134            True if pass.
135        """
136        return wifi_cell_switching(self.log, self.android_devices[0],
137                                   self.wifi_network_ssid,
138                                   self.wifi_network_pass, GEN_4G)
139
140    @TelephonyBaseTest.tel_test_wrap
141    def test_wcdma_wifi_switching(self):
142        """Test data connection network switching when phone camped on WCDMA.
143
144        Ensure phone is camped on WCDMA
145        Ensure WiFi can connect to live network,
146        Airplane mode is off, data connection is on, WiFi is on.
147        Turn off WiFi, verify data is on cell and browse to google.com is OK.
148        Turn on WiFi, verify data is on WiFi and browse to google.com is OK.
149        Turn off WiFi, verify data is on cell and browse to google.com is OK.
150
151        Returns:
152            True if pass.
153        """
154        return wifi_cell_switching(self.log, self.android_devices[0],
155                                   self.wifi_network_ssid,
156                                   self.wifi_network_pass, GEN_3G)
157
158    @TelephonyBaseTest.tel_test_wrap
159    def test_gsm_wifi_switching(self):
160        """Test data connection network switching when phone camped on GSM.
161
162        Ensure phone is camped on GSM
163        Ensure WiFi can connect to live network,,
164        Airplane mode is off, data connection is on, WiFi is on.
165        Turn off WiFi, verify data is on cell and browse to google.com is OK.
166        Turn on WiFi, verify data is on WiFi and browse to google.com is OK.
167        Turn off WiFi, verify data is on cell and browse to google.com is OK.
168
169        Returns:
170            True if pass.
171        """
172        return wifi_cell_switching(self.log, self.android_devices[0],
173                                   self.wifi_network_ssid,
174                                   self.wifi_network_pass, GEN_2G)
175
176    @TelephonyBaseTest.tel_test_wrap
177    def test_lte_multi_bearer(self):
178        """Test LTE data connection before call and in call. (VoLTE call)
179
180
181        Turn off airplane mode, disable WiFi, enable Cellular Data.
182        Make sure phone in LTE, verify Internet.
183        Initiate a voice call. verify Internet.
184        Disable Cellular Data, verify Internet is inaccessible.
185        Enable Cellular Data, verify Internet.
186        Hangup Voice Call, verify Internet.
187
188        Returns:
189            True if success.
190            False if failed.
191        """
192        if not phone_setup_volte(self.log, self.android_devices[0]):
193            self.log.error("Failed to setup VoLTE")
194            return False
195        return self._test_data_connectivity_multi_bearer(GEN_4G)
196
197    @TelephonyBaseTest.tel_test_wrap
198    def test_wcdma_multi_bearer(self):
199        """Test WCDMA data connection before call and in call.
200
201        Turn off airplane mode, disable WiFi, enable Cellular Data.
202        Make sure phone in WCDMA, verify Internet.
203        Initiate a voice call. verify Internet.
204        Disable Cellular Data, verify Internet is inaccessible.
205        Enable Cellular Data, verify Internet.
206        Hangup Voice Call, verify Internet.
207
208        Returns:
209            True if success.
210            False if failed.
211        """
212
213        return self._test_data_connectivity_multi_bearer(GEN_3G)
214
215    @TelephonyBaseTest.tel_test_wrap
216    def test_gsm_multi_bearer_mo(self):
217        """Test gsm data connection before call and in call.
218
219        Turn off airplane mode, disable WiFi, enable Cellular Data.
220        Make sure phone in GSM, verify Internet.
221        Initiate a MO voice call. Verify there is no Internet during call.
222        Hangup Voice Call, verify Internet.
223
224        Returns:
225            True if success.
226            False if failed.
227        """
228
229        return self._test_data_connectivity_multi_bearer(GEN_2G,
230            False, DIRECTION_MOBILE_ORIGINATED)
231
232    @TelephonyBaseTest.tel_test_wrap
233    def test_gsm_multi_bearer_mt(self):
234        """Test gsm data connection before call and in call.
235
236        Turn off airplane mode, disable WiFi, enable Cellular Data.
237        Make sure phone in GSM, verify Internet.
238        Initiate a MT voice call. Verify there is no Internet during call.
239        Hangup Voice Call, verify Internet.
240
241        Returns:
242            True if success.
243            False if failed.
244        """
245
246        return self._test_data_connectivity_multi_bearer(GEN_2G,
247            False, DIRECTION_MOBILE_TERMINATED)
248
249    @TelephonyBaseTest.tel_test_wrap
250    def test_wcdma_multi_bearer_stress(self):
251        """Stress Test WCDMA data connection before call and in call.
252
253        This is a stress test for "test_wcdma_multi_bearer".
254        Default MINIMUM_SUCCESS_RATE is set to 95%.
255
256        Returns:
257            True stress pass rate is higher than MINIMUM_SUCCESS_RATE.
258            False otherwise.
259        """
260        ads = self.android_devices
261        MINIMUM_SUCCESS_RATE = .95
262        success_count = 0
263        fail_count = 0
264
265        for i in range(1, self.stress_test_number + 1):
266
267            ensure_phones_default_state(
268                self.log, [self.android_devices[0], self.android_devices[1]])
269
270            if self.test_wcdma_multi_bearer():
271                success_count += 1
272                result_str = "Succeeded"
273            else:
274                fail_count += 1
275                result_str = "Failed"
276            self.log.info("Iteration {} {}. Current: {} / {} passed.".format(
277                i, result_str, success_count, self.stress_test_number))
278
279        self.log.info("Final Count - Success: {}, Failure: {} - {}%".format(
280            success_count, fail_count, str(100 * success_count / (
281                success_count + fail_count))))
282        if success_count / (
283                success_count + fail_count) >= MINIMUM_SUCCESS_RATE:
284            return True
285        else:
286            return False
287
288    @TelephonyBaseTest.tel_test_wrap
289    def test_lte_multi_bearer_stress(self):
290        """Stress Test LTE data connection before call and in call. (VoLTE call)
291
292        This is a stress test for "test_lte_multi_bearer".
293        Default MINIMUM_SUCCESS_RATE is set to 95%.
294
295        Returns:
296            True stress pass rate is higher than MINIMUM_SUCCESS_RATE.
297            False otherwise.
298        """
299        ads = self.android_devices
300        MINIMUM_SUCCESS_RATE = .95
301        success_count = 0
302        fail_count = 0
303
304        for i in range(1, self.stress_test_number + 1):
305
306            ensure_phones_default_state(
307                self.log, [self.android_devices[0], self.android_devices[1]])
308
309            if self.test_lte_multi_bearer():
310                success_count += 1
311                result_str = "Succeeded"
312            else:
313                fail_count += 1
314                result_str = "Failed"
315            self.log.info("Iteration {} {}. Current: {} / {} passed.".format(
316                i, result_str, success_count, self.stress_test_number))
317
318        self.log.info("Final Count - Success: {}, Failure: {} - {}%".format(
319            success_count, fail_count, str(100 * success_count / (
320                success_count + fail_count))))
321        if success_count / (
322                success_count + fail_count) >= MINIMUM_SUCCESS_RATE:
323            return True
324        else:
325            return False
326
327    def _test_data_connectivity_multi_bearer(self, nw_gen,
328        simultaneous_voice_data=True,
329        call_direction=DIRECTION_MOBILE_ORIGINATED):
330        """Test data connection before call and in call.
331
332        Turn off airplane mode, disable WiFi, enable Cellular Data.
333        Make sure phone in <nw_gen>, verify Internet.
334        Initiate a voice call.
335        if simultaneous_voice_data is True, then:
336            Verify Internet.
337            Disable Cellular Data, verify Internet is inaccessible.
338            Enable Cellular Data, verify Internet.
339        if simultaneous_voice_data is False, then:
340            Verify Internet is not available during voice call.
341        Hangup Voice Call, verify Internet.
342
343        Returns:
344            True if success.
345            False if failed.
346        """
347
348        class _LocalException(Exception):
349            pass
350
351        ad_list = [self.android_devices[0], self.android_devices[1]]
352        ensure_phones_idle(self.log, ad_list)
353
354        if not ensure_network_generation_for_subscription(self.log,
355            self.android_devices[0],
356            self.android_devices[0].droid.subscriptionGetDefaultDataSubId(),
357            nw_gen, MAX_WAIT_TIME_NW_SELECTION,
358            NETWORK_SERVICE_DATA):
359            self.log.error("Device failed to reselect in {}s.".format(
360                MAX_WAIT_TIME_NW_SELECTION))
361            return False
362
363        if not wait_for_voice_attach_for_subscription(
364                self.log, self.android_devices[0], self.android_devices[
365                    0].droid.subscriptionGetDefaultVoiceSubId(),
366                MAX_WAIT_TIME_NW_SELECTION):
367            return False
368
369        self.log.info("Step1 WiFi is Off, Data is on Cell.")
370        toggle_airplane_mode(self.log, self.android_devices[0], False)
371        WifiUtils.wifi_toggle_state(self.log, self.android_devices[0], False)
372        self.android_devices[0].droid.telephonyToggleDataConnection(True)
373        if (not wait_for_cell_data_connection(self.log,
374                                              self.android_devices[0], True) or
375                not verify_http_connection(self.log, self.android_devices[0])):
376            self.log.error("Data not available on cell")
377            return False
378
379        try:
380            self.log.info("Step2 Initiate call and accept.")
381            if call_direction == DIRECTION_MOBILE_ORIGINATED:
382                ad_caller = self.android_devices[0]
383                ad_callee = self.android_devices[1]
384            else:
385                ad_caller = self.android_devices[1]
386                ad_callee = self.android_devices[0]
387            if not call_setup_teardown(self.log, ad_caller, ad_callee, None,
388                                       None, None):
389                self.log.error("Failed to Establish {} Voice Call".format(
390                    call_direction))
391                return False
392            if simultaneous_voice_data:
393                self.log.info("Step3 Verify internet.")
394                time.sleep(WAIT_TIME_ANDROID_STATE_SETTLING)
395                if not verify_http_connection(self.log, self.android_devices[0]):
396                    raise _LocalException("Internet Inaccessible when Enabled")
397
398                self.log.info("Step4 Turn off data and verify not connected.")
399                self.android_devices[0].droid.telephonyToggleDataConnection(False)
400                if not wait_for_cell_data_connection(
401                        self.log, self.android_devices[0], False):
402                    raise _LocalException("Failed to Disable Cellular Data")
403
404                if verify_http_connection(self.log, self.android_devices[0]):
405                    raise _LocalException("Internet Accessible when Disabled")
406
407                self.log.info("Step5 Re-enable data.")
408                self.android_devices[0].droid.telephonyToggleDataConnection(True)
409                if not wait_for_cell_data_connection(
410                        self.log, self.android_devices[0], True):
411                    raise _LocalException("Failed to Re-Enable Cellular Data")
412                if not verify_http_connection(self.log, self.android_devices[0]):
413                    raise _LocalException("Internet Inaccessible when Enabled")
414            else:
415                self.log.info("Step3 Verify no Internet and skip step 4-5.")
416                if verify_http_connection(self.log, self.android_devices[0],
417                    retry=0):
418                    raise _LocalException("Internet Accessible.")
419
420            self.log.info("Step6 Verify phones still in call and Hang up.")
421            if not verify_incall_state(
422                    self.log,
423                [self.android_devices[0], self.android_devices[1]], True):
424                return False
425            if not hangup_call(self.log, self.android_devices[0]):
426                self.log.error("Failed to hang up call")
427                return False
428            if not verify_http_connection(self.log, self.android_devices[0]):
429                raise _LocalException("Internet Inaccessible when Enabled")
430
431        except _LocalException as e:
432            self.log.error(str(e))
433            try:
434                hangup_call(self.log, self.android_devices[0])
435                self.android_devices[0].droid.telephonyToggleDataConnection(
436                    True)
437            except Exception:
438                pass
439            return False
440
441        return True
442
443    @TelephonyBaseTest.tel_test_wrap
444    def test_2g(self):
445        """Test data connection in 2G.
446
447        Turn off airplane mode, disable WiFi, enable Cellular Data.
448        Ensure phone data generation is 2G.
449        Verify Internet.
450        Disable Cellular Data, verify Internet is inaccessible.
451        Enable Cellular Data, verify Internet.
452
453        Returns:
454            True if success.
455            False if failed.
456        """
457        WifiUtils.wifi_reset(self.log, self.android_devices[0])
458        WifiUtils.wifi_toggle_state(self.log, self.android_devices[0], False)
459        return data_connectivity_single_bearer(self.log,
460                                               self.android_devices[0], RAT_2G)
461
462    @TelephonyBaseTest.tel_test_wrap
463    def test_2g_wifi_not_associated(self):
464        """Test data connection in 2G.
465
466        Turn off airplane mode, enable WiFi (but not connected), enable Cellular Data.
467        Ensure phone data generation is 2G.
468        Verify Internet.
469        Disable Cellular Data, verify Internet is inaccessible.
470        Enable Cellular Data, verify Internet.
471
472        Returns:
473            True if success.
474            False if failed.
475        """
476        WifiUtils.wifi_reset(self.log, self.android_devices[0])
477        WifiUtils.wifi_toggle_state(self.log, self.android_devices[0], False)
478        WifiUtils.wifi_toggle_state(self.log, self.android_devices[0], True)
479        return data_connectivity_single_bearer(self.log,
480                                               self.android_devices[0], RAT_2G)
481
482    @TelephonyBaseTest.tel_test_wrap
483    def test_3g(self):
484        """Test data connection in 3G.
485
486        Turn off airplane mode, disable WiFi, enable Cellular Data.
487        Ensure phone data generation is 3G.
488        Verify Internet.
489        Disable Cellular Data, verify Internet is inaccessible.
490        Enable Cellular Data, verify Internet.
491
492        Returns:
493            True if success.
494            False if failed.
495        """
496        WifiUtils.wifi_reset(self.log, self.android_devices[0])
497        WifiUtils.wifi_toggle_state(self.log, self.android_devices[0], False)
498        return data_connectivity_single_bearer(self.log,
499                                               self.android_devices[0], RAT_3G)
500
501    @TelephonyBaseTest.tel_test_wrap
502    def test_3g_wifi_not_associated(self):
503        """Test data connection in 3G.
504
505        Turn off airplane mode, enable WiFi (but not connected), enable Cellular Data.
506        Ensure phone data generation is 3G.
507        Verify Internet.
508        Disable Cellular Data, verify Internet is inaccessible.
509        Enable Cellular Data, verify Internet.
510
511        Returns:
512            True if success.
513            False if failed.
514        """
515        WifiUtils.wifi_reset(self.log, self.android_devices[0])
516        WifiUtils.wifi_toggle_state(self.log, self.android_devices[0], False)
517        WifiUtils.wifi_toggle_state(self.log, self.android_devices[0], True)
518        return data_connectivity_single_bearer(self.log,
519                                               self.android_devices[0], RAT_3G)
520
521    @TelephonyBaseTest.tel_test_wrap
522    def test_4g(self):
523        """Test data connection in 4g.
524
525        Turn off airplane mode, disable WiFi, enable Cellular Data.
526        Ensure phone data generation is 4g.
527        Verify Internet.
528        Disable Cellular Data, verify Internet is inaccessible.
529        Enable Cellular Data, verify Internet.
530
531        Returns:
532            True if success.
533            False if failed.
534        """
535        WifiUtils.wifi_reset(self.log, self.android_devices[0])
536        WifiUtils.wifi_toggle_state(self.log, self.android_devices[0], False)
537        return data_connectivity_single_bearer(self.log,
538                                               self.android_devices[0], RAT_4G)
539
540    @TelephonyBaseTest.tel_test_wrap
541    def test_4g_wifi_not_associated(self):
542        """Test data connection in 4g.
543
544        Turn off airplane mode, enable WiFi (but not connected), enable Cellular Data.
545        Ensure phone data generation is 4g.
546        Verify Internet.
547        Disable Cellular Data, verify Internet is inaccessible.
548        Enable Cellular Data, verify Internet.
549
550        Returns:
551            True if success.
552            False if failed.
553        """
554        WifiUtils.wifi_reset(self.log, self.android_devices[0])
555        WifiUtils.wifi_toggle_state(self.log, self.android_devices[0], False)
556        WifiUtils.wifi_toggle_state(self.log, self.android_devices[0], True)
557        return data_connectivity_single_bearer(self.log,
558                                               self.android_devices[0], RAT_4G)
559
560    @TelephonyBaseTest.tel_test_wrap
561    def test_3g_stress(self):
562        """Stress Test data connection in 3G.
563
564        This is a stress test for "test_3g".
565        Default MINIMUM_SUCCESS_RATE is set to 95%.
566
567        Returns:
568            True stress pass rate is higher than MINIMUM_SUCCESS_RATE.
569            False otherwise.
570        """
571        ads = self.android_devices
572        MINIMUM_SUCCESS_RATE = .95
573        success_count = 0
574        fail_count = 0
575
576        for i in range(1, self.stress_test_number + 1):
577
578            ensure_phones_default_state(
579                self.log, [self.android_devices[0], self.android_devices[1]])
580            WifiUtils.wifi_reset(self.log, self.android_devices[0])
581            WifiUtils.wifi_toggle_state(self.log, self.android_devices[0],
582                                        False)
583
584            if data_connectivity_single_bearer(
585                    self.log, self.android_devices[0], RAT_3G):
586                success_count += 1
587                result_str = "Succeeded"
588            else:
589                fail_count += 1
590                result_str = "Failed"
591            self.log.info("Iteration {} {}. Current: {} / {} passed.".format(
592                i, result_str, success_count, self.stress_test_number))
593
594        self.log.info("Final Count - Success: {}, Failure: {} - {}%".format(
595            success_count, fail_count, str(100 * success_count / (
596                success_count + fail_count))))
597        if success_count / (
598                success_count + fail_count) >= MINIMUM_SUCCESS_RATE:
599            return True
600        else:
601            return False
602
603    @TelephonyBaseTest.tel_test_wrap
604    def test_4g_stress(self):
605        """Stress Test data connection in 4g.
606
607        This is a stress test for "test_4g".
608        Default MINIMUM_SUCCESS_RATE is set to 95%.
609
610        Returns:
611            True stress pass rate is higher than MINIMUM_SUCCESS_RATE.
612            False otherwise.
613        """
614        ads = self.android_devices
615        MINIMUM_SUCCESS_RATE = .95
616        success_count = 0
617        fail_count = 0
618
619        for i in range(1, self.stress_test_number + 1):
620
621            ensure_phones_default_state(
622                self.log, [self.android_devices[0], self.android_devices[1]])
623            WifiUtils.wifi_reset(self.log, self.android_devices[0])
624            WifiUtils.wifi_toggle_state(self.log, self.android_devices[0],
625                                        False)
626
627            if data_connectivity_single_bearer(
628                    self.log, self.android_devices[0], RAT_4G):
629                success_count += 1
630                result_str = "Succeeded"
631            else:
632                fail_count += 1
633                result_str = "Failed"
634            self.log.info("Iteration {} {}. Current: {} / {} passed.".format(
635                i, result_str, success_count, self.stress_test_number))
636
637        self.log.info("Final Count - Success: {}, Failure: {} - {}%".format(
638            success_count, fail_count, str(100 * success_count / (
639                success_count + fail_count))))
640        if success_count / (
641                success_count + fail_count) >= MINIMUM_SUCCESS_RATE:
642            return True
643        else:
644            return False
645
646    def _test_setup_tethering(self, ads, network_generation=None):
647        """Pre setup steps for WiFi tethering test.
648
649        Ensure all ads are idle.
650        Ensure tethering provider:
651            turn off APM, turn off WiFI, turn on Data.
652            have Internet connection, no active ongoing WiFi tethering.
653
654        Returns:
655            True if success.
656            False if failed.
657        """
658        ensure_phones_idle(self.log, ads)
659
660        if network_generation is not None:
661            if not ensure_network_generation_for_subscription(self.log,
662                self.android_devices[0],
663                self.android_devices[0].droid.subscriptionGetDefaultDataSubId(),
664                network_generation, MAX_WAIT_TIME_NW_SELECTION,
665                NETWORK_SERVICE_DATA):
666                self.log.error("Device failed to reselect in {}s.".format(
667                    MAX_WAIT_TIME_NW_SELECTION))
668                return False
669
670        self.log.info("Airplane Off, Wifi Off, Data On.")
671        toggle_airplane_mode(self.log, self.android_devices[0], False)
672        WifiUtils.wifi_toggle_state(self.log, self.android_devices[0], False)
673        self.android_devices[0].droid.telephonyToggleDataConnection(True)
674        if not wait_for_cell_data_connection(self.log, self.android_devices[0],
675                                             True):
676            self.log.error("Failed to enable data connection.")
677            return False
678
679        self.log.info("Verify internet")
680        if not verify_http_connection(self.log, self.android_devices[0]):
681            self.log.error("Data not available on cell.")
682            return False
683
684        # Turn off active SoftAP if any.
685        if ads[0].droid.wifiIsApEnabled():
686            WifiUtils.stop_wifi_tethering(self.log, ads[0])
687
688        return True
689
690    @TelephonyBaseTest.tel_test_wrap
691    def test_tethering_4g_to_2gwifi(self):
692        """WiFi Tethering test: LTE to WiFI 2.4G Tethering
693
694        1. DUT in LTE mode, idle.
695        2. DUT start 2.4G WiFi Tethering
696        3. PhoneB disable data, connect to DUT's softAP
697        4. Verify Internet access on DUT and PhoneB
698
699        Returns:
700            True if success.
701            False if failed.
702        """
703        ads = self.android_devices
704        if not self._test_setup_tethering(ads, RAT_4G):
705            self.log.error("Verify 4G Internet access failed.")
706            return False
707
708        return wifi_tethering_setup_teardown(
709            self.log,
710            ads[0],
711            [ads[1]],
712            ap_band=WifiUtils.WIFI_CONFIG_APBAND_2G,
713            check_interval=10,
714            check_iteration=10)
715
716    @TelephonyBaseTest.tel_test_wrap
717    def test_tethering_4g_to_5gwifi(self):
718        """WiFi Tethering test: LTE to WiFI 5G Tethering
719
720        1. DUT in LTE mode, idle.
721        2. DUT start 5G WiFi Tethering
722        3. PhoneB disable data, connect to DUT's softAP
723        4. Verify Internet access on DUT and PhoneB
724
725        Returns:
726            True if success.
727            False if failed.
728        """
729        ads = self.android_devices
730        if not self._test_setup_tethering(ads, RAT_4G):
731            self.log.error("Verify 4G Internet access failed.")
732            return False
733
734        return wifi_tethering_setup_teardown(
735            self.log,
736            ads[0],
737            [ads[1]],
738            ap_band=WifiUtils.WIFI_CONFIG_APBAND_5G,
739            check_interval=10,
740            check_iteration=10)
741
742    @TelephonyBaseTest.tel_test_wrap
743    def test_tethering_3g_to_2gwifi(self):
744        """WiFi Tethering test: 3G to WiFI 2.4G Tethering
745
746        1. DUT in 3G mode, idle.
747        2. DUT start 2.4G WiFi Tethering
748        3. PhoneB disable data, connect to DUT's softAP
749        4. Verify Internet access on DUT and PhoneB
750
751        Returns:
752            True if success.
753            False if failed.
754        """
755        ads = self.android_devices
756        if not self._test_setup_tethering(ads, RAT_3G):
757            self.log.error("Verify 3G Internet access failed.")
758            return False
759
760        return wifi_tethering_setup_teardown(
761            self.log,
762            ads[0],
763            [ads[1]],
764            ap_band=WifiUtils.WIFI_CONFIG_APBAND_2G,
765            check_interval=10,
766            check_iteration=10)
767
768    @TelephonyBaseTest.tel_test_wrap
769    def test_tethering_3g_to_5gwifi(self):
770        """WiFi Tethering test: 3G to WiFI 5G Tethering
771
772        1. DUT in 3G mode, idle.
773        2. DUT start 5G WiFi Tethering
774        3. PhoneB disable data, connect to DUT's softAP
775        4. Verify Internet access on DUT and PhoneB
776
777        Returns:
778            True if success.
779            False if failed.
780        """
781        ads = self.android_devices
782        if not self._test_setup_tethering(ads, RAT_3G):
783            self.log.error("Verify 3G Internet access failed.")
784            return False
785
786        return wifi_tethering_setup_teardown(
787            self.log,
788            ads[0],
789            [ads[1]],
790            ap_band=WifiUtils.WIFI_CONFIG_APBAND_5G,
791            check_interval=10,
792            check_iteration=10)
793
794    @TelephonyBaseTest.tel_test_wrap
795    def test_tethering_4g_to_2gwifi_2clients(self):
796        """WiFi Tethering test: LTE to WiFI 2.4G Tethering, with multiple clients
797
798        1. DUT in 3G mode, idle.
799        2. DUT start 5G WiFi Tethering
800        3. PhoneB and PhoneC disable data, connect to DUT's softAP
801        4. Verify Internet access on DUT and PhoneB PhoneC
802
803        Returns:
804            True if success.
805            False if failed.
806        """
807        ads = self.android_devices
808        if not self._test_setup_tethering(ads, RAT_4G):
809            self.log.error("Verify 4G Internet access failed.")
810            return False
811
812        return wifi_tethering_setup_teardown(
813            self.log,
814            ads[0],
815            [ads[1], ads[2]],
816            ap_band=WifiUtils.WIFI_CONFIG_APBAND_2G,
817            check_interval=10,
818            check_iteration=10)
819
820    @TelephonyBaseTest.tel_test_wrap
821    def test_tethering_2g_to_2gwifi(self):
822        """WiFi Tethering test: 2G to WiFI 2.4G Tethering
823
824        1. DUT in 2G mode, idle.
825        2. DUT start 2.4G WiFi Tethering
826        3. PhoneB disable data, connect to DUT's softAP
827        4. Verify Internet access on DUT and PhoneB
828
829        Returns:
830            True if success.
831            False if failed.
832        """
833        ads = self.android_devices
834        if not self._test_setup_tethering(ads, RAT_2G):
835            self.log.error("Verify 2G Internet access failed.")
836            return False
837
838        return wifi_tethering_setup_teardown(
839            self.log,
840            ads[0],
841            [ads[1]],
842            ap_band=WifiUtils.WIFI_CONFIG_APBAND_2G,
843            check_interval=10,
844            check_iteration=10)
845
846    @TelephonyBaseTest.tel_test_wrap
847    def test_tethering_2g_to_5gwifi(self):
848        """WiFi Tethering test: 2G to WiFI 5G Tethering
849
850        1. DUT in 2G mode, idle.
851        2. DUT start 5G WiFi Tethering
852        3. PhoneB disable data, connect to DUT's softAP
853        4. Verify Internet access on DUT and PhoneB
854
855        Returns:
856            True if success.
857            False if failed.
858        """
859        ads = self.android_devices
860        if not self._test_setup_tethering(ads, RAT_2G):
861            self.log.error("Verify 2G Internet access failed.")
862            return False
863
864        return wifi_tethering_setup_teardown(
865            self.log,
866            ads[0],
867            [ads[1]],
868            ap_band=WifiUtils.WIFI_CONFIG_APBAND_5G,
869            check_interval=10,
870            check_iteration=10)
871
872    @TelephonyBaseTest.tel_test_wrap
873    def test_disable_wifi_tethering_resume_connected_wifi(self):
874        """WiFi Tethering test: WiFI connected to 2.4G network,
875        start (LTE) 2.4G WiFi tethering, then stop tethering
876
877        1. DUT in LTE mode, idle. WiFi connected to 2.4G Network
878        2. DUT start 2.4G WiFi Tethering
879        3. PhoneB disable data, connect to DUT's softAP
880        4. Verify Internet access on DUT and PhoneB
881        5. Disable WiFi Tethering on DUT.
882        6. Verify DUT automatically connect to previous WiFI network
883
884        Returns:
885            True if success.
886            False if failed.
887        """
888        ads = self.android_devices
889        if not self._test_setup_tethering(ads, RAT_4G):
890            self.log.error("Verify 4G Internet access failed.")
891            return False
892        self.log.info("Connect WiFi.")
893        if not ensure_wifi_connected(self.log, ads[0], self.wifi_network_ssid,
894                                     self.wifi_network_pass):
895            self.log.error("WiFi connect fail.")
896            return False
897        self.log.info("Start WiFi Tethering.")
898        if not wifi_tethering_setup_teardown(self.log,
899                                             ads[0],
900                                             [ads[1]],
901                                             check_interval=10,
902                                             check_iteration=2):
903            self.log.error("WiFi Tethering failed.")
904            return False
905
906        if (not wait_for_wifi_data_connection(self.log, ads[0], True) or
907                not verify_http_connection(self.log, ads[0])):
908            self.log.error("Provider data did not return to Wifi")
909            return False
910        return True
911
912    @TelephonyBaseTest.tel_test_wrap
913    def test_toggle_data_during_active_wifi_tethering(self):
914        """WiFi Tethering test: Toggle Data during active WiFi Tethering
915
916        1. DUT in LTE mode, idle.
917        2. DUT start 2.4G WiFi Tethering
918        3. PhoneB disable data, connect to DUT's softAP
919        4. Verify Internet access on DUT and PhoneB
920        5. Disable Data on DUT, verify PhoneB still connected to WiFi, but no Internet access.
921        6. Enable Data on DUT, verify PhoneB still connected to WiFi and have Internet access.
922
923        Returns:
924            True if success.
925            False if failed.
926        """
927        ads = self.android_devices
928        if not self._test_setup_tethering(ads, RAT_4G):
929            self.log.error("Verify 4G Internet access failed.")
930            return False
931        try:
932            ssid = rand_ascii_str(10)
933            if not wifi_tethering_setup_teardown(
934                    self.log,
935                    ads[0],
936                [ads[1]],
937                    ap_band=WifiUtils.WIFI_CONFIG_APBAND_2G,
938                    check_interval=10,
939                    check_iteration=2,
940                    do_cleanup=False,
941                    ssid=ssid):
942                self.log.error("WiFi Tethering failed.")
943                return False
944
945            if not ads[0].droid.wifiIsApEnabled():
946                self.log.error("Provider WiFi tethering stopped.")
947                return False
948
949            self.log.info(
950                "Disable Data on Provider, verify no data on Client.")
951            ads[0].droid.telephonyToggleDataConnection(False)
952            time.sleep(WAIT_TIME_DATA_STATUS_CHANGE_DURING_WIFI_TETHERING)
953            if verify_http_connection(self.log, ads[0]):
954                self.log.error("Disable data on provider failed.")
955                return False
956            if not ads[0].droid.wifiIsApEnabled():
957                self.log.error("Provider WiFi tethering stopped.")
958                return False
959            wifi_info = ads[1].droid.wifiGetConnectionInfo()
960
961            if wifi_info[WifiEnums.SSID_KEY] != ssid:
962                self.log.error("WiFi error. Info: {}".format(wifi_info))
963                return False
964            if verify_http_connection(self.log, ads[1]):
965                self.log.error("Client should not have Internet connection.")
966                return False
967
968            self.log.info(
969                "Enable Data on Provider, verify data available on Client.")
970            ads[0].droid.telephonyToggleDataConnection(True)
971            time.sleep(WAIT_TIME_DATA_STATUS_CHANGE_DURING_WIFI_TETHERING)
972            if not verify_http_connection(self.log, ads[0]):
973                self.log.error("Enable data on provider failed.")
974                return False
975            if not ads[0].droid.wifiIsApEnabled():
976                self.log.error("Provider WiFi tethering stopped.")
977                return False
978            wifi_info = ads[1].droid.wifiGetConnectionInfo()
979
980            if wifi_info[WifiEnums.SSID_KEY] != ssid:
981                self.log.error("WiFi error. Info: {}".format(wifi_info))
982                return False
983            if not verify_http_connection(self.log, ads[1]):
984                self.log.error("Client have no Internet connection!")
985                return False
986        finally:
987            if not wifi_tethering_cleanup(self.log, ads[0], [ads[1]]):
988                return False
989        return True
990
991    # Invalid Live Test. Can't rely on the result of this test with live network.
992    # Network may decide not to change the RAT when data conenction is active.
993    @TelephonyBaseTest.tel_test_wrap
994    def test_change_rat_during_active_wifi_tethering_lte_to_3g(self):
995        """WiFi Tethering test: Change Cellular Data RAT generation from LTE to 3G,
996            during active WiFi Tethering.
997
998        1. DUT in LTE mode, idle.
999        2. DUT start 2.4G WiFi Tethering
1000        3. PhoneB disable data, connect to DUT's softAP
1001        4. Verily Internet access on DUT and PhoneB
1002        5. Change DUT Cellular Data RAT generation from LTE to 3G.
1003        6. Verify both DUT and PhoneB have Internet access.
1004
1005        Returns:
1006            True if success.
1007            False if failed.
1008        """
1009        ads = self.android_devices
1010        if not self._test_setup_tethering(ads, RAT_4G):
1011            self.log.error("Verify 4G Internet access failed.")
1012            return False
1013        try:
1014            if not wifi_tethering_setup_teardown(
1015                    self.log,
1016                    ads[0],
1017                [ads[1]],
1018                    ap_band=WifiUtils.WIFI_CONFIG_APBAND_2G,
1019                    check_interval=10,
1020                    check_iteration=2,
1021                    do_cleanup=False):
1022                self.log.error("WiFi Tethering failed.")
1023                return False
1024
1025            if not ads[0].droid.wifiIsApEnabled():
1026                self.log.error("Provider WiFi tethering stopped.")
1027                return False
1028
1029            self.log.info("Provider change RAT from LTE to 3G.")
1030            if not ensure_network_generation(
1031                    self.log,
1032                    ads[0],
1033                    RAT_3G,
1034                    voice_or_data=NETWORK_SERVICE_DATA,
1035                    toggle_apm_after_setting=False):
1036                self.log.error("Provider failed to reselect to 3G.")
1037                return False
1038            time.sleep(WAIT_TIME_DATA_STATUS_CHANGE_DURING_WIFI_TETHERING)
1039            if not verify_http_connection(self.log, ads[0]):
1040                self.log.error("Data not available on Provider.")
1041                return False
1042            if not ads[0].droid.wifiIsApEnabled():
1043                self.log.error("Provider WiFi tethering stopped.")
1044                return False
1045            if not tethering_check_internet_connection(self.log, ads[0],
1046                                                       [ads[1]], 10, 5):
1047                return False
1048        finally:
1049            if not wifi_tethering_cleanup(self.log, ads[0], [ads[1]]):
1050                return False
1051        return True
1052
1053    # Invalid Live Test. Can't rely on the result of this test with live network.
1054    # Network may decide not to change the RAT when data conenction is active.
1055    @TelephonyBaseTest.tel_test_wrap
1056    def test_change_rat_during_active_wifi_tethering_3g_to_lte(self):
1057        """WiFi Tethering test: Change Cellular Data RAT generation from 3G to LTE,
1058            during active WiFi Tethering.
1059
1060        1. DUT in 3G mode, idle.
1061        2. DUT start 2.4G WiFi Tethering
1062        3. PhoneB disable data, connect to DUT's softAP
1063        4. Verily Internet access on DUT and PhoneB
1064        5. Change DUT Cellular Data RAT generation from 3G to LTE.
1065        6. Verify both DUT and PhoneB have Internet access.
1066
1067        Returns:
1068            True if success.
1069            False if failed.
1070        """
1071        ads = self.android_devices
1072        if not self._test_setup_tethering(ads, RAT_3G):
1073            self.log.error("Verify 3G Internet access failed.")
1074            return False
1075        try:
1076            if not wifi_tethering_setup_teardown(
1077                    self.log,
1078                    ads[0],
1079                [ads[1]],
1080                    ap_band=WifiUtils.WIFI_CONFIG_APBAND_2G,
1081                    check_interval=10,
1082                    check_iteration=2,
1083                    do_cleanup=False):
1084                self.log.error("WiFi Tethering failed.")
1085                return False
1086
1087            if not ads[0].droid.wifiIsApEnabled():
1088                self.log.error("Provider WiFi tethering stopped.")
1089                return False
1090
1091            self.log.info("Provider change RAT from 3G to 4G.")
1092            if not ensure_network_generation(
1093                    self.log,
1094                    ads[0],
1095                    RAT_4G,
1096                    voice_or_data=NETWORK_SERVICE_DATA,
1097                    toggle_apm_after_setting=False):
1098                self.log.error("Provider failed to reselect to 4G.")
1099                return False
1100            time.sleep(WAIT_TIME_DATA_STATUS_CHANGE_DURING_WIFI_TETHERING)
1101            if not verify_http_connection(self.log, ads[0]):
1102                self.log.error("Data not available on Provider.")
1103                return False
1104            if not ads[0].droid.wifiIsApEnabled():
1105                self.log.error("Provider WiFi tethering stopped.")
1106                return False
1107            if not tethering_check_internet_connection(self.log, ads[0],
1108                                                       [ads[1]], 10, 5):
1109                return False
1110        finally:
1111            if not wifi_tethering_cleanup(self.log, ads[0], [ads[1]]):
1112                return False
1113        return True
1114
1115    @TelephonyBaseTest.tel_test_wrap
1116    def test_toggle_apm_during_active_wifi_tethering(self):
1117        """WiFi Tethering test: Toggle APM during active WiFi Tethering
1118
1119        1. DUT in LTE mode, idle.
1120        2. DUT start 2.4G WiFi Tethering
1121        3. PhoneB disable data, connect to DUT's softAP
1122        4. Verify Internet access on DUT and PhoneB
1123        5. DUT toggle APM on, verify WiFi tethering stopped, PhoneB lost WiFi connection.
1124        6. DUT toggle APM off, verify PhoneA have cellular data and Internet connection.
1125
1126        Returns:
1127            True if success.
1128            False if failed.
1129        """
1130        ads = self.android_devices
1131        if not self._test_setup_tethering(ads, RAT_4G):
1132            self.log.error("Verify 4G Internet access failed.")
1133            return False
1134        try:
1135            ssid = rand_ascii_str(10)
1136            if not wifi_tethering_setup_teardown(
1137                    self.log,
1138                    ads[0],
1139                [ads[1]],
1140                    ap_band=WifiUtils.WIFI_CONFIG_APBAND_2G,
1141                    check_interval=10,
1142                    check_iteration=2,
1143                    do_cleanup=False,
1144                    ssid=ssid):
1145                self.log.error("WiFi Tethering failed.")
1146                return False
1147
1148            if not ads[0].droid.wifiIsApEnabled():
1149                self.log.error("Provider WiFi tethering stopped.")
1150                return False
1151
1152            self.log.info(
1153                "Provider turn on APM, verify no wifi/data on Client.")
1154            if not toggle_airplane_mode(self.log, ads[0], True):
1155                self.log.error("Provider turn on APM failed.")
1156                return False
1157            time.sleep(WAIT_TIME_DATA_STATUS_CHANGE_DURING_WIFI_TETHERING)
1158            if ads[0].droid.wifiIsApEnabled():
1159                self.log.error("Provider WiFi tethering not stopped.")
1160                return False
1161            if verify_http_connection(self.log, ads[1]):
1162                self.log.error("Client should not have Internet connection.")
1163                return False
1164            wifi_info = ads[1].droid.wifiGetConnectionInfo()
1165            self.log.info("WiFi Info: {}".format(wifi_info))
1166
1167            if wifi_info[WifiEnums.SSID_KEY] == ssid:
1168                self.log.error(
1169                    "WiFi error. WiFi should not be connected.".format(
1170                        wifi_info))
1171                return False
1172
1173            self.log.info("Provider turn off APM.")
1174            if not toggle_airplane_mode(self.log, ads[0], False):
1175                self.log.error("Provider turn on APM failed.")
1176                return False
1177            time.sleep(WAIT_TIME_DATA_STATUS_CHANGE_DURING_WIFI_TETHERING)
1178            if ads[0].droid.wifiIsApEnabled():
1179                self.log.error("Provider WiFi tethering should not on.")
1180                return False
1181            if not verify_http_connection(self.log, ads[0]):
1182                self.log.error("Provider should have Internet connection.")
1183                return False
1184        finally:
1185            ads[1].droid.telephonyToggleDataConnection(True)
1186            WifiUtils.wifi_reset(self.log, ads[1])
1187        return True
1188
1189    @TelephonyBaseTest.tel_test_wrap
1190    def test_tethering_entitlement_check(self):
1191        """Tethering Entitlement Check Test
1192
1193        Get tethering entitlement check result.
1194
1195        Returns:
1196            True if entitlement check returns True.
1197        """
1198        ad = self.android_devices[0]
1199
1200        if (not wait_for_cell_data_connection(self.log,
1201                                              self.android_devices[0], True) or
1202                not verify_http_connection(self.log, self.android_devices[0])):
1203            self.log.error("Failed cell data call for entitlement check.")
1204            return False
1205
1206        result = ad.droid.carrierConfigIsTetheringModeAllowed(
1207            TETHERING_MODE_WIFI, MAX_WAIT_TIME_TETHERING_ENTITLEMENT_CHECK)
1208        self.log.info("{} tethering entitlement check result: {}.".format(
1209            ad.serial, result))
1210        return result
1211
1212    @TelephonyBaseTest.tel_test_wrap
1213    def test_tethering_4g_to_2gwifi_stress(self):
1214        """Stress Test LTE to WiFI 2.4G Tethering
1215
1216        This is a stress test for "test_tethering_4g_to_2gwifi".
1217        Default MINIMUM_SUCCESS_RATE is set to 95%.
1218
1219        Returns:
1220            True stress pass rate is higher than MINIMUM_SUCCESS_RATE.
1221            False otherwise.
1222        """
1223        MINIMUM_SUCCESS_RATE = .95
1224        success_count = 0
1225        fail_count = 0
1226
1227        for i in range(1, self.stress_test_number + 1):
1228
1229            ensure_phones_default_state(
1230                self.log, [self.android_devices[0], self.android_devices[1]])
1231
1232            if self.test_tethering_4g_to_2gwifi():
1233                success_count += 1
1234                result_str = "Succeeded"
1235            else:
1236                fail_count += 1
1237                result_str = "Failed"
1238            self.log.info("Iteration {} {}. Current: {} / {} passed.".format(
1239                i, result_str, success_count, self.stress_test_number))
1240
1241        self.log.info("Final Count - Success: {}, Failure: {} - {}%".format(
1242            success_count, fail_count, str(100 * success_count / (
1243                success_count + fail_count))))
1244        if success_count / (
1245                success_count + fail_count) >= MINIMUM_SUCCESS_RATE:
1246            return True
1247        else:
1248            return False
1249
1250    @TelephonyBaseTest.tel_test_wrap
1251    def test_tethering_wifi_ssid_quotes(self):
1252        """WiFi Tethering test: SSID name have quotes.
1253        1. Set SSID name have double quotes.
1254        2. Start LTE to WiFi (2.4G) tethering.
1255        3. Verify tethering.
1256
1257        Returns:
1258            True if success.
1259            False if failed.
1260        """
1261        ads = self.android_devices
1262        if not self._test_setup_tethering(ads):
1263            self.log.error("Verify Internet access failed.")
1264            return False
1265        ssid = "\"" + rand_ascii_str(10) + "\""
1266        self.log.info("Starting WiFi Tethering test with ssid: {}".format(
1267            ssid))
1268
1269        return wifi_tethering_setup_teardown(
1270            self.log,
1271            ads[0],
1272            [ads[1]],
1273            ap_band=WifiUtils.WIFI_CONFIG_APBAND_2G,
1274            check_interval=10,
1275            check_iteration=10,
1276            ssid=ssid)
1277
1278    @TelephonyBaseTest.tel_test_wrap
1279    def test_tethering_wifi_password_escaping_characters(self):
1280        """WiFi Tethering test: password have escaping characters.
1281        1. Set password have escaping characters.
1282            e.g.: '"DQ=/{Yqq;M=(^_3HzRvhOiL8S%`]w&l<Qp8qH)bs<4E9v_q=HLr^)}w$blA0Kg'
1283        2. Start LTE to WiFi (2.4G) tethering.
1284        3. Verify tethering.
1285
1286        Returns:
1287            True if success.
1288            False if failed.
1289        """
1290        ads = self.android_devices
1291        if not self._test_setup_tethering(ads):
1292            self.log.error("Verify Internet access failed.")
1293            return False
1294
1295        password = '"DQ=/{Yqq;M=(^_3HzRvhOiL8S%`]w&l<Qp8qH)bs<4E9v_q=HLr^)}w$blA0Kg'
1296        self.log.info("Starting WiFi Tethering test with password: {}".format(
1297            password))
1298
1299        return wifi_tethering_setup_teardown(
1300            self.log,
1301            ads[0],
1302            [ads[1]],
1303            ap_band=WifiUtils.WIFI_CONFIG_APBAND_2G,
1304            check_interval=10,
1305            check_iteration=10,
1306            password=password)
1307
1308    def _test_start_wifi_tethering_connect_teardown(self, ad_host, ad_client,
1309                                                    ssid, password):
1310        """Private test util for WiFi Tethering.
1311
1312        1. Host start WiFi tethering.
1313        2. Client connect to tethered WiFi.
1314        3. Host tear down WiFi tethering.
1315
1316        Args:
1317            ad_host: android device object for host
1318            ad_client: android device object for client
1319            ssid: WiFi tethering ssid
1320            password: WiFi tethering password
1321
1322        Returns:
1323            True if no error happen, otherwise False.
1324        """
1325        result = True
1326        # Turn off active SoftAP if any.
1327        if ad_host.droid.wifiIsApEnabled():
1328            WifiUtils.stop_wifi_tethering(self.log, ad_host)
1329
1330        time.sleep(WAIT_TIME_ANDROID_STATE_SETTLING)
1331        if not WifiUtils.start_wifi_tethering(self.log, ad_host, ssid,
1332                                              password,
1333                                              WifiUtils.WIFI_CONFIG_APBAND_2G):
1334            self.log.error("Start WiFi tethering failed.")
1335            result = False
1336        time.sleep(WAIT_TIME_ANDROID_STATE_SETTLING)
1337        if not ensure_wifi_connected(self.log, ad_client, ssid, password):
1338            self.log.error("Client connect to WiFi failed.")
1339            result = False
1340        if not WifiUtils.wifi_reset(self.log, ad_client):
1341            self.log.error("Reset client WiFi failed. {}".format(
1342                ad_client.serial))
1343            result = False
1344        if not WifiUtils.stop_wifi_tethering(self.log, ad_host):
1345            self.log.error("Stop WiFi tethering failed.")
1346            result = False
1347        return result
1348
1349    @TelephonyBaseTest.tel_test_wrap
1350    def test_tethering_wifi_ssid(self):
1351        """WiFi Tethering test: start WiFi tethering with all kinds of SSIDs.
1352
1353        For each listed SSID, start WiFi tethering on DUT, client connect WiFi,
1354        then tear down WiFi tethering.
1355
1356        Returns:
1357            True if WiFi tethering succeed on all SSIDs.
1358            False if failed.
1359        """
1360        ads = self.android_devices
1361        if not self._test_setup_tethering(ads, RAT_4G):
1362            self.log.error("Setup Failed.")
1363            return False
1364        ssid_list = [" !\"#$%&'()*+,-./0123456789:;<=>?",
1365                     "@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_",
1366                     "`abcdefghijklmnopqrstuvwxyz{|}~", " a ", "!b!", "#c#",
1367                     "$d$", "%e%", "&f&", "'g'", "(h(", ")i)", "*j*", "+k+",
1368                     "-l-", ".m.", "/n/", "_",
1369                     " !\"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}",
1370                     "\u0644\u062c\u0648\u062c", "\u8c37\u6b4c", "\uad6c\uae00"
1371                     "\u30b0\u30fc\u30eb",
1372                     "\u0417\u0434\u0440\u0430\u0432\u0441\u0442\u0443\u0439"]
1373        fail_list = {}
1374
1375        for ssid in ssid_list:
1376            password = rand_ascii_str(8)
1377            self.log.info("SSID: <{}>, Password: <{}>".format(ssid, password))
1378            if not self._test_start_wifi_tethering_connect_teardown(
1379                    ads[0], ads[1], ssid, password):
1380                fail_list[ssid] = password
1381
1382        if (len(fail_list) > 0):
1383            self.log.error("Failed cases: {}".format(fail_list))
1384            return False
1385        else:
1386            return True
1387
1388    @TelephonyBaseTest.tel_test_wrap
1389    def test_tethering_wifi_password(self):
1390        """WiFi Tethering test: start WiFi tethering with all kinds of passwords.
1391
1392        For each listed password, start WiFi tethering on DUT, client connect WiFi,
1393        then tear down WiFi tethering.
1394
1395        Returns:
1396            True if WiFi tethering succeed on all passwords.
1397            False if failed.
1398        """
1399        ads = self.android_devices
1400        if not self._test_setup_tethering(ads, RAT_4G):
1401            self.log.error("Setup Failed.")
1402            return False
1403        password_list = [
1404            " !\"#$%&'()*+,-./0123456789:;<=>?",
1405            "@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_",
1406            "`abcdefghijklmnopqrstuvwxyz{|}~",
1407            " !\"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}", "abcdefgh",
1408            "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!",
1409            " a12345 ", "!b12345!", "#c12345#", "$d12345$", "%e12345%",
1410            "&f12345&", "'g12345'", "(h12345(", ")i12345)", "*j12345*",
1411            "+k12345+", "-l12345-", ".m12345.", "/n12345/"
1412        ]
1413        fail_list = {}
1414
1415        for password in password_list:
1416            result = True
1417            ssid = rand_ascii_str(8)
1418            self.log.info("SSID: <{}>, Password: <{}>".format(ssid, password))
1419            if not self._test_start_wifi_tethering_connect_teardown(
1420                    ads[0], ads[1], ssid, password):
1421                fail_list[ssid] = password
1422
1423        if (len(fail_list) > 0):
1424            self.log.error("Failed cases: {}".format(fail_list))
1425            return False
1426        else:
1427            return True
1428
1429    def _test_tethering_wifi_and_voice_call(
1430            self, provider, client, provider_data_rat, provider_setup_func,
1431            provider_in_call_check_func):
1432        if not self._test_setup_tethering(
1433            [provider, client], provider_data_rat):
1434            self.log.error("Verify 4G Internet access failed.")
1435            return False
1436
1437        tasks = [(provider_setup_func, (self.log, provider)),
1438                 (phone_setup_voice_general, (self.log, client))]
1439        if not multithread_func(self.log, tasks):
1440            self.log.error("Phone Failed to Set Up VoLTE.")
1441            return False
1442
1443        try:
1444            self.log.info("1. Setup WiFi Tethering.")
1445            if not wifi_tethering_setup_teardown(
1446                    self.log,
1447                    provider,
1448                [client],
1449                    ap_band=WifiUtils.WIFI_CONFIG_APBAND_2G,
1450                    check_interval=10,
1451                    check_iteration=2,
1452                    do_cleanup=False):
1453                self.log.error("WiFi Tethering failed.")
1454                return False
1455            self.log.info("2. Make outgoing call.")
1456            if not call_setup_teardown(
1457                    self.log,
1458                    provider,
1459                    client,
1460                    ad_hangup=None,
1461                    verify_caller_func=provider_in_call_check_func):
1462                self.log.error("Setup Call Failed.")
1463                return False
1464            self.log.info("3. Verify data.")
1465            if not verify_http_connection(self.log, provider):
1466                self.log.error("Provider have no Internet access.")
1467            if not verify_http_connection(self.log, client):
1468                self.log.error("Client have no Internet access.")
1469            hangup_call(self.log, provider)
1470
1471            time.sleep(WAIT_TIME_BETWEEN_REG_AND_CALL)
1472
1473            self.log.info("4. Make incoming call.")
1474            if not call_setup_teardown(
1475                    self.log,
1476                    client,
1477                    provider,
1478                    ad_hangup=None,
1479                    verify_callee_func=provider_in_call_check_func):
1480                self.log.error("Setup Call Failed.")
1481                return False
1482            self.log.info("5. Verify data.")
1483            if not verify_http_connection(self.log, provider):
1484                self.log.error("Provider have no Internet access.")
1485            if not verify_http_connection(self.log, client):
1486                self.log.error("Client have no Internet access.")
1487            hangup_call(self.log, provider)
1488
1489        finally:
1490            if not wifi_tethering_cleanup(self.log, provider, [client]):
1491                return False
1492        return True
1493
1494    @TelephonyBaseTest.tel_test_wrap
1495    def test_tethering_wifi_volte_call(self):
1496        """WiFi Tethering test: VoLTE call during WiFi tethering
1497        1. Start LTE to WiFi (2.4G) tethering.
1498        2. Verify tethering.
1499        3. Make outgoing VoLTE call on tethering provider.
1500        4. Verify tethering still works.
1501        5. Make incoming VoLTE call on tethering provider.
1502        6. Verify tethering still works.
1503
1504        Returns:
1505            True if success.
1506            False if failed.
1507        """
1508        return self._test_tethering_wifi_and_voice_call(
1509            self.android_devices[0], self.android_devices[1], RAT_4G,
1510            phone_setup_volte, is_phone_in_call_volte)
1511
1512    @TelephonyBaseTest.tel_test_wrap
1513    def test_tethering_wifi_csfb_call(self):
1514        """WiFi Tethering test: CSFB call during WiFi tethering
1515        1. Start LTE to WiFi (2.4G) tethering.
1516        2. Verify tethering.
1517        3. Make outgoing CSFB call on tethering provider.
1518        4. Verify tethering still works.
1519        5. Make incoming CSFB call on tethering provider.
1520        6. Verify tethering still works.
1521
1522        Returns:
1523            True if success.
1524            False if failed.
1525        """
1526        return self._test_tethering_wifi_and_voice_call(
1527            self.android_devices[0], self.android_devices[1], RAT_4G,
1528            phone_setup_csfb, is_phone_in_call_csfb)
1529
1530    @TelephonyBaseTest.tel_test_wrap
1531    def test_tethering_wifi_3g_call(self):
1532        """WiFi Tethering test: 3G call during WiFi tethering
1533        1. Start 3G to WiFi (2.4G) tethering.
1534        2. Verify tethering.
1535        3. Make outgoing CS call on tethering provider.
1536        4. Verify tethering still works.
1537        5. Make incoming CS call on tethering provider.
1538        6. Verify tethering still works.
1539
1540        Returns:
1541            True if success.
1542            False if failed.
1543        """
1544        return self._test_tethering_wifi_and_voice_call(
1545            self.android_devices[0], self.android_devices[1], RAT_3G,
1546            phone_setup_voice_3g, is_phone_in_call_3g)
1547
1548    @TelephonyBaseTest.tel_test_wrap
1549    def test_tethering_wifi_no_password(self):
1550        """WiFi Tethering test: Start WiFi tethering with no password
1551
1552        1. DUT is idle.
1553        2. DUT start 2.4G WiFi Tethering, with no WiFi password.
1554        3. PhoneB disable data, connect to DUT's softAP
1555        4. Verify Internet access on DUT and PhoneB
1556
1557        Returns:
1558            True if success.
1559            False if failed.
1560        """
1561        ads = self.android_devices
1562        if not self._test_setup_tethering(ads):
1563            self.log.error("Verify Internet access failed.")
1564            return False
1565
1566        return wifi_tethering_setup_teardown(
1567            self.log,
1568            ads[0],
1569            [ads[1]],
1570            ap_band=WifiUtils.WIFI_CONFIG_APBAND_2G,
1571            check_interval=10,
1572            check_iteration=10,
1573            password="")
1574
1575    @TelephonyBaseTest.tel_test_wrap
1576    def test_tethering_wifi_reboot(self):
1577        """WiFi Tethering test: Start WiFi tethering then Reboot device
1578
1579        1. DUT is idle.
1580        2. DUT start 2.4G WiFi Tethering.
1581        3. PhoneB disable data, connect to DUT's softAP
1582        4. Verify Internet access on DUT and PhoneB
1583        5. Reboot DUT
1584        6. After DUT reboot, verify tethering is stopped.
1585
1586        Returns:
1587            True if success.
1588            False if failed.
1589        """
1590        ads = self.android_devices
1591        if not self._test_setup_tethering(ads):
1592            self.log.error("Verify Internet access failed.")
1593            return False
1594        try:
1595            if not wifi_tethering_setup_teardown(
1596                    self.log,
1597                    ads[0],
1598                [ads[1]],
1599                    ap_band=WifiUtils.WIFI_CONFIG_APBAND_2G,
1600                    check_interval=10,
1601                    check_iteration=2,
1602                    do_cleanup=False):
1603                self.log.error("WiFi Tethering failed.")
1604                return False
1605
1606            if not ads[0].droid.wifiIsApEnabled():
1607                self.log.error("Provider WiFi tethering stopped.")
1608                return False
1609
1610            self.log.info("Reboot DUT:{}".format(ads[0].serial))
1611            ads[0].reboot()
1612            time.sleep(WAIT_TIME_AFTER_REBOOT +
1613                       WAIT_TIME_TETHERING_AFTER_REBOOT)
1614
1615            self.log.info("After reboot check if tethering stopped.")
1616            if ads[0].droid.wifiIsApEnabled():
1617                self.log.error("Provider WiFi tethering did NOT stopped.")
1618                return False
1619        finally:
1620            ads[1].droid.telephonyToggleDataConnection(True)
1621            WifiUtils.wifi_reset(self.log, ads[1])
1622            if ads[0].droid.wifiIsApEnabled():
1623                WifiUtils.stop_wifi_tethering(self.log, ads[0])
1624        return True
1625
1626    @TelephonyBaseTest.tel_test_wrap
1627    def test_connect_wifi_start_tethering_wifi_reboot(self):
1628        """WiFi Tethering test: WiFI connected, then start WiFi tethering,
1629            then reboot device.
1630
1631        Initial Condition: DUT in 4G mode, idle, DUT connect to WiFi.
1632        1. DUT start 2.4G WiFi Tethering.
1633        2. PhoneB disable data, connect to DUT's softAP
1634        3. Verify Internet access on DUT and PhoneB
1635        4. Reboot DUT
1636        5. After DUT reboot, verify tethering is stopped. DUT is able to connect
1637            to previous WiFi AP.
1638
1639        Returns:
1640            True if success.
1641            False if failed.
1642        """
1643        ads = self.android_devices
1644        if not self._test_setup_tethering(ads):
1645            self.log.error("Verify Internet access failed.")
1646            return False
1647
1648        self.log.info("Make sure DUT can connect to live network by WIFI")
1649        if ((not ensure_wifi_connected(self.log, ads[0],
1650                                       self.wifi_network_ssid,
1651                                       self.wifi_network_pass)) or
1652            (not verify_http_connection(self.log, ads[0]))):
1653            self.log.error("WiFi connect fail.")
1654            return False
1655
1656        try:
1657            if not wifi_tethering_setup_teardown(
1658                    self.log,
1659                    ads[0],
1660                [ads[1]],
1661                    ap_band=WifiUtils.WIFI_CONFIG_APBAND_2G,
1662                    check_interval=10,
1663                    check_iteration=2,
1664                    do_cleanup=False):
1665                self.log.error("WiFi Tethering failed.")
1666                return False
1667
1668            if not ads[0].droid.wifiIsApEnabled():
1669                self.log.error("Provider WiFi tethering stopped.")
1670                return False
1671
1672            self.log.info("Reboot DUT:{}".format(ads[0].serial))
1673            ads[0].reboot()
1674            time.sleep(WAIT_TIME_AFTER_REBOOT)
1675            time.sleep(WAIT_TIME_TETHERING_AFTER_REBOOT)
1676
1677            self.log.info("After reboot check if tethering stopped.")
1678            if ads[0].droid.wifiIsApEnabled():
1679                self.log.error("Provider WiFi tethering did NOT stopped.")
1680                return False
1681
1682            self.log.info("Make sure WiFi can connect automatically.")
1683            if (not wait_for_wifi_data_connection(self.log, ads[0], True) or
1684                    not verify_http_connection(self.log, ads[0])):
1685                self.log.error("Data did not return to WiFi")
1686                return False
1687
1688        finally:
1689            ads[1].droid.telephonyToggleDataConnection(True)
1690            WifiUtils.wifi_reset(self.log, ads[1])
1691            if ads[0].droid.wifiIsApEnabled():
1692                WifiUtils.stop_wifi_tethering(self.log, ads[0])
1693        return True
1694
1695    @TelephonyBaseTest.tel_test_wrap
1696    def test_connect_wifi_reboot_start_tethering_wifi(self):
1697        """WiFi Tethering test: DUT connected to WiFi, then reboot,
1698        After reboot, start WiFi tethering, verify tethering actually works.
1699
1700        Initial Condition: Device set to 4G mode, idle, DUT connect to WiFi.
1701        1. Verify Internet is working on DUT (by WiFi).
1702        2. Reboot DUT.
1703        3. DUT start 2.4G WiFi Tethering.
1704        4. PhoneB disable data, connect to DUT's softAP
1705        5. Verify Internet access on DUT and PhoneB
1706
1707        Returns:
1708            True if success.
1709            False if failed.
1710        """
1711        ads = self.android_devices
1712
1713        if not self._test_setup_tethering(ads):
1714            self.log.error("Verify Internet access failed.")
1715            return False
1716
1717        self.log.info("Make sure DUT can connect to live network by WIFI")
1718        if ((not ensure_wifi_connected(self.log, ads[0],
1719                                       self.wifi_network_ssid,
1720                                       self.wifi_network_pass)) or
1721            (not verify_http_connection(self.log, ads[0]))):
1722            self.log.error("WiFi connect fail.")
1723            return False
1724
1725        self.log.info("Reboot DUT:{}".format(ads[0].serial))
1726        ads[0].reboot()
1727        time.sleep(WAIT_TIME_AFTER_REBOOT)
1728        time.sleep(WAIT_TIME_TETHERING_AFTER_REBOOT)
1729
1730        return wifi_tethering_setup_teardown(
1731            self.log,
1732            ads[0],
1733            [ads[1]],
1734            ap_band=WifiUtils.WIFI_CONFIG_APBAND_2G,
1735            check_interval=10,
1736            check_iteration=10)
1737
1738    @TelephonyBaseTest.tel_test_wrap
1739    def test_tethering_wifi_screen_off_enable_doze_mode(self):
1740        """WiFi Tethering test: Start WiFi tethering, then turn off DUT's screen,
1741            then enable doze mode.
1742
1743        1. Start WiFi tethering on DUT.
1744        2. PhoneB disable data, and connect to DUT's softAP
1745        3. Verify Internet access on DUT and PhoneB
1746        4. Turn off DUT's screen. Wait for 1 minute and
1747            verify Internet access on Client PhoneB.
1748        5. Enable doze mode on DUT. Wait for 1 minute and
1749            verify Internet access on Client PhoneB.
1750
1751        Returns:
1752            True if success.
1753            False if failed.
1754        """
1755        ads = self.android_devices
1756        if not self._test_setup_tethering(ads):
1757            self.log.error("Verify Internet access failed.")
1758            return False
1759        try:
1760            if not wifi_tethering_setup_teardown(
1761                    self.log,
1762                    ads[0],
1763                [ads[1]],
1764                    ap_band=WifiUtils.WIFI_CONFIG_APBAND_2G,
1765                    check_interval=10,
1766                    check_iteration=2,
1767                    do_cleanup=False):
1768                self.log.error("WiFi Tethering failed.")
1769                return False
1770
1771            if not ads[0].droid.wifiIsApEnabled():
1772                self.log.error("Provider WiFi tethering stopped.")
1773                return False
1774
1775            self.log.info("Turn off screen on provider: <{}>.".format(ads[
1776                0].serial))
1777            ads[0].droid.goToSleepNow()
1778            time.sleep(60)
1779            if not verify_http_connection(self.log, ads[1]):
1780                self.log.error("Client have no Internet access.")
1781                return False
1782
1783            self.log.info("Enable doze mode on provider: <{}>.".format(ads[
1784                0].serial))
1785            if not enable_doze(ads[0]):
1786                self.log.error("Failed to enable doze mode.")
1787                return False
1788            time.sleep(60)
1789            if not verify_http_connection(self.log, ads[1]):
1790                self.log.error("Client have no Internet access.")
1791                return False
1792        finally:
1793            self.log.info("Disable doze mode.")
1794            if not disable_doze(ads[0]):
1795                self.log.error("Failed to disable doze mode.")
1796                return False
1797            if not wifi_tethering_cleanup(self.log, ads[0], [ads[1]]):
1798                return False
1799        return True
1800
1801    @TelephonyBaseTest.tel_test_wrap
1802    def test_msim_switch_data_sim_2g(self):
1803        """Switch Data SIM on 2G network.
1804
1805        Steps:
1806        1. Data on default Data SIM.
1807        2. Switch Data to another SIM. Make sure data is still available.
1808        3. Switch Data back to previous SIM. Make sure data is still available.
1809
1810        Expected Results:
1811        1. Verify Data on Cell
1812        2. Verify Data on Wifi
1813
1814        Returns:
1815            True if success.
1816            False if failed.
1817        """
1818        ad = self.android_devices[0]
1819        current_data_sub_id = ad.droid.subscriptionGetDefaultDataSubId()
1820        current_sim_slot_index = get_slot_index_from_subid(self.log, ad,
1821            current_data_sub_id)
1822        if current_sim_slot_index == SIM1_SLOT_INDEX:
1823            next_sim_slot_index = SIM2_SLOT_INDEX
1824        else:
1825            next_sim_slot_index = SIM1_SLOT_INDEX
1826        next_data_sub_id = get_subid_from_slot_index(self.log, ad,
1827            next_sim_slot_index)
1828        self.log.info("Current Data is on subId: {}, SIM slot: {}".format(
1829            current_data_sub_id, current_sim_slot_index))
1830        if not ensure_network_generation_for_subscription(
1831            self.log, ad, ad.droid.subscriptionGetDefaultDataSubId(), GEN_2G,
1832            voice_or_data=NETWORK_SERVICE_DATA):
1833            self.log.error("Device data does not attach to 2G.")
1834            return False
1835        if not verify_http_connection(self.log, ad):
1836            self.log.error("No Internet access on default Data SIM.")
1837            return False
1838
1839        self.log.info("Change Data to subId: {}, SIM slot: {}".format(
1840            next_data_sub_id, next_sim_slot_index))
1841        if not change_data_sim_and_verify_data(self.log, ad, next_sim_slot_index):
1842            self.log.error("Failed to change data SIM.")
1843            return False
1844
1845        next_data_sub_id = current_data_sub_id
1846        next_sim_slot_index = current_sim_slot_index
1847        self.log.info("Change Data back to subId: {}, SIM slot: {}".format(
1848            next_data_sub_id, next_sim_slot_index))
1849        if not change_data_sim_and_verify_data(self.log, ad, next_sim_slot_index):
1850            self.log.error("Failed to change data SIM.")
1851            return False
1852
1853        return True
1854
1855    def _test_wifi_connect_disconnect(self):
1856        """Perform multiple connects and disconnects from WiFi and verify that
1857            data switches between WiFi and Cell.
1858
1859        Steps:
1860        1. Reset Wifi on DUT
1861        2. Connect DUT to a WiFi AP
1862        3. Repeat steps 1-2, alternately disconnecting and disabling wifi
1863
1864        Expected Results:
1865        1. Verify Data on Cell
1866        2. Verify Data on Wifi
1867
1868        Returns:
1869            True if success.
1870            False if failed.
1871        """
1872        ad = self.android_devices[0]
1873
1874        wifi_toggles = [True, False, True, False, False, True, False, False,
1875                        False, False, True, False, False, False, False, False,
1876                        False, False, False]
1877
1878        for toggle in wifi_toggles:
1879
1880            WifiUtils.wifi_reset(self.log, ad, toggle)
1881
1882            if not wait_for_cell_data_connection(
1883                    self.log, ad, True, MAX_WAIT_TIME_WIFI_CONNECTION):
1884                self.log.error("Failed wifi connection, aborting!")
1885                return False
1886
1887            if not verify_http_connection(self.log, ad,
1888                                          'http://www.google.com', 100, .1):
1889                self.log.error("Failed to get user-plane traffic, aborting!")
1890                return False
1891
1892            if toggle:
1893                WifiUtils.wifi_toggle_state(self.log, ad, True)
1894
1895            WifiUtils.wifi_connect(self.log, ad, self.wifi_network_ssid,
1896                                   self.wifi_network_pass)
1897
1898            if not wait_for_wifi_data_connection(
1899                    self.log, ad, True, MAX_WAIT_TIME_WIFI_CONNECTION):
1900                self.log.error("Failed wifi connection, aborting!")
1901                return False
1902
1903            if not verify_http_connection(self.log, ad,
1904                                          'http://www.google.com', 100, .1):
1905                self.log.error("Failed to get user-plane traffic, aborting!")
1906                return False
1907        return True
1908
1909    @TelephonyBaseTest.tel_test_wrap
1910    def test_wifi_connect_disconnect_4g(self):
1911        """Perform multiple connects and disconnects from WiFi and verify that
1912            data switches between WiFi and Cell.
1913
1914        Steps:
1915        1. DUT Cellular Data is on 4G. Reset Wifi on DUT
1916        2. Connect DUT to a WiFi AP
1917        3. Repeat steps 1-2, alternately disconnecting and disabling wifi
1918
1919        Expected Results:
1920        1. Verify Data on Cell
1921        2. Verify Data on Wifi
1922
1923        Returns:
1924            True if success.
1925            False if failed.
1926        """
1927
1928        ad = self.android_devices[0]
1929        if not ensure_network_generation_for_subscription(self.log, ad,
1930            ad.droid.subscriptionGetDefaultDataSubId(), GEN_4G,
1931            MAX_WAIT_TIME_NW_SELECTION, NETWORK_SERVICE_DATA):
1932            self.log.error("Device {} failed to reselect in {}s.".format(
1933                ad.serial, MAX_WAIT_TIME_NW_SELECTION))
1934            return False
1935        return self._test_wifi_connect_disconnect()
1936
1937    @TelephonyBaseTest.tel_test_wrap
1938    def test_wifi_connect_disconnect_3g(self):
1939        """Perform multiple connects and disconnects from WiFi and verify that
1940            data switches between WiFi and Cell.
1941
1942        Steps:
1943        1. DUT Cellular Data is on 3G. Reset Wifi on DUT
1944        2. Connect DUT to a WiFi AP
1945        3. Repeat steps 1-2, alternately disconnecting and disabling wifi
1946
1947        Expected Results:
1948        1. Verify Data on Cell
1949        2. Verify Data on Wifi
1950
1951        Returns:
1952            True if success.
1953            False if failed.
1954        """
1955
1956        ad = self.android_devices[0]
1957        if not ensure_network_generation_for_subscription(self.log, ad,
1958            ad.droid.subscriptionGetDefaultDataSubId(), GEN_3G,
1959            MAX_WAIT_TIME_NW_SELECTION, NETWORK_SERVICE_DATA):
1960            self.log.error("Device {} failed to reselect in {}s.".format(
1961                ad.serial, MAX_WAIT_TIME_NW_SELECTION))
1962            return False
1963        return self._test_wifi_connect_disconnect()
1964
1965    @TelephonyBaseTest.tel_test_wrap
1966    def test_wifi_connect_disconnect_2g(self):
1967        """Perform multiple connects and disconnects from WiFi and verify that
1968            data switches between WiFi and Cell.
1969
1970        Steps:
1971        1. DUT Cellular Data is on 2G. Reset Wifi on DUT
1972        2. Connect DUT to a WiFi AP
1973        3. Repeat steps 1-2, alternately disconnecting and disabling wifi
1974
1975        Expected Results:
1976        1. Verify Data on Cell
1977        2. Verify Data on Wifi
1978
1979        Returns:
1980            True if success.
1981            False if failed.
1982        """
1983        ad = self.android_devices[0]
1984        if not ensure_network_generation_for_subscription(self.log, ad,
1985            ad.droid.subscriptionGetDefaultDataSubId(), GEN_2G,
1986            MAX_WAIT_TIME_NW_SELECTION, NETWORK_SERVICE_DATA):
1987            self.log.error("Device {} failed to reselect in {}s.".format(
1988                ad.serial, MAX_WAIT_TIME_NW_SELECTION))
1989            return False
1990        return self._test_wifi_connect_disconnect()
1991
1992    def _test_wifi_tethering_enabled_add_voice_call(self, network_generation,
1993        voice_call_direction, is_data_available_during_call):
1994        """Tethering enabled + voice call.
1995
1996        Steps:
1997        1. DUT data is on <network_generation>. Start WiFi Tethering.
1998        2. PhoneB connect to DUT's softAP
1999        3. DUT make a MO/MT (<voice_call_direction>) phone call.
2000        4. DUT end phone call.
2001
2002        Expected Results:
2003        1. DUT is able to start WiFi tethering.
2004        2. PhoneB connected to DUT's softAP and able to browse Internet.
2005        3. DUT WiFi tethering is still on. Phone call works OK.
2006            If is_data_available_during_call is True, then PhoneB still has
2007            Internet access.
2008            Else, then Data is suspend, PhoneB has no Internet access.
2009        4. WiFi Tethering still on, voice call stopped, and PhoneB have Internet
2010            access.
2011
2012        Returns:
2013            True if success.
2014            False if failed.
2015        """
2016        ads = self.android_devices
2017        if not self._test_setup_tethering(ads, network_generation):
2018            self.log.error("Verify Internet access failed.")
2019            return False
2020        try:
2021            # Start WiFi Tethering
2022            if not wifi_tethering_setup_teardown(
2023                    self.log,
2024                    ads[0],
2025                    [ads[1]],
2026                    ap_band=WifiUtils.WIFI_CONFIG_APBAND_2G,
2027                    check_interval=10,
2028                    check_iteration=2,
2029                    do_cleanup=False):
2030                self.log.error("WiFi Tethering failed.")
2031                return False
2032
2033            if not ads[0].droid.wifiIsApEnabled():
2034                self.log.error("Provider WiFi tethering stopped.")
2035                return False
2036
2037            # Make a voice call
2038            if voice_call_direction == DIRECTION_MOBILE_ORIGINATED:
2039                ad_caller = ads[0]
2040                ad_callee = ads[1]
2041            else:
2042                ad_caller = ads[1]
2043                ad_callee = ads[0]
2044            if not call_setup_teardown(self.log, ad_caller, ad_callee, None,
2045                                       None, None):
2046                self.log.error("Failed to Establish {} Voice Call".format(
2047                    voice_call_direction))
2048                return False
2049
2050            # Tethering should still be on.
2051            if not ads[0].droid.wifiIsApEnabled():
2052                self.log.error("Provider WiFi tethering stopped.")
2053                return False
2054            if not is_data_available_during_call:
2055                if verify_http_connection(self.log, ads[1], retry=0):
2056                    self.log.error("Client should not have Internet Access.")
2057                    return False
2058            else:
2059                if not verify_http_connection(self.log, ads[1]):
2060                    self.log.error("Client should have Internet Access.")
2061                    return False
2062
2063            # Hangup call. Client should have data.
2064            if not hangup_call(self.log, ads[0]):
2065                self.log.error("Failed to hang up call")
2066                return False
2067            if not ads[0].droid.wifiIsApEnabled():
2068                self.log.error("Provider WiFi tethering stopped.")
2069                return False
2070            if not verify_http_connection(self.log, ads[1]):
2071                self.log.error("Client should have Internet Access.")
2072                return False
2073        finally:
2074            ads[1].droid.telephonyToggleDataConnection(True)
2075            WifiUtils.wifi_reset(self.log, ads[1])
2076            if ads[0].droid.wifiIsApEnabled():
2077                WifiUtils.stop_wifi_tethering(self.log, ads[0])
2078        return True
2079
2080    @TelephonyBaseTest.tel_test_wrap
2081    def test_wifi_tethering_enabled_add_mo_voice_call_2g_dsds(self):
2082        """Tethering enabled + voice call
2083
2084        Steps:
2085        1. DUT is DSDS device, Data on 2G. Start WiFi Tethering on <Data SIM>
2086        2. PhoneB connect to DUT's softAP
2087        3. DUT make a mo phone call on <Voice SIM>
2088        4. DUT end phone call.
2089
2090        Expected Results:
2091        1. DUT is able to start WiFi tethering.
2092        2. PhoneB connected to DUT's softAP and able to browse Internet.
2093        3. DUT WiFi tethering is still on. Phone call works OK. Data is suspend,
2094            PhoneB still connected to DUT's softAP, but no data available.
2095        4. DUT data resumes, and PhoneB have Internet access.
2096
2097        Returns:
2098            True if success.
2099            False if failed.
2100        """
2101
2102        return self._test_wifi_tethering_enabled_add_voice_call(GEN_2G,
2103            DIRECTION_MOBILE_ORIGINATED, False)
2104
2105    @TelephonyBaseTest.tel_test_wrap
2106    def test_wifi_tethering_enabled_add_mt_voice_call_2g_dsds(self):
2107        """Tethering enabled + voice call
2108
2109        Steps:
2110        1. DUT is DSDS device, Data on 2G. Start WiFi Tethering on <Data SIM>
2111        2. PhoneB connect to DUT's softAP
2112        3. DUT make a mt phone call on <Voice SIM>
2113        4. DUT end phone call.
2114
2115        Expected Results:
2116        1. DUT is able to start WiFi tethering.
2117        2. PhoneB connected to DUT's softAP and able to browse Internet.
2118        3. DUT WiFi tethering is still on. Phone call works OK. Data is suspend,
2119            PhoneB still connected to DUT's softAP, but no data available.
2120        4. DUT data resumes, and PhoneB have Internet access.
2121
2122        Returns:
2123            True if success.
2124            False if failed.
2125        """
2126
2127        return self._test_wifi_tethering_enabled_add_voice_call(GEN_2G,
2128            DIRECTION_MOBILE_TERMINATED, False)
2129
2130    @TelephonyBaseTest.tel_test_wrap
2131    def test_wifi_tethering_msim_switch_data_sim(self):
2132        """Tethering enabled + switch data SIM.
2133
2134        Steps:
2135        1. Start WiFi Tethering on <Default Data SIM>
2136        2. PhoneB connect to DUT's softAP
2137        3. DUT change Default Data SIM.
2138
2139        Expected Results:
2140        1. DUT is able to start WiFi tethering.
2141        2. PhoneB connected to DUT's softAP and able to browse Internet.
2142        3. DUT Data changed to 2nd SIM, WiFi tethering should continues,
2143            PhoneB should have Internet access.
2144
2145        Returns:
2146            True if success.
2147            False if failed.
2148        """
2149        ads = self.android_devices
2150        current_data_sub_id = ads[0].droid.subscriptionGetDefaultDataSubId()
2151        current_sim_slot_index = get_slot_index_from_subid(self.log, ads[0],
2152            current_data_sub_id)
2153        self.log.info("Current Data is on subId: {}, SIM slot: {}".format(
2154            current_data_sub_id, current_sim_slot_index))
2155        if not self._test_setup_tethering(ads):
2156            self.log.error("Verify Internet access failed.")
2157            return False
2158        try:
2159            # Start WiFi Tethering
2160            if not wifi_tethering_setup_teardown(
2161                    self.log,
2162                    ads[0],
2163                    [ads[1]],
2164                    ap_band=WifiUtils.WIFI_CONFIG_APBAND_2G,
2165                    check_interval=10,
2166                    check_iteration=2,
2167                    do_cleanup=False):
2168                self.log.error("WiFi Tethering failed.")
2169                return False
2170            for i in range(0, 2):
2171                next_sim_slot_index = \
2172                    {SIM1_SLOT_INDEX : SIM2_SLOT_INDEX,
2173                     SIM2_SLOT_INDEX : SIM1_SLOT_INDEX}[current_sim_slot_index]
2174                self.log.info("Change Data to SIM slot: {}".
2175                    format(next_sim_slot_index))
2176                if not change_data_sim_and_verify_data(self.log, ads[0],
2177                    next_sim_slot_index):
2178                    self.log.error("Failed to change data SIM.")
2179                    return False
2180                current_sim_slot_index = next_sim_slot_index
2181                if not verify_http_connection(self.log, ads[1]):
2182                    self.log.error("Client should have Internet Access.")
2183                    return False
2184        finally:
2185            ads[1].droid.telephonyToggleDataConnection(True)
2186            WifiUtils.wifi_reset(self.log, ads[1])
2187            if ads[0].droid.wifiIsApEnabled():
2188                WifiUtils.stop_wifi_tethering(self.log, ads[0])
2189        return True
2190
2191    @TelephonyBaseTest.tel_test_wrap
2192    def test_msim_cell_data_switch_to_wifi_switch_data_sim_2g(self):
2193        """Switch Data SIM on 2G network.
2194
2195        Steps:
2196        1. Data on default Data SIM.
2197        2. Turn on WiFi, then data should be on WiFi.
2198        3. Switch Data to another SIM. Disable WiFi.
2199
2200        Expected Results:
2201        1. Verify Data on Cell
2202        2. Verify Data on WiFi
2203        3. After WiFi disabled, Cell Data is available on 2nd SIM.
2204
2205        Returns:
2206            True if success.
2207            False if failed.
2208        """
2209        ad = self.android_devices[0]
2210        current_data_sub_id = ad.droid.subscriptionGetDefaultDataSubId()
2211        current_sim_slot_index = get_slot_index_from_subid(self.log, ad,
2212                                                           current_data_sub_id)
2213        if current_sim_slot_index == SIM1_SLOT_INDEX:
2214            next_sim_slot_index = SIM2_SLOT_INDEX
2215        else:
2216            next_sim_slot_index = SIM1_SLOT_INDEX
2217        next_data_sub_id = get_subid_from_slot_index(self.log, ad,
2218                                                     next_sim_slot_index)
2219        self.log.info("Current Data is on subId: {}, SIM slot: {}".format(
2220            current_data_sub_id, current_sim_slot_index))
2221        if not ensure_network_generation_for_subscription(
2222                self.log,
2223                ad,
2224                ad.droid.subscriptionGetDefaultDataSubId(),
2225                GEN_2G,
2226                voice_or_data=NETWORK_SERVICE_DATA):
2227            self.log.error("Device data does not attach to 2G.")
2228            return False
2229        if not verify_http_connection(self.log, ad):
2230            self.log.error("No Internet access on default Data SIM.")
2231            return False
2232
2233        self.log.info("Connect to WiFi and verify Internet access.")
2234        if not ensure_wifi_connected(self.log, ad, self.wifi_network_ssid,
2235                                     self.wifi_network_pass):
2236            self.log.error("WiFi connect fail.")
2237            return False
2238        if (not wait_for_wifi_data_connection(self.log, ad, True) or
2239                not verify_http_connection(self.log, ad)):
2240            self.log.error("Data is not on WiFi")
2241            return False
2242
2243        try:
2244            self.log.info(
2245                "Change Data SIM, Disable WiFi and verify Internet access.")
2246            set_subid_for_data(ad, next_data_sub_id)
2247            WifiUtils.wifi_toggle_state(self.log, ad, False)
2248            if not wait_for_data_attach_for_subscription(
2249                    self.log, ad, next_data_sub_id,
2250                    MAX_WAIT_TIME_NW_SELECTION):
2251                self.log.error("Failed to attach data on subId:{}".format(
2252                    next_data_sub_id))
2253                return False
2254            if not verify_http_connection(self.log, ad):
2255                self.log.error("No Internet access after changing Data SIM.")
2256                return False
2257
2258        finally:
2259            self.log.info("Change Data SIM back.")
2260            set_subid_for_data(ad, current_data_sub_id)
2261
2262        return True
2263
2264    @TelephonyBaseTest.tel_test_wrap
2265    def test_disable_data_on_non_active_data_sim(self):
2266        """Switch Data SIM on 2G network.
2267
2268        Steps:
2269        1. Data on default Data SIM.
2270        2. Disable data on non-active Data SIM.
2271
2272        Expected Results:
2273        1. Verify Data Status on Default Data SIM and non-active Data SIM.
2274        1. Verify Data Status on Default Data SIM and non-active Data SIM.
2275
2276        Returns:
2277            True if success.
2278            False if failed.
2279        """
2280        ad = self.android_devices[0]
2281        current_data_sub_id = ad.droid.subscriptionGetDefaultDataSubId()
2282        current_sim_slot_index = get_slot_index_from_subid(self.log, ad,
2283                                                           current_data_sub_id)
2284        if current_sim_slot_index == SIM1_SLOT_INDEX:
2285            non_active_sim_slot_index = SIM2_SLOT_INDEX
2286        else:
2287            non_active_sim_slot_index = SIM1_SLOT_INDEX
2288        non_active_sub_id = get_subid_from_slot_index(
2289            self.log, ad, non_active_sim_slot_index)
2290        self.log.info("Current Data is on subId: {}, SIM slot: {}".format(
2291            current_data_sub_id, current_sim_slot_index))
2292
2293        if not ensure_network_generation_for_subscription(
2294                self.log,
2295                ad,
2296                ad.droid.subscriptionGetDefaultDataSubId(),
2297                GEN_2G,
2298                voice_or_data=NETWORK_SERVICE_DATA):
2299            self.log.error("Device data does not attach to 2G.")
2300            return False
2301        if not verify_http_connection(self.log, ad):
2302            self.log.error("No Internet access on default Data SIM.")
2303            return False
2304
2305        if ad.droid.telephonyGetDataConnectionState() != DATA_STATE_CONNECTED:
2306            self.log.error("Data Connection State should be connected.")
2307            return False
2308        # TODO: Check Data state for non-active subId.
2309
2310        try:
2311            self.log.info("Disable Data on Non-Active Sub ID")
2312            ad.droid.telephonyToggleDataConnectionForSubscription(
2313                non_active_sub_id, False)
2314            # TODO: Check Data state for non-active subId.
2315            if ad.droid.telephonyGetDataConnectionState(
2316            ) != DATA_STATE_CONNECTED:
2317                self.log.error("Data Connection State should be connected.")
2318                return False
2319        finally:
2320            self.log.info("Enable Data on Non-Active Sub ID")
2321            ad.droid.telephonyToggleDataConnectionForSubscription(
2322                non_active_sub_id, True)
2323        return True
2324        """ Tests End """
2325