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 */
15import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index'
16import data_rdb from '@ohos.data.rdb'
17import ability_featureAbility from '@ohos.ability.featureAbility'
18
19const TAG = "[RDB_JSKITS_TEST]"
20const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" +
21                          "id INTEGER PRIMARY KEY AUTOINCREMENT, " +
22                          "name TEXT NOT NULL, age INTEGER, salary REAL, blobType BLOB)"
23
24let context = null;
25const STORE_CONFIG_ENCRYPT = {
26    name: "Encrypt.db",
27    encrypt: true,
28}
29const STORE_CONFIG_ENCRYPT2 = {
30    name: "Encrypt2.db",
31    encrypt: true,
32}
33const STORE_CONFIG_UNENCRYPT = {
34    name: "Unencrypt.db",
35    encrypt: false,
36}
37const STORE_CONFIG_WRONG = {
38    name: "Encrypt.db",
39    encrypt: false,
40}
41
42async function CreateRdbStore(context, STORE_CONFIG) {
43    let rdbStore = await data_rdb.getRdbStore(context, STORE_CONFIG, 1)
44    await rdbStore.executeSql(CREATE_TABLE_TEST, null)
45    let u8 = new Uint8Array([1, 2, 3])
46    {
47        const valueBucket = {
48            "name": "zhangsan",
49            "age": 18,
50            "salary": 100.5,
51            "blobType": u8,
52        }
53        await rdbStore.insert("test", valueBucket)
54    }
55    {
56        const valueBucket = {
57            "name": "lisi",
58            "age": 28,
59            "salary": 100.5,
60            "blobType": u8,
61        }
62        await rdbStore.insert("test", valueBucket)
63    }
64    {
65        const valueBucket = {
66            "name": "wangwu",
67            "age": 38,
68            "salary": 90.0,
69            "blobType": u8,
70        }
71        await rdbStore.insert("test", valueBucket)
72    }
73    return rdbStore
74}
75
76describe('rdbEncryptTest', function () {
77    beforeAll(async function () {
78        console.info(TAG + 'beforeAll')
79    })
80
81    beforeEach(async function () {
82        console.info(TAG + 'beforeEach')
83    })
84
85    afterEach(async function () {
86        console.info(TAG + 'afterEach')
87        await data_rdb.deleteRdbStore(context, STORE_CONFIG_ENCRYPT.name)
88        await data_rdb.deleteRdbStore(context, STORE_CONFIG_UNENCRYPT.name)
89        await data_rdb.deleteRdbStore(context, STORE_CONFIG_WRONG.name)
90    })
91
92    afterAll(async function () {
93        console.info(TAG + 'afterAll')
94    })
95
96    console.log(TAG + "*************Unit Test Begin*************")
97
98    /**
99     * @tc.name RDB encrypted test
100     * @tc.number SUB_DDM_RDB_JS_RdbEncryptTest_0010
101     * @tc.desc RDB create encrypt db test
102     */
103    it('RdbEncryptTest_0010', 0, async function () {
104        await console.log(TAG + "************* RdbEncryptTest_0010 start *************")
105        try {
106            context = ability_featureAbility.getContext()
107            await data_rdb.getRdbStore(context, STORE_CONFIG_ENCRYPT, 1);
108        } catch (err) {
109            console.log(TAG + `failed, errcode:${JSON.stringify(err)}.`);
110            expect(null).assertFail();
111        }
112        await console.log(TAG + "************* RdbEncryptTest_0010 end *************")
113    })
114
115    /**
116     * @tc.name RDB unencrypted test
117     * @tc.number SUB_DDM_RDB_JS_RdbEncryptTest_0020
118     * @tc.desc RDB create unencrypted db test
119     */
120    it('RdbEncryptTest_0020', 0, async function () {
121        await console.log(TAG + "************* RdbEncryptTest_0020 start *************")
122        context = ability_featureAbility.getContext()
123        try {
124            await data_rdb.getRdbStore(context, STORE_CONFIG_UNENCRYPT, 1);
125        } catch (err) {
126            console.log(TAG + `failed, errcode:${JSON.stringify(err)}.`);
127            expect(null).assertFail();
128        }
129        await console.log(TAG + "************* RdbEncryptTest_0020 end *************")
130    })
131
132
133    /**
134     * @tc.name RDB encrypt test
135     * @tc.number SUB_DDM_RDB_JS_RdbEncryptTest_0030
136     * @tc.desc RDB encrypt function test
137     */
138    it('RdbEncryptTest_0030', 0, async function () {
139        await console.log(TAG + "************* RdbEncryptTest_0030 start *************")
140        context = ability_featureAbility.getContext()
141        let rdbStore = await CreateRdbStore(context, STORE_CONFIG_ENCRYPT)
142        let predicates = new data_rdb.RdbPredicates("test")
143        predicates.equalTo("name", "zhangsan")
144        let resultSet = await rdbStore.query(predicates)
145        try {
146            console.log(TAG + "After restore resultSet query done")
147            expect(true).assertEqual(resultSet.goToFirstRow())
148            const id = resultSet.getLong(resultSet.getColumnIndex("id"))
149            const name = resultSet.getString(resultSet.getColumnIndex("name"))
150            const blobType = resultSet.getBlob(resultSet.getColumnIndex("blobType"))
151            expect(1).assertEqual(id)
152            expect("zhangsan").assertEqual(name)
153            expect(1).assertEqual(blobType[0])
154        } catch (err) {
155            console.log(TAG + `failed, errcode:${JSON.stringify(err)}.`);
156            expect().assertFail()
157        } finally {
158            resultSet.close()
159            resultSet = null
160            rdbStore = null
161        }
162        await console.log(TAG + "************* RdbEncryptTest_0030 end *************")
163    })
164
165    /**
166     * @tc.name RDB encrypt test
167     * @tc.number SUB_DDM_RDB_JS_RdbEncryptTest_0040
168     * @tc.desc RDB encrypt function test
169     */
170    it('RdbEncryptTest_0040', 0, async function () {
171        await console.log(TAG + "************* RdbEncryptTest_0040 start *************")
172        context = ability_featureAbility.getContext()
173
174        await CreateRdbStore(context, STORE_CONFIG_ENCRYPT)
175        try {
176            await CreateRdbStore(context, STORE_CONFIG_WRONG)
177            expect().assertFail()
178        } catch (err) {
179            console.log(TAG + `failed, errcode:${JSON.stringify(err)}.`);
180        }
181
182        await console.log(TAG + "************* RdbEncryptTest_0040 end *************")
183    })
184
185    /**
186     * @tc.name Scenario testcase of RDB, get correct encrypt file when open database
187     * @tc.number SUB_DDM_RDB_JS_RdbEncryptTest_0050
188     * @tc.desc 1. create db1 and insert data
189     *          2. query db1
190     *          3. create db2 and create table in db1
191     *          4. query db1 and db2
192     */
193    it('RdbEncryptTest_0050', 0, async function () {
194        await console.info(TAG + "************* RdbEncryptTest_0050 start *************")
195        context = ability_featureAbility.getContext()
196        let rdbStore1;
197        let rdbStore2;
198        // create 'rdbstore1'
199        try {
200            rdbStore1 = await CreateRdbStore(context, STORE_CONFIG_ENCRYPT);
201        } catch (err) {
202            expect().assertFail()
203            console.error(`CreatRdbStore1 failed, error code: ${err.code}, err message: ${err.message}`);
204        }
205
206        // query 'rdbstore1'
207        try {
208            let predicates1 = new data_rdb.RdbPredicates("test")
209            let resultSet1 = await rdbStore1.query(predicates1)
210            expect(3).assertEqual(resultSet1.rowCount)
211        } catch (err) {
212            expect().assertFail()
213            console.error(`First query rdbstore1 failed, error code: ${err.code}, err message: ${err.message}`);
214        }
215
216        // create 'rdbStore2'
217        try {
218            rdbStore2 = await CreateRdbStore(context, STORE_CONFIG_ENCRYPT2)
219        } catch (err) {
220            expect().assertFail()
221            console.error(`CreatRdbStore2 failed, error code: ${err.code}, err message: ${err.message}`);
222        }
223
224        // create table and query 'rdbStore1'
225        try {
226            await rdbStore1.executeSql(CREATE_TABLE_TEST, null)
227            let predicates1 = new data_rdb.RdbPredicates("test")
228            let resultSet1 = await rdbStore1.query(predicates1)
229            expect(3).assertEqual(resultSet1.rowCount)
230        } catch (err) {
231            expect().assertFail()
232            console.error(`Second query rdbstore1 failed, error code: ${err.code}, err message: ${err.message}`);
233        }
234
235        // create table and query 'rdbStore2'
236        try {
237            await rdbStore2.executeSql(CREATE_TABLE_TEST, null)
238            let predicates2 = new data_rdb.RdbPredicates("test")
239            let resultSet2 = await rdbStore2.query(predicates2)
240            expect(3).assertEqual(resultSet2.rowCount)
241        } catch (err) {
242            expect().assertFail()
243            console.error(`Query rdbstore2 failed, error code: ${err.code}, err message: ${err.message}`);
244        }
245        console.info(TAG + "************* RdbEncryptTest_0060 end *************")
246    })
247    console.log(TAG + "*************Unit Test End*************")
248})