1package muduo.codec.tests;
2
3import static org.junit.Assert.assertEquals;
4import muduo.codec.ProtobufDecoder;
5import muduo.codec.ProtobufEncoder;
6import muduo.codec.tests.QueryProtos.Empty;
7import muduo.codec.tests.QueryProtos.Query;
8
9import org.jboss.netty.buffer.BigEndianHeapChannelBuffer;
10import org.jboss.netty.buffer.ChannelBuffer;
11import org.junit.Test;
12
13import com.google.protobuf.Message;
14
15public class CodecTest {
16
17    @Test
18    public void testEncoderEmpty() throws Exception {
19        ProtobufEncoder encoder = new ProtobufEncoder();
20        Empty empty = Empty.getDefaultInstance();
21        encoder.encode(null, null, empty);
22    }
23
24    @Test
25    public void testDecodeEmpty() throws Exception {
26        ProtobufEncoder encoder = new ProtobufEncoder();
27        Empty empty = Empty.getDefaultInstance();
28        ChannelBuffer buf = (ChannelBuffer) encoder.encode(null, null, empty);
29
30        ProtobufDecoder decoder = new ProtobufDecoder();
31        decoder.addMessageType(Empty.getDefaultInstance());
32        Message message = (Message) decoder.decode(null, null, buf);
33        assertEquals(empty, message);
34    }
35
36    @Test
37    public void testQuery() throws Exception {
38        ProtobufEncoder encoder = new ProtobufEncoder();
39        Query query = Query.newBuilder()
40                .setId(1)
41                .setQuestioner("Chen Shuo")
42                .addQuestion("Running?")
43                .build();
44        ChannelBuffer buf = (ChannelBuffer) encoder.encode(null, null, query);
45
46        ProtobufDecoder decoder = new ProtobufDecoder();
47        decoder.addMessageType(Query.getDefaultInstance());
48        Message message = (Message) decoder.decode(null, null, buf);
49        assertEquals(query, message);
50    }
51
52    @Test
53    public void testQuery2() throws Exception {
54        ProtobufEncoder encoder = new ProtobufEncoder();
55        Query query = Query.newBuilder()
56                .setId(1)
57                .setQuestioner("Chen Shuo")
58                .addQuestion("Running?")
59                .build();
60        ChannelBuffer buf = (ChannelBuffer) encoder.encode(null, null, query);
61        ChannelBuffer buf2 = new BigEndianHeapChannelBuffer(buf.readableBytes() + 8);
62        buf2.writeInt(123);
63        buf2.writeBytes(buf);
64
65        buf2.readInt();
66        ProtobufDecoder decoder = new ProtobufDecoder();
67        decoder.addMessageType(Query.getDefaultInstance());
68        Message message = (Message) decoder.decode(null, null, buf2);
69        assertEquals(query, message);
70    }
71}
72