• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python3
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
17import time
18import random
19import re
20from queue import Empty
21
22from acts.utils import adb_shell_ping
23from acts.utils import rand_ascii_str
24from acts.utils import disable_doze
25from acts.utils import enable_doze
26from acts_contrib.test_utils.bt.bt_test_utils import bluetooth_enabled_check
27from acts_contrib.test_utils.bt.bt_test_utils import disable_bluetooth
28from acts_contrib.test_utils.bt.bt_test_utils import pair_pri_to_sec
29from acts_contrib.test_utils.tel.tel_subscription_utils import get_default_data_sub_id
30from acts_contrib.test_utils.tel.tel_subscription_utils import get_outgoing_message_sub_id
31from acts_contrib.test_utils.tel.tel_subscription_utils import get_outgoing_voice_sub_id
32from acts_contrib.test_utils.tel.tel_subscription_utils import \
33    get_subid_from_slot_index
34from acts_contrib.test_utils.tel.tel_subscription_utils import set_subid_for_data
35from acts_contrib.test_utils.tel.tel_defines import DIRECTION_MOBILE_ORIGINATED
36from acts_contrib.test_utils.tel.tel_defines import EventNetworkCallback
37from acts_contrib.test_utils.tel.tel_defines import GEN_5G
38from acts_contrib.test_utils.tel.tel_defines import MAX_WAIT_TIME_FOR_STATE_CHANGE
39from acts_contrib.test_utils.tel.tel_defines import MAX_WAIT_TIME_NW_SELECTION
40from acts_contrib.test_utils.tel.tel_defines import MAX_WAIT_TIME_USER_PLANE_DATA
41from acts_contrib.test_utils.tel.tel_defines import MAX_WAIT_TIME_WIFI_CONNECTION
42from acts_contrib.test_utils.tel.tel_defines import NETWORK_SERVICE_DATA
43from acts_contrib.test_utils.tel.tel_defines import NETWORK_SERVICE_VOICE
44from acts_contrib.test_utils.tel.tel_defines import RAT_5G
45from acts_contrib.test_utils.tel.tel_defines import RAT_UNKNOWN
46from acts_contrib.test_utils.tel.tel_defines import WAIT_TIME_AFTER_REBOOT
47from acts_contrib.test_utils.tel.tel_defines import WAIT_TIME_ANDROID_STATE_SETTLING
48from acts_contrib.test_utils.tel.tel_defines import WAIT_TIME_BETWEEN_REG_AND_CALL
49from acts_contrib.test_utils.tel.tel_defines import WAIT_TIME_BETWEEN_STATE_CHECK
50from acts_contrib.test_utils.tel.tel_defines import WAIT_TIME_IN_CALL_FOR_IMS
51from acts_contrib.test_utils.tel.tel_defines import \
52    WAIT_TIME_DATA_STATUS_CHANGE_DURING_WIFI_TETHERING
53from acts_contrib.test_utils.tel.tel_defines import TETHERING_MODE_WIFI
54from acts_contrib.test_utils.tel.tel_defines import MAX_WAIT_TIME_TETHERING_ENTITLEMENT_CHECK
55from acts_contrib.test_utils.tel.tel_defines import WAIT_TIME_TETHERING_AFTER_REBOOT
56from acts_contrib.test_utils.tel.tel_test_utils import call_setup_teardown
57from acts_contrib.test_utils.tel.tel_test_utils import check_is_wifi_connected
58from acts_contrib.test_utils.tel.tel_test_utils import ensure_network_generation
59from acts_contrib.test_utils.tel.tel_test_utils import ensure_network_generation_for_subscription
60from acts_contrib.test_utils.tel.tel_test_utils import ensure_phones_idle
61from acts_contrib.test_utils.tel.tel_test_utils import ensure_phone_idle
62from acts_contrib.test_utils.tel.tel_test_utils import ensure_wifi_connected
63from acts_contrib.test_utils.tel.tel_test_utils import get_mobile_data_usage
64from acts_contrib.test_utils.tel.tel_test_utils import get_network_rat_for_subscription
65from acts_contrib.test_utils.tel.tel_test_utils import get_service_state_by_adb
66from acts_contrib.test_utils.tel.tel_test_utils import get_wifi_usage
67from acts_contrib.test_utils.tel.tel_test_utils import hangup_call
68from acts_contrib.test_utils.tel.tel_test_utils import is_droid_in_network_generation_for_subscription
69from acts_contrib.test_utils.tel.tel_test_utils import is_ims_registered
70from acts_contrib.test_utils.tel.tel_test_utils import multithread_func
71from acts_contrib.test_utils.tel.tel_test_utils import rat_generation_from_rat
72from acts_contrib.test_utils.tel.tel_test_utils import set_wifi_to_default
73from acts_contrib.test_utils.tel.tel_test_utils import start_youtube_video
74from acts_contrib.test_utils.tel.tel_test_utils import start_wifi_tethering
75from acts_contrib.test_utils.tel.tel_test_utils import stop_wifi_tethering
76from acts_contrib.test_utils.tel.tel_test_utils import toggle_airplane_mode
77from acts_contrib.test_utils.tel.tel_test_utils import verify_http_connection
78from acts_contrib.test_utils.tel.tel_test_utils import verify_incall_state
79from acts_contrib.test_utils.tel.tel_test_utils import verify_internet_connection
80from acts_contrib.test_utils.tel.tel_test_utils import wait_for_cell_data_connection
81from acts_contrib.test_utils.tel.tel_test_utils import wait_for_data_attach_for_subscription
82from acts_contrib.test_utils.tel.tel_test_utils import wait_for_network_service
83from acts_contrib.test_utils.tel.tel_test_utils import wait_for_state
84from acts_contrib.test_utils.tel.tel_test_utils import \
85    wait_for_voice_attach_for_subscription
86from acts_contrib.test_utils.tel.tel_test_utils import wait_for_wifi_data_connection
87from acts_contrib.test_utils.tel.tel_test_utils import WIFI_CONFIG_APBAND_2G
88from acts_contrib.test_utils.tel.tel_test_utils import WIFI_CONFIG_APBAND_5G
89from acts_contrib.test_utils.tel.tel_test_utils import wifi_reset
90from acts_contrib.test_utils.tel.tel_test_utils import wifi_toggle_state
91from acts_contrib.test_utils.tel.tel_test_utils import active_file_download_task
92from acts_contrib.test_utils.tel.tel_test_utils import run_multithread_func
93from acts_contrib.test_utils.tel.tel_test_utils import ensure_phones_default_state
94from acts_contrib.test_utils.tel.tel_test_utils import WIFI_SSID_KEY
95from acts_contrib.test_utils.tel.tel_test_utils import is_phone_in_call_active
96from acts_contrib.test_utils.tel.tel_5g_utils import is_current_network_5g_nsa
97from acts_contrib.test_utils.tel.tel_5g_test_utils import check_current_network_5g
98from acts_contrib.test_utils.tel.tel_5g_test_utils import provision_device_for_5g
99from acts_contrib.test_utils.tel.tel_5g_test_utils import verify_5g_attach_for_both_devices
100from acts_contrib.test_utils.tel.tel_voice_utils import phone_setup_voice_general
101from acts_contrib.test_utils.tel.tel_voice_utils import phone_setup_iwlan
102from acts_contrib.test_utils.tel.tel_voice_utils import two_phone_call_short_seq
103from acts_contrib.test_utils.tel.tel_voice_utils import phone_idle_iwlan
104from acts_contrib.test_utils.tel.tel_voice_utils import is_phone_in_call_iwlan
105
106
107def wifi_tethering_cleanup(log, provider, client_list):
108    """Clean up steps for WiFi Tethering.
109
110    Make sure provider turn off tethering.
111    Make sure clients reset WiFi and turn on cellular data.
112
113    Args:
114        log: log object.
115        provider: android object provide WiFi tethering.
116        client_list: a list of clients using tethered WiFi.
117
118    Returns:
119        True if no error happened. False otherwise.
120    """
121    for client in client_list:
122        client.droid.telephonyToggleDataConnection(True)
123        set_wifi_to_default(log, client)
124    # If wifi tethering is enabled, disable it.
125    if provider.droid.wifiIsApEnabled() and not stop_wifi_tethering(log, provider):
126        provider.log.error("Provider stop WiFi tethering failed.")
127        return False
128    if provider.droid.wifiIsApEnabled():
129        provider.log.error("Provider WiFi tethering is still enabled.")
130        return False
131    return True
132
133
134def wifi_tethering_setup_teardown(log,
135                                  provider,
136                                  client_list,
137                                  ap_band=WIFI_CONFIG_APBAND_2G,
138                                  check_interval=30,
139                                  check_iteration=4,
140                                  do_cleanup=True,
141                                  ssid=None,
142                                  password=None):
143    """Test WiFi Tethering.
144
145    Turn off WiFi on clients.
146    Turn off data and reset WiFi on clients.
147    Verify no Internet access on clients.
148    Turn on WiFi tethering on provider.
149    Clients connect to provider's WiFI.
150    Verify Internet on provider and clients.
151    Tear down WiFi tethering setup and clean up.
152
153    Args:
154        log: log object.
155        provider: android object provide WiFi tethering.
156        client_list: a list of clients using tethered WiFi.
157        ap_band: setup WiFi tethering on 2G or 5G.
158            This is optional, default value is WIFI_CONFIG_APBAND_2G
159        check_interval: delay time between each around of Internet connection check.
160            This is optional, default value is 30 (seconds).
161        check_iteration: check Internet connection for how many times in total.
162            This is optional, default value is 4 (4 times).
163        do_cleanup: after WiFi tethering test, do clean up to tear down tethering
164            setup or not. This is optional, default value is True.
165        ssid: use this string as WiFi SSID to setup tethered WiFi network.
166            This is optional. Default value is None.
167            If it's None, a random string will be generated.
168        password: use this string as WiFi password to setup tethered WiFi network.
169            This is optional. Default value is None.
170            If it's None, a random string will be generated.
171
172    Returns:
173        True if no error happened. False otherwise.
174    """
175    log.info("--->Start wifi_tethering_setup_teardown<---")
176    log.info("Provider: {}".format(provider.serial))
177    if not provider.droid.connectivityIsTetheringSupported():
178        provider.log.error(
179            "Provider does not support tethering. Stop tethering test.")
180        return False
181
182    if ssid is None:
183        ssid = rand_ascii_str(10)
184    if password is None:
185        password = rand_ascii_str(8)
186
187    # No password
188    if password == "":
189        password = None
190
191    try:
192        for client in client_list:
193            log.info("Client: {}".format(client.serial))
194            wifi_toggle_state(log, client, False)
195            client.droid.telephonyToggleDataConnection(False)
196        log.info("WiFI Tethering: Verify client have no Internet access.")
197        for client in client_list:
198            if not verify_internet_connection(
199                    log, client, expected_state=False):
200                client.log.error("Turn off Data on client fail")
201                return False
202
203        provider.log.info(
204            "Provider turn on WiFi tethering. SSID: %s, password: %s", ssid,
205            password)
206
207        if not start_wifi_tethering(log, provider, ssid, password, ap_band):
208            provider.log.error("Provider start WiFi tethering failed.")
209            return False
210        time.sleep(WAIT_TIME_ANDROID_STATE_SETTLING)
211
212        provider.log.info("Provider check Internet connection.")
213        if not verify_internet_connection(log, provider):
214            return False
215        for client in client_list:
216            client.log.info(
217                "Client connect to WiFi and verify AP band correct.")
218            if not ensure_wifi_connected(log, client, ssid, password):
219                client.log.error("Client connect to WiFi failed.")
220                return False
221
222            wifi_info = client.droid.wifiGetConnectionInfo()
223            if ap_band == WIFI_CONFIG_APBAND_5G:
224                if wifi_info["is_24ghz"]:
225                    client.log.error("Expected 5g network. WiFi Info: %s",
226                                     wifi_info)
227                    return False
228            else:
229                if wifi_info["is_5ghz"]:
230                    client.log.error("Expected 2g network. WiFi Info: %s",
231                                     wifi_info)
232                    return False
233
234            client.log.info("Client check Internet connection.")
235            if (not wait_for_wifi_data_connection(log, client, True)
236                    or not verify_internet_connection(log, client)):
237                client.log.error("No WiFi Data on client")
238                return False
239
240        if not tethering_check_internet_connection(
241                log, provider, client_list, check_interval, check_iteration):
242            return False
243
244    finally:
245        if (do_cleanup
246                and (not wifi_tethering_cleanup(log, provider, client_list))):
247            return False
248    return True
249
250
251def tethering_check_internet_connection(log, provider, client_list,
252                                        check_interval, check_iteration):
253    """During tethering test, check client(s) and provider Internet connection.
254
255    Do the following for <check_iteration> times:
256        Delay <check_interval> seconds.
257        Check Tethering provider's Internet connection.
258        Check each client's Internet connection.
259
260    Args:
261        log: log object.
262        provider: android object provide WiFi tethering.
263        client_list: a list of clients using tethered WiFi.
264        check_interval: delay time between each around of Internet connection check.
265        check_iteration: check Internet connection for how many times in total.
266
267    Returns:
268        True if no error happened. False otherwise.
269    """
270    for i in range(1, check_iteration + 1):
271        result = True
272        time.sleep(check_interval)
273        provider.log.info(
274            "Provider check Internet connection after %s seconds.",
275            check_interval * i)
276        if not verify_internet_connection(log, provider):
277            result = False
278            continue
279        for client in client_list:
280            client.log.info(
281                "Client check Internet connection after %s seconds.",
282                check_interval * i)
283            if not verify_internet_connection(log, client):
284                result = False
285                break
286        if result: return result
287    return False
288
289
290def wifi_cell_switching(log, ad, nw_gen, wifi_network_ssid=None, wifi_network_pass=None, sa_5g=False):
291    """Test data connection network switching when phone on <nw_gen>.
292
293    Ensure phone is on <nw_gen>
294    Ensure WiFi can connect to live network,
295    Airplane mode is off, data connection is on, WiFi is on.
296    Turn off WiFi, verify data is on cell and browse to google.com is OK.
297    Turn on WiFi, verify data is on WiFi and browse to google.com is OK.
298    Turn off WiFi, verify data is on cell and browse to google.com is OK.
299
300    Args:
301        log: log object.
302        ad: android object.
303        wifi_network_ssid: ssid for live wifi network.
304        wifi_network_pass: password for live wifi network.
305        nw_gen: network generation the phone should be camped on.
306
307    Returns:
308        True if pass.
309    """
310    try:
311        if nw_gen == GEN_5G:
312            if not provision_device_for_5g(log, ad, sa_5g):
313                return False
314        elif nw_gen:
315            if not ensure_network_generation_for_subscription(
316                    log, ad, get_default_data_sub_id(ad), nw_gen,
317                    MAX_WAIT_TIME_NW_SELECTION, NETWORK_SERVICE_DATA):
318                ad.log.error("Device failed to register in %s", nw_gen)
319                return False
320        else:
321            ad.log.debug("Skipping network generation since it is None")
322
323        start_youtube_video(ad)
324        # Ensure WiFi can connect to live network
325        ad.log.info("Make sure phone can connect to live network by WIFI")
326        if not ensure_wifi_connected(log, ad, wifi_network_ssid,
327                                     wifi_network_pass):
328            ad.log.error("WiFi connect fail.")
329            return False
330        log.info("Phone connected to WIFI.")
331
332        log.info("Step1 Airplane Off, WiFi On, Data On.")
333        toggle_airplane_mode(log, ad, False)
334        wifi_toggle_state(log, ad, True)
335        ad.droid.telephonyToggleDataConnection(True)
336        if (not wait_for_wifi_data_connection(log, ad, True)
337                or not verify_internet_connection(log, ad)):
338            ad.log.error("Data is not on WiFi")
339            return False
340
341        log.info("Step2 WiFi is Off, Data is on Cell.")
342        wifi_toggle_state(log, ad, False)
343        if (not wait_for_cell_data_connection(log, ad, True)
344                or not verify_internet_connection(log, ad)):
345            ad.log.error("Data did not return to cell")
346            return False
347
348        log.info("Step3 WiFi is On, Data is on WiFi.")
349        wifi_toggle_state(log, ad, True)
350        if (not wait_for_wifi_data_connection(log, ad, True)
351                or not verify_internet_connection(log, ad)):
352            ad.log.error("Data did not return to WiFi")
353            return False
354
355        log.info("Step4 WiFi is Off, Data is on Cell.")
356        wifi_toggle_state(log, ad, False)
357        if (not wait_for_cell_data_connection(log, ad, True)
358                or not verify_internet_connection(log, ad)):
359            ad.log.error("Data did not return to cell")
360            return False
361        return True
362
363    finally:
364        ad.force_stop_apk("com.google.android.youtube")
365        wifi_toggle_state(log, ad, False)
366
367
368def airplane_mode_test(log, ad, wifi_ssid=None, retries=3):
369    """ Test airplane mode basic on Phone and Live SIM.
370
371    Test steps:
372        1. Ensure airplane mode is disabled and multiple network services are
373           available. Check WiFi and IMS registration status.
374        2. Turn on airplane mode and ensure cellular data and internet
375           connection are not available.
376        3. Turn off airplane mode and then ensure multiple network services are
377           available. Check if WiFi and IMS registration status keep the same.
378
379    Args:
380        log: log object.
381        ad: android object.
382        wifi_ssid: SSID of WiFi AP which ad should connect to.
383        retries: times of retry
384
385    Returns:
386        True if pass; False if fail.
387    """
388    if not ensure_phones_idle(log, [ad]):
389        log.error("Failed to return phones to idle.")
390        return False
391
392    try:
393        log.info("Step1: disable airplane mode and ensure attach")
394
395        if not toggle_airplane_mode(log, ad, False):
396            ad.log.error("Failed to disable airplane mode,")
397            return False
398
399        wifi_connected = False
400        if wifi_ssid:
401            wifi_connected = check_is_wifi_connected(log, ad, wifi_ssid)
402
403        ims_reg = is_ims_registered(log, ad)
404
405        if not wait_for_network_service(
406            log,
407            ad,
408            wifi_connected=wifi_connected,
409            wifi_ssid=wifi_ssid,
410            ims_reg=ims_reg):
411
412            return False
413
414        log.info("Step2: enable airplane mode and ensure detach")
415        if not toggle_airplane_mode(log, ad, True):
416            ad.log.error("Failed to enable Airplane Mode")
417            return False
418
419        if not wait_for_cell_data_connection(log, ad, False):
420            ad.log.error("Failed to disable cell data connection")
421            return False
422
423        if not verify_internet_connection(log, ad, expected_state=False):
424            ad.log.error("Data available in airplane mode.")
425            return False
426
427        log.info("Step3: disable airplane mode and ensure attach")
428        if not toggle_airplane_mode(log, ad, False):
429            ad.log.error("Failed to disable Airplane Mode")
430            return False
431
432        if not wait_for_network_service(
433            log,
434            ad,
435            wifi_connected=wifi_connected,
436            wifi_ssid=wifi_ssid,
437            ims_reg=ims_reg):
438
439            return False
440
441        return True
442    finally:
443        toggle_airplane_mode(log, ad, False)
444
445
446def data_connectivity_single_bearer(log, ad, nw_gen=None, sa_5g=False):
447    """Test data connection: single-bearer (no voice).
448
449    Turn off airplane mode, enable Cellular Data.
450    Ensure phone data generation is expected.
451    Verify Internet.
452    Disable Cellular Data, verify Internet is inaccessible.
453    Enable Cellular Data, verify Internet.
454
455    Args:
456        log: log object.
457        ad: android object.
458        nw_gen: network generation the phone should on.
459
460    Returns:
461        True if success.
462        False if failed.
463    """
464    ensure_phones_idle(log, [ad])
465    wait_time = MAX_WAIT_TIME_NW_SELECTION
466    if getattr(ad, 'roaming', False):
467        wait_time = 2 * wait_time
468
469    if nw_gen == GEN_5G:
470        if not provision_device_for_5g(log, ad, sa_5g):
471            return False
472    elif nw_gen:
473        if not ensure_network_generation_for_subscription(
474                log, ad, get_default_data_sub_id(ad), nw_gen,
475                MAX_WAIT_TIME_NW_SELECTION, NETWORK_SERVICE_DATA):
476            ad.log.error("Device failed to connect to %s in %s seconds.", nw_gen,
477                         wait_time)
478            return False
479    else:
480        ad.log.debug("Skipping network generation since it is None")
481
482    try:
483        log.info("Step1 Airplane Off, Data On.")
484        toggle_airplane_mode(log, ad, False)
485        ad.droid.telephonyToggleDataConnection(True)
486        if not wait_for_cell_data_connection(log, ad, True, timeout_value=wait_time):
487            ad.log.error("Failed to enable data connection.")
488            return False
489
490        log.info("Step2 Verify internet")
491        if not verify_internet_connection(log, ad, retries=3):
492            ad.log.error("Data not available on cell.")
493            return False
494
495        log.info("Step3 Turn off data and verify not connected.")
496        ad.droid.telephonyToggleDataConnection(False)
497        if not wait_for_cell_data_connection(log, ad, False):
498            ad.log.error("Step3 Failed to disable data connection.")
499            return False
500
501        if not verify_internet_connection(log, ad, expected_state=False):
502            ad.log.error("Step3 Data still available when disabled.")
503            return False
504
505        log.info("Step4 Re-enable data.")
506        ad.droid.telephonyToggleDataConnection(True)
507        if not wait_for_cell_data_connection(log, ad, True, timeout_value=wait_time):
508            ad.log.error("Step4 failed to re-enable data.")
509            return False
510        if not verify_internet_connection(log, ad, retries=3):
511            ad.log.error("Data not available on cell.")
512            return False
513
514        if nw_gen == GEN_5G:
515            if not check_current_network_5g(ad, sa_5g):
516                return False
517        else:
518            if not is_droid_in_network_generation_for_subscription(
519                    log, ad, get_default_data_sub_id(ad), nw_gen,
520                    NETWORK_SERVICE_DATA):
521                ad.log.error("Failed: droid is no longer on correct network")
522                ad.log.info("Expected:%s, Current:%s", nw_gen,
523                            rat_generation_from_rat(
524                                get_network_rat_for_subscription(
525                                    log, ad, get_default_data_sub_id(ad),
526                                    NETWORK_SERVICE_DATA)))
527                return False
528        return True
529    finally:
530        ad.droid.telephonyToggleDataConnection(True)
531
532
533def change_data_sim_and_verify_data(log, ad, sim_slot):
534    """Change Data SIM and verify Data attach and Internet access
535
536    Args:
537        log: log object.
538        ad: android device object.
539        sim_slot: SIM slot index.
540
541    Returns:
542        Data SIM changed successfully, data attached and Internet access is OK.
543    """
544    sub_id = get_subid_from_slot_index(log, ad, sim_slot)
545    ad.log.info("Change Data to subId: %s, SIM slot: %s", sub_id, sim_slot)
546    set_subid_for_data(ad, sub_id)
547    if not wait_for_data_attach_for_subscription(log, ad, sub_id,
548                                                 MAX_WAIT_TIME_NW_SELECTION):
549        ad.log.error("Failed to attach data on subId:%s", sub_id)
550        return False
551    if not verify_internet_connection(log, ad):
552        ad.log.error("No Internet access after changing Data SIM.")
553        return False
554    return True
555
556
557def browsing_test(log, ad, wifi_ssid=None, pass_threshold_in_mb = 1.0):
558    """ Ramdomly browse 6 among 23 selected web sites. The idle time is used to
559    simulate visit duration and normally distributed with the mean 35 seconds
560    and std dev 15 seconds, which means 95% of visit duration will be between
561    5 and 65 seconds. DUT will enter suspend mode when idle time is greater than
562    35 seconds.
563
564    Args:
565        log: log object.
566        ad: android object.
567        pass_threshold_in_mb: minimum traffic of browsing 6 web sites in MB for
568            test pass
569
570    Returns:
571        True if the total traffic of Chrome for browsing 6 web sites is greater
572        than pass_threshold_in_mb. Otherwise False.
573    """
574    web_sites = [
575        "http://tw.yahoo.com",
576        "http://24h.pchome.com.tw",
577        "http://www.mobile01.com",
578        "https://www.android.com/phones/",
579        "http://www.books.com.tw",
580        "http://www.udn.com.tw",
581        "http://news.baidu.com",
582        "http://www.google.com",
583        "http://www.cnn.com",
584        "http://www.nytimes.com",
585        "http://www.amazon.com",
586        "http://www.wikipedia.com",
587        "http://www.ebay.com",
588        "http://www.youtube.com",
589        "http://espn.go.com",
590        "http://www.sueddeutsche.de",
591        "http://www.bild.de",
592        "http://www.welt.de",
593        "http://www.lefigaro.fr",
594        "http://www.accuweather.com",
595        "https://www.flickr.com",
596        "http://world.taobao.com",
597        "http://www.theguardian.com",
598        "http://www.abc.net.au",
599        "http://www.gumtree.com.au",
600        "http://www.commbank.com.au",
601        "http://www.news.com.au",
602        "http://rakuten.co.jp",
603        "http://livedoor.jp",
604        "http://yahoo.co.jp"]
605
606    wifi_connected = False
607    if wifi_ssid and check_is_wifi_connected(ad.log, ad, wifi_ssid):
608        wifi_connected = True
609        usage_level_at_start = get_wifi_usage(ad, apk="com.android.chrome")
610    else:
611        usage_level_at_start = get_mobile_data_usage(ad, apk="com.android.chrome")
612
613    for web_site in random.sample(web_sites, 6):
614        ad.log.info("Browsing %s..." % web_site)
615        ad.adb.shell(
616            "am start -a android.intent.action.VIEW -d %s --es "
617            "com.android.browser.application_id com.android.browser" % web_site)
618
619        idle_time = round(random.normalvariate(35, 15))
620        if idle_time < 2:
621            idle_time = 2
622        elif idle_time > 90:
623            idle_time = 90
624
625        ad.log.info(
626            "Idle time before browsing next web site: %s sec." % idle_time)
627
628        if idle_time > 35:
629            time.sleep(35)
630            rest_idle_time = idle_time-35
631            if rest_idle_time < 3:
632                rest_idle_time = 3
633            ad.log.info("Let device go to sleep for %s sec." % rest_idle_time)
634            ad.droid.wakeLockRelease()
635            ad.droid.goToSleepNow()
636            time.sleep(rest_idle_time)
637            ad.log.info("Wake up device.")
638            ad.wakeup_screen()
639            ad.adb.shell("input keyevent 82")
640            time.sleep(3)
641        else:
642            time.sleep(idle_time)
643
644    if wifi_connected:
645        usage_level = get_wifi_usage(ad, apk="com.android.chrome")
646    else:
647        usage_level = get_mobile_data_usage(ad, apk="com.android.chrome")
648
649    try:
650        usage = round((usage_level - usage_level_at_start)/1024/1024, 2)
651        if usage < pass_threshold_in_mb:
652            ad.log.error(
653                "Usage of browsing '%s MB' is smaller than %s " % (
654                    usage, pass_threshold_in_mb))
655            return False
656        else:
657            ad.log.info("Usage of browsing: %s MB" % usage)
658            return True
659    except Exception as e:
660        ad.log.error(e)
661        usage = "unknown"
662        ad.log.info("Usage of browsing: %s MB" % usage)
663        return False
664
665
666def reboot_test(log, ad, wifi_ssid=None):
667    """ Reboot test to verify the service availability after reboot.
668
669    Test procedure:
670    1. Check WiFi and IMS registration status.
671    2. Reboot
672    3. Wait WAIT_TIME_AFTER_REBOOT for reboot complete.
673    4. Wait for multiple network services, including:
674       - service state
675       - network connection
676       - wifi connection if connected before reboot
677       - cellular data
678       - internet connection
679       - IMS registration if available before reboot
680    5. Check if DSDS mode, data sub ID, voice sub ID and message sub ID still keep the same.
681    6. Check if voice and data RAT keep the same.
682
683    Args:
684        log: log object.
685        ad: android object.
686        wifi_ssid: SSID of Wi-Fi AP for Wi-Fi connection.
687
688    Returns:
689        True if pass; False if fail.
690    """
691    try:
692        data_subid = get_default_data_sub_id(ad)
693        voice_subid = get_outgoing_voice_sub_id(ad)
694        sms_subid = get_outgoing_message_sub_id(ad)
695
696        data_rat_before_reboot = get_network_rat_for_subscription(
697            log, ad, data_subid, NETWORK_SERVICE_DATA)
698        voice_rat_before_reboot = get_network_rat_for_subscription(
699            log, ad, voice_subid, NETWORK_SERVICE_VOICE)
700
701        wifi_connected = False
702        if wifi_ssid:
703            wifi_connected = check_is_wifi_connected(log, ad, wifi_ssid)
704
705        ims_reg = is_ims_registered(log, ad)
706
707        ad.reboot()
708        time.sleep(WAIT_TIME_AFTER_REBOOT)
709
710        if not wait_for_network_service(
711            log,
712            ad,
713            wifi_connected=wifi_connected,
714            wifi_ssid=wifi_ssid,
715            ims_reg=ims_reg):
716
717            return False
718
719        sim_mode = ad.droid.telephonyGetPhoneCount()
720        if getattr(ad, 'dsds', False):
721            if sim_mode == 1:
722                ad.log.error("Phone is in single SIM mode after reboot.")
723                return False
724            elif sim_mode == 2:
725                ad.log.info("Phone keeps being in dual SIM mode after reboot.")
726        else:
727            if sim_mode == 1:
728                ad.log.info("Phone keeps being in single SIM mode after reboot.")
729            elif sim_mode == 2:
730                ad.log.error("Phone is in dual SIM mode after reboot.")
731                return False
732
733        data_subid_after_reboot = get_default_data_sub_id(ad)
734        if data_subid_after_reboot != data_subid:
735            ad.log.error(
736                "Data sub ID changed! (Before reboot: %s; after reboot: %s)",
737                data_subid, data_subid_after_reboot)
738            return False
739        else:
740            ad.log.info("Data sub ID does not change after reboot.")
741
742        voice_subid_after_reboot = get_outgoing_voice_sub_id(ad)
743        if voice_subid_after_reboot != voice_subid:
744            ad.log.error(
745                "Voice sub ID changed! (Before reboot: %s; after reboot: %s)",
746                voice_subid, voice_subid_after_reboot)
747            return False
748        else:
749            ad.log.info("Voice sub ID does not change after reboot.")
750
751        sms_subid_after_reboot = get_outgoing_message_sub_id(ad)
752        if sms_subid_after_reboot != sms_subid:
753            ad.log.error(
754                "Message sub ID changed! (Before reboot: %s; after reboot: %s)",
755                sms_subid, sms_subid_after_reboot)
756            return False
757        else:
758            ad.log.info("Message sub ID does not change after reboot.")
759
760        data_rat_after_reboot = get_network_rat_for_subscription(
761            log, ad, data_subid_after_reboot, NETWORK_SERVICE_DATA)
762        voice_rat_after_reboot = get_network_rat_for_subscription(
763            log, ad, voice_subid_after_reboot, NETWORK_SERVICE_VOICE)
764
765        if data_rat_after_reboot == data_rat_before_reboot:
766            ad.log.info(
767                "Data RAT (%s) does not change after reboot.",
768                data_rat_after_reboot)
769        else:
770            ad.log.error(
771                "Data RAT changed! (Before reboot: %s; after reboot: %s)",
772                data_rat_before_reboot,
773                data_rat_after_reboot)
774            return False
775
776        if voice_rat_after_reboot == voice_rat_before_reboot:
777            ad.log.info(
778                "Voice RAT (%s) does not change after reboot.",
779                voice_rat_after_reboot)
780        else:
781            ad.log.error(
782                "Voice RAT changed! (Before reboot: %s; after reboot: %s)",
783                voice_rat_before_reboot,
784                voice_rat_after_reboot)
785            return False
786
787    except Exception as e:
788        ad.log.error(e)
789        return False
790
791    return True
792
793
794def verify_for_network_callback(log, ad, event, apm_mode=False):
795    """Verify network callback for Meteredness
796
797    Args:
798        ad: DUT to get the network callback for
799        event: Network callback event
800
801    Returns:
802        True: if the expected network callback found, False if not
803    """
804    key = ad.droid.connectivityRegisterDefaultNetworkCallback()
805    ad.droid.connectivityNetworkCallbackStartListeningForEvent(key, event)
806    if apm_mode:
807        ad.log.info("Turn on Airplane Mode")
808        toggle_airplane_mode(ad.log, ad, True)
809    curr_time = time.time()
810    status = False
811    while time.time() < curr_time + MAX_WAIT_TIME_USER_PLANE_DATA:
812        try:
813            nc_event = ad.ed.pop_event(EventNetworkCallback)
814            ad.log.info("Received: %s" %
815                        nc_event["data"]["networkCallbackEvent"])
816            if nc_event["data"]["networkCallbackEvent"] == event:
817                status = nc_event["data"]["metered"]
818                ad.log.info("Current state of Meteredness is %s", status)
819                break
820        except Empty:
821            pass
822
823    ad.droid.connectivityNetworkCallbackStopListeningForEvent(key, event)
824    ad.droid.connectivityUnregisterNetworkCallback(key)
825    if apm_mode:
826        ad.log.info("Turn off Airplane Mode")
827        toggle_airplane_mode(ad.log, ad, False)
828        time.sleep(WAIT_TIME_BETWEEN_STATE_CHECK)
829    return status
830
831
832def test_data_connectivity_multi_bearer(
833        log,
834        android_devices,
835        nw_gen=None,
836        simultaneous_voice_data=True,
837        call_direction=DIRECTION_MOBILE_ORIGINATED,
838        sa_5g=False):
839    """Test data connection before call and in call.
840
841    Turn off airplane mode, disable WiFi, enable Cellular Data.
842    Make sure phone in <nw_gen>, verify Internet.
843    Initiate a voice call.
844    if simultaneous_voice_data is True, then:
845        Verify Internet.
846        Disable Cellular Data, verify Internet is inaccessible.
847        Enable Cellular Data, verify Internet.
848    if simultaneous_voice_data is False, then:
849        Verify Internet is not available during voice call.
850    Hangup Voice Call, verify Internet.
851
852    Returns:
853        True if success.
854        False if failed.
855    """
856
857    class _LocalException(Exception):
858        pass
859
860    ad_list = [android_devices[0], android_devices[1]]
861    ensure_phones_idle(log, ad_list)
862
863    if nw_gen == GEN_5G:
864        if not provision_device_for_5g(log, android_devices, sa_5g):
865            return False
866    elif nw_gen:
867        if not ensure_network_generation_for_subscription(
868                log, android_devices[0], android_devices[0]
869                .droid.subscriptionGetDefaultDataSubId(), nw_gen,
870                MAX_WAIT_TIME_NW_SELECTION, NETWORK_SERVICE_DATA):
871            log.error("Device failed to reselect in {}s.".format(
872                MAX_WAIT_TIME_NW_SELECTION))
873            return False
874    else:
875        log.debug("Skipping network generation since it is None")
876
877    if not wait_for_voice_attach_for_subscription(
878            log, android_devices[0], android_devices[0]
879            .droid.subscriptionGetDefaultVoiceSubId(),
880            MAX_WAIT_TIME_NW_SELECTION):
881        return False
882
883    log.info("Step1 WiFi is Off, Data is on Cell.")
884    toggle_airplane_mode(log, android_devices[0], False)
885    wifi_toggle_state(log, android_devices[0], False)
886    android_devices[0].droid.telephonyToggleDataConnection(True)
887    if (not wait_for_cell_data_connection(log,
888                                          android_devices[0], True)
889            or not verify_internet_connection(log,
890                                              android_devices[0])):
891        log.error("Data not available on cell")
892        return False
893
894    log.info(
895        "b/69431819, sending data to increase NW threshold limit")
896    adb_shell_ping(
897        android_devices[0], count=30, timeout=60, loss_tolerance=100)
898
899    try:
900        log.info("Step2 Initiate call and accept.")
901        if call_direction == DIRECTION_MOBILE_ORIGINATED:
902            ad_caller = android_devices[0]
903            ad_callee = android_devices[1]
904        else:
905            ad_caller = android_devices[1]
906            ad_callee = android_devices[0]
907        if not call_setup_teardown(log, ad_caller, ad_callee, None,
908                                   None, None):
909            log.error(
910                "Failed to Establish {} Voice Call".format(call_direction))
911            return False
912        if simultaneous_voice_data:
913            log.info("Step3 Verify internet.")
914            time.sleep(WAIT_TIME_ANDROID_STATE_SETTLING)
915            if not verify_internet_connection(
916                    log, android_devices[0], retries=3):
917                raise _LocalException("Internet Inaccessible when Enabled")
918
919            log.info("Step4 Turn off data and verify not connected.")
920            android_devices[0].droid.telephonyToggleDataConnection(
921                False)
922            if not wait_for_cell_data_connection(
923                    log, android_devices[0], False):
924                raise _LocalException("Failed to Disable Cellular Data")
925
926            if not verify_internet_connection(log,
927                                          android_devices[0], expected_state=False):
928                raise _LocalException("Internet Accessible when Disabled")
929
930            log.info("Step5 Re-enable data.")
931            android_devices[0].droid.telephonyToggleDataConnection(
932                True)
933            if not wait_for_cell_data_connection(
934                    log, android_devices[0], True):
935                raise _LocalException("Failed to Re-Enable Cellular Data")
936            if not verify_internet_connection(
937                    log, android_devices[0], retries=3):
938                raise _LocalException("Internet Inaccessible when Enabled")
939        else:
940            log.info("Step3 Verify no Internet and skip step 4-5.")
941            if verify_internet_connection(
942                    log, android_devices[0], retries=0):
943                raise _LocalException("Internet Accessible.")
944
945        log.info("Step6 Verify phones still in call and Hang up.")
946        if not verify_incall_state(
947                log,
948            [android_devices[0], android_devices[1]], True):
949            return False
950        if not hangup_call(log, android_devices[0]):
951            log.error("Failed to hang up call")
952            return False
953        if not verify_internet_connection(
954                log, android_devices[0], retries=3):
955            raise _LocalException("Internet Inaccessible when Enabled")
956
957    except _LocalException as e:
958        log.error(str(e))
959        try:
960            hangup_call(log, android_devices[0])
961            android_devices[0].droid.telephonyToggleDataConnection(
962                True)
963        except Exception:
964            pass
965        return False
966
967    return True
968
969
970def test_internet_connection(log, provider, clients,
971                              client_status=True,
972                              provider_status=True):
973    client_retry = 10 if client_status else 1
974    for client in clients:
975        if not verify_internet_connection(
976                log,
977                client,
978                retries=client_retry,
979                expected_state=client_status):
980            client.log.error("client internet connection state is not %s",
981                             client_status)
982            return False
983        else:
984            client.log.info("client internet connection state is %s",
985                            client_status)
986    if not verify_internet_connection(
987            log, provider, retries=3,
988            expected_state=provider_status):
989        provider.log.error(
990            "provider internet connection is not %s" % provider_status)
991        return False
992    else:
993        provider.log.info(
994            "provider internet connection is %s" % provider_status)
995    return True
996
997
998def test_setup_tethering(log, provider, clients, network_generation=None, sa_5g=False):
999    """Pre setup steps for WiFi tethering test.
1000
1001    Ensure all ads are idle.
1002    Ensure tethering provider:
1003        turn off APM, turn off WiFI, turn on Data.
1004        have Internet connection, no active ongoing WiFi tethering.
1005
1006    Returns:
1007        True if success.
1008        False if failed.
1009    """
1010
1011    ensure_phone_idle(log, provider)
1012    ensure_phones_idle(log, clients)
1013    wifi_toggle_state(log, provider, False)
1014    if network_generation == RAT_5G:
1015        if not provision_device_for_5g(log, provider, sa_5g):
1016            return False
1017    elif network_generation:
1018        if not ensure_network_generation(
1019                log, provider, network_generation,
1020                MAX_WAIT_TIME_NW_SELECTION, NETWORK_SERVICE_DATA):
1021            provider.log.error("Provider failed to connect to %s.",
1022                                    network_generation)
1023            return False
1024    else:
1025        log.debug("Skipping network generation since it is None")
1026
1027    provider.log.info(
1028        "Set provider Airplane Off, Wifi Off, Bluetooth Off, Data On.")
1029    toggle_airplane_mode(log, provider, False)
1030    provider.droid.telephonyToggleDataConnection(True)
1031    provider.log.info("Provider disable wifi")
1032    wifi_toggle_state(log, provider, False)
1033
1034    # Turn off active SoftAP if any.
1035    if provider.droid.wifiIsApEnabled():
1036        provider.log.info("Disable provider wifi tethering")
1037        stop_wifi_tethering(log, provider)
1038    provider.log.info("Provider disable bluetooth")
1039    disable_bluetooth(provider.droid)
1040    time.sleep(10)
1041
1042    for ad in clients:
1043        ad.log.info(
1044            "Set client Airplane Off, Wifi Off, Bluetooth Off, Data Off.")
1045        toggle_airplane_mode(log, ad, False)
1046        ad.log.info("Client disable data")
1047        ad.droid.telephonyToggleDataConnection(False)
1048        ad.log.info("Client disable bluetooth")
1049        disable_bluetooth(ad.droid)
1050        ad.log.info("Client disable wifi")
1051        wifi_toggle_state(log, ad, False)
1052
1053    if not wait_for_cell_data_connection(log, provider, True):
1054        provider.log.error(
1055            "Provider failed to enable data connection.")
1056        return False
1057
1058    time.sleep(10)
1059    log.info("Verify internet")
1060    if not test_internet_connection(log, provider, clients,
1061            client_status=False, provider_status=True):
1062        log.error("Internet connection check failed before tethering")
1063        return False
1064
1065    return True
1066
1067
1068def enable_bluetooth_tethering_connection(log, provider, clients):
1069    for ad in [provider] + clients:
1070        if not bluetooth_enabled_check(ad):
1071            ad.log.info("Bluetooth is not enabled")
1072            return False
1073        else:
1074            ad.log.info("Bluetooth is enabled")
1075    time.sleep(5)
1076    provider.log.info("Provider enabling bluetooth tethering")
1077    try:
1078        provider.droid.bluetoothPanSetBluetoothTethering(True)
1079    except Exception as e:
1080        provider.log.warning(
1081            "Failed to enable provider Bluetooth tethering with %s", e)
1082        provider.droid.bluetoothPanSetBluetoothTethering(True)
1083
1084    if wait_for_state(provider.droid.bluetoothPanIsTetheringOn, True):
1085        provider.log.info("Provider Bluetooth tethering is enabled.")
1086    else:
1087        provider.log.error(
1088            "Failed to enable provider Bluetooth tethering.")
1089        provider.log.error("bluetoothPanIsTetheringOn = %s",
1090                           provider.droid.bluetoothPanIsTetheringOn())
1091        return False
1092    for client in clients:
1093        if not (pair_pri_to_sec(provider, client)):
1094            client.log.error("Client failed to pair with provider")
1095            return False
1096        else:
1097            client.log.info("Client paired with provider")
1098
1099    time.sleep(5)
1100    for client in clients:
1101        client.droid.bluetoothConnectBonded(provider.droid.bluetoothGetLocalAddress())
1102
1103    time.sleep(20)
1104    return True
1105
1106
1107def verify_bluetooth_tethering_connection(log, provider, clients,
1108                                           change_rat=None,
1109                                           toggle_data=False,
1110                                           toggle_tethering=False,
1111                                           voice_call=False,
1112                                           toggle_bluetooth=True):
1113    """Setups up a bluetooth tethering connection between two android devices.
1114
1115    Returns:
1116        True if PAN connection and verification is successful,
1117        false if unsuccessful.
1118    """
1119
1120
1121    if not enable_bluetooth_tethering_connection(log, provider, clients):
1122        return False
1123
1124    if not test_internet_connection(log, provider, clients):
1125        log.error("Internet connection check failed")
1126        return False
1127    if voice_call:
1128        log.info("====== Voice call test =====")
1129        for caller, callee in [(provider, clients[0]),
1130                               (clients[0], provider)]:
1131            if not call_setup_teardown(
1132                    log, caller, callee, ad_hangup=None):
1133                log.error("Setup Call Failed.")
1134                hangup_call(log, caller)
1135                return False
1136            log.info("Verify data.")
1137            if not verify_internet_connection(
1138                    log, clients[0], retries=1):
1139                clients[0].log.warning(
1140                    "client internet connection state is not on")
1141            else:
1142                clients[0].log.info(
1143                    "client internet connection state is on")
1144            hangup_call(log, caller)
1145            if not verify_internet_connection(
1146                    log, clients[0], retries=1):
1147                clients[0].log.warning(
1148                    "client internet connection state is not on")
1149                return False
1150            else:
1151                clients[0].log.info(
1152                    "client internet connection state is on")
1153    if toggle_tethering:
1154        log.info("====== Toggling provider bluetooth tethering =====")
1155        provider.log.info("Disable bluetooth tethering")
1156        provider.droid.bluetoothPanSetBluetoothTethering(False)
1157        if not test_internet_connection(log, provider, clients, False, True):
1158            log.error(
1159                "Internet connection check failed after disable tethering")
1160            return False
1161        provider.log.info("Enable bluetooth tethering")
1162        if not enable_bluetooth_tethering_connection(log,
1163                provider, clients):
1164            provider.log.error(
1165                "Fail to re-enable bluetooth tethering")
1166            return False
1167        if not test_internet_connection(log, provider, clients, True, True):
1168            log.error(
1169                "Internet connection check failed after enable tethering")
1170            return False
1171    if toggle_bluetooth:
1172        log.info("====== Toggling provider bluetooth =====")
1173        provider.log.info("Disable provider bluetooth")
1174        disable_bluetooth(provider.droid)
1175        time.sleep(10)
1176        if not test_internet_connection(log, provider, clients, False, True):
1177            log.error(
1178                "Internet connection check failed after disable bluetooth")
1179            return False
1180        if not enable_bluetooth_tethering_connection(log,
1181                provider, clients):
1182            provider.log.error(
1183                "Fail to re-enable bluetooth tethering")
1184            return False
1185        if not test_internet_connection(log, provider, clients, True, True):
1186            log.error(
1187                "Internet connection check failed after enable bluetooth")
1188            return False
1189    if toggle_data:
1190        log.info("===== Toggling provider data connection =====")
1191        provider.log.info("Disable provider data connection")
1192        provider.droid.telephonyToggleDataConnection(False)
1193        time.sleep(10)
1194        if not test_internet_connection(log, provider, clients, False, False):
1195            return False
1196        provider.log.info("Enable provider data connection")
1197        provider.droid.telephonyToggleDataConnection(True)
1198        if not wait_for_cell_data_connection(log, provider,
1199                                             True):
1200            provider.log.error(
1201                "Provider failed to enable data connection.")
1202            return False
1203        if not test_internet_connection(log, provider, clients, True, True):
1204            log.error(
1205                "Internet connection check failed after enable data")
1206            return False
1207    if change_rat:
1208        log.info("===== Change provider RAT to %s =====", change_rat)
1209        if not ensure_network_generation(
1210                log,
1211                provider,
1212                change_rat,
1213                voice_or_data=NETWORK_SERVICE_DATA,
1214                toggle_apm_after_setting=False):
1215            provider.log.error("Provider failed to reselect to %s.",
1216                                    change_rat)
1217            return False
1218        if not test_internet_connection(log, provider, clients, True, True):
1219            log.error(
1220                "Internet connection check failed after RAT change to %s",
1221                change_rat)
1222            return False
1223    return True
1224
1225
1226def test_tethering_wifi_and_voice_call(log, provider, clients,
1227                                        provider_data_rat,
1228                                        provider_setup_func,
1229                                        provider_in_call_check_func,
1230                                        sa_5g=False):
1231
1232    if not test_setup_tethering(log, provider, clients, provider_data_rat):
1233        log.error("Verify 4G Internet access failed.")
1234        return False
1235
1236    tasks = [(provider_setup_func, (log, provider)),
1237             (phone_setup_voice_general, (log, clients[0]))]
1238    if not multithread_func(log, tasks):
1239        log.error("Phone Failed to Set Up VoLTE.")
1240        return False
1241
1242    if provider_setup_func == RAT_5G:
1243        if not provision_device_for_5g(log, provider, sa_5g):
1244            return False
1245    try:
1246        log.info("1. Setup WiFi Tethering.")
1247        if not wifi_tethering_setup_teardown(
1248                log,
1249                provider, [clients[0]],
1250                ap_band=WIFI_CONFIG_APBAND_2G,
1251                check_interval=10,
1252                check_iteration=2,
1253                do_cleanup=False):
1254            log.error("WiFi Tethering failed.")
1255            return False
1256        log.info("2. Make outgoing call.")
1257        if not call_setup_teardown(
1258                log,
1259                provider,
1260                clients[0],
1261                ad_hangup=None,
1262                verify_caller_func=provider_in_call_check_func):
1263            log.error("Setup Call Failed.")
1264            return False
1265        log.info("3. Verify data.")
1266        if not verify_internet_connection(log, provider):
1267            provider.log.error("Provider have no Internet access.")
1268        if not verify_internet_connection(log, clients[0]):
1269            clients[0].log.error("Client have no Internet access.")
1270        hangup_call(log, provider)
1271        time.sleep(WAIT_TIME_BETWEEN_REG_AND_CALL)
1272
1273        log.info("4. Make incoming call.")
1274        if not call_setup_teardown(
1275                log,
1276                clients[0],
1277                provider,
1278                ad_hangup=None,
1279                verify_callee_func=provider_in_call_check_func):
1280            log.error("Setup Call Failed.")
1281            return False
1282        log.info("5. Verify data.")
1283        if not verify_internet_connection(log, provider):
1284            provider.log.error("Provider have no Internet access.")
1285        if not verify_internet_connection(log, clients[0]):
1286            clients[0].log.error("Client have no Internet access.")
1287        hangup_call(log, provider)
1288
1289    finally:
1290        if not wifi_tethering_cleanup(log, provider, clients):
1291            return False
1292    return True
1293
1294
1295def test_wifi_connect_disconnect(log, ad, wifi_network_ssid=None, wifi_network_pass=None):
1296    """Perform multiple connects and disconnects from WiFi and verify that
1297        data switches between WiFi and Cell.
1298
1299    Steps:
1300    1. Reset Wifi on DUT
1301    2. Connect DUT to a WiFi AP
1302    3. Repeat steps 1-2, alternately disconnecting and disabling wifi
1303
1304    Expected Results:
1305    1. Verify Data on Cell
1306    2. Verify Data on Wifi
1307
1308    Returns:
1309        True if success.
1310        False if failed.
1311    """
1312
1313    wifi_toggles = [
1314        True, False, True, False, False, True, False, False, False, False,
1315        True, False, False, False, False, False, False, False, False
1316    ]
1317
1318    for toggle in wifi_toggles:
1319
1320        wifi_reset(log, ad, toggle)
1321
1322        if not wait_for_cell_data_connection(
1323                log, ad, True, MAX_WAIT_TIME_WIFI_CONNECTION):
1324            log.error("Failed wifi connection, aborting!")
1325            return False
1326
1327        if not verify_internet_connection(log, ad):
1328            log.error("Failed to get user-plane traffic, aborting!")
1329            return False
1330
1331        if toggle:
1332            wifi_toggle_state(log, ad, True)
1333
1334        ensure_wifi_connected(log, ad, wifi_network_ssid,
1335                     wifi_network_pass)
1336
1337        if not wait_for_wifi_data_connection(
1338                log, ad, True, MAX_WAIT_TIME_WIFI_CONNECTION):
1339            log.error("Failed wifi connection, aborting!")
1340            return False
1341
1342        if not verify_http_connection(
1343                log, ad, 'http://www.google.com', 100, .1):
1344            log.error("Failed to get user-plane traffic, aborting!")
1345            return False
1346    return True
1347
1348
1349def test_call_setup_in_active_data_transfer(
1350        log,
1351        ads,
1352        nw_gen=None,
1353        call_direction=DIRECTION_MOBILE_ORIGINATED,
1354        allow_data_transfer_interruption=False,
1355        sa_5g=False):
1356    """Test call can be established during active data connection.
1357
1358    Turn off airplane mode, disable WiFi, enable Cellular Data.
1359    Make sure phone in <nw_gen>.
1360    Starting downloading file from Internet.
1361    Initiate a voice call. Verify call can be established.
1362    Hangup Voice Call, verify file is downloaded successfully.
1363    Note: file download will be suspended when call is initiated if voice
1364          is using voice channel and voice channel and data channel are
1365          on different RATs.
1366    Args:
1367        log: log object.
1368        ads: list of android objects, this list should have two ad.
1369        nw_gen: network generation.
1370        call_direction: MO(DIRECTION_MOBILE_ORIGINATED) or MT(DIRECTION_MOBILE_TERMINATED) call.
1371        allow_data_transfer_interruption: if allow to interrupt data transfer.
1372
1373    Returns:
1374        True if success.
1375        False if failed.
1376    """
1377
1378    def _call_setup_teardown(log, ad_caller, ad_callee, ad_hangup,
1379                             caller_verifier, callee_verifier,
1380                             wait_time_in_call):
1381        # wait time for active data transfer
1382        time.sleep(5)
1383        return call_setup_teardown(log, ad_caller, ad_callee, ad_hangup,
1384                                   caller_verifier, callee_verifier,
1385                                   wait_time_in_call)
1386
1387    if nw_gen == GEN_5G:
1388        if not provision_device_for_5g(log, ads[0], sa_5g):
1389            return False
1390    elif nw_gen:
1391        if not ensure_network_generation(log, ads[0], nw_gen,
1392                                         MAX_WAIT_TIME_NW_SELECTION,
1393                                         NETWORK_SERVICE_DATA):
1394            ads[0].log.error("Device failed to reselect in %s.",
1395                             MAX_WAIT_TIME_NW_SELECTION)
1396            return False
1397
1398        ads[0].droid.telephonyToggleDataConnection(True)
1399        if not wait_for_cell_data_connection(log, ads[0], True):
1400            ads[0].log.error("Data connection is not on cell")
1401            return False
1402    else:
1403        ads[0].log.debug("Skipping network generation since it is None")
1404
1405    if not verify_internet_connection(log, ads[0]):
1406        ads[0].log.error("Internet connection is not available")
1407        return False
1408
1409    if call_direction == DIRECTION_MOBILE_ORIGINATED:
1410        ad_caller = ads[0]
1411        ad_callee = ads[1]
1412    else:
1413        ad_caller = ads[1]
1414        ad_callee = ads[0]
1415    ad_download = ads[0]
1416
1417    start_youtube_video(ad_download)
1418    call_task = (_call_setup_teardown, (log, ad_caller, ad_callee,
1419                                        ad_caller, None, None, 30))
1420    download_task = active_file_download_task(log, ad_download)
1421    results = run_multithread_func(log, [download_task, call_task])
1422    if wait_for_state(ad_download.droid.audioIsMusicActive, True, 15, 1):
1423        ad_download.log.info("After call hangup, audio is back to music")
1424    else:
1425        ad_download.log.warning(
1426            "After call hang up, audio is not back to music")
1427    ad_download.force_stop_apk("com.google.android.youtube")
1428    if not results[1]:
1429        log.error("Call setup failed in active data transfer.")
1430    if results[0]:
1431        ad_download.log.info("Data transfer succeeded.")
1432    elif not allow_data_transfer_interruption:
1433        ad_download.log.error(
1434            "Data transfer failed with parallel phone call.")
1435        return False
1436    else:
1437        ad_download.log.info("Retry data connection after call hung up")
1438        if not verify_internet_connection(log, ad_download):
1439            ad_download.log.error("Internet connection is not available")
1440            return False
1441    # Disable airplane mode if test under apm on.
1442    toggle_airplane_mode(log, ads[0], False)
1443    if nw_gen == GEN_5G and not check_current_network_5g(ads[0], sa_5g):
1444        ads[0].log.error("Phone not attached on 5G after call.")
1445        return False
1446    return True
1447
1448
1449def test_call_setup_in_active_youtube_video(
1450        log,
1451        ads,
1452        nw_gen=None,
1453        call_direction=DIRECTION_MOBILE_ORIGINATED,
1454        allow_data_transfer_interruption=False,
1455        sa_5g=False):
1456    """Test call can be established during active data connection.
1457
1458    Turn off airplane mode, disable WiFi, enable Cellular Data.
1459    Make sure phone in <nw_gen>.
1460    Starting playing youtube video.
1461    Initiate a voice call. Verify call can be established.
1462    Args:
1463        log: log object.
1464        ads: list of android objects, this list should have two ad.
1465        nw_gen: network generation.
1466        call_direction: MO(DIRECTION_MOBILE_ORIGINATED) or MT(DIRECTION_MOBILE_TERMINATED) call.
1467        allow_data_transfer_interruption: if allow to interrupt data transfer.
1468
1469    Returns:
1470        True if success.
1471        False if failed.
1472    """
1473    if nw_gen == GEN_5G:
1474        if not provision_device_for_5g(log, ads[0], sa_5g):
1475            return False
1476    elif nw_gen:
1477        if not ensure_network_generation(log, ads[0], nw_gen,
1478                                         MAX_WAIT_TIME_NW_SELECTION,
1479                                         NETWORK_SERVICE_DATA):
1480            ads[0].log.error("Device failed to reselect in %s.",
1481                             MAX_WAIT_TIME_NW_SELECTION)
1482            return False
1483        ads[0].droid.telephonyToggleDataConnection(True)
1484        if not wait_for_cell_data_connection(log, ads[0], True):
1485            ads[0].log.error("Data connection is not on cell")
1486            return False
1487    else:
1488        ensure_phones_default_state(log, ads)
1489
1490    if not verify_internet_connection(log, ads[0]):
1491        ads[0].log.error("Internet connection is not available")
1492        return False
1493
1494    if call_direction == DIRECTION_MOBILE_ORIGINATED:
1495        ad_caller = ads[0]
1496        ad_callee = ads[1]
1497    else:
1498        ad_caller = ads[1]
1499        ad_callee = ads[0]
1500    ad_download = ads[0]
1501
1502    if not start_youtube_video(ad_download):
1503        ad_download.log.warning("Fail to bring up youtube video")
1504
1505    if not call_setup_teardown(log, ad_caller, ad_callee, ad_caller,
1506                               None, None, 30):
1507        ad_download.log.error("Call setup failed in active youtube video")
1508        result = False
1509    else:
1510        ad_download.log.info("Call setup succeed in active youtube video")
1511        result = True
1512
1513    if wait_for_state(ad_download.droid.audioIsMusicActive, True, 15, 1):
1514        ad_download.log.info("After call hangup, audio is back to music")
1515    else:
1516        ad_download.log.warning(
1517                "After call hang up, audio is not back to music")
1518    ad_download.force_stop_apk("com.google.android.youtube")
1519    # Disable airplane mode if test under apm on.
1520    toggle_airplane_mode(log, ads[0], False)
1521    if nw_gen == GEN_5G and not check_current_network_5g(ads[0], sa_5g):
1522        ads[0].log.error("Phone not attached on 5G after call.")
1523        result = False
1524    return result
1525
1526
1527def call_epdg_to_epdg_wfc(log,
1528                          ads,
1529                          apm_mode,
1530                          wfc_mode,
1531                          wifi_ssid,
1532                          wifi_pwd,
1533                          nw_gen=None,
1534                          sa_5g=False):
1535    """ Test epdg<->epdg call functionality.
1536
1537    Make Sure PhoneA is set to make epdg call.
1538    Make Sure PhoneB is set to make epdg call.
1539    Call from PhoneA to PhoneB, accept on PhoneB, hang up on PhoneA.
1540    Call from PhoneA to PhoneB, accept on PhoneB, hang up on PhoneB.
1541
1542    Args:
1543        log: log object.
1544        ads: list of android objects, this list should have two ad.
1545        apm_mode: phones' airplane mode.
1546            if True, phones are in airplane mode during test.
1547            if False, phones are not in airplane mode during test.
1548        wfc_mode: phones' wfc mode.
1549            Valid mode includes: WFC_MODE_WIFI_ONLY, WFC_MODE_CELLULAR_PREFERRED,
1550            WFC_MODE_WIFI_PREFERRED, WFC_MODE_DISABLED.
1551        wifi_ssid: WiFi ssid to connect during test.
1552        wifi_pwd: WiFi password.
1553        nw_gen: network generation.
1554
1555    Returns:
1556        True if pass; False if fail.
1557    """
1558    DEFAULT_PING_DURATION = 120
1559
1560    if nw_gen == GEN_5G:
1561        # Turn off apm first before setting network preferred mode to 5G NSA.
1562        log.info("Turn off APM mode before starting testing.")
1563        tasks = [(toggle_airplane_mode, (log, ads[0], False)),
1564                 (toggle_airplane_mode, (log, ads[1], False))]
1565        if not multithread_func(log, tasks):
1566            log.error("Failed to turn off airplane mode")
1567            return False
1568        if not provision_device_for_5g(log, ad, sa_5g):
1569            return False
1570
1571    tasks = [(phone_setup_iwlan, (log, ads[0], apm_mode, wfc_mode,
1572                                  wifi_ssid, wifi_pwd)),
1573             (phone_setup_iwlan, (log, ads[1], apm_mode, wfc_mode,
1574                                  wifi_ssid, wifi_pwd))]
1575    if not multithread_func(log, tasks):
1576        log.error("Phone Failed to Set Up Properly.")
1577        return False
1578
1579    ad_ping = ads[0]
1580
1581    call_task = (two_phone_call_short_seq,
1582                 (log, ads[0], phone_idle_iwlan,
1583                  is_phone_in_call_iwlan, ads[1], phone_idle_iwlan,
1584                  is_phone_in_call_iwlan, None, WAIT_TIME_IN_CALL_FOR_IMS))
1585    ping_task = (adb_shell_ping, (ad_ping, DEFAULT_PING_DURATION))
1586
1587    results = run_multithread_func(log, [ping_task, call_task])
1588
1589    time.sleep(WAIT_TIME_ANDROID_STATE_SETTLING)
1590
1591    if nw_gen == GEN_5G and not verify_5g_attach_for_both_devices(log, ads, sa_5g):
1592        log.error("Phone not attached on 5G after epdg call.")
1593        return False
1594
1595    if not results[1]:
1596        log.error("Call setup failed in active ICMP transfer.")
1597    if results[0]:
1598        log.info("ICMP transfer succeeded with parallel phone call.")
1599    else:
1600        log.error("ICMP transfer failed with parallel phone call.")
1601    return all(results)
1602
1603
1604def verify_toggle_apm_tethering_internet_connection(log, provider, clients, ssid):
1605    """ Verify internet connection by toggling apm during wifi tethering.
1606    Args:
1607        log: log object.
1608        provider: android object provide WiFi tethering.
1609        clients: a list of clients using tethered WiFi.
1610        ssid: use this string as WiFi SSID to setup tethered WiFi network.
1611
1612    """
1613    if not provider.droid.wifiIsApEnabled():
1614        log.error("Provider WiFi tethering stopped.")
1615        return False
1616
1617    log.info(
1618        "Provider turn on APM, verify no wifi/data on Client.")
1619
1620    if not toggle_airplane_mode(log, provider, True):
1621        log.error("Provider turn on APM failed.")
1622        return False
1623    time.sleep(WAIT_TIME_DATA_STATUS_CHANGE_DURING_WIFI_TETHERING)
1624
1625    if provider.droid.wifiIsApEnabled():
1626        provider.log.error("Provider WiFi tethering not stopped.")
1627        return False
1628
1629    if not verify_internet_connection(log, clients[0], expected_state=False):
1630        clients[0].log.error(
1631            "Client should not have Internet connection.")
1632        return False
1633
1634    wifi_info = clients[0].droid.wifiGetConnectionInfo()
1635    clients[0].log.info("WiFi Info: {}".format(wifi_info))
1636    if wifi_info[WIFI_SSID_KEY] == ssid:
1637        clients[0].log.error(
1638            "WiFi error. WiFi should not be connected.".format(
1639                wifi_info))
1640        return False
1641
1642    log.info("Provider turn off APM.")
1643    if not toggle_airplane_mode(log, provider, False):
1644        provider.log.error("Provider turn on APM failed.")
1645        return False
1646    time.sleep(WAIT_TIME_DATA_STATUS_CHANGE_DURING_WIFI_TETHERING)
1647    if provider.droid.wifiIsApEnabled():
1648        provider.log.error(
1649            "Provider WiFi tethering should not on.")
1650        return False
1651    if not verify_internet_connection(log, provider):
1652        provider.log.error(
1653            "Provider should have Internet connection.")
1654        return False
1655    return True
1656
1657
1658def verify_tethering_entitlement_check(log, provider):
1659    """Tethering Entitlement Check Test
1660
1661    Get tethering entitlement check result.
1662    Args:
1663        log: log object.
1664        provider: android object provide WiFi tethering.
1665
1666    Returns:
1667        True if entitlement check returns True.
1668    """
1669    if (not wait_for_cell_data_connection(log, provider, True)
1670            or not verify_internet_connection(log, provider)):
1671        log.error("Failed cell data call for entitlement check.")
1672        return False
1673
1674    result = provider.droid.carrierConfigIsTetheringModeAllowed(
1675        TETHERING_MODE_WIFI, MAX_WAIT_TIME_TETHERING_ENTITLEMENT_CHECK)
1676    provider.log.info("Tethering entitlement check result: %s",
1677                      result)
1678    return result
1679
1680
1681def test_wifi_tethering(log, provider,
1682                        clients,
1683                        clients_tethering,
1684                        nw_gen,
1685                        ap_band=WIFI_CONFIG_APBAND_2G,
1686                        check_interval=30,
1687                        check_iteration=4,
1688                        do_cleanup=True,
1689                        ssid=None,
1690                        password=None,
1691                        pre_teardown_func=None):
1692    """WiFi Tethering test
1693    Args:
1694        log: log object.
1695        provider: android object provide WiFi tethering.
1696        clients: a list of clients are valid for tethered WiFi.
1697        clients_tethering: a list of clients using tethered WiFi.
1698        nw_gen: network generation.
1699        ap_band: setup WiFi tethering on 2G or 5G.
1700            This is optional, default value is WIFI_CONFIG_APBAND_2G
1701        check_interval: delay time between each around of Internet connection check.
1702            This is optional, default value is 30 (seconds).
1703        check_iteration: check Internet connection for how many times in total.
1704            This is optional, default value is 4 (4 times).
1705        do_cleanup: after WiFi tethering test, do clean up to tear down tethering
1706            setup or not. This is optional, default value is True.
1707        ssid: use this string as WiFi SSID to setup tethered WiFi network.
1708            This is optional. Default value is None.
1709            If it's None, a random string will be generated.
1710        password: use this string as WiFi password to setup tethered WiFi network.
1711            This is optional. Default value is None.
1712            If it's None, a random string will be generated.
1713        pre_teardown_func: execute custom actions between tethering setup adn teardown.
1714
1715    """
1716    if not test_setup_tethering(log, provider, clients, nw_gen):
1717        log.error("Verify %s Internet access failed.", nw_gen)
1718        return False
1719
1720    if pre_teardown_func:
1721        if not pre_teardown_func():
1722            return False
1723
1724    return wifi_tethering_setup_teardown(
1725        log,
1726        provider,
1727        clients_tethering,
1728        ap_band=ap_band,
1729        check_interval=check_interval,
1730        check_iteration=check_iteration,
1731        do_cleanup=do_cleanup,
1732        ssid=ssid,
1733        password=password)
1734
1735
1736def run_stress_test(log,
1737                    stress_test_number,
1738                    precondition_func=None,
1739                    test_case_func=None):
1740    """Run stress test of a test case.
1741
1742    Args:
1743        log: log object.
1744        stress_test_number: The number of times the test case is run.
1745        precondition_func: A function performing set up before running test case
1746        test_case_func: A test case function.
1747
1748    Returns:
1749        True stress pass rate is higher than MINIMUM_SUCCESS_RATE.
1750        False otherwise.
1751
1752    """
1753    MINIMUM_SUCCESS_RATE = .95
1754    success_count = 0
1755    fail_count = 0
1756    for i in range(1, stress_test_number + 1):
1757        if precondition_func:
1758            precondition_func()
1759        if test_case_func:
1760            result = test_case_func()
1761        if result:
1762            success_count += 1
1763            result_str = "Succeeded"
1764        else:
1765            fail_count += 1
1766            result_str = "Failed"
1767        log.info("Iteration {} {}. Current: {} / {} passed.".format(
1768            i, result_str, success_count, stress_test_number))
1769
1770    log.info("Final Count - Success: {}, Failure: {} - {}%".format(
1771        success_count, fail_count,
1772        str(100 * success_count / (success_count + fail_count))))
1773    if success_count / (
1774            success_count + fail_count) >= MINIMUM_SUCCESS_RATE:
1775        return True
1776    else:
1777        return False
1778
1779
1780def test_start_wifi_tethering_connect_teardown(log,
1781                                               ad_host,
1782                                               ad_client,
1783                                               ssid,
1784                                               password):
1785    """Private test util for WiFi Tethering.
1786
1787    1. Host start WiFi tethering.
1788    2. Client connect to tethered WiFi.
1789    3. Host tear down WiFi tethering.
1790
1791    Args:
1792        log: log object.
1793        ad_host: android device object for host
1794        ad_client: android device object for client
1795        ssid: WiFi tethering ssid
1796        password: WiFi tethering password
1797
1798    Returns:
1799        True if pass, otherwise False.
1800    """
1801    result = True
1802    # Turn off active SoftAP if any.
1803    if ad_host.droid.wifiIsApEnabled():
1804        stop_wifi_tethering(log, ad_host)
1805
1806    time.sleep(WAIT_TIME_ANDROID_STATE_SETTLING)
1807    if not start_wifi_tethering(log, ad_host, ssid, password,
1808                                WIFI_CONFIG_APBAND_2G):
1809        log.error("Start WiFi tethering failed.")
1810        result = False
1811    time.sleep(WAIT_TIME_ANDROID_STATE_SETTLING)
1812    if not ensure_wifi_connected(log, ad_client, ssid, password):
1813        log.error("Client connect to WiFi failed.")
1814        result = False
1815    if not wifi_reset(log, ad_client):
1816        log.error("Reset client WiFi failed. {}".format(
1817            ad_client.serial))
1818        result = False
1819    if not stop_wifi_tethering(log, ad_host):
1820        log.error("Stop WiFi tethering failed.")
1821        result = False
1822    return result
1823
1824
1825def verify_wifi_tethering_when_reboot(log,
1826                                      provider,
1827                                      post_reboot_func=None):
1828    """ Verify wifi tethering when reboot.
1829
1830    Verify wifi tethering is enabled before reboot and disabled
1831    after reboot, and execute additional custom actions verification
1832    of wifi tethering.
1833
1834    Args:
1835        log: log object.
1836        provider: android object provide WiFi tethering.
1837        post_reboot_func: execute custom actions after reboot.
1838    Returns:
1839        True if pass, otherwise False.
1840
1841    """
1842    if not provider.droid.wifiIsApEnabled():
1843        log.error("Provider WiFi tethering stopped.")
1844        return False
1845
1846    provider.log.info("Reboot provider")
1847    provider.reboot()
1848    time.sleep(
1849        WAIT_TIME_AFTER_REBOOT + WAIT_TIME_TETHERING_AFTER_REBOOT)
1850
1851    log.info("After reboot check if tethering stopped.")
1852    if provider.droid.wifiIsApEnabled():
1853        log.error("Provider WiFi tethering did NOT stopped.")
1854        return False
1855    if post_reboot_func:
1856        post_reboot_func()
1857    return True
1858
1859
1860def setup_device_internet_connection(log,
1861                                     device,
1862                                     network_ssid,
1863                                     network_password):
1864    """Setup wifi network for device and verify internet connection.
1865    Args:
1866        log: log object.
1867        device: android device object.
1868        network_ssid: wifi network ssid.
1869        network_password: wifi network password.
1870    Returns:
1871        True if pass, otherwise False.
1872
1873    """
1874    log.info("Make sure DUT can connect to live network by WIFI")
1875    if ((not ensure_wifi_connected(log,
1876                                   device,
1877                                   network_ssid,
1878                                   network_password))
1879            or (not verify_internet_connection(log, device))):
1880        log.error("WiFi connect fail.")
1881        return False
1882    return True
1883
1884
1885def wait_and_verify_device_internet_connection(log,
1886                                               device):
1887    """Wait for device connecting to wifi network and verify internet connection.
1888    Args:
1889        log: log object.
1890        device: Android device object.
1891    Returns:
1892        True if pass, otherwise False.
1893
1894    """
1895    log.info("Make sure WiFi can connect automatically.")
1896    if (not wait_for_wifi_data_connection(log, device, True) or
1897            not verify_internet_connection(log, device)):
1898        log.error("Data did not return to WiFi")
1899        return False
1900    return True
1901
1902
1903def setup_device_internet_connection_then_reboot(log,
1904                                                 device,
1905                                                 network_ssid,
1906                                                 network_password):
1907    """Setup wifi network for device and verify internet connection, then reboot.
1908    Args:
1909        log: log object.
1910        device: android device object.
1911        network_ssid: wifi network ssid.
1912        network_password: wifi network password.
1913    Returns:
1914        True if pass, otherwise False.
1915
1916    """
1917    if not setup_device_internet_connection(log,
1918                                            device,
1919                                            network_ssid,
1920                                            network_password):
1921        return False
1922
1923    device.log.info("Reboot!")
1924    device.reboot()
1925    time.sleep(WAIT_TIME_AFTER_REBOOT)
1926    time.sleep(WAIT_TIME_TETHERING_AFTER_REBOOT)
1927    return True
1928
1929
1930def verify_internet_connection_in_doze_mode(log,
1931                                            provider,
1932                                            client):
1933    """Set provider in doze mode and verify client's internet connection.
1934    Args:
1935        log: log object.
1936        provider: android device object for provider.
1937        client: android device object for client.
1938    Returns:
1939        True if pass, otherwise False.
1940
1941    """
1942    try:
1943        if not provider.droid.wifiIsApEnabled():
1944            provider.log.error("Provider WiFi tethering stopped.")
1945            return False
1946        provider.log.info("Turn off screen on provider")
1947        provider.droid.goToSleepNow()
1948        time.sleep(60)
1949        if not verify_internet_connection(log, client):
1950            client.log.error("Client have no Internet access.")
1951            return False
1952
1953        provider.log.info("Enable doze mode on provider")
1954        if not enable_doze(provider):
1955            provider.log.error("Failed to enable doze mode.")
1956            return False
1957        time.sleep(60)
1958        if not verify_internet_connection(log, client):
1959            client.log.error("Client have no Internet access.")
1960            return False
1961    finally:
1962        log.info("Disable doze mode.")
1963        if not disable_doze(provider):
1964            log.error("Failed to disable doze mode.")
1965            return False
1966    return True
1967
1968
1969def test_wifi_cell_switching_in_call(log,
1970                                     ads,
1971                                     network_ssid,
1972                                     network_password,
1973                                     new_gen=None):
1974    """Test data connection network switching during voice call when phone on <nw_gen>
1975    Args:
1976        log: log object.
1977        ads: android device objects.
1978        network_ssid: wifi network ssid.
1979        network_password: wifi network password.
1980        new_gen: network generation.
1981    Returns:
1982        True if pass, otherwise False.
1983
1984    """
1985    result = True
1986    if not call_setup_teardown(log, ads[0], ads[1], None, None, None,
1987                               5):
1988        log.error("Call setup failed")
1989        return False
1990    else:
1991        log.info("Call setup succeed")
1992
1993    if not wifi_cell_switching(log,
1994                               ads[0],
1995                               new_gen,
1996                               network_ssid,
1997                               network_password):
1998        ads[0].log.error("Failed to do WIFI and Cell switch in call")
1999        result = False
2000
2001    if not is_phone_in_call_active(ads[0]):
2002        return False
2003    else:
2004        if not ads[0].droid.telecomCallGetAudioState():
2005            ads[0].log.error("Audio is not on call")
2006            result = False
2007        else:
2008            ads[0].log.info("Audio is on call")
2009        hangup_call(log, ads[0])
2010        return result
2011
2012
2013def verify_toggle_data_during_wifi_tethering(log,
2014                                             provider,
2015                                             clients,
2016                                             new_gen=None):
2017    """Verify toggle Data network during WiFi Tethering.
2018    Args:
2019        log: log object.
2020        provider: android device object for provider.
2021        clients: android device objects for clients.
2022        new_gen: network generation.
2023    Returns:
2024        True if pass, otherwise False.
2025
2026    """
2027    try:
2028        ssid = rand_ascii_str(10)
2029        if not test_wifi_tethering(log,
2030                                   provider,
2031                                   clients,
2032                                   [clients[0]],
2033                                   new_gen,
2034                                   WIFI_CONFIG_APBAND_2G,
2035                                   check_interval=10,
2036                                   check_iteration=2,
2037                                   do_cleanup=False,
2038                                   ssid=ssid):
2039            log.error("WiFi Tethering failed.")
2040            return False
2041        if not provider.droid.wifiIsApEnabled():
2042            provider.log.error("Provider WiFi tethering stopped.")
2043            return False
2044
2045        provider.log.info(
2046            "Disable Data on Provider, verify no data on Client.")
2047        provider.droid.telephonyToggleDataConnection(False)
2048        time.sleep(WAIT_TIME_DATA_STATUS_CHANGE_DURING_WIFI_TETHERING)
2049        if not verify_internet_connection(log, provider, expected_state=False):
2050            provider.log.error("Disable data on provider failed.")
2051            return False
2052        if not provider.droid.wifiIsApEnabled():
2053            provider.log.error("Provider WiFi tethering stopped.")
2054            return False
2055        if not check_is_wifi_connected(log, clients[0], ssid):
2056            clients[0].log.error("Client WiFi is not connected")
2057            return False
2058
2059        log.info(
2060            "Enable Data on Provider, verify data available on Client.")
2061        provider.droid.telephonyToggleDataConnection(True)
2062        if not wait_for_cell_data_connection(log, provider,
2063                                             True):
2064            provider.log.error(
2065                "Provider failed to enable data connection.")
2066            return False
2067        if not verify_internet_connection(log, provider):
2068            provider.log.error(
2069                "Provider internet connection check failed.")
2070            return False
2071        if not provider.droid.wifiIsApEnabled():
2072            provider.log.error("Provider WiFi tethering stopped.")
2073            return False
2074
2075        if not check_is_wifi_connected(log, clients[0], ssid) or (not verify_internet_connection(log, clients[0])):
2076            clients[0].log.error("Client wifi connection check failed!")
2077            return False
2078
2079    finally:
2080        if not wifi_tethering_cleanup(log,
2081                                      provider,
2082                                      clients):
2083            return False
2084    return True
2085