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.hc.core5.http.io.entity;
29
30 import java.io.ByteArrayOutputStream;
31 import java.io.File;
32 import java.io.FileOutputStream;
33 import java.io.InputStream;
34
35 import org.apache.hc.core5.http.ContentType;
36 import org.junit.jupiter.api.Assertions;
37 import org.junit.jupiter.api.Test;
38
39
40
41
42
43 public class TestFileEntity {
44
45 @Test
46 public void testBasics() throws Exception {
47 final File tmpfile = File.createTempFile("testfile", ".txt");
48 tmpfile.deleteOnExit();
49 try (final FileEntity httpentity = new FileEntity(tmpfile, ContentType.TEXT_PLAIN)) {
50
51 Assertions.assertEquals(tmpfile.length(), httpentity.getContentLength());
52 final InputStream content = httpentity.getContent();
53 Assertions.assertNotNull(content);
54 content.close();
55 Assertions.assertTrue(httpentity.isRepeatable());
56 Assertions.assertFalse(httpentity.isStreaming());
57 Assertions.assertTrue(tmpfile.delete(), "Failed to delete " + tmpfile);
58 }
59 }
60
61 @Test
62 public void testNullConstructor() throws Exception {
63 Assertions.assertThrows(NullPointerException.class, () -> new FileEntity(null, ContentType.TEXT_PLAIN));
64 }
65
66 @Test
67 public void testWriteTo() throws Exception {
68 final File tmpfile = File.createTempFile("testfile", ".txt");
69 tmpfile.deleteOnExit();
70
71 final FileOutputStream outStream = new FileOutputStream(tmpfile);
72 outStream.write(0);
73 outStream.write(1);
74 outStream.write(2);
75 outStream.write(3);
76 outStream.close();
77
78 try (final FileEntity httpentity = new FileEntity(tmpfile, ContentType.TEXT_PLAIN)) {
79
80 final ByteArrayOutputStream out = new ByteArrayOutputStream();
81 httpentity.writeTo(out);
82 final byte[] bytes = out.toByteArray();
83 Assertions.assertNotNull(bytes);
84 Assertions.assertEquals(tmpfile.length(), bytes.length);
85 for (int i = 0; i < 4; i++) {
86 Assertions.assertEquals(i, bytes[i]);
87 }
88 Assertions.assertTrue(tmpfile.delete(), "Failed to delete: " + tmpfile);
89
90 Assertions.assertThrows(NullPointerException.class, () -> httpentity.writeTo(null));
91 }
92 }
93
94 }