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;
14 import com.google.common.collect.Lists;
15 import io.netty.buffer.ByteBuf;
16 import io.netty.buffer.Unpooled;
17 import io.netty.channel.ChannelHandlerContext;
18 import java.util.List;
19 import org.junit.Before;
20 import org.junit.Test;
21 import org.mockito.Mock;
22 import org.mockito.MockitoAnnotations;
23 import org.mockito.invocation.InvocationOnMock;
24 import org.mockito.stubbing.Answer;
25 import org.opendaylight.controller.netconf.util.messages.NetconfMessageConstants;
27 public class ChunkedFramingMechanismEncoderTest {
29 private int chunkSize;
31 private ChannelHandlerContext ctx;
34 public void setUp() throws Exception {
35 MockitoAnnotations.initMocks(this);
39 @Test(expected = IllegalArgumentException.class)
40 public void testIllegalSize() throws Exception {
41 new ChunkedFramingMechanismEncoder(10);
44 @Test(expected = IllegalArgumentException.class)
45 public void testIllegalSizeMax() throws Exception {
46 new ChunkedFramingMechanismEncoder(Integer.MAX_VALUE);
50 public void testEncode() throws Exception {
51 final List<ByteBuf> chunks = Lists.newArrayList();
52 doAnswer(new Answer<Object>() {
54 public Object answer(final InvocationOnMock invocation) throws Throwable {
55 chunks.add((ByteBuf) invocation.getArguments()[0]);
58 }).when(ctx).write(anyObject());
60 final ChunkedFramingMechanismEncoder encoder = new ChunkedFramingMechanismEncoder(chunkSize);
61 final int lastChunkSize = 20;
62 final ByteBuf src = Unpooled.wrappedBuffer(getByteArray(chunkSize * 4 + lastChunkSize));
63 final ByteBuf destination = Unpooled.buffer();
64 encoder.encode(ctx, src, destination);
65 assertEquals(4, chunks.size());
67 final int framingSize = "#256\n".getBytes().length + 1/* new line at end */;
69 for (final ByteBuf chunk : chunks) {
70 assertEquals(chunkSize + framingSize, chunk.readableBytes());
73 final int lastFramingSize = "#20\n".length() + NetconfMessageConstants.END_OF_CHUNK.length + 1/* new line at end */;
74 assertEquals(lastChunkSize + lastFramingSize, destination.readableBytes());
77 private byte[] getByteArray(final int size) {
78 final byte[] bytes = new byte[size];
79 for (int i = 0; i < size; i++) {