summaryrefslogtreecommitdiffstats
path: root/simple/simple-http/src/test/java/org/simpleframework/http/core/FixedConsumerTest.java
blob: f0011ce59944cd45498991fe0a14cc68b4090759 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package org.simpleframework.http.core;

import java.io.IOException;

import junit.framework.TestCase;

import org.simpleframework.common.buffer.Allocator;
import org.simpleframework.common.buffer.ArrayAllocator;
import org.simpleframework.common.buffer.Buffer;
import org.simpleframework.http.message.FixedLengthConsumer;
import org.simpleframework.transport.ByteCursor;

public class FixedConsumerTest extends TestCase implements Allocator {
   
   private Buffer buffer;
   
   public Buffer allocate() {
      return buffer;
   }
   
   public Buffer allocate(long size) {
      return buffer;
   }
   
   public void testConsumer() throws Exception {
      testConsumer(10, 10, 10);
      testConsumer(1024, 10, 1024);
      testConsumer(1024, 1024, 1024);
      testConsumer(1024, 1024, 1023);
      testConsumer(1024, 1, 1024);
      testConsumer(1, 1, 1);
      testConsumer(2, 2, 2);
      testConsumer(3, 1, 2);
   }
   
   public void testConsumer(int entitySize, int dribble, int limitSize) throws Exception {
      StringBuffer buf = new StringBuffer();
      
      // Ensure that we dont try read forever
      limitSize = Math.min(entitySize, limitSize);
      
      for(int i = 0, line = 0; i < entitySize; i++) {
         String text = "["+String.valueOf(i)+"]";        
        
         line += text.length();
         buf.append(text);
         
         if(line >= 48) {
            buf.append("\n");           
            line = 0;
         }

      }
      buffer = new ArrayAllocator().allocate();
      
      String requestBody = buf.toString();
      FixedLengthConsumer consumer = new FixedLengthConsumer(this, limitSize);
      ByteCursor cursor = new DribbleCursor(new StreamCursor(requestBody), dribble);
      byte[] requestBytes = requestBody.getBytes("UTF-8");
      
      while(!consumer.isFinished()) {
         consumer.consume(cursor);
      }
      byte[] consumedBytes = buffer.encode("UTF-8").getBytes("UTF-8");
      
      assertEquals(buffer.encode("UTF-8").length(), limitSize);
      
      for(int i = 0; i < limitSize; i++) {
         if(consumedBytes[i] != requestBytes[i]) {
            throw new IOException("Fixed consumer modified the request!");
         }
      }
   }

   public void close() throws IOException {
      // TODO Auto-generated method stub
      
   }

}