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 package org.apache.http.entity;
29
30 import java.io.ByteArrayOutputStream;
31 import java.io.File;
32 import java.io.FileOutputStream;
33 import java.io.IOException;
34 import java.io.InputStream;
35 import java.io.RandomAccessFile;
36
37 import org.junit.Assert;
38 import org.junit.ClassRule;
39 import org.junit.Test;
40 import org.junit.rules.TemporaryFolder;
41
42
43
44
45
46 public class TestFileEntity {
47
48 @ClassRule
49 public static final TemporaryFolder tempFolder = new TemporaryFolder();
50
51 @Test
52 public void testFileLengthMaxIntPlusOne() throws IOException {
53 final File file = tempFolder.newFile("test.bin");
54 final RandomAccessFile raFile = new RandomAccessFile(file, "rw");
55 try {
56 final long expectedLength = 1L + Integer.MAX_VALUE;
57 raFile.setLength(expectedLength);
58 final FileEntity fileEntity = new FileEntity(file);
59 Assert.assertEquals(expectedLength, fileEntity.getContentLength());
60 } finally {
61 raFile.close();
62 }
63 }
64
65 @Test
66 public void testBasics() throws Exception {
67 final File tmpfile = File.createTempFile("testfile", ".txt");
68 tmpfile.deleteOnExit();
69 final FileEntity httpentity = new FileEntity(tmpfile, ContentType.TEXT_PLAIN);
70
71 Assert.assertEquals(tmpfile.length(), httpentity.getContentLength());
72 final InputStream content = httpentity.getContent();
73 Assert.assertNotNull(content);
74 content.close();
75 Assert.assertTrue(httpentity.isRepeatable());
76 Assert.assertFalse(httpentity.isStreaming());
77 if (!tmpfile.delete()) {
78 Assert.fail("Failed to delete: " + tmpfile);
79 }
80 }
81
82 @Test
83 public void testIllegalConstructor() throws Exception {
84 try {
85 new FileEntity(null, ContentType.TEXT_PLAIN);
86 Assert.fail("IllegalArgumentException should have been thrown");
87 } catch (final IllegalArgumentException ex) {
88
89 }
90 }
91
92 @Test
93 public void testWriteTo() throws Exception {
94 final File tmpfile = File.createTempFile("testfile", ".txt");
95 tmpfile.deleteOnExit();
96
97 final FileOutputStream outStream = new FileOutputStream(tmpfile);
98 outStream.write(0);
99 outStream.write(1);
100 outStream.write(2);
101 outStream.write(3);
102 outStream.close();
103
104 final FileEntity httpentity = new FileEntity(tmpfile, ContentType.TEXT_PLAIN);
105
106 final ByteArrayOutputStream out = new ByteArrayOutputStream();
107 httpentity.writeTo(out);
108 final byte[] bytes = out.toByteArray();
109 Assert.assertNotNull(bytes);
110 Assert.assertEquals(tmpfile.length(), bytes.length);
111 for (int i = 0; i < 4; i++) {
112 Assert.assertEquals(i, bytes[i]);
113 }
114 if (!tmpfile.delete()) {
115 Assert.fail("Failed to delete: " + tmpfile);
116 }
117
118 try {
119 httpentity.writeTo(null);
120 Assert.fail("IllegalArgumentException should have been thrown");
121 } catch (final IllegalArgumentException ex) {
122
123 }
124 }
125
126 }