using StudySystemClient.Der; static bool bytes_equal(uint8[] expected, uint8[] actual) { if (expected.length != actual.length) return false; return Memory.cmp(expected, actual, expected.length) == 0; } static string bytes_to_string(uint8[] bytes) { var s = ""; foreach (var byte in bytes) s += "%02x".printf(byte); return s; } static void test_encode(Datum datum, uint8[] expected) { var bytes = datum.encode(); if (!bytes_equal(expected, bytes)) { Test.message("Encoding is incorrect: expected %s got %s", bytes_to_string(expected), bytes_to_string(bytes)); Test.fail(); return; } } void main(string[] args) { Test.init(ref args); /* * Encoding */ Test.add_func("/encode/boolean/true", () => { test_encode(new Boolean(true), {0x01, 0x01, 0xff}); }); Test.add_func("/encode/boolean/false", () => { test_encode(new Boolean(false), {0x01, 0x01, 0x00}); }); Test.add_func("/encode/integer/small/0", () => { test_encode(new Integer(0), {0x02, 0x01, 0x00}); }); Test.add_func("/encode/integer/small/5", () => { test_encode(new Integer(5), {0x02, 0x01, 0x05}); }); Test.add_func("/encode/integer/small/42", () => { test_encode(new Integer(42), {0x02, 0x01, 0x2a}); }); Test.add_func("/encode/integer/large/1337", () => { test_encode(new Integer(1337), {0x02, 0x02, 0x05, 0x39}); }); Test.add_func("/encode/integer/sign/128", () => { test_encode(new Integer(128), {0x02, 0x02, 0x00, 0x80}); }); Test.add_func("/encode/integer/sign/0xbeef", () => { test_encode(new Integer(0xbeef), {0x02, 0x03, 0x00, 0xbe, 0xef}); }); Test.add_func("/encode/integer/sign/-128", () => { test_encode(new Integer(-128), {0x02, 0x01, 0x80}); }); Test.add_func("/encode/integer/sign/-1337", () => { test_encode(new Integer(-1337), {0x02, 0x02, 0xfa, 0xc7}); }); Test.add_func("/encode/utf8string/short/foo", () => { test_encode(new Utf8String("foo"), {0x0c, 0x03, 0x66, 0x6f, 0x6f}); }); Test.add_func("/encode/utf8string/short/bar", () => { test_encode(new Utf8String("bar"), {0x0c, 0x03, 0x62, 0x61, 0x72}); }); Test.add_func("/encode/utf8string/long/x300", () => { var expected = new uint8[304]; expected[0] = 0x0c; expected[1] = 0x82; expected[2] = 0x01; expected[3] = 0x2c; Memory.set(expected[4:], 0x78, 300); test_encode(new Utf8String(string.nfill(300, 'x')), expected); }); Test.add_func("/encode/utf8string/long/x128", () => { var expected = new uint8[131]; expected[0] = 0x0c; expected[1] = 0x81; expected[2] = 0x80; Memory.set(expected[3:], 0x78, 128); test_encode(new Utf8String(string.nfill(128, 'x')), expected); }); Test.run(); }