1#!/usr/bin/env python3.4
2#
3#   Copyright 2022 - The Android Open Source Project
4#
5#   Licensed under the Apache License, Version 2.0 (the "License");
6#   you may not use this file except in compliance with the License.
7#   You may obtain a copy of the License at
8#
9#       http://www.apache.org/licenses/LICENSE-2.0
10#
11#   Unless required by applicable law or agreed to in writing, software
12#   distributed under the License is distributed on an "AS IS" BASIS,
13#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14#   See the License for the specific language governing permissions and
15#   limitations under the License.
16
17import itertools
18import time
19
20from acts_contrib.test_utils.net import ui_utils as uutils
21import acts_contrib.test_utils.wifi.wifi_test_utils as wutils
22from acts_contrib.test_utils.wifi.WifiBaseTest import WifiBaseTest
23
24from acts import asserts
25from acts import signals
26from acts.test_decorators import test_tracker_info
27
28WifiEnums = wutils.WifiEnums
29
30DEFAULT_TIMEOUT = 15
31OSU_TEST_TIMEOUT = 300
32
33# Constants for providers.
34OSU_BOINGO = 0
35BOINGO = 1
36
37# Constants used for various device operations.
38
39UNKNOWN_FQDN = "@#@@!00fffffx"
40
41# Constants for Boingo UI automator
42EDIT_TEXT_CLASS_NAME = "android.widget.EditText"
43PASSWORD_TEXT = "Password"
44PASSPOINT_BUTTON = "Get Passpoint"
45
46
47class WifiPasspointLanguageTest(WifiBaseTest):
48    """Tests for APIs in Android's WifiManager class.
49
50    Test Bed Requirement:
51    * One Android device
52    * Several Wi-Fi networks visible to the device, including an open Wi-Fi
53      network.
54    """
55    BOINGO_UI_TEXT = {
56        'CHT': "線上註冊",
57        'FRA': "Inscription en ligne",
58        'US': "Online Sign Up",
59        'SPA': "Registro online",
60        'ARA': "الاشتراك على الإنترنت"
61    }
62
63    def setup_class(self):
64        super().setup_class()
65        self.dut = self.android_devices[0]
66        wutils.wifi_test_device_init(self.dut)
67        req_params = [
68            "passpoint_networks", "boingo_username", "boingo_password",
69            "osu_configs"
70        ]
71        self.unpack_userparams(req_param_names=req_params, )
72        asserts.assert_true(
73            len(self.passpoint_networks) > 0,
74            "Need at least one Passpoint network.")
75        wutils.wifi_toggle_state(self.dut, True)
76        self.unknown_fqdn = UNKNOWN_FQDN
77
78    def setup_test(self):
79        super().setup_test()
80        self.dut.droid.wakeLockAcquireBright()
81        self.dut.droid.wakeUpNow()
82        self.dut.unlock_screen()
83        self.dut.adb.shell("input keyevent KEYCODE_HOME")
84
85    def teardown_test(self):
86        super().teardown_test()
87        self.dut.droid.wakeLockRelease()
88        self.dut.droid.goToSleepNow()
89        passpoint_configs = self.dut.droid.getPasspointConfigs()
90        for config in passpoint_configs:
91            wutils.delete_passpoint(self.dut, config)
92        wutils.reset_wifi(self.dut)
93        self.language_change('US')
94
95    """Helper Functions"""
96
97    def install_passpoint_profile(self, passpoint_config):
98        """Install the Passpoint network Profile.
99
100        Args:
101            passpoint_config: A JSON dict of the Passpoint configuration.
102
103        """
104        asserts.assert_true(
105            WifiEnums.SSID_KEY in passpoint_config,
106            "Key '%s' must be present in network definition." %
107            WifiEnums.SSID_KEY)
108        # Install the Passpoint profile.
109        self.dut.droid.addUpdatePasspointConfig(passpoint_config)
110
111    def check_passpoint_connection(self, passpoint_network):
112        """Verify the device is automatically able to connect to the Passpoint
113           network.
114
115           Args:
116               passpoint_network: SSID of the Passpoint network.
117
118        """
119        ad = self.dut
120        ad.ed.clear_all_events()
121        try:
122            wutils.start_wifi_connection_scan_and_return_status(ad)
123            wutils.wait_for_connect(ad)
124        except:
125            pass
126        # Re-verify we are connected to the correct network.
127        network_info = self.dut.droid.wifiGetConnectionInfo()
128        self.log.info("Network Info: %s" % network_info)
129        if not network_info or not network_info[WifiEnums.SSID_KEY] or \
130            network_info[WifiEnums.SSID_KEY] not in passpoint_network:
131            raise signals.TestFailure(
132                "Device did not connect to passpoint network.")
133
134    def get_configured_passpoint_and_delete(self):
135        """Get configured Passpoint network and delete using its FQDN."""
136        passpoint_config = self.dut.droid.getPasspointConfigs()
137        if not len(passpoint_config):
138            raise signals.TestFailure("Failed to fetch the list of configured"
139                                      "passpoint networks.")
140        if not wutils.delete_passpoint(self.dut, passpoint_config[0]):
141            raise signals.TestFailure(
142                "Failed to delete Passpoint configuration"
143                " with FQDN = %s" % passpoint_config[0])
144
145    def language_change(self, lang):
146        """Run UI automator for boingo passpoint.
147
148        Args:
149            lang: For testing language.
150
151        """
152        langs = {
153            'CHT': "zh-TW",
154            'FRA': "fr-FR",
155            'US': "en-US",
156            'ARA': "ar-SA",
157            'SPA': "es-ES"
158        }
159        self.dut.ed.clear_all_events()
160        self.dut.adb.shell('settings put system system_locales %s ' %
161                           langs[lang])
162        self.dut.reboot()
163        time.sleep(DEFAULT_TIMEOUT)
164
165    def ui_automator_boingo(self, lang):
166        """Changing device language.
167
168        Args:
169            lang: For testing language.
170
171        """
172        # Verify the boingo login page shows
173        langtext = self.BOINGO_UI_TEXT[lang]
174        asserts.assert_true(uutils.has_element(self.dut, text=langtext),
175                            "Failed to launch boingohotspot login page")
176        # Go to the bottom of the page
177        for _ in range(3):
178            self.dut.adb.shell("input swipe 300 900 300 300")
179        time.sleep(5)
180        screen_dump = uutils.get_screen_dump_xml(self.dut)
181        nodes = screen_dump.getElementsByTagName("node")
182        index = 0
183        for node in nodes:
184            if uutils.match_node(node, class_name="android.widget.EditText"):
185                x, y = eval(node.attributes["bounds"].value.split("][")[0][1:])
186                self.dut.adb.shell("input tap %s %s" % (x, y))
187                time.sleep(2)
188                if index == 0:
189                    #stop the ime launch
190                    self.dut.adb.shell(
191                        "am force-stop com.google.android.inputmethod.latin")
192                    self.dut.adb.shell("input text %s" % self.boingo_username)
193                    index += 1
194                else:
195                    self.dut.adb.shell("input text %s" % self.boingo_password)
196                    break
197                self.dut.adb.shell("input keyevent 111")
198        self.dut.adb.shell("input keyevent 111")  # collapse keyboard
199        self.dut.adb.shell(
200            "input swipe 300 900 300 750")  # swipe up to show text
201
202        # Login
203        uutils.wait_and_click(self.dut, text=PASSPOINT_BUTTON)
204        time.sleep(DEFAULT_TIMEOUT)
205
206    def start_subscription_provisioning_language(self, lang):
207        """Start subscription provisioning with a default provider.
208
209        Args:
210            lang: For testing language.
211
212        """
213        self.language_change(lang)
214        self.unpack_userparams(('osu_configs', ))
215        asserts.assert_true(
216            len(self.osu_configs) > 0, "Need at least one osu config.")
217        osu_config = self.osu_configs[OSU_BOINGO]
218        # Clear all previous events.
219        self.dut.ed.clear_all_events()
220        self.dut.droid.startSubscriptionProvisioning(osu_config)
221        start_time = time.time()
222        while time.time() < start_time + OSU_TEST_TIMEOUT:
223            dut_event = self.dut.ed.pop_event("onProvisioningCallback",
224                                              DEFAULT_TIMEOUT * 18)
225            if dut_event['data']['tag'] == 'success':
226                self.log.info("Passpoint Provisioning Success")
227                break
228            if dut_event['data']['tag'] == 'failure':
229                raise signals.TestFailure(
230                    "Passpoint Provisioning is failed with %s" %
231                    dut_event['data']['reason'])
232                break
233            if dut_event['data']['tag'] == 'status':
234                self.log.info("Passpoint Provisioning status %s" %
235                              dut_event['data']['status'])
236                if int(dut_event['data']['status']) == 7:
237                    time.sleep(DEFAULT_TIMEOUT)
238                    self.ui_automator_boingo(lang)
239
240        # Clear all previous events.
241        self.dut.ed.clear_all_events()
242        # Verify device connects to the Passpoint network.
243        time.sleep(DEFAULT_TIMEOUT)
244        current_passpoint = self.dut.droid.wifiGetConnectionInfo()
245        if current_passpoint[
246                WifiEnums.SSID_KEY] not in osu_config["expected_ssids"]:
247            raise signals.TestFailure("Device did not connect to the %s"
248                                      " passpoint network" %
249                                      osu_config["expected_ssids"])
250        self.get_configured_passpoint_and_delete()
251        wutils.wait_for_disconnect(self.dut, timeout=15)
252
253    """Tests"""
254
255    @test_tracker_info(uuid="78a939e2-bddc-4bee-8e9d-75f4d953f9eb")
256    def test_passpoint_release_2_connectivity_language_ara(self):
257        """Changing the device's language to ARA(Arabic)
258        to connected passpoint
259
260        """
261
262        self.start_subscription_provisioning_language('ARA')
263
264    @test_tracker_info(uuid="e04ac983-1fe6-436b-a2e1-339c1d73cb95")
265    def test_passpoint_release_2_connectivity_language_cht(self):
266        """Changing the device's language to CHT(Chinese (Traditional))
267        to connected passpoint
268
269        """
270
271        self.start_subscription_provisioning_language('CHT')
272
273    @test_tracker_info(uuid="215452c8-f425-48ac-a057-6f67c2e84d9e")
274    def test_passpoint_release_2_connectivity_language_fra(self):
275        """Changing the device's language to FRA(French)
276        to connected passpoint
277
278        """
279
280        self.start_subscription_provisioning_language('FRA')
281
282    @test_tracker_info(uuid="b602c998-2d42-44bc-af4a-f4ee42febe65")
283    def test_passpoint_release_2_connectivity_language_spa(self):
284        """Changing the device's language to SPA(Spanish)
285        to connected passpoint
286
287        """
288
289        self.start_subscription_provisioning_language('SPA')
290