| 1 |
// SPDX-License-Identifier: LGPL-2.1-or-later |
| 2 |
import cockpit from "cockpit"; |
| 3 |
import QUnit from "qunit-tests"; |
| 4 |
|
| 5 |
QUnit.test("base64 array", function (assert) { |
| 6 |
let data = new Array(5); |
| 7 |
for (let i = 0; i < 5; i++) |
| 8 |
data[i] = i; |
| 9 |
assert.equal(cockpit.base64_encode(data), "AAECAwQ=", "encoded from Array"); |
| 10 |
|
| 11 |
data = cockpit.base64_decode("AAECAwQFBg=="); |
| 12 |
assert.equal(data.length, 7, "right length"); |
| 13 |
|
| 14 |
let match = 1; |
| 15 |
for (let i = 0; i < data.length; i++) { |
| 16 |
if (data[i] != i) { |
| 17 |
match = false; |
| 18 |
break; |
| 19 |
} |
| 20 |
} |
| 21 |
|
| 22 |
assert.ok(match, "right data"); |
| 23 |
}); |
| 24 |
|
| 25 |
QUnit.test("base64 arraybuffer", function (assert) { |
| 26 |
const view = new Uint8Array(5); |
| 27 |
for (let i = 0; i < 5; i++) |
| 28 |
view[i] = i; |
| 29 |
assert.equal(cockpit.base64_encode(view), "AAECAwQ=", "encoded from Uint8Array"); |
| 30 |
|
| 31 |
const data = cockpit.base64_decode("AAECAwQFBg==", Uint8Array); |
| 32 |
assert.equal(data.length, 7, "right length"); |
| 33 |
|
| 34 |
let match = 1; |
| 35 |
for (let i = 0; i < data.length; i++) { |
| 36 |
if (data[i] != i) { |
| 37 |
match = false; |
| 38 |
break; |
| 39 |
} |
| 40 |
} |
| 41 |
|
| 42 |
assert.ok(match, "right data"); |
| 43 |
}); |
| 44 |
|
| 45 |
QUnit.test("base64 string", function (assert) { |
| 46 |
assert.equal(cockpit.base64_encode("blah"), "YmxhaA==", "encoded right"); |
| 47 |
assert.strictEqual(cockpit.base64_decode("YmxhaA==", String), "blah", "decoded right"); |
| 48 |
}); |
| 49 |
|
| 50 |
QUnit.test("base64 round trip", function (assert) { |
| 51 |
function random_int(min, max) { |
| 52 |
return Math.floor(Math.random() * (max - min)) + min; |
| 53 |
} |
| 54 |
|
| 55 |
const length = random_int(1000000, 5000000); |
| 56 |
const data = new Array(length); |
| 57 |
for (let i = 0; i < length; i++) |
| 58 |
data[i] = random_int(0, 255); |
| 59 |
|
| 60 |
const encoded = cockpit.base64_encode(data); |
| 61 |
const decoded = cockpit.base64_decode(encoded); |
| 62 |
|
| 63 |
assert.equal(decoded.length, length, "right length: " + length); |
| 64 |
|
| 65 |
let match = true; |
| 66 |
for (let i = 0; i < length; i++) { |
| 67 |
if (data[i] != decoded[i]) { |
| 68 |
match = false; |
| 69 |
break; |
| 70 |
} |
| 71 |
} |
| 72 |
|
| 73 |
assert.ok(match, "data correct"); |
| 74 |
}); |
| 75 |
|
| 76 |
QUnit.start(); |