File tree Expand file tree Collapse file tree 2 files changed +63
-0
lines changed
main/java/io/github/nstdio/http/ext
test/kotlin/io/github/nstdio/http/ext Expand file tree Collapse file tree 2 files changed +63
-0
lines changed Original file line number Diff line number Diff line change 1818
1919import java .net .URI ;
2020import java .net .http .HttpRequest ;
21+ import java .net .http .HttpResponse ;
2122import java .util .Objects ;
2223import java .util .function .Predicate ;
2324
@@ -45,4 +46,32 @@ public static Predicate<HttpRequest> uri(URI uri) {
4546 Objects .requireNonNull (uri );
4647 return r -> r .uri ().equals (uri );
4748 }
49+
50+ /**
51+ * The {@code Predicate} that matches only {@code HttpResponse} with given header.
52+ *
53+ * @param name The header name.
54+ * @param value The header value.
55+ *
56+ * @return The {@code Predicate} that matches {@code HttpResponse} with given header.
57+ */
58+ public static <T > Predicate <HttpResponse <T >> hasHeader (String name , String value ) {
59+ Objects .requireNonNull (name );
60+ Objects .requireNonNull (value );
61+
62+ return r -> r .headers ().firstValue (name ).filter (value ::equals ).isPresent ();
63+ }
64+
65+ /**
66+ * The {@code Predicate} that matches only {@code HttpRequest} with given header.
67+ *
68+ * @param name The header name.
69+ *
70+ * @return The {@code Predicate} that matches {@code HttpRequest} with given header.
71+ */
72+ public static <T > Predicate <HttpResponse <T >> hasHeader (String name ) {
73+ Objects .requireNonNull (name );
74+
75+ return r -> r .headers ().firstValue (name ).isPresent ();
76+ }
4877}
Original file line number Diff line number Diff line change @@ -34,4 +34,38 @@ class PredicatesTest {
3434 .accepts(r1)
3535 .rejects(r2)
3636 }
37+
38+ @Test
39+ fun `Should accept or reject with header name and value` () {
40+ // given
41+ val r = StaticHttpResponse .builder<Any >()
42+ .statusCode(200 )
43+ .headers(HttpHeadersBuilder ().add(" Content-Type" , " text/plain" ).build())
44+ .build()
45+
46+ // when + then
47+ assertThat(Predicates .hasHeader<Any >(" Content-Type" , " text/plain" ))
48+ .accepts(r)
49+
50+ assertThat(Predicates .hasHeader<Any >(" Content-Type" , " text/plain;charset=UTF-8" ))
51+ .rejects(r)
52+ assertThat(Predicates .hasHeader<Any >(" Content-Length" , " 12" ))
53+ .rejects(r)
54+ }
55+
56+ @Test
57+ fun `Should accept or reject with header name` () {
58+ // given
59+ val r = StaticHttpResponse .builder<Any >()
60+ .statusCode(200 )
61+ .headers(HttpHeadersBuilder ().add(" Content-Type" , " */*" ).build())
62+ .build()
63+
64+ // when + then
65+ assertThat(Predicates .hasHeader<Any >(" Content-Type" ))
66+ .accepts(r)
67+
68+ assertThat(Predicates .hasHeader<Any >(" Content-Length" ))
69+ .rejects(r)
70+ }
3771}
You can’t perform that action at this time.
0 commit comments