1
2
3
4
5 package com.jcabi.http.response;
6
7 import com.jcabi.http.Response;
8 import com.jcabi.http.request.FakeRequest;
9 import jakarta.json.stream.JsonParsingException;
10 import org.hamcrest.MatcherAssert;
11 import org.hamcrest.Matchers;
12 import org.junit.jupiter.api.Assertions;
13 import org.junit.jupiter.api.Test;
14
15
16
17
18
19 final class JsonResponseTest {
20
21
22
23
24
25 @Test
26 void readsJsonDocument() throws Exception {
27 final Response resp = new FakeRequest()
28 .withBody("{\n\t\r\"foo-foo\":2,\n\"bar\":\"\u20ac\"}")
29 .fetch();
30 final JsonResponse response = new JsonResponse(resp);
31 MatcherAssert.assertThat(
32 "should be equal 2",
33 response.json().readObject().getInt("foo-foo"),
34 Matchers.equalTo(2)
35 );
36 MatcherAssert.assertThat(
37 "should be equal \u20ac",
38 response.json().readObject().getString("bar"),
39 Matchers.equalTo("\u20ac")
40 );
41 }
42
43
44
45
46
47
48 @Test
49 void readsControlCharacters() throws Exception {
50 final Response resp = new FakeRequest()
51 .withBody("{\"test\":\n\"\u001Fblah\uFFFDcwhoa\u0000!\"}").fetch();
52 final JsonResponse response = new JsonResponse(resp);
53 MatcherAssert.assertThat(
54 "should be \u001Fblah\uFFFDcwhoa\u0000!",
55 response.json().readObject().getString("test"),
56 Matchers.is("\u001Fblah\uFFFDcwhoa\u0000!")
57 );
58 }
59
60
61
62
63
64
65 @Test
66 void logsForInvalidJsonObject() throws Exception {
67 final String body = "{\"test\": \"logged!\"$@%#^&%@$#}";
68 final Response resp = new FakeRequest().withBody(body).fetch();
69 MatcherAssert.assertThat(
70 "should contains json body",
71 Assertions.assertThrows(
72 JsonParsingException.class,
73 () -> new JsonResponse(resp).json().readObject(),
74 "readObject() should have thrown JsonParsingException"
75 ),
76 Matchers.hasToString(Matchers.containsString(body))
77 );
78 }
79
80
81
82
83
84
85 @Test
86 void logsForInvalidJsonArray() throws Exception {
87 final String body = "[\"test\": \"logged!\"$@%#^&%@$#]";
88 final Response resp = new FakeRequest().withBody(body).fetch();
89 MatcherAssert.assertThat(
90 "should contains json body",
91 Assertions.assertThrows(
92 JsonParsingException.class,
93 () -> new JsonResponse(resp).json().readArray(),
94 "readArray() should have thrown JsonParsingException"
95 ),
96 Matchers.hasToString(
97 Matchers.containsString(
98 body
99 )
100 )
101 );
102 }
103
104
105
106
107
108
109 @Test
110 void logsForInvalidJson() throws Exception {
111 final String body = "{test:[]}}}";
112 final Response resp = new FakeRequest().withBody(body).fetch();
113 MatcherAssert.assertThat(
114 "should contains json body",
115 Assertions.assertThrows(
116 JsonParsingException.class,
117 () -> new JsonResponse(resp).json().read(),
118 "readStructure() should have thrown JsonParsingException"
119 ),
120 Matchers.<JsonParsingException>hasToString(
121 Matchers.containsString(
122 body
123 )
124 )
125 );
126 }
127
128 }