1/*
2 * Copyright (C) 2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from '@ohos/hypium'
17
18import wifi from '@ohos.wifi'
19import osaccount from '@ohos.account.osAccount'
20import bundle from '@ohos.bundle'
21import abilityAccessCtrl from '@ohos.abilityAccessCtrl'
22
23async function applyPermission() {
24    let osAccountManager = osaccount.getAccountManager();
25    console.info("=== getAccountManager finish");
26    let localId = await osAccountManager.getOsAccountLocalIdFromProcess();
27    console.info("LocalId is :" + localId);
28    let appInfo = await bundle.getApplicationInfo('ohos.acts.communication.wifi.wifidevice', 0, localId);
29    let atManager = abilityAccessCtrl.createAtManager();
30    if (atManager != null) {
31        let tokenID = appInfo.accessTokenId;
32        console.info('[permission] case accessTokenID is ' + tokenID);
33        let permissionName1 = 'ohos.permission.LOCATION';
34        await atManager.grantUserGrantedPermission(tokenID, permissionName1, 1).then((result) => {
35            console.info('[permission] case grantUserGrantedPermission success :' + JSON.stringify(result));
36        }).catch((err) => {
37            console.info('[permission] case grantUserGrantedPermission failed :' + JSON.stringify(err));
38        });
39    } else {
40        console.info('[permission] case apply permission failed, createAtManager failed');
41    }
42}
43
44function sleep(delay) {
45    return new Promise(resovle => setTimeout(resovle, delay))
46}
47
48function checkWifiPowerOn(){
49    console.info("[wifi_test]wifi status:" + wifi.isWifiActive());
50}
51
52export default function actsWifiEventTest() {
53    describe('actsWifiEventTest', function () {
54        beforeAll(async function (done) {
55            console.info('beforeAll case');
56            await applyPermission();
57            done();
58        })
59
60        beforeEach(function () {
61            console.info("[wifi_test]beforeEach start" );
62            checkWifiPowerOn();
63        })
64        afterEach(async function () {
65            console.info("[wifi_test]afterEach start" );
66        })
67
68        /**
69        * @tc.number Communication_WiFi_Event_Test_0008
70        * @tc.name testp2pStateChange
71        * @tc.desc Test p2pStateChange callback
72        * @tc.type Function
73        * @tc.level Level 3
74        */
75        it('Communication_WiFi_Event_Test_0008', 0, async function (done) {
76            let p2pState = "p2pStateChange";
77            let p2pStateChangeCallback = result => {
78                console.info("[wifi_test]p2pStateChange callback, result: " + JSON.stringify(result));
79            }
80            wifi.on(p2pState, p2pStateChangeCallback);
81            await sleep(3000);
82            wifi.off(p2pState, p2pStateChangeCallback);
83            done();
84        })
85
86        /**
87        * @tc.number Communication_WiFi_Event_Test_0009
88        * @tc.name testp2pConnectionChange
89        * @tc.desc Test p2pConnectionChange callback
90        * @tc.type Function
91        * @tc.level Level 3
92        */
93        it('Communication_WiFi_Event_Test_0009', 0, async function (done) {
94            let p2pConnectionState = "p2pConnectionChange";
95            let p2pConnectionChangeCallback = result => {
96                console.info("[wifi_test]p2pConnectionChange callback, result: " + JSON.stringify(result));
97            }
98            wifi.on(p2pConnectionState, p2pConnectionChangeCallback);
99            let wifiP2PConfig = {
100                deviceAddress : "22:9b:e6:48:1f:5c",
101                netId : -1,
102                passphrase : "12345678",
103                groupName : "DIRECT-AAAZZZ456",
104                goBand : wifi.GroupOwnerBand.GO_BAND_AUTO
105            };
106            let connectResult = wifi.p2pConnect(wifiP2PConfig);
107            console.info("[wifi_test]test p2pConnect result." + connectResult);
108            let p2pCancelResult = wifi.p2pCancelConnect();
109            await sleep(2000);
110            console.info("[wifi_test]test p2pCancelConnect result." + p2pCancelResult);
111            await wifi.getP2pLinkedInfo()
112                .then(data => {
113                    let resultLength = Object.keys(data).length;
114                    console.info("[wifi_test]getP2pLinkedInfo  promise result : " + JSON.stringify(data));
115                    expect(true).assertEqual(resultLength!=0);
116                    done()
117                });
118            await sleep(2000);
119            wifi.off(p2pConnectionState, p2pConnectionChangeCallback);
120            done();
121        })
122
123        /**
124        * @tc.number Communication_WiFi_Event_Test_0012
125        * @tc.name testp2pDeviceChange
126        * @tc.desc Test p2pDeviceChange callback
127        * @tc.type Function
128        * @tc.level Level 3
129        */
130        it('Communication_WiFi_Event_Test_0012', 0, async function (done) {
131            let p2pDeviceState = "p2pDeviceChange";
132            let p2pDeviceChangeCallback = result => {
133                console.info("[wifi_test]p2pDeviceChange callback, result: " + JSON.stringify(result));
134            }
135            wifi.on(p2pDeviceState, p2pDeviceChangeCallback);
136            await sleep(3000);
137            wifi.off(p2pDeviceState, p2pDeviceChangeCallback);
138            done();
139        })
140
141        /**
142        * @tc.number Communication_WiFi_Event_Test_0010
143        * @tc.name testp2pPeerDeviceChange
144        * @tc.desc Test p2pPeerDeviceChange callback
145        * @tc.type Function
146        * @tc.level Level 3
147        */
148        it('Communication_WiFi_Event_Test_0010', 0, async function (done) {
149            let p2pPeerDeviceState = "p2pPeerDeviceChange";
150            let p2pPeerDeviceChangeCallback = result => {
151                console.info("[wifi_test]p2pPeerDeviceChange callback, result: " + JSON.stringify(result));
152            }
153            wifi.on(p2pPeerDeviceState, p2pPeerDeviceChangeCallback);
154            let startDiscover = wifi.startDiscoverDevices();
155            await sleep(3000);
156            expect(startDiscover).assertTrue();
157            let stopDiscover = wifi.stopDiscoverDevices();
158            console.info("[wifi_test] test stopDiscoverDevices result." + stopDiscover);
159            wifi.off(p2pPeerDeviceState, p2pPeerDeviceChangeCallback);
160            done();
161        })
162
163        /**
164        * @tc.number Communication_WiFi_Event_Test_0013
165        * @tc.name testp2pPersistentGroupChange
166        * @tc.desc Test p2pPersistentGroupChange callback
167        * @tc.type Function
168        * @tc.level Level 3
169        */
170        it('Communication_WiFi_Event_Test_0013', 0, async function (done) {
171            let p2pGroupState = "p2pPersistentGroupChange";
172            let p2pPersistentGroupChangeCallback = () => {
173                console.info("[wifi_test]p2pPersistentGroupChange callback, result: " + JSON.stringify(result));
174            }
175            wifi.on(p2pGroupState, p2pPersistentGroupChangeCallback);
176            let WifiP2PConfig = {
177                deviceAddress : "22:9b:e6:48:1f:5c",
178                netId : -2,
179                passphrase : "12345678",
180                groupName : "DIRECT-AAAZZZ123",
181                goBand : wifi.GroupOwnerBand.GO_BAND_AUTO,
182            };
183            try {
184                await wifi.getCurrentGroup()
185                    .then(data => {
186                        let resultLength = Object.keys(data).length;
187                        console.info("[wifi_test] getCurrentGroup  promise result -> " + JSON.stringify(data));
188                        expect(true).assertEqual(resultLength!=0);
189                    }).catch((error) => {
190                        console.error('[wifi_test] getCurrentGroup  promise failed :' + JSON.stringify(error));
191                        expect(true).assertEqual(error !=null);
192                    });
193            }catch(error){
194                console.info("[wifi_test]getCurrentGroup promise error: " + JSON.stringify(error.message));
195                expect(true).assertEqual( (JSON.stringify(error.message)) !=null);
196            }
197            wifi.off(p2pGroupState, p2pPersistentGroupChangeCallback);
198            done();
199        })
200
201        /**
202        * @tc.number Communication_WiFi_Event_Test_0011
203        * @tc.name testpp2pDiscoveryChange
204        * @tc.desc Test p2pDiscoveryChange callback
205        * @tc.type Function
206        * @tc.level Level 3
207        */
208        it('Communication_WiFi_Event_Test_0011', 0, async function (done) {
209            let p2pPeerDeviceState = "p2pDiscoveryChange";
210            let p2pDiscoveryChangeCallback = result => {
211                console.info("[wifi_test]p2pDiscoveryChange callback, result: " + JSON.stringify(result));
212            }
213            wifi.on(p2pPeerDeviceState, p2pDiscoveryChangeCallback);
214            let startDiscover = wifi.startDiscoverDevices();
215            await sleep(3000);
216            expect(startDiscover).assertTrue();
217            let stopDiscover = wifi.stopDiscoverDevices();
218            console.info("[wifi_test] test stopDiscoverDevices result." + stopDiscover);
219            wifi.off(p2pPeerDeviceState, p2pDiscoveryChangeCallback);
220            done();
221        })
222        console.log("*************[wifi_test] start wifi js unit test end*************");
223    })
224}
225
226