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.InputStream;
32 import java.io.OutputStream;
33 import java.nio.file.Files;
34 import java.nio.file.Path;
35
36 import org.apache.hc.core5.http.ContentType;
37 import org.junit.Assert;
38 import org.junit.Test;
39
40
41
42
43 public class TestPathEntity {
44
45 @Test
46 public void testBasics() throws Exception {
47 final Path tmpPath = Files.createTempFile("testfile", ".txt");
48
49 tmpPath.toFile().deleteOnExit();
50 try (final PathEntity httpEntity = new PathEntity(tmpPath, ContentType.TEXT_PLAIN)) {
51 Assert.assertEquals(Files.size(tmpPath), httpEntity.getContentLength());
52 try (final InputStream content = httpEntity.getContent()) {
53 Assert.assertNotNull(content);
54 }
55 Assert.assertTrue(httpEntity.isRepeatable());
56 Assert.assertFalse(httpEntity.isStreaming());
57
58 if (!Files.deleteIfExists(tmpPath)) {
59 Assert.fail("Failed to delete: " + tmpPath);
60 }
61 }
62 }
63
64 @Test
65 public void testNullConstructor() throws Exception {
66 try (final PathEntity httpEntity = new PathEntity(null, ContentType.TEXT_PLAIN)) {
67 Assert.fail("NullPointerException should have been thrown");
68 } catch (final NullPointerException ex) {
69
70 }
71 }
72
73 @Test
74 public void testWriteTo() throws Exception {
75 final Path tmpPath = Files.createTempFile("testfile", ".txt");
76
77 tmpPath.toFile().deleteOnExit();
78 try (final OutputStream outStream = Files.newOutputStream(tmpPath)) {
79 outStream.write(0);
80 outStream.write(1);
81 outStream.write(2);
82 outStream.write(3);
83 }
84
85 try (final PathEntity httpEntity = new PathEntity(tmpPath, ContentType.TEXT_PLAIN)) {
86 final ByteArrayOutputStream out = new ByteArrayOutputStream();
87 httpEntity.writeTo(out);
88 final byte[] bytes = out.toByteArray();
89 Assert.assertNotNull(bytes);
90 Assert.assertEquals(Files.size(tmpPath), bytes.length);
91 for (int i = 0; i < 4; i++) {
92 Assert.assertEquals(i, bytes[i]);
93 }
94
95 if (!Files.deleteIfExists(tmpPath)) {
96 Assert.fail("Failed to delete: " + tmpPath);
97 }
98
99 try {
100 httpEntity.writeTo(null);
101 Assert.fail("NullPointerException should have been thrown");
102 } catch (final NullPointerException ex) {
103
104 }
105 }
106 }
107 }