comparison src/test/java/org/msgpack/simple/TestSimpleDynamicTyping.java @ 0:cb825acd883a

first commit
author sugi
date Sat, 18 Oct 2014 15:06:15 +0900
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:cb825acd883a
1 package org.msgpack.simple;
2
3 import org.msgpack.MessagePack;
4 import org.msgpack.type.Value;
5 import org.msgpack.type.IntegerValue;
6 import org.msgpack.type.RawValue;
7 import org.msgpack.type.ArrayValue;
8
9 import java.io.IOException;
10
11 import static org.junit.Assert.assertEquals;
12 import static org.junit.Assert.assertArrayEquals;
13 import org.junit.Test;
14
15
16 public class TestSimpleDynamicTyping {
17 @Test
18 @SuppressWarnings("unused")
19 public void testTypes() throws IOException {
20 MessagePack msgpack = new MessagePack();
21
22 byte[] raw = msgpack.write(new int[] {1,2,3});
23 Value v = msgpack.read(raw);
24
25 if(v.isArrayValue()) {
26 // ArrayValue extends List<Value>
27 ArrayValue array = v.asArrayValue();
28 int n0 = array.get(0).asIntegerValue().intValue();
29 assertEquals(1, n0);
30 int n1 = array.get(1).asIntegerValue().intValue();
31 assertEquals(2, n1);
32 int n2 = array.get(2).asIntegerValue().intValue();
33 assertEquals(3, n2);
34
35 } else if(v.isIntegerValue()) {
36 // IntegerValue extends Number
37 int num = v.asIntegerValue().intValue();
38
39 } else if(v.isRawValue()) {
40 // getString() or getByteArray()
41 String str = v.asRawValue().getString();
42 }
43 // other types:
44 // NilValue asNilValue() / isNilValue()
45 // BooleanValue asBooleanValue() / isBooleanValue()
46 // IntegerValue asIntegerValue() / isIntegerValue()
47 // FloatValue asFloatValue() / isFloatValue()
48 // ArrayValue asArrayValue() / isArrayValue()
49 // MapValue asMapValue() / isMapValue()
50 // RawValue asRawValue() / isRawValue
51 }
52
53 @Test
54 public void testSimpleConvert() throws IOException {
55 MessagePack msgpack = new MessagePack();
56
57 byte[] raw = msgpack.write(new int[] {1,2,3});
58 Value v = msgpack.read(raw);
59
60 // convert from dynamic type (Value) to static type (int[])
61 int[] array = msgpack.convert(v, new int[3]);
62 assertArrayEquals(new int[] {1,2,3}, array);
63
64 // unconvert from static type (int[]) to dynamic type (Value)
65 Value v2 = msgpack.unconvert(array);
66 assertEquals(v, v2);
67 }
68 }
69