2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.controller.netconf.nettyutil.handler;
11 import static org.junit.Assert.assertEquals;
12 import static org.mockito.Matchers.anyObject;
13 import static org.mockito.Mockito.doAnswer;
15 import com.google.common.collect.Lists;
16 import io.netty.buffer.ByteBuf;
17 import io.netty.buffer.Unpooled;
18 import io.netty.channel.ChannelHandlerContext;
19 import java.util.List;
20 import org.junit.Before;
21 import org.junit.Test;
22 import org.mockito.Mock;
23 import org.mockito.MockitoAnnotations;
24 import org.mockito.invocation.InvocationOnMock;
25 import org.mockito.stubbing.Answer;
26 import org.opendaylight.controller.netconf.util.messages.NetconfMessageConstants;
28 public class ChunkedFramingMechanismEncoderTest {
30 private int chunkSize;
32 private ChannelHandlerContext ctx;
35 public void setUp() throws Exception {
36 MockitoAnnotations.initMocks(this);
40 @Test(expected = IllegalArgumentException.class)
41 public void testIllegalSize() throws Exception {
42 new ChunkedFramingMechanismEncoder(10);
45 @Test(expected = IllegalArgumentException.class)
46 public void testIllegalSizeMax() throws Exception {
47 new ChunkedFramingMechanismEncoder(Integer.MAX_VALUE);
51 public void testEncode() throws Exception {
52 final List<ByteBuf> chunks = Lists.newArrayList();
53 doAnswer(new Answer() {
55 public Object answer(final InvocationOnMock invocation) throws Throwable {
56 chunks.add((ByteBuf) invocation.getArguments()[0]);
59 }).when(ctx).write(anyObject());
61 final ChunkedFramingMechanismEncoder encoder = new ChunkedFramingMechanismEncoder(chunkSize);
62 final int lastChunkSize = 20;
63 final ByteBuf src = Unpooled.wrappedBuffer(getByteArray(chunkSize * 4 + lastChunkSize));
64 final ByteBuf destination = Unpooled.buffer();
65 encoder.encode(ctx, src, destination);
66 assertEquals(4, chunks.size());
68 final int framingSize = "#256\n".getBytes().length + 1/* new line at end */;
70 for (final ByteBuf chunk : chunks) {
71 assertEquals(chunkSize + framingSize, chunk.readableBytes());
74 final int lastFramingSize = "#20\n".length() + NetconfMessageConstants.END_OF_CHUNK.length + 1/* new line at end */;
75 assertEquals(lastChunkSize + lastFramingSize, destination.readableBytes());
78 private byte[] getByteArray(final int size) {
79 final byte[] bytes = new byte[size];
80 for (int i = 0; i < size; i++) {