v / vlib / encoding / cbor / tests / time_test.v
39 lines · 33 sloc · 1.15 KB · 468855eef1db0ff73c62be2d1bf176ffa0e1478e
Raw
1// Tests that `time.Time` auto-tags as RFC 8949 tag 1 (epoch seconds)
2// on encode and accepts both tag 0 (RFC 3339 text) and tag 1 (epoch
3// seconds, integer or float) on decode.
4module main
5
6import encoding.cbor
7import encoding.hex
8import time
9
10fn h(s string) []u8 {
11 return hex.decode(s) or { panic('invalid hex: ${s}') }
12}
13
14fn test_time_encode_tag1() {
15 t := time.unix(1363896240)
16 bytes := cbor.encode[time.Time](t, cbor.EncodeOpts{})!
17 // Wire form: c1 (tag 1) + 1a 51 4b 67 b0 (4-byte uint).
18 assert bytes == h('c11a514b67b0'), 'got ${hex.encode(bytes)}'
19}
20
21fn test_time_decode_tag1() {
22 got := cbor.decode[time.Time](h('c11a514b67b0'), cbor.DecodeOpts{})!
23 assert got.unix() == 1363896240
24}
25
26fn test_time_decode_tag0_iso8601() {
27 // Tag 0 + text "2013-03-21T20:04:00Z".
28 got :=
29 cbor.decode[time.Time](h('c074323031332d30332d32315432303a30343a30305a'), cbor.DecodeOpts{})!
30 assert got.unix() == 1363896240
31}
32
33fn test_time_decode_tag1_float() {
34 got := cbor.decode[time.Time](h('c1fb41d452d9ec200000'), cbor.DecodeOpts{})!
35 // 1363896240.5 — half-second offset.
36 assert got.unix() == 1363896240
37 // Sub-second component is non-zero (~500ms).
38 assert got.nanosecond > 0
39}
40