Adam Langley | 80b7f6a | 2009-11-17 18:09:41 -0800 | [diff] [blame] | 1 | // Copyright 2009 The Go Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
| 5 | package asn1 |
| 6 | |
| 7 | import ( |
| 8 | "bytes"; |
| 9 | "encoding/hex"; |
| 10 | "testing"; |
| 11 | "time"; |
| 12 | ) |
| 13 | |
| 14 | type intStruct struct { |
| 15 | A int; |
| 16 | } |
| 17 | |
| 18 | type nestedStruct struct { |
| 19 | A intStruct; |
| 20 | } |
| 21 | |
| 22 | type marshalTest struct { |
| 23 | in interface{}; |
| 24 | out string; // hex encoded |
| 25 | } |
| 26 | |
| 27 | type implicitTagTest struct { |
| 28 | A int "implicit,tag:5"; |
| 29 | } |
| 30 | |
| 31 | type explicitTagTest struct { |
| 32 | A int "explicit,tag:5"; |
| 33 | } |
| 34 | |
| 35 | type ia5StringTest struct { |
| 36 | A string "ia5"; |
| 37 | } |
| 38 | |
| 39 | type printableStringTest struct { |
| 40 | A string "printable"; |
| 41 | } |
| 42 | |
| 43 | func setPST(t *time.Time) *time.Time { |
| 44 | t.ZoneOffset = -28800; |
| 45 | return t; |
| 46 | } |
| 47 | |
| 48 | var marshalTests = []marshalTest{ |
| 49 | marshalTest{10, "02010a"}, |
| 50 | marshalTest{intStruct{64}, "3003020140"}, |
| 51 | marshalTest{nestedStruct{intStruct{127}}, "3005300302017f"}, |
| 52 | marshalTest{[]byte{1, 2, 3}, "0403010203"}, |
| 53 | marshalTest{implicitTagTest{64}, "3003850140"}, |
| 54 | marshalTest{explicitTagTest{64}, "3005a503020140"}, |
| 55 | marshalTest{time.SecondsToUTC(0), "170d3730303130313030303030305a"}, |
| 56 | marshalTest{time.SecondsToUTC(1258325776), "170d3039313131353232353631365a"}, |
| 57 | marshalTest{setPST(time.SecondsToUTC(1258325776)), "17113039313131353232353631362d30383030"}, |
| 58 | marshalTest{BitString{[]byte{0x80}, 1}, "03020780"}, |
| 59 | marshalTest{BitString{[]byte{0x81, 0xf0}, 12}, "03030481f0"}, |
| 60 | marshalTest{ObjectIdentifier([]int{1, 2, 3, 4}), "06032a0304"}, |
| 61 | marshalTest{"test", "130474657374"}, |
| 62 | marshalTest{ia5StringTest{"test"}, "3006160474657374"}, |
| 63 | marshalTest{printableStringTest{"test"}, "3006130474657374"}, |
| 64 | } |
| 65 | |
| 66 | func TestMarshal(t *testing.T) { |
| 67 | for i, test := range marshalTests { |
| 68 | buf := bytes.NewBuffer(nil); |
| 69 | err := Marshal(buf, test.in); |
| 70 | if err != nil { |
| 71 | t.Errorf("#%d failed: %s", i, err) |
| 72 | } |
| 73 | out, _ := hex.DecodeString(test.out); |
| 74 | if bytes.Compare(out, buf.Bytes()) != 0 { |
| 75 | t.Errorf("#%d got: %x want %x", i, buf.Bytes(), out) |
| 76 | } |
| 77 | } |
| 78 | } |