HTTPCLIENT-2186 - Migrate Test to Unit 5.

This commit is contained in:
Arturo Bernal 2021-11-18 06:40:38 +01:00 committed by Oleg Kalnichevski
parent ef9f8ba9ab
commit 0a42d173ef
174 changed files with 3777 additions and 3844 deletions

View File

@ -70,8 +70,8 @@
<optional>true</optional>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest</artifactId>
<scope>test</scope>
</dependency>
<dependency>
@ -86,6 +86,11 @@
<type>test-jar</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>

View File

@ -26,14 +26,14 @@
*/
package org.apache.hc.client5.http.cache;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.Mockito.mock;
import java.time.Instant;
@ -46,8 +46,8 @@ import org.apache.hc.client5.http.utils.DateUtils;
import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.message.BasicHeader;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class TestHttpCacheEntry {
@ -57,7 +57,7 @@ public class TestHttpCacheEntry {
private Resource mockResource;
private HttpCacheEntry entry;
@Before
@BeforeEach
public void setUp() {
now = Instant.now();
elevenSecondsAgo = now.minusSeconds(11);

View File

@ -34,7 +34,6 @@ import org.apache.hc.core5.http.MessageHeaders;
import org.apache.hc.core5.util.LangUtils;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.hamcrest.Factory;
import org.hamcrest.Matcher;
public class ContainsHeaderMatcher extends BaseMatcher<HttpCacheEntry> {
@ -66,7 +65,6 @@ public class ContainsHeaderMatcher extends BaseMatcher<HttpCacheEntry> {
description.appendText("contains header ").appendValue(headerValue).appendText(": ").appendValue(headerValue);
}
@Factory
public static Matcher<HttpCacheEntry> contains(final String headerName, final Object headerValue) {
return new ContainsHeaderMatcher(headerName, headerValue);
}

View File

@ -45,11 +45,10 @@ import org.apache.hc.client5.http.cache.Resource;
import org.apache.hc.client5.http.cache.ResourceIOException;
import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.http.message.BasicHeader;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.fail;
class HttpByteArrayCacheEntrySerializerTestUtils {
private final static String TEST_RESOURCE_DIR = "src/test/resources/";
@ -227,8 +226,7 @@ class HttpByteArrayCacheEntrySerializerTestUtils {
assertArrayEquals(expectedContent.getVariantMap().keySet().toArray(), actualContent.getVariantMap().keySet().toArray());
for (final String key : expectedContent.getVariantMap().keySet()) {
assertEquals("Expected same variantMap values for key '" + key + "'",
expectedContent.getVariantMap().get(key), actualContent.getVariantMap().get(key));
assertEquals(expectedContent.getVariantMap().get(key), actualContent.getVariantMap().get(key), "Expected same variantMap values for key '" + key + "'");
}
// Verify that the same headers are present on the expected and actual content.
@ -248,7 +246,7 @@ class HttpByteArrayCacheEntrySerializerTestUtils {
}
if (expectedContent.getResource() == null) {
assertNull("Expected null resource", actualContent.getResource());
assertNull(actualContent.getResource(), "Expected null resource");
} else {
final byte[] expectedBytes = readFullyStrict(
expectedContent.getResource().getInputStream(),

View File

@ -36,7 +36,6 @@ import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.util.LangUtils;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.hamcrest.Factory;
import org.hamcrest.Matcher;
public class HttpCacheEntryMatcher extends BaseMatcher<HttpCacheEntry> {
@ -97,7 +96,6 @@ public class HttpCacheEntryMatcher extends BaseMatcher<HttpCacheEntry> {
description.appendValue(expectedValue);
}
@Factory
public static Matcher<HttpCacheEntry> equivalent(final HttpCacheEntry target) {
return new HttpCacheEntryMatcher(target);
}

View File

@ -57,7 +57,7 @@ import org.apache.hc.core5.http.message.BasicHeader;
import org.apache.hc.core5.http.message.MessageSupport;
import org.apache.hc.core5.util.ByteArrayBuffer;
import org.apache.hc.core5.util.LangUtils;
import org.junit.Assert;
import org.junit.jupiter.api.Assertions;
public class HttpTestUtils {
@ -114,7 +114,7 @@ public class HttpTestUtils {
return false;
}
/*
* Assert.asserts that two request or response bodies are byte-equivalent.
* Assertions.asserts that two request or response bodies are byte-equivalent.
*/
public static boolean equivalent(final HttpEntity e1, final HttpEntity e2) throws Exception {
final InputStream i1 = e1.getContent();
@ -158,7 +158,7 @@ public class HttpTestUtils {
}
/*
* Assert.asserts that all the headers appearing in r1 also appear in r2
* Assertions.asserts that all the headers appearing in r1 also appear in r2
* with the same canonical header values.
*/
public static boolean isEndToEndHeaderSubset(final HttpMessage r1, final HttpMessage r2) {
@ -175,7 +175,7 @@ public class HttpTestUtils {
}
/*
* Assert.asserts that message {@code r2} represents exactly the same
* Assertions.asserts that message {@code r2} represents exactly the same
* message as {@code r1}, except for hop-by-hop headers. "When a cache
* is semantically transparent, the client receives exactly the same
* response (except for hop-by-hop headers) that it would have received had
@ -197,12 +197,12 @@ public class HttpTestUtils {
return isEndToEndHeaderSubset(r1, r2);
}
/* Assert.asserts that protocol versions equivalent. */
/* Assertions.asserts that protocol versions equivalent. */
public static boolean equivalent(final ProtocolVersion v1, final ProtocolVersion v2) {
return LangUtils.equals(v1 != null ? v1 : HttpVersion.DEFAULT, v2 != null ? v2 : HttpVersion.DEFAULT );
}
/* Assert.asserts that two requests are morally equivalent. */
/* Assertions.asserts that two requests are morally equivalent. */
public static boolean equivalent(final HttpRequest r1, final HttpRequest r2) {
return equivalent(r1.getVersion(), r2.getVersion()) &&
LangUtils.equals(r1.getMethod(), r2.getMethod()) &&
@ -210,7 +210,7 @@ public class HttpTestUtils {
isEndToEndHeaderSubset(r1, r2);
}
/* Assert.asserts that two requests are morally equivalent. */
/* Assertions.asserts that two requests are morally equivalent. */
public static boolean equivalent(final HttpResponse r1, final HttpResponse r2) {
return equivalent(r1.getVersion(), r2.getVersion()) &&
r1.getCode() == r2.getCode() &&
@ -352,7 +352,7 @@ public class HttpTestUtils {
break;
}
}
Assert.assertTrue(found110Warning);
Assertions.assertTrue(found110Warning);
}
public static ClassicHttpRequest makeDefaultRequest() {

View File

@ -26,6 +26,7 @@
*/
package org.apache.hc.client5.http.impl.cache;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ -42,20 +43,17 @@ import org.apache.hc.client5.http.cache.ResourceIOException;
import org.apache.hc.core5.concurrent.Cancellable;
import org.apache.hc.core5.concurrent.FutureCallback;
import org.hamcrest.CoreMatchers;
import org.hamcrest.MatcherAssert;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Answers;
import org.mockito.ArgumentCaptor;
import org.mockito.ArgumentMatchers;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.MockitoAnnotations;
import org.mockito.stubbing.Answer;
@RunWith(MockitoJUnitRunner.class)
public class TestAbstractSerializingAsyncCacheStorage {
@Mock
@ -73,9 +71,10 @@ public class TestAbstractSerializingAsyncCacheStorage {
return ByteArrayCacheEntrySerializer.INSTANCE.serialize(new HttpCacheStorageEntry(key, value));
}
@Before
@BeforeEach
@SuppressWarnings("unchecked")
public void setUp() {
MockitoAnnotations.openMocks(this);
impl = Mockito.mock(AbstractBinaryAsyncCacheStorage.class,
Mockito.withSettings().defaultAnswer(Answers.CALLS_REAL_METHODS).useConstructor(3));
}
@ -99,7 +98,7 @@ public class TestAbstractSerializingAsyncCacheStorage {
final ArgumentCaptor<byte[]> argumentCaptor = ArgumentCaptor.forClass(byte[].class);
Mockito.verify(impl).store(ArgumentMatchers.eq("bar"), argumentCaptor.capture(), ArgumentMatchers.any());
Assert.assertArrayEquals(serialize(key, value), argumentCaptor.getValue());
Assertions.assertArrayEquals(serialize(key, value), argumentCaptor.getValue());
Mockito.verify(operationCallback).completed(Boolean.TRUE);
}
@ -117,7 +116,7 @@ public class TestAbstractSerializingAsyncCacheStorage {
impl.getEntry(key, cacheEntryCallback);
final ArgumentCaptor<HttpCacheEntry> argumentCaptor = ArgumentCaptor.forClass(HttpCacheEntry.class);
Mockito.verify(cacheEntryCallback).completed(argumentCaptor.capture());
MatcherAssert.assertThat(argumentCaptor.getValue(), CoreMatchers.nullValue());
assertThat(argumentCaptor.getValue(), CoreMatchers.nullValue());
Mockito.verify(impl).restore(ArgumentMatchers.eq("bar"), ArgumentMatchers.any());
}
@ -137,7 +136,7 @@ public class TestAbstractSerializingAsyncCacheStorage {
final ArgumentCaptor<HttpCacheEntry> argumentCaptor = ArgumentCaptor.forClass(HttpCacheEntry.class);
Mockito.verify(cacheEntryCallback).completed(argumentCaptor.capture());
final HttpCacheEntry resultingEntry = argumentCaptor.getValue();
MatcherAssert.assertThat(resultingEntry, HttpCacheEntryMatcher.equivalent(value));
assertThat(resultingEntry, HttpCacheEntryMatcher.equivalent(value));
Mockito.verify(impl).restore(ArgumentMatchers.eq("bar"), ArgumentMatchers.any());
}
@ -155,7 +154,7 @@ public class TestAbstractSerializingAsyncCacheStorage {
impl.getEntry(key, cacheEntryCallback);
final ArgumentCaptor<HttpCacheEntry> argumentCaptor = ArgumentCaptor.forClass(HttpCacheEntry.class);
Mockito.verify(cacheEntryCallback).completed(argumentCaptor.capture());
MatcherAssert.assertThat(argumentCaptor.getValue(), CoreMatchers.nullValue());
assertThat(argumentCaptor.getValue(), CoreMatchers.nullValue());
Mockito.verify(impl).restore(ArgumentMatchers.eq("bar"), ArgumentMatchers.any());
}
@ -198,7 +197,7 @@ public class TestAbstractSerializingAsyncCacheStorage {
});
impl.updateEntry(key, existing -> {
MatcherAssert.assertThat(existing, CoreMatchers.nullValue());
assertThat(existing, CoreMatchers.nullValue());
return updatedValue;
}, operationCallback);
@ -262,7 +261,7 @@ public class TestAbstractSerializingAsyncCacheStorage {
});
impl.updateEntry(key, existing -> {
MatcherAssert.assertThat(existing, CoreMatchers.nullValue());
assertThat(existing, CoreMatchers.nullValue());
return updatedValue;
}, operationCallback);
@ -384,9 +383,9 @@ public class TestAbstractSerializingAsyncCacheStorage {
Mockito.verify(bulkCacheEntryCallback).completed(argumentCaptor.capture());
final Map<String, HttpCacheEntry> entryMap = argumentCaptor.getValue();
MatcherAssert.assertThat(entryMap, CoreMatchers.notNullValue());
MatcherAssert.assertThat(entryMap.get(key1), HttpCacheEntryMatcher.equivalent(value1));
MatcherAssert.assertThat(entryMap.get(key2), HttpCacheEntryMatcher.equivalent(value2));
assertThat(entryMap, CoreMatchers.notNullValue());
assertThat(entryMap.get(key1), HttpCacheEntryMatcher.equivalent(value1));
assertThat(entryMap.get(key2), HttpCacheEntryMatcher.equivalent(value2));
verify(impl, Mockito.times(2)).digestToStorageKey(key1);
verify(impl, Mockito.times(2)).digestToStorageKey(key2);
@ -429,9 +428,9 @@ public class TestAbstractSerializingAsyncCacheStorage {
Mockito.verify(bulkCacheEntryCallback).completed(argumentCaptor.capture());
final Map<String, HttpCacheEntry> entryMap = argumentCaptor.getValue();
MatcherAssert.assertThat(entryMap, CoreMatchers.notNullValue());
MatcherAssert.assertThat(entryMap.get(key1), HttpCacheEntryMatcher.equivalent(value1));
MatcherAssert.assertThat(entryMap.get(key2), CoreMatchers.nullValue());
assertThat(entryMap, CoreMatchers.notNullValue());
assertThat(entryMap.get(key1), HttpCacheEntryMatcher.equivalent(value1));
assertThat(entryMap.get(key2), CoreMatchers.nullValue());
verify(impl, Mockito.times(2)).digestToStorageKey(key1);
verify(impl, Mockito.times(2)).digestToStorageKey(key2);

View File

@ -26,6 +26,7 @@
*/
package org.apache.hc.client5.http.impl.cache;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ -40,10 +41,9 @@ import org.apache.hc.client5.http.cache.HttpCacheStorageEntry;
import org.apache.hc.client5.http.cache.HttpCacheUpdateException;
import org.apache.hc.client5.http.cache.ResourceIOException;
import org.hamcrest.CoreMatchers;
import org.hamcrest.MatcherAssert;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Answers;
import org.mockito.ArgumentCaptor;
import org.mockito.ArgumentMatchers;
@ -59,7 +59,7 @@ public class TestAbstractSerializingCacheStorage {
private AbstractBinaryCacheStorage<String> impl;
@Before
@BeforeEach
@SuppressWarnings("unchecked")
public void setUp() {
impl = Mockito.mock(AbstractBinaryCacheStorage.class,
@ -77,7 +77,7 @@ public class TestAbstractSerializingCacheStorage {
final ArgumentCaptor<byte[]> argumentCaptor = ArgumentCaptor.forClass(byte[].class);
verify(impl).store(eq("bar"), argumentCaptor.capture());
Assert.assertArrayEquals(serialize(key, value), argumentCaptor.getValue());
Assertions.assertArrayEquals(serialize(key, value), argumentCaptor.getValue());
}
@Test
@ -91,7 +91,7 @@ public class TestAbstractSerializingCacheStorage {
verify(impl).restore("bar");
MatcherAssert.assertThat(resultingEntry, CoreMatchers.nullValue());
assertThat(resultingEntry, CoreMatchers.nullValue());
}
@Test
@ -106,7 +106,7 @@ public class TestAbstractSerializingCacheStorage {
verify(impl).restore("bar");
MatcherAssert.assertThat(resultingEntry, HttpCacheEntryMatcher.equivalent(value));
assertThat(resultingEntry, HttpCacheEntryMatcher.equivalent(value));
}
@Test
@ -121,7 +121,7 @@ public class TestAbstractSerializingCacheStorage {
verify(impl).restore("bar");
MatcherAssert.assertThat(resultingEntry, CoreMatchers.nullValue());
assertThat(resultingEntry, CoreMatchers.nullValue());
}
@Test
@ -143,7 +143,7 @@ public class TestAbstractSerializingCacheStorage {
when(impl.getForUpdateCAS("bar")).thenReturn(null);
impl.updateEntry(key, existing -> {
MatcherAssert.assertThat(existing, CoreMatchers.nullValue());
assertThat(existing, CoreMatchers.nullValue());
return updatedValue;
});
@ -181,7 +181,7 @@ public class TestAbstractSerializingCacheStorage {
when(impl.updateCAS(ArgumentMatchers.eq("bar"), ArgumentMatchers.eq("stuff"), ArgumentMatchers.any())).thenReturn(true);
impl.updateEntry(key, existing -> {
MatcherAssert.assertThat(existing, CoreMatchers.nullValue());
assertThat(existing, CoreMatchers.nullValue());
return updatedValue;
});
@ -220,7 +220,7 @@ public class TestAbstractSerializingCacheStorage {
when(impl.updateCAS(ArgumentMatchers.eq("bar"), ArgumentMatchers.eq("stuff"), ArgumentMatchers.any()))
.thenReturn(false, false, false, true);
Assert.assertThrows(HttpCacheUpdateException.class, () -> impl.updateEntry(key, existing -> updatedValue));
Assertions.assertThrows(HttpCacheUpdateException.class, () -> impl.updateEntry(key, existing -> updatedValue));
verify(impl, Mockito.times(3)).getForUpdateCAS("bar");
verify(impl, Mockito.times(3)).getStorageObject("stuff");
@ -252,9 +252,9 @@ public class TestAbstractSerializingCacheStorage {
});
final Map<String, HttpCacheEntry> entryMap = impl.getEntries(Arrays.asList(key1, key2));
MatcherAssert.assertThat(entryMap, CoreMatchers.notNullValue());
MatcherAssert.assertThat(entryMap.get(key1), HttpCacheEntryMatcher.equivalent(value1));
MatcherAssert.assertThat(entryMap.get(key2), HttpCacheEntryMatcher.equivalent(value2));
assertThat(entryMap, CoreMatchers.notNullValue());
assertThat(entryMap.get(key1), HttpCacheEntryMatcher.equivalent(value1));
assertThat(entryMap.get(key2), HttpCacheEntryMatcher.equivalent(value2));
verify(impl, Mockito.times(2)).digestToStorageKey(key1);
verify(impl, Mockito.times(2)).digestToStorageKey(key2);
@ -286,9 +286,9 @@ public class TestAbstractSerializingCacheStorage {
});
final Map<String, HttpCacheEntry> entryMap = impl.getEntries(Arrays.asList(key1, key2));
MatcherAssert.assertThat(entryMap, CoreMatchers.notNullValue());
MatcherAssert.assertThat(entryMap.get(key1), HttpCacheEntryMatcher.equivalent(value1));
MatcherAssert.assertThat(entryMap.get(key2), CoreMatchers.nullValue());
assertThat(entryMap, CoreMatchers.notNullValue());
assertThat(entryMap.get(key1), HttpCacheEntryMatcher.equivalent(value1));
assertThat(entryMap.get(key2), CoreMatchers.nullValue());
verify(impl, Mockito.times(2)).digestToStorageKey(key1);
verify(impl, Mockito.times(2)).digestToStorageKey(key2);

View File

@ -26,11 +26,12 @@
*/
package org.apache.hc.client5.http.impl.cache;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import java.time.Instant;
import java.util.Date;
@ -53,16 +54,15 @@ import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.message.BasicHeader;
import org.apache.hc.core5.http.message.BasicHttpResponse;
import org.apache.hc.core5.util.ByteArrayBuffer;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class TestBasicHttpCache {
private BasicHttpCache impl;
private SimpleHttpCacheStorage backing;
@Before
@BeforeEach
public void setUp() throws Exception {
backing = new SimpleHttpCacheStorage();
impl = new BasicHttpCache(new HeapResourceFactory(), backing);
@ -198,7 +198,7 @@ public class TestBasicHttpCache {
final HttpHost host = new HttpHost("foo.example.com");
final HttpRequest request = new HttpGet("http://foo.example.com/bar");
final HttpCacheEntry result = impl.getCacheEntry(host, request);
Assert.assertNull(result);
assertNull(result);
}
@Test
@ -213,7 +213,7 @@ public class TestBasicHttpCache {
backing.map.put(key,entry);
final HttpCacheEntry result = impl.getCacheEntry(host, request);
Assert.assertSame(entry, result);
assertSame(entry, result);
}
@Test

View File

@ -26,9 +26,11 @@
*/
package org.apache.hc.client5.http.impl.cache;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@ -46,15 +48,14 @@ import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.message.BasicHeader;
import org.apache.hc.core5.http.message.StatusLine;
import org.hamcrest.MatcherAssert;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class TestByteArrayCacheEntrySerializer {
private ByteArrayCacheEntrySerializer impl;
@Before
@BeforeEach
public void setUp() {
impl = new ByteArrayCacheEntrySerializer();
}
@ -253,7 +254,7 @@ public class TestByteArrayCacheEntrySerializer {
final HttpCacheStorageEntry readEntry = impl.deserialize(bytes);
// compare
assertEquals(readEntry.getKey(), writeEntry.getKey());
MatcherAssert. assertThat(readEntry.getContent(), HttpCacheEntryMatcher.equivalent(writeEntry.getContent()));
assertThat(readEntry.getContent(), HttpCacheEntryMatcher.equivalent(writeEntry.getContent()));
}
private HttpCacheStorageEntry makeCacheEntryWithVariantMap(final String key) {

View File

@ -38,9 +38,9 @@ import org.apache.hc.core5.http.HttpRequest;
import org.apache.hc.core5.http.message.BasicHeader;
import org.apache.hc.core5.http.message.BasicHeaderIterator;
import org.apache.hc.core5.http.message.BasicHttpRequest;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@SuppressWarnings({"boxing","static-access"}) // this is test code
public class TestCacheKeyGenerator {
@ -54,7 +54,7 @@ public class TestCacheKeyGenerator {
private HttpCacheEntry mockEntry;
private HttpRequest mockRequest;
@Before
@BeforeEach
public void setUp() throws Exception {
defaultHost = new HttpHost("foo.example.com");
mockEntry = mock(HttpCacheEntry.class);
@ -66,50 +66,50 @@ public class TestCacheKeyGenerator {
public void testExtractsUriFromAbsoluteUriInRequest() {
final HttpHost host = new HttpHost("bar.example.com");
final HttpRequest req = new HttpGet("http://foo.example.com/");
Assert.assertEquals("http://foo.example.com:80/", extractor.generateKey(host, req));
Assertions.assertEquals("http://foo.example.com:80/", extractor.generateKey(host, req));
}
@Test
public void testGetURIWithDefaultPortAndScheme() {
Assert.assertEquals("http://www.comcast.net:80/", extractor.generateKey(new HttpHost(
Assertions.assertEquals("http://www.comcast.net:80/", extractor.generateKey(new HttpHost(
"www.comcast.net"), REQUEST_ROOT));
Assert.assertEquals("http://www.fancast.com:80/full_episodes", extractor.generateKey(new HttpHost(
Assertions.assertEquals("http://www.fancast.com:80/full_episodes", extractor.generateKey(new HttpHost(
"www.fancast.com"), REQUEST_FULL_EPISODES));
}
@Test
public void testGetURIWithDifferentScheme() {
Assert.assertEquals("https://www.comcast.net:443/", extractor.generateKey(
Assertions.assertEquals("https://www.comcast.net:443/", extractor.generateKey(
new HttpHost("https", "www.comcast.net", -1), REQUEST_ROOT));
Assert.assertEquals("myhttp://www.fancast.com/full_episodes", extractor.generateKey(
Assertions.assertEquals("myhttp://www.fancast.com/full_episodes", extractor.generateKey(
new HttpHost("myhttp", "www.fancast.com", -1), REQUEST_FULL_EPISODES));
}
@Test
public void testGetURIWithDifferentPort() {
Assert.assertEquals("http://www.comcast.net:8080/", extractor.generateKey(new HttpHost(
Assertions.assertEquals("http://www.comcast.net:8080/", extractor.generateKey(new HttpHost(
"www.comcast.net", 8080), REQUEST_ROOT));
Assert.assertEquals("http://www.fancast.com:9999/full_episodes", extractor.generateKey(
Assertions.assertEquals("http://www.fancast.com:9999/full_episodes", extractor.generateKey(
new HttpHost("www.fancast.com", 9999), REQUEST_FULL_EPISODES));
}
@Test
public void testGetURIWithDifferentPortAndScheme() {
Assert.assertEquals("https://www.comcast.net:8080/", extractor.generateKey(
Assertions.assertEquals("https://www.comcast.net:8080/", extractor.generateKey(
new HttpHost("https", "www.comcast.net", 8080), REQUEST_ROOT));
Assert.assertEquals("myhttp://www.fancast.com:9999/full_episodes", extractor.generateKey(
Assertions.assertEquals("myhttp://www.fancast.com:9999/full_episodes", extractor.generateKey(
new HttpHost("myhttp", "www.fancast.com", 9999), REQUEST_FULL_EPISODES));
}
@Test
public void testGetURIWithQueryParameters() {
Assert.assertEquals("http://www.comcast.net:80/?foo=bar", extractor.generateKey(
Assertions.assertEquals("http://www.comcast.net:80/?foo=bar", extractor.generateKey(
new HttpHost("http", "www.comcast.net", -1), new BasicHttpRequest("GET", "/?foo=bar")));
Assert.assertEquals("http://www.fancast.com:80/full_episodes?foo=bar", extractor.generateKey(
Assertions.assertEquals("http://www.fancast.com:80/full_episodes?foo=bar", extractor.generateKey(
new HttpHost("http", "www.fancast.com", -1), new BasicHttpRequest("GET",
"/full_episodes?foo=bar")));
}
@ -121,15 +121,15 @@ public class TestCacheKeyGenerator {
extractor = new CacheKeyGenerator() {
@Override
public String generateKey(final HttpHost h, final HttpRequest request) {
Assert.assertSame(defaultHost, h);
Assert.assertSame(mockRequest, request);
Assertions.assertSame(defaultHost, h);
Assertions.assertSame(mockRequest, request);
return theURI;
}
};
final String result = extractor.generateKey(defaultHost, mockRequest, mockEntry);
verify(mockEntry).hasVariants();
Assert.assertSame(theURI, result);
Assertions.assertSame(theURI, result);
}
@Test
@ -141,8 +141,8 @@ public class TestCacheKeyGenerator {
extractor = new CacheKeyGenerator() {
@Override
public String generateKey(final HttpHost h, final HttpRequest request) {
Assert.assertSame(defaultHost, h);
Assert.assertSame(mockRequest, request);
Assertions.assertSame(defaultHost, h);
Assertions.assertSame(mockRequest, request);
return theURI;
}
};
@ -155,7 +155,7 @@ public class TestCacheKeyGenerator {
verify(mockEntry).hasVariants();
verify(mockEntry).headerIterator("Vary");
verify(mockRequest).getHeaders("Accept-Encoding");
Assert.assertEquals("{Accept-Encoding=gzip}" + theURI, result);
Assertions.assertEquals("{Accept-Encoding=gzip}" + theURI, result);
}
@Test
@ -166,8 +166,8 @@ public class TestCacheKeyGenerator {
extractor = new CacheKeyGenerator() {
@Override
public String generateKey(final HttpHost h, final HttpRequest request) {
Assert.assertSame(defaultHost, h);
Assert.assertSame(mockRequest, request);
Assertions.assertSame(defaultHost, h);
Assertions.assertSame(mockRequest, request);
return theURI;
}
};
@ -181,7 +181,7 @@ public class TestCacheKeyGenerator {
verify(mockEntry).hasVariants();
verify(mockEntry).headerIterator("Vary");
verify(mockRequest).getHeaders("Accept-Encoding");
Assert.assertEquals("{Accept-Encoding=}" + theURI, result);
Assertions.assertEquals("{Accept-Encoding=}" + theURI, result);
}
@Test
@ -193,8 +193,8 @@ public class TestCacheKeyGenerator {
extractor = new CacheKeyGenerator() {
@Override
public String generateKey(final HttpHost h, final HttpRequest request) {
Assert.assertSame(defaultHost, h);
Assert.assertSame(mockRequest, request);
Assertions.assertSame(defaultHost, h);
Assertions.assertSame(mockRequest, request);
return theURI;
}
};
@ -209,7 +209,7 @@ public class TestCacheKeyGenerator {
verify(mockEntry).headerIterator("Vary");
verify(mockRequest).getHeaders("Accept-Encoding");
verify(mockRequest).getHeaders("User-Agent");
Assert.assertEquals("{Accept-Encoding=gzip&User-Agent=browser}" + theURI, result);
Assertions.assertEquals("{Accept-Encoding=gzip&User-Agent=browser}" + theURI, result);
}
@Test
@ -222,8 +222,8 @@ public class TestCacheKeyGenerator {
extractor = new CacheKeyGenerator() {
@Override
public String generateKey(final HttpHost h, final HttpRequest request) {
Assert.assertSame(defaultHost, h);
Assert.assertSame(mockRequest, request);
Assertions.assertSame(defaultHost, h);
Assertions.assertSame(mockRequest, request);
return theURI;
}
};
@ -238,7 +238,7 @@ public class TestCacheKeyGenerator {
verify(mockEntry).headerIterator("Vary");
verify(mockRequest).getHeaders("Accept-Encoding");
verify(mockRequest).getHeaders("User-Agent");
Assert.assertEquals("{Accept-Encoding=gzip&User-Agent=browser}" + theURI, result);
Assertions.assertEquals("{Accept-Encoding=gzip&User-Agent=browser}" + theURI, result);
}
@Test
@ -251,8 +251,8 @@ public class TestCacheKeyGenerator {
extractor = new CacheKeyGenerator() {
@Override
public String generateKey(final HttpHost h, final HttpRequest request) {
Assert.assertSame(defaultHost, h);
Assert.assertSame(mockRequest, request);
Assertions.assertSame(defaultHost, h);
Assertions.assertSame(mockRequest, request);
return theURI;
}
};
@ -267,7 +267,7 @@ public class TestCacheKeyGenerator {
verify(mockEntry).headerIterator("Vary");
verify(mockRequest).getHeaders("Accept-Encoding");
verify(mockRequest).getHeaders("User-Agent");
Assert.assertEquals("{Accept-Encoding=gzip%2C+deflate&User-Agent=browser}" + theURI, result);
Assertions.assertEquals("{Accept-Encoding=gzip%2C+deflate&User-Agent=browser}" + theURI, result);
}
/*
@ -289,7 +289,7 @@ public class TestCacheKeyGenerator {
final HttpHost host1 = new HttpHost("foo.example.com:");
final HttpHost host2 = new HttpHost("foo.example.com:80");
final HttpRequest req = new BasicHttpRequest("GET", "/");
Assert.assertEquals(extractor.generateKey(host1, req), extractor.generateKey(host2, req));
Assertions.assertEquals(extractor.generateKey(host1, req), extractor.generateKey(host2, req));
}
@Test
@ -299,7 +299,7 @@ public class TestCacheKeyGenerator {
final HttpRequest req = new BasicHttpRequest("GET", "/");
final String uri1 = extractor.generateKey(host1, req);
final String uri2 = extractor.generateKey(host2, req);
Assert.assertEquals(uri1, uri2);
Assertions.assertEquals(uri1, uri2);
}
@Test
@ -309,7 +309,7 @@ public class TestCacheKeyGenerator {
final HttpGet get2 = new HttpGet("https://bar.example.com:443/");
final String uri1 = extractor.generateKey(host, get1);
final String uri2 = extractor.generateKey(host, get2);
Assert.assertEquals(uri1, uri2);
Assertions.assertEquals(uri1, uri2);
}
@Test
@ -319,7 +319,7 @@ public class TestCacheKeyGenerator {
final HttpGet get2 = new HttpGet("https://bar.example.com:443/");
final String uri1 = extractor.generateKey(host, get1);
final String uri2 = extractor.generateKey(host, get2);
Assert.assertEquals(uri1, uri2);
Assertions.assertEquals(uri1, uri2);
}
@Test
@ -327,7 +327,7 @@ public class TestCacheKeyGenerator {
final HttpHost host1 = new HttpHost("foo.example.com");
final HttpHost host2 = new HttpHost("foo.example.com:80");
final HttpRequest req = new BasicHttpRequest("GET", "/");
Assert.assertEquals(extractor.generateKey(host1, req), extractor.generateKey(host2, req));
Assertions.assertEquals(extractor.generateKey(host1, req), extractor.generateKey(host2, req));
}
@Test
@ -335,7 +335,7 @@ public class TestCacheKeyGenerator {
final HttpHost host1 = new HttpHost("foo.example.com");
final HttpHost host2 = new HttpHost("FOO.EXAMPLE.COM");
final HttpRequest req = new BasicHttpRequest("GET", "/");
Assert.assertEquals(extractor.generateKey(host1, req), extractor.generateKey(host2, req));
Assertions.assertEquals(extractor.generateKey(host1, req), extractor.generateKey(host2, req));
}
@Test
@ -343,7 +343,7 @@ public class TestCacheKeyGenerator {
final HttpHost host1 = new HttpHost("http", "foo.example.com", -1);
final HttpHost host2 = new HttpHost("HTTP", "foo.example.com", -1);
final HttpRequest req = new BasicHttpRequest("GET", "/");
Assert.assertEquals(extractor.generateKey(host1, req), extractor.generateKey(host2, req));
Assertions.assertEquals(extractor.generateKey(host1, req), extractor.generateKey(host2, req));
}
@Test
@ -351,7 +351,7 @@ public class TestCacheKeyGenerator {
final HttpHost host = new HttpHost("foo.example.com");
final HttpRequest req1 = new BasicHttpRequest("GET", "/");
final HttpRequest req2 = new HttpGet("http://foo.example.com");
Assert.assertEquals(extractor.generateKey(host, req1), extractor.generateKey(host, req2));
Assertions.assertEquals(extractor.generateKey(host, req1), extractor.generateKey(host, req2));
}
@Test
@ -359,7 +359,7 @@ public class TestCacheKeyGenerator {
final HttpHost host = new HttpHost("foo.example.com");
final HttpRequest req1 = new BasicHttpRequest("GET", "/");
final HttpRequest req2 = new HttpGet("http://foo.example.com/./");
Assert.assertEquals(extractor.generateKey(host, req1), extractor.generateKey(host, req2));
Assertions.assertEquals(extractor.generateKey(host, req1), extractor.generateKey(host, req2));
}
@Test
@ -367,7 +367,7 @@ public class TestCacheKeyGenerator {
final HttpHost host = new HttpHost("foo.example.com");
final HttpRequest req1 = new BasicHttpRequest("GET", "/");
final HttpRequest req2 = new HttpGet("http://foo.example.com/.././../");
Assert.assertEquals(extractor.generateKey(host, req1), extractor.generateKey(host, req2));
Assertions.assertEquals(extractor.generateKey(host, req1), extractor.generateKey(host, req2));
}
@Test
@ -375,7 +375,7 @@ public class TestCacheKeyGenerator {
final HttpHost host = new HttpHost("foo.example.com");
final HttpRequest req1 = new BasicHttpRequest("GET", "/home.html");
final HttpRequest req2 = new BasicHttpRequest("GET", "/%7Esmith/../home.html");
Assert.assertEquals(extractor.generateKey(host, req1), extractor.generateKey(host, req2));
Assertions.assertEquals(extractor.generateKey(host, req1), extractor.generateKey(host, req2));
}
@Test
@ -383,7 +383,7 @@ public class TestCacheKeyGenerator {
final HttpHost host = new HttpHost("foo.example.com");
final HttpRequest req1 = new BasicHttpRequest("GET", "/home.html");
final HttpRequest req2 = new BasicHttpRequest("GET", "/%7Esmith/../home.html");
Assert.assertEquals(extractor.generateKey(host, req1), extractor.generateKey(host, req2));
Assertions.assertEquals(extractor.generateKey(host, req1), extractor.generateKey(host, req2));
}
@Test
@ -391,7 +391,7 @@ public class TestCacheKeyGenerator {
final HttpHost host = new HttpHost("foo.example.com");
final HttpRequest req1 = new BasicHttpRequest("GET", "/~smith/home.html");
final HttpRequest req2 = new BasicHttpRequest("GET", "/%7Esmith/./home.html");
Assert.assertEquals(extractor.generateKey(host, req1), extractor.generateKey(host, req2));
Assertions.assertEquals(extractor.generateKey(host, req1), extractor.generateKey(host, req2));
}
@Test
@ -399,7 +399,7 @@ public class TestCacheKeyGenerator {
final HttpHost host = new HttpHost("foo.example.com");
final HttpRequest req1 = new BasicHttpRequest("GET", "/~smith/home.html");
final HttpRequest req2 = new BasicHttpRequest("GET", "/%7Esmith/home.html");
Assert.assertEquals(extractor.generateKey(host, req1), extractor.generateKey(host, req2));
Assertions.assertEquals(extractor.generateKey(host, req1), extractor.generateKey(host, req2));
}
@Test
@ -407,7 +407,7 @@ public class TestCacheKeyGenerator {
final HttpHost host = new HttpHost("foo.example.com");
final HttpRequest req1 = new BasicHttpRequest("GET", "/~smith/home.html");
final HttpRequest req2 = new BasicHttpRequest("GET", "/%7Esmith/home.html");
Assert.assertEquals(extractor.generateKey(host, req1), extractor.generateKey(host, req2));
Assertions.assertEquals(extractor.generateKey(host, req1), extractor.generateKey(host, req2));
}
@Test
@ -415,6 +415,6 @@ public class TestCacheKeyGenerator {
final HttpHost host = new HttpHost("foo.example.com");
final HttpRequest req1 = new BasicHttpRequest("GET", "/~smith/home%20folder.html");
final HttpRequest req2 = new BasicHttpRequest("GET", "/%7Esmith/home%20folder.html");
Assert.assertEquals(extractor.generateKey(host, req1), extractor.generateKey(host, req2));
Assertions.assertEquals(extractor.generateKey(host, req1), extractor.generateKey(host, req2));
}
}

View File

@ -26,6 +26,7 @@
*/
package org.apache.hc.client5.http.impl.cache;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ -40,16 +41,13 @@ import org.apache.hc.core5.http.message.BasicHttpResponse;
import org.apache.hc.core5.util.TimeValue;
import org.apache.hc.core5.util.Timeout;
import org.hamcrest.CoreMatchers;
import org.hamcrest.MatcherAssert;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentMatchers;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.MockitoAnnotations;
@RunWith(MockitoJUnitRunner.class)
public class TestCacheRevalidatorBase {
@Mock
@ -62,8 +60,9 @@ public class TestCacheRevalidatorBase {
private CacheRevalidatorBase impl;
@Before
@BeforeEach
public void setUp() {
MockitoAnnotations.openMocks(this);
impl = new CacheRevalidatorBase(mockScheduledExecutor, mockSchedulingStrategy);
}
@ -77,7 +76,7 @@ public class TestCacheRevalidatorBase {
verify(mockSchedulingStrategy).schedule(0);
verify(mockScheduledExecutor).schedule(ArgumentMatchers.same(mockOperation), ArgumentMatchers.eq(TimeValue.ofSeconds(1)));
Assert.assertEquals(1, impl.getScheduledIdentifiers().size());
Assertions.assertEquals(1, impl.getScheduledIdentifiers().size());
}
@Test
@ -90,12 +89,12 @@ public class TestCacheRevalidatorBase {
verify(mockSchedulingStrategy).schedule(0);
verify(mockScheduledExecutor).schedule(ArgumentMatchers.any(), ArgumentMatchers.eq(TimeValue.ofSeconds(3)));
Assert.assertEquals(1, impl.getScheduledIdentifiers().size());
Assert.assertTrue(impl.getScheduledIdentifiers().contains(cacheKey));
Assertions.assertEquals(1, impl.getScheduledIdentifiers().size());
Assertions.assertTrue(impl.getScheduledIdentifiers().contains(cacheKey));
impl.jobSuccessful(cacheKey);
Assert.assertEquals(0, impl.getScheduledIdentifiers().size());
Assertions.assertEquals(0, impl.getScheduledIdentifiers().size());
}
@Test
@ -106,7 +105,7 @@ public class TestCacheRevalidatorBase {
final String cacheKey = "blah";
impl.scheduleRevalidation(cacheKey, mockOperation);
Assert.assertEquals(0, impl.getScheduledIdentifiers().size());
Assertions.assertEquals(0, impl.getScheduledIdentifiers().size());
verify(mockScheduledExecutor).schedule(ArgumentMatchers.any(), ArgumentMatchers.eq(TimeValue.ofSeconds(2)));
}
@ -122,25 +121,25 @@ public class TestCacheRevalidatorBase {
verify(mockSchedulingStrategy).schedule(ArgumentMatchers.anyInt());
verify(mockScheduledExecutor).schedule(ArgumentMatchers.any(), ArgumentMatchers.eq(TimeValue.ofSeconds(2)));
Assert.assertEquals(1, impl.getScheduledIdentifiers().size());
Assertions.assertEquals(1, impl.getScheduledIdentifiers().size());
}
@Test
public void testStaleResponse() {
final HttpResponse response1 = new BasicHttpResponse(HttpStatus.SC_OK);
response1.addHeader(HeaderConstants.WARNING, "110 localhost \"Response is stale\"");
MatcherAssert.assertThat(impl.isStale(response1), CoreMatchers.equalTo(true));
assertThat(impl.isStale(response1), CoreMatchers.equalTo(true));
final HttpResponse response2 = new BasicHttpResponse(HttpStatus.SC_OK);
response2.addHeader(HeaderConstants.WARNING, "111 localhost \"Revalidation failed\"");
MatcherAssert.assertThat(impl.isStale(response2), CoreMatchers.equalTo(true));
assertThat(impl.isStale(response2), CoreMatchers.equalTo(true));
final HttpResponse response3 = new BasicHttpResponse(HttpStatus.SC_OK);
response3.addHeader(HeaderConstants.WARNING, "xxx localhost \"Huh?\"");
MatcherAssert.assertThat(impl.isStale(response3), CoreMatchers.equalTo(false));
assertThat(impl.isStale(response3), CoreMatchers.equalTo(false));
final HttpResponse response4 = new BasicHttpResponse(HttpStatus.SC_OK);
MatcherAssert.assertThat(impl.isStale(response4), CoreMatchers.equalTo(false));
assertThat(impl.isStale(response4), CoreMatchers.equalTo(false));
}
@Test

View File

@ -26,9 +26,11 @@
*/
package org.apache.hc.client5.http.impl.cache;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.fail;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.fail;
import java.io.IOException;
import java.time.Instant;
@ -43,9 +45,8 @@ import org.apache.hc.core5.http.HttpResponse;
import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.message.BasicHeader;
import org.apache.hc.core5.http.message.BasicHttpResponse;
import org.hamcrest.MatcherAssert;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class TestCacheUpdateHandler {
@ -61,7 +62,7 @@ public class TestCacheUpdateHandler {
private Instant tenSecondsAgo;
private HttpResponse response;
@Before
@BeforeEach
public void setUp() throws Exception {
requestDate = Instant.now().minusSeconds(1);
responseDate = Instant.now();
@ -97,8 +98,8 @@ public class TestCacheUpdateHandler {
final HttpCacheEntry updatedEntry = impl.updateCacheEntry(null, entry,
new Date(), new Date(), response);
MatcherAssert. assertThat(updatedEntry, ContainsHeaderMatcher.contains("Date", DateUtils.formatStandardDate(responseDate)));
MatcherAssert. assertThat(updatedEntry, ContainsHeaderMatcher.contains("ETag", "\"etag\""));
assertThat(updatedEntry, ContainsHeaderMatcher.contains("Date", DateUtils.formatStandardDate(responseDate)));
assertThat(updatedEntry, ContainsHeaderMatcher.contains("ETag", "\"etag\""));
}
@Test
@ -117,10 +118,10 @@ public class TestCacheUpdateHandler {
final HttpCacheEntry updatedEntry = impl.updateCacheEntry(null, entry,
new Date(), new Date(), response);
MatcherAssert. assertThat(updatedEntry, ContainsHeaderMatcher.contains("Date", DateUtils.formatStandardDate(requestDate)));
MatcherAssert. assertThat(updatedEntry, ContainsHeaderMatcher.contains("ETag", "\"etag\""));
MatcherAssert. assertThat(updatedEntry, ContainsHeaderMatcher.contains("Last-Modified", DateUtils.formatStandardDate(responseDate)));
MatcherAssert. assertThat(updatedEntry, ContainsHeaderMatcher.contains("Cache-Control", "public"));
assertThat(updatedEntry, ContainsHeaderMatcher.contains("Date", DateUtils.formatStandardDate(requestDate)));
assertThat(updatedEntry, ContainsHeaderMatcher.contains("ETag", "\"etag\""));
assertThat(updatedEntry, ContainsHeaderMatcher.contains("Last-Modified", DateUtils.formatStandardDate(responseDate)));
assertThat(updatedEntry, ContainsHeaderMatcher.contains("Cache-Control", "public"));
}
@Test
@ -137,10 +138,10 @@ public class TestCacheUpdateHandler {
final HttpCacheEntry updatedEntry = impl.updateCacheEntry(null, entry,
new Date(), new Date(), response);
MatcherAssert. assertThat(updatedEntry, ContainsHeaderMatcher.contains("Date", DateUtils.formatStandardDate(requestDate)));
MatcherAssert. assertThat(updatedEntry, ContainsHeaderMatcher.contains("ETag", "\"etag\""));
MatcherAssert. assertThat(updatedEntry, ContainsHeaderMatcher.contains("Last-Modified", DateUtils.formatStandardDate(responseDate)));
MatcherAssert. assertThat(updatedEntry, ContainsHeaderMatcher.contains("Cache-Control", "public"));
assertThat(updatedEntry, ContainsHeaderMatcher.contains("Date", DateUtils.formatStandardDate(requestDate)));
assertThat(updatedEntry, ContainsHeaderMatcher.contains("ETag", "\"etag\""));
assertThat(updatedEntry, ContainsHeaderMatcher.contains("Last-Modified", DateUtils.formatStandardDate(responseDate)));
assertThat(updatedEntry, ContainsHeaderMatcher.contains("Cache-Control", "public"));
}
@Test
@ -155,8 +156,8 @@ public class TestCacheUpdateHandler {
response.setHeader("ETag", "\"old-etag\"");
final HttpCacheEntry result = impl.updateCacheEntry("A", entry, new Date(),
new Date(), response);
MatcherAssert. assertThat(result, ContainsHeaderMatcher.contains("Date", DateUtils.formatStandardDate(oneSecondAgo)));
MatcherAssert. assertThat(result, ContainsHeaderMatcher.contains("ETag", "\"new-etag\""));
assertThat(result, ContainsHeaderMatcher.contains("Date", DateUtils.formatStandardDate(oneSecondAgo)));
assertThat(result, ContainsHeaderMatcher.contains("ETag", "\"new-etag\""));
}
@Test

View File

@ -26,10 +26,11 @@
*/
package org.apache.hc.client5.http.impl.cache;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.time.Instant;
import java.util.Date;
@ -42,8 +43,8 @@ import org.apache.hc.core5.http.HttpRequest;
import org.apache.hc.core5.http.message.BasicHeader;
import org.apache.hc.core5.http.message.BasicHttpRequest;
import org.apache.hc.core5.util.TimeValue;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class TestCacheValidityPolicy {
@ -54,7 +55,7 @@ public class TestCacheValidityPolicy {
private Instant tenSecondsAgo;
private Instant elevenSecondsAgo;
@Before
@BeforeEach
public void setUp() {
impl = new CacheValidityPolicy();
now = Instant.now();

View File

@ -27,15 +27,15 @@
package org.apache.hc.client5.http.impl.cache;
import org.apache.hc.core5.http.message.BasicHttpRequest;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class TestCacheableRequestPolicy {
private CacheableRequestPolicy policy;
@Before
@BeforeEach
public void setUp() throws Exception {
policy = new CacheableRequestPolicy();
}
@ -44,7 +44,7 @@ public class TestCacheableRequestPolicy {
public void testIsGetServableFromCache() {
final BasicHttpRequest request = new BasicHttpRequest("GET", "someUri");
Assert.assertTrue(policy.isServableFromCache(request));
Assertions.assertTrue(policy.isServableFromCache(request));
}
@Test
@ -52,19 +52,19 @@ public class TestCacheableRequestPolicy {
BasicHttpRequest request = new BasicHttpRequest("GET", "someUri");
request.addHeader("Cache-Control", "no-cache");
Assert.assertFalse(policy.isServableFromCache(request));
Assertions.assertFalse(policy.isServableFromCache(request));
request = new BasicHttpRequest("GET", "someUri");
request.addHeader("Cache-Control", "no-store");
request.addHeader("Cache-Control", "max-age=20");
Assert.assertFalse(policy.isServableFromCache(request));
Assertions.assertFalse(policy.isServableFromCache(request));
request = new BasicHttpRequest("GET", "someUri");
request.addHeader("Cache-Control", "public");
request.addHeader("Cache-Control", "no-store, max-age=20");
Assert.assertFalse(policy.isServableFromCache(request));
Assertions.assertFalse(policy.isServableFromCache(request));
}
@Test
@ -72,26 +72,26 @@ public class TestCacheableRequestPolicy {
BasicHttpRequest request = new BasicHttpRequest("GET", "someUri");
request.addHeader("Pragma", "no-cache");
Assert.assertFalse(policy.isServableFromCache(request));
Assertions.assertFalse(policy.isServableFromCache(request));
request = new BasicHttpRequest("GET", "someUri");
request.addHeader("Pragma", "value1");
request.addHeader("Pragma", "value2");
Assert.assertFalse(policy.isServableFromCache(request));
Assertions.assertFalse(policy.isServableFromCache(request));
}
@Test
public void testIsHeadServableFromCache() {
BasicHttpRequest request = new BasicHttpRequest("HEAD", "someUri");
Assert.assertTrue(policy.isServableFromCache(request));
Assertions.assertTrue(policy.isServableFromCache(request));
request = new BasicHttpRequest("HEAD", "someUri");
request.addHeader("Cache-Control", "public");
request.addHeader("Cache-Control", "max-age=20");
Assert.assertTrue(policy.isServableFromCache(request));
Assertions.assertTrue(policy.isServableFromCache(request));
}
@Test
@ -99,19 +99,19 @@ public class TestCacheableRequestPolicy {
BasicHttpRequest request = new BasicHttpRequest("HEAD", "someUri");
request.addHeader("Cache-Control", "no-cache");
Assert.assertFalse(policy.isServableFromCache(request));
Assertions.assertFalse(policy.isServableFromCache(request));
request = new BasicHttpRequest("HEAD", "someUri");
request.addHeader("Cache-Control", "no-store");
request.addHeader("Cache-Control", "max-age=20");
Assert.assertFalse(policy.isServableFromCache(request));
Assertions.assertFalse(policy.isServableFromCache(request));
request = new BasicHttpRequest("HEAD", "someUri");
request.addHeader("Cache-Control", "public");
request.addHeader("Cache-Control", "no-store, max-age=20");
Assert.assertFalse(policy.isServableFromCache(request));
Assertions.assertFalse(policy.isServableFromCache(request));
}
@Test
@ -119,24 +119,24 @@ public class TestCacheableRequestPolicy {
BasicHttpRequest request = new BasicHttpRequest("HEAD", "someUri");
request.addHeader("Pragma", "no-cache");
Assert.assertFalse(policy.isServableFromCache(request));
Assertions.assertFalse(policy.isServableFromCache(request));
request = new BasicHttpRequest("HEAD", "someUri");
request.addHeader("Pragma", "value1");
request.addHeader("Pragma", "value2");
Assert.assertFalse(policy.isServableFromCache(request));
Assertions.assertFalse(policy.isServableFromCache(request));
}
@Test
public void testIsArbitraryMethodServableFromCache() {
BasicHttpRequest request = new BasicHttpRequest("TRACE", "someUri");
Assert.assertFalse(policy.isServableFromCache(request));
Assertions.assertFalse(policy.isServableFromCache(request));
request = new BasicHttpRequest("get", "someUri");
Assert.assertFalse(policy.isServableFromCache(request));
Assertions.assertFalse(policy.isServableFromCache(request));
}

View File

@ -41,9 +41,9 @@ import org.apache.hc.core5.http.ClassicHttpRequest;
import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.http.message.BasicHeader;
import org.apache.hc.core5.util.TimeValue;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@SuppressWarnings({"boxing","static-access"}) // test code
public class TestCachedHttpResponseGenerator {
@ -53,7 +53,7 @@ public class TestCachedHttpResponseGenerator {
private CacheValidityPolicy mockValidityPolicy;
private CachedHttpResponseGenerator impl;
@Before
@BeforeEach
public void setUp() {
entry = HttpTestUtils.makeCacheEntry(new HashMap<>());
request = HttpTestUtils.makeDefaultRequest();
@ -69,10 +69,9 @@ public class TestCachedHttpResponseGenerator {
final SimpleHttpResponse response = impl.generateResponse(request, entry1);
final Header length = response.getFirstHeader("Content-Length");
Assert.assertNotNull("Content-Length Header is missing", length);
Assertions.assertNotNull(length, "Content-Length Header is missing");
Assert.assertEquals("Content-Length does not match buffer length", buf.length, Integer
.parseInt(length.getValue()));
Assertions.assertEquals(buf.length, Integer.parseInt(length.getValue()), "Content-Length does not match buffer length");
}
@Test
@ -86,25 +85,25 @@ public class TestCachedHttpResponseGenerator {
final Header length = response.getFirstHeader("Content-Length");
Assert.assertNull(length);
Assertions.assertNull(length);
}
@Test
public void testResponseMatchesCacheEntry() throws Exception {
final SimpleHttpResponse response = impl.generateResponse(request, entry);
Assert.assertTrue(response.containsHeader("Content-Length"));
Assertions.assertTrue(response.containsHeader("Content-Length"));
Assert.assertSame("HTTP", response.getVersion().getProtocol());
Assert.assertEquals(1, response.getVersion().getMajor());
Assert.assertEquals(1, response.getVersion().getMinor());
Assertions.assertSame("HTTP", response.getVersion().getProtocol());
Assertions.assertEquals(1, response.getVersion().getMajor());
Assertions.assertEquals(1, response.getVersion().getMinor());
}
@Test
public void testResponseStatusCodeMatchesCacheEntry() throws Exception {
final SimpleHttpResponse response = impl.generateResponse(request, entry);
Assert.assertEquals(entry.getStatus(), response.getCode());
Assertions.assertEquals(entry.getStatus(), response.getCode());
}
@Test
@ -116,8 +115,8 @@ public class TestCachedHttpResponseGenerator {
verify(mockValidityPolicy).getCurrentAge(same(entry), isA(Date.class));
final Header ageHdr = response.getFirstHeader("Age");
Assert.assertNotNull(ageHdr);
Assert.assertEquals(10L, Long.parseLong(ageHdr.getValue()));
Assertions.assertNotNull(ageHdr);
Assertions.assertEquals(10L, Long.parseLong(ageHdr.getValue()));
}
@Test
@ -129,7 +128,7 @@ public class TestCachedHttpResponseGenerator {
verify(mockValidityPolicy).getCurrentAge(same(entry), isA(Date.class));
final Header ageHdr = response.getFirstHeader("Age");
Assert.assertNull(ageHdr);
Assertions.assertNull(ageHdr);
}
@Test
@ -141,8 +140,8 @@ public class TestCachedHttpResponseGenerator {
verify(mockValidityPolicy).getCurrentAge(same(entry), isA(Date.class));
final Header ageHdr = response.getFirstHeader("Age");
Assert.assertNotNull(ageHdr);
Assert.assertEquals(CacheValidityPolicy.MAX_AGE.toSeconds(), Long.parseLong(ageHdr.getValue()));
Assertions.assertNotNull(ageHdr);
Assertions.assertEquals(CacheValidityPolicy.MAX_AGE.toSeconds(), Long.parseLong(ageHdr.getValue()));
}
private void currentAge(final TimeValue age) {
@ -155,7 +154,7 @@ public class TestCachedHttpResponseGenerator {
public void testResponseContainsEntityToServeGETRequestIfEntryContainsResource() throws Exception {
final SimpleHttpResponse response = impl.generateResponse(request, entry);
Assert.assertNotNull(response.getBody());
Assertions.assertNotNull(response.getBody());
}
@Test
@ -163,7 +162,7 @@ public class TestCachedHttpResponseGenerator {
final ClassicHttpRequest headRequest = HttpTestUtils.makeDefaultHEADRequest();
final SimpleHttpResponse response = impl.generateResponse(headRequest, entry);
Assert.assertNull(response.getBody());
Assertions.assertNull(response.getBody());
}
}

View File

@ -36,9 +36,9 @@ import org.apache.hc.core5.http.HttpRequest;
import org.apache.hc.core5.http.message.BasicHeader;
import org.apache.hc.core5.http.message.BasicHttpRequest;
import org.apache.hc.core5.util.TimeValue;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class TestCachedResponseSuitabilityChecker {
@ -52,7 +52,7 @@ public class TestCachedResponseSuitabilityChecker {
private HttpCacheEntry entry;
private CachedResponseSuitabilityChecker impl;
@Before
@BeforeEach
public void setUp() {
now = Instant.now();
elevenSecondsAgo = now.minusSeconds(11);
@ -78,7 +78,7 @@ public class TestCachedResponseSuitabilityChecker {
new BasicHeader("Content-Length","1")
};
entry = getEntry(headers);
Assert.assertFalse(impl.canCachedResponseBeUsed(host, request, entry, DateUtils.toDate(now)));
Assertions.assertFalse(impl.canCachedResponseBeUsed(host, request, entry, DateUtils.toDate(now)));
}
@Test
@ -89,7 +89,7 @@ public class TestCachedResponseSuitabilityChecker {
new BasicHeader("Content-Length","128")
};
entry = getEntry(headers);
Assert.assertTrue(impl.canCachedResponseBeUsed(host, request, entry, DateUtils.toDate(now)));
Assertions.assertTrue(impl.canCachedResponseBeUsed(host, request, entry, DateUtils.toDate(now)));
}
@Test
@ -100,7 +100,7 @@ public class TestCachedResponseSuitabilityChecker {
new BasicHeader("Content-Length","128")
};
entry = getEntry(headers);
Assert.assertFalse(impl.canCachedResponseBeUsed(host, request, entry, DateUtils.toDate(now)));
Assertions.assertFalse(impl.canCachedResponseBeUsed(host, request, entry, DateUtils.toDate(now)));
}
@Test
@ -112,7 +112,7 @@ public class TestCachedResponseSuitabilityChecker {
new BasicHeader("Content-Length","128")
};
entry = getEntry(headers);
Assert.assertFalse(impl.canCachedResponseBeUsed(host, request, entry, DateUtils.toDate(now)));
Assertions.assertFalse(impl.canCachedResponseBeUsed(host, request, entry, DateUtils.toDate(now)));
}
@Test
@ -124,7 +124,7 @@ public class TestCachedResponseSuitabilityChecker {
new BasicHeader("Content-Length","128")
};
entry = getEntry(headers);
Assert.assertFalse(impl.canCachedResponseBeUsed(host, request, entry, DateUtils.toDate(now)));
Assertions.assertFalse(impl.canCachedResponseBeUsed(host, request, entry, DateUtils.toDate(now)));
}
@Test
@ -136,7 +136,7 @@ public class TestCachedResponseSuitabilityChecker {
new BasicHeader("Content-Length","128")
};
entry = getEntry(headers);
Assert.assertTrue(impl.canCachedResponseBeUsed(host, request, entry, DateUtils.toDate(now)));
Assertions.assertTrue(impl.canCachedResponseBeUsed(host, request, entry, DateUtils.toDate(now)));
}
@Test
@ -148,7 +148,7 @@ public class TestCachedResponseSuitabilityChecker {
new BasicHeader("Content-Length","128")
};
entry = getEntry(headers);
Assert.assertTrue(impl.canCachedResponseBeUsed(host, request, entry, DateUtils.toDate(now)));
Assertions.assertTrue(impl.canCachedResponseBeUsed(host, request, entry, DateUtils.toDate(now)));
}
@Test
@ -160,7 +160,7 @@ public class TestCachedResponseSuitabilityChecker {
new BasicHeader("Content-Length","128")
};
entry = getEntry(headers);
Assert.assertFalse(impl.canCachedResponseBeUsed(host, request, entry, DateUtils.toDate(now)));
Assertions.assertFalse(impl.canCachedResponseBeUsed(host, request, entry, DateUtils.toDate(now)));
}
@Test
@ -172,7 +172,7 @@ public class TestCachedResponseSuitabilityChecker {
new BasicHeader("Content-Length","128")
};
entry = getEntry(headers);
Assert.assertTrue(impl.canCachedResponseBeUsed(host, request, entry, DateUtils.toDate(now)));
Assertions.assertTrue(impl.canCachedResponseBeUsed(host, request, entry, DateUtils.toDate(now)));
}
@Test
@ -184,7 +184,7 @@ public class TestCachedResponseSuitabilityChecker {
new BasicHeader("Content-Length","128")
};
entry = getEntry(headers);
Assert.assertFalse(impl.canCachedResponseBeUsed(host, request, entry, DateUtils.toDate(now)));
Assertions.assertFalse(impl.canCachedResponseBeUsed(host, request, entry, DateUtils.toDate(now)));
}
@ -197,7 +197,7 @@ public class TestCachedResponseSuitabilityChecker {
new BasicHeader("Content-Length","128")
};
entry = getEntry(headers);
Assert.assertFalse(impl.canCachedResponseBeUsed(host, request, entry, DateUtils.toDate(now)));
Assertions.assertFalse(impl.canCachedResponseBeUsed(host, request, entry, DateUtils.toDate(now)));
}
@Test
@ -209,7 +209,7 @@ public class TestCachedResponseSuitabilityChecker {
new BasicHeader("Content-Length","128")
};
entry = getEntry(headers);
Assert.assertFalse(impl.canCachedResponseBeUsed(host, request, entry, DateUtils.toDate(now)));
Assertions.assertFalse(impl.canCachedResponseBeUsed(host, request, entry, DateUtils.toDate(now)));
}
@Test
@ -230,7 +230,7 @@ public class TestCachedResponseSuitabilityChecker {
.setHeuristicCoefficient(0.1f).build();
impl = new CachedResponseSuitabilityChecker(config);
Assert.assertTrue(impl.canCachedResponseBeUsed(host, request, entry, DateUtils.toDate(now)));
Assertions.assertTrue(impl.canCachedResponseBeUsed(host, request, entry, DateUtils.toDate(now)));
}
@Test
@ -248,7 +248,7 @@ public class TestCachedResponseSuitabilityChecker {
.build();
impl = new CachedResponseSuitabilityChecker(config);
Assert.assertTrue(impl.canCachedResponseBeUsed(host, request, entry, DateUtils.toDate(now)));
Assertions.assertTrue(impl.canCachedResponseBeUsed(host, request, entry, DateUtils.toDate(now)));
}
@Test
@ -261,7 +261,7 @@ public class TestCachedResponseSuitabilityChecker {
};
entry = getEntry(headers);
Assert.assertTrue(impl.canCachedResponseBeUsed(host, headRequest, entry, DateUtils.toDate(now)));
Assertions.assertTrue(impl.canCachedResponseBeUsed(host, headRequest, entry, DateUtils.toDate(now)));
}
@Test
@ -273,7 +273,7 @@ public class TestCachedResponseSuitabilityChecker {
};
entry = HttpTestUtils.makeHeadCacheEntry(headers);
Assert.assertFalse(impl.canCachedResponseBeUsed(host, request, entry, DateUtils.toDate(now)));
Assertions.assertFalse(impl.canCachedResponseBeUsed(host, request, entry, DateUtils.toDate(now)));
}
@Test
@ -286,7 +286,7 @@ public class TestCachedResponseSuitabilityChecker {
};
entry = HttpTestUtils.makeCacheEntryWithNoRequestMethodOrEntity(headers);
Assert.assertFalse(impl.canCachedResponseBeUsed(host, request, entry, DateUtils.toDate(now)));
Assertions.assertFalse(impl.canCachedResponseBeUsed(host, request, entry, DateUtils.toDate(now)));
}
@Test
@ -299,7 +299,7 @@ public class TestCachedResponseSuitabilityChecker {
};
entry = HttpTestUtils.makeCacheEntryWithNoRequestMethod(headers);
Assert.assertTrue(impl.canCachedResponseBeUsed(host, request, entry, DateUtils.toDate(now)));
Assertions.assertTrue(impl.canCachedResponseBeUsed(host, request, entry, DateUtils.toDate(now)));
}
@Test
@ -311,7 +311,7 @@ public class TestCachedResponseSuitabilityChecker {
};
entry = HttpTestUtils.make204CacheEntryWithNoRequestMethod(headers);
Assert.assertTrue(impl.canCachedResponseBeUsed(host, request, entry, DateUtils.toDate(now)));
Assertions.assertTrue(impl.canCachedResponseBeUsed(host, request, entry, DateUtils.toDate(now)));
}
@Test
@ -325,6 +325,6 @@ public class TestCachedResponseSuitabilityChecker {
};
entry = HttpTestUtils.makeHeadCacheEntryWithNoRequestMethod(headers);
Assert.assertTrue(impl.canCachedResponseBeUsed(host, headRequest, entry, DateUtils.toDate(now)));
Assertions.assertTrue(impl.canCachedResponseBeUsed(host, headRequest, entry, DateUtils.toDate(now)));
}
}

View File

@ -26,7 +26,8 @@
*/
package org.apache.hc.client5.http.impl.cache;
import static org.junit.Assert.assertSame;
import static org.junit.jupiter.api.Assertions.assertSame;
import java.io.IOException;
import java.io.InputStream;
@ -61,17 +62,15 @@ import org.apache.hc.core5.http.io.support.ClassicRequestBuilder;
import org.apache.hc.core5.http.message.BasicClassicHttpRequest;
import org.apache.hc.core5.http.message.BasicClassicHttpResponse;
import org.apache.hc.core5.net.URIAuthority;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class TestCachingExecChain {
@Mock
@ -91,8 +90,9 @@ public class TestCachingExecChain {
HttpCacheEntry entry;
CachingExec impl;
@Before
@BeforeEach
public void setUp() {
MockitoAnnotations.openMocks(this);
config = CacheConfig.DEFAULT;
host = new HttpHost("foo.example.com", 80);
@ -156,7 +156,7 @@ public class TestCachingExecChain {
execute(req2);
final ClassicHttpResponse result = execute(req3);
Assert.assertEquals("\"new-etag\"", result.getFirstHeader("ETag").getValue());
Assertions.assertEquals("\"new-etag\"", result.getFirstHeader("ETag").getValue());
}
@Test
@ -188,7 +188,7 @@ public class TestCachingExecChain {
execute(req2);
final ClassicHttpResponse result = execute(req3);
Assert.assertEquals("\"new-etag\"", result.getFirstHeader("ETag").getValue());
Assertions.assertEquals("\"new-etag\"", result.getFirstHeader("ETag").getValue());
}
@Test
@ -205,7 +205,7 @@ public class TestCachingExecChain {
final ClassicHttpResponse result = execute(req1);
Assert.assertTrue(HttpTestUtils.semanticallyTransparent(resp1, result));
Assertions.assertTrue(HttpTestUtils.semanticallyTransparent(resp1, result));
Mockito.verify(mockStorage, Mockito.never()).putEntry(Mockito.any(), Mockito.any());
}
@ -216,7 +216,7 @@ public class TestCachingExecChain {
req.setHeader("Max-Forwards", "0");
execute(req);
Assert.assertEquals(CacheResponseStatus.CACHE_MODULE_RESPONSE, context.getCacheResponseStatus());
Assertions.assertEquals(CacheResponseStatus.CACHE_MODULE_RESPONSE, context.getCacheResponseStatus());
}
@Test
@ -226,7 +226,7 @@ public class TestCachingExecChain {
req.setHeader("If-Range", "W/\"weak-etag\"");
execute(req);
Assert.assertEquals(CacheResponseStatus.CACHE_MODULE_RESPONSE, context.getCacheResponseStatus());
Assertions.assertEquals(CacheResponseStatus.CACHE_MODULE_RESPONSE, context.getCacheResponseStatus());
}
@Test
@ -247,7 +247,7 @@ public class TestCachingExecChain {
final HttpRequest captured = reqCapture.getValue();
final String via = captured.getFirstHeader("Via").getValue();
final String proto = via.split("\\s+")[0];
Assert.assertTrue("http/1.0".equalsIgnoreCase(proto) || "1.0".equalsIgnoreCase(proto));
Assertions.assertTrue("http/1.0".equalsIgnoreCase(proto) || "1.0".equalsIgnoreCase(proto));
}
@Test
@ -259,7 +259,7 @@ public class TestCachingExecChain {
Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(resp);
execute(req);
Assert.assertEquals(CacheResponseStatus.CACHE_MISS, context.getCacheResponseStatus());
Assertions.assertEquals(CacheResponseStatus.CACHE_MISS, context.getCacheResponseStatus());
}
@Test
@ -271,7 +271,7 @@ public class TestCachingExecChain {
Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(resp);
final ClassicHttpResponse result = execute(req);
Assert.assertNotNull(result.getFirstHeader("Via"));
Assertions.assertNotNull(result.getFirstHeader("Via"));
}
@Test
@ -287,7 +287,7 @@ public class TestCachingExecChain {
Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(resp1);
final ClassicHttpResponse result = execute(req1);
Assert.assertNotNull(result.getFirstHeader("Via"));
Assertions.assertNotNull(result.getFirstHeader("Via"));
}
@Test
@ -305,7 +305,7 @@ public class TestCachingExecChain {
execute(req1);
execute(req2);
Assert.assertEquals(CacheResponseStatus.CACHE_HIT, context.getCacheResponseStatus());
Assertions.assertEquals(CacheResponseStatus.CACHE_HIT, context.getCacheResponseStatus());
}
@Test
@ -323,7 +323,7 @@ public class TestCachingExecChain {
execute(req1);
final ClassicHttpResponse result = execute(req2);
Assert.assertNotNull(result.getFirstHeader("Via"));
Assertions.assertNotNull(result.getFirstHeader("Via"));
}
@Test
@ -345,7 +345,7 @@ public class TestCachingExecChain {
execute(req1);
final ClassicHttpResponse result = execute(req2);
Assert.assertEquals(HttpStatus.SC_NOT_MODIFIED, result.getCode());
Assertions.assertEquals(HttpStatus.SC_NOT_MODIFIED, result.getCode());
}
@Test
@ -368,8 +368,8 @@ public class TestCachingExecChain {
execute(req1);
final ClassicHttpResponse result = execute(req2);
Assert.assertEquals(HttpStatus.SC_NOT_MODIFIED, result.getCode());
Assert.assertFalse(result.containsHeader("Last-Modified"));
Assertions.assertEquals(HttpStatus.SC_NOT_MODIFIED, result.getCode());
Assertions.assertFalse(result.containsHeader("Last-Modified"));
Mockito.verify(mockExecChain).proceed(Mockito.any(), Mockito.any());
}
@ -401,7 +401,7 @@ public class TestCachingExecChain {
Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(resp2);
final ClassicHttpResponse result = execute(req2);
Assert.assertEquals(HttpStatus.SC_OK, result.getCode());
Assertions.assertEquals(HttpStatus.SC_OK, result.getCode());
}
@Test
@ -426,7 +426,7 @@ public class TestCachingExecChain {
execute(req1);
final ClassicHttpResponse result = execute(req2);
Assert.assertEquals(HttpStatus.SC_OK, result.getCode());
Assertions.assertEquals(HttpStatus.SC_OK, result.getCode());
Mockito.verify(mockExecChain, Mockito.times(2)).proceed(Mockito.any(), Mockito.any());
}
@ -447,7 +447,7 @@ public class TestCachingExecChain {
execute(req1);
final ClassicHttpResponse result = execute(req2);
Assert.assertEquals(HttpStatus.SC_NOT_MODIFIED, result.getCode());
Assertions.assertEquals(HttpStatus.SC_NOT_MODIFIED, result.getCode());
}
@ -474,7 +474,7 @@ public class TestCachingExecChain {
Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(resp2);
final ClassicHttpResponse result = execute(req2);
Assert.assertEquals(200, result.getCode());
Assertions.assertEquals(200, result.getCode());
}
@Test
@ -499,7 +499,7 @@ public class TestCachingExecChain {
execute(req1);
final ClassicHttpResponse result = execute(req2);
Assert.assertEquals(HttpStatus.SC_NOT_MODIFIED, result.getCode());
Assertions.assertEquals(HttpStatus.SC_NOT_MODIFIED, result.getCode());
}
@Test
@ -522,7 +522,7 @@ public class TestCachingExecChain {
execute(req1);
final ClassicHttpResponse result = execute(req2);
Assert.assertEquals(200, result.getCode());
Assertions.assertEquals(200, result.getCode());
}
@Test
@ -553,7 +553,7 @@ public class TestCachingExecChain {
Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(resp2);
final ClassicHttpResponse result = execute(req2);
Assert.assertEquals(200, result.getCode());
Assertions.assertEquals(200, result.getCode());
}
@Test
@ -584,7 +584,7 @@ public class TestCachingExecChain {
Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(resp2);
execute(req2);
Assert.assertEquals(CacheResponseStatus.VALIDATED, context.getCacheResponseStatus());
Assertions.assertEquals(CacheResponseStatus.VALIDATED, context.getCacheResponseStatus());
}
@Test
@ -616,7 +616,7 @@ public class TestCachingExecChain {
Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(resp2);
final ClassicHttpResponse result = execute(req2);
Assert.assertNotNull(result.getFirstHeader("Via"));
Assertions.assertNotNull(result.getFirstHeader("Via"));
}
@Test
@ -641,7 +641,7 @@ public class TestCachingExecChain {
Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenThrow(new IOException());
execute(req2);
Assert.assertEquals(CacheResponseStatus.CACHE_MODULE_RESPONSE,
Assertions.assertEquals(CacheResponseStatus.CACHE_MODULE_RESPONSE,
context.getCacheResponseStatus());
}
@ -667,7 +667,7 @@ public class TestCachingExecChain {
Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenThrow(new IOException());
execute(req2);
Assert.assertEquals(CacheResponseStatus.CACHE_HIT, context.getCacheResponseStatus());
Assertions.assertEquals(CacheResponseStatus.CACHE_HIT, context.getCacheResponseStatus());
}
@Test
@ -692,7 +692,7 @@ public class TestCachingExecChain {
Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenThrow(new IOException());
final ClassicHttpResponse result = execute(req2);
Assert.assertNotNull(result.getFirstHeader("Via"));
Assertions.assertNotNull(result.getFirstHeader("Via"));
}
@Test
@ -724,7 +724,7 @@ public class TestCachingExecChain {
final ClassicHttpResponse result = execute(req2);
Assert.assertEquals(HttpStatus.SC_NOT_MODIFIED, result.getCode());
Assertions.assertEquals(HttpStatus.SC_NOT_MODIFIED, result.getCode());
}
@Test
@ -758,7 +758,7 @@ public class TestCachingExecChain {
final ClassicHttpResponse result = execute(req2);
Assert.assertEquals(HttpStatus.SC_OK, result.getCode());
Assertions.assertEquals(HttpStatus.SC_OK, result.getCode());
}
@Test
@ -792,7 +792,7 @@ public class TestCachingExecChain {
final ClassicHttpResponse result = execute(req2);
Assert.assertEquals(HttpStatus.SC_NOT_MODIFIED, result.getCode());
Assertions.assertEquals(HttpStatus.SC_NOT_MODIFIED, result.getCode());
}
@Test
@ -828,7 +828,7 @@ public class TestCachingExecChain {
final ClassicHttpResponse result = execute(req2);
Assert.assertEquals(HttpStatus.SC_OK, result.getCode());
Assertions.assertEquals(HttpStatus.SC_OK, result.getCode());
}
@Test
@ -888,9 +888,9 @@ public class TestCachingExecChain {
final ClassicHttpResponse result3 = execute(req3);
Assert.assertEquals(HttpStatus.SC_OK, result1.getCode());
Assert.assertEquals(HttpStatus.SC_OK, result2.getCode());
Assert.assertEquals(HttpStatus.SC_OK, result3.getCode());
Assertions.assertEquals(HttpStatus.SC_OK, result1.getCode());
Assertions.assertEquals(HttpStatus.SC_OK, result2.getCode());
Assertions.assertEquals(HttpStatus.SC_OK, result3.getCode());
}
@Test
@ -948,9 +948,9 @@ public class TestCachingExecChain {
Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(resp4);
final ClassicHttpResponse result4 = execute(req4);
Assert.assertEquals(HttpStatus.SC_OK, result1.getCode());
Assert.assertEquals(HttpStatus.SC_OK, result2.getCode());
Assert.assertEquals(HttpStatus.SC_NOT_MODIFIED, result4.getCode());
Assertions.assertEquals(HttpStatus.SC_OK, result1.getCode());
Assertions.assertEquals(HttpStatus.SC_OK, result2.getCode());
Assertions.assertEquals(HttpStatus.SC_NOT_MODIFIED, result4.getCode());
}
@ -981,7 +981,7 @@ public class TestCachingExecChain {
Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(resp1);
Assert.assertThrows(SocketTimeoutException.class, () -> {
Assertions.assertThrows(SocketTimeoutException.class, () -> {
final ClassicHttpResponse result1 = execute(req1);
EntityUtils.toString(result1.getEntity());
});
@ -989,7 +989,7 @@ public class TestCachingExecChain {
@Test
public void testIsSharedCache() {
Assert.assertTrue(config.isSharedCache());
Assertions.assertTrue(config.isSharedCache());
}
@Test
@ -1065,7 +1065,7 @@ public class TestCachingExecChain {
final ClassicHttpResponse resp = execute(request);
Assert.assertEquals(HttpStatus.SC_GATEWAY_TIMEOUT, resp.getCode());
Assertions.assertEquals(HttpStatus.SC_GATEWAY_TIMEOUT, resp.getCode());
}
@Test
@ -1077,7 +1077,7 @@ public class TestCachingExecChain {
final HttpClientContext ctx = HttpClientContext.create();
impl.execute(request, new ExecChain.Scope("test", route, request, mockExecRuntime, context), mockExecChain);
impl.execute(request, new ExecChain.Scope("test", route, request, mockExecRuntime, ctx), mockExecChain);
Assert.assertEquals(route, ctx.getHttpRoute());
Assertions.assertEquals(route, ctx.getHttpRoute());
}
@Test
@ -1150,8 +1150,8 @@ public class TestCachingExecChain {
Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(resp1);
final ClassicHttpResponse result = execute(req1);
Assert.assertEquals(HttpStatus.SC_NOT_MODIFIED, result.getCode());
Assert.assertNull("The 304 response messages MUST NOT contain a message-body", result.getEntity());
Assertions.assertEquals(HttpStatus.SC_NOT_MODIFIED, result.getCode());
Assertions.assertNull(result.getEntity(), "The 304 response messages MUST NOT contain a message-body");
}
@Test
@ -1182,10 +1182,10 @@ public class TestCachingExecChain {
final ClassicHttpResponse result2 = execute(req2);
Assert.assertEquals(HttpStatus.SC_NOT_MODIFIED, result1.getCode());
Assert.assertEquals("etag", result1.getFirstHeader("Etag").getValue());
Assert.assertEquals(HttpStatus.SC_NOT_MODIFIED, result2.getCode());
Assert.assertEquals("etag", result2.getFirstHeader("Etag").getValue());
Assertions.assertEquals(HttpStatus.SC_NOT_MODIFIED, result1.getCode());
Assertions.assertEquals("etag", result1.getFirstHeader("Etag").getValue());
Assertions.assertEquals(HttpStatus.SC_NOT_MODIFIED, result2.getCode());
Assertions.assertEquals("etag", result2.getFirstHeader("Etag").getValue());
}
@Test
@ -1219,10 +1219,10 @@ public class TestCachingExecChain {
final ClassicHttpResponse result2 = execute(req2);
Assert.assertEquals(HttpStatus.SC_NOT_MODIFIED, result1.getCode());
Assert.assertEquals("etag", result1.getFirstHeader("Etag").getValue());
Assert.assertEquals(HttpStatus.SC_NOT_MODIFIED, result2.getCode());
Assert.assertEquals("etag", result2.getFirstHeader("Etag").getValue());
Assertions.assertEquals(HttpStatus.SC_NOT_MODIFIED, result1.getCode());
Assertions.assertEquals("etag", result1.getFirstHeader("Etag").getValue());
Assertions.assertEquals(HttpStatus.SC_NOT_MODIFIED, result2.getCode());
Assertions.assertEquals("etag", result2.getFirstHeader("Etag").getValue());
}
@Test
@ -1260,10 +1260,10 @@ public class TestCachingExecChain {
final ClassicHttpResponse result2 = execute(req2);
Assert.assertEquals(HttpStatus.SC_NOT_MODIFIED, result1.getCode());
Assert.assertNull(result1.getEntity());
Assert.assertEquals(HttpStatus.SC_OK, result2.getCode());
Assert.assertNotNull(result2.getEntity());
Assertions.assertEquals(HttpStatus.SC_NOT_MODIFIED, result1.getCode());
Assertions.assertNull(result1.getEntity());
Assertions.assertEquals(HttpStatus.SC_OK, result2.getCode());
Assertions.assertNotNull(result2.getEntity());
}
@Test

View File

@ -35,8 +35,8 @@ import java.io.ByteArrayInputStream;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.util.ByteArrayBuffer;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class TestCombinedEntity {
@ -50,11 +50,11 @@ public class TestCombinedEntity {
final byte[] tmp = new byte[] { 1, 2, 3, 4, 5 };
buf.append(tmp, 0, tmp.length);
final CombinedEntity entity = new CombinedEntity(httpEntity, buf);
Assert.assertEquals(-1, entity.getContentLength());
Assert.assertFalse(entity.isRepeatable());
Assert.assertTrue(entity.isStreaming());
Assertions.assertEquals(-1, entity.getContentLength());
Assertions.assertFalse(entity.isRepeatable());
Assertions.assertTrue(entity.isStreaming());
Assert.assertArrayEquals(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, EntityUtils.toByteArray(entity));
Assertions.assertArrayEquals(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, EntityUtils.toByteArray(entity));
verify(httpEntity).getContent();

View File

@ -41,16 +41,16 @@ import org.apache.hc.core5.http.message.BasicHeader;
import org.apache.hc.core5.http.message.BasicHttpRequest;
import org.apache.hc.core5.http.message.MessageSupport;
import org.apache.hc.core5.http.support.BasicRequestBuilder;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class TestConditionalRequestBuilder {
private ConditionalRequestBuilder<HttpRequest> impl;
private HttpRequest request;
@Before
@BeforeEach
public void setUp() throws Exception {
impl = new ConditionalRequestBuilder<>(request -> BasicRequestBuilder.copy(request).build());
request = new BasicHttpRequest("GET", "/");
@ -72,15 +72,15 @@ public class TestConditionalRequestBuilder {
final HttpCacheEntry cacheEntry = HttpTestUtils.makeCacheEntry(headers);
final HttpRequest newRequest = impl.buildConditionalRequest(basicRequest, cacheEntry);
Assert.assertEquals(theMethod, newRequest.getMethod());
Assert.assertEquals(theUri, newRequest.getRequestUri());
Assert.assertEquals(2, newRequest.getHeaders().length);
Assertions.assertEquals(theMethod, newRequest.getMethod());
Assertions.assertEquals(theUri, newRequest.getRequestUri());
Assertions.assertEquals(2, newRequest.getHeaders().length);
Assert.assertEquals("Accept-Encoding", newRequest.getHeaders()[0].getName());
Assert.assertEquals("gzip", newRequest.getHeaders()[0].getValue());
Assertions.assertEquals("Accept-Encoding", newRequest.getHeaders()[0].getName());
Assertions.assertEquals("gzip", newRequest.getHeaders()[0].getValue());
Assert.assertEquals("If-Modified-Since", newRequest.getHeaders()[1].getName());
Assert.assertEquals(lastModified, newRequest.getHeaders()[1].getValue());
Assertions.assertEquals("If-Modified-Since", newRequest.getHeaders()[1].getName());
Assertions.assertEquals(lastModified, newRequest.getHeaders()[1].getValue());
}
@Test
@ -99,9 +99,9 @@ public class TestConditionalRequestBuilder {
final HttpRequest basicRequest = new BasicHttpRequest("GET", "/");
final HttpCacheEntry cacheEntry = HttpTestUtils.makeCacheEntry(headers);
final HttpRequest result = impl.buildConditionalRequest(basicRequest, cacheEntry);
Assert.assertEquals(lmDate,
Assertions.assertEquals(lmDate,
result.getFirstHeader("If-Modified-Since").getValue());
Assert.assertEquals(etag,
Assertions.assertEquals(etag,
result.getFirstHeader("If-None-Match").getValue());
}
@ -123,16 +123,16 @@ public class TestConditionalRequestBuilder {
final HttpRequest newRequest = impl.buildConditionalRequest(basicRequest, cacheEntry);
Assert.assertEquals(theMethod, newRequest.getMethod());
Assert.assertEquals(theUri, newRequest.getRequestUri());
Assertions.assertEquals(theMethod, newRequest.getMethod());
Assertions.assertEquals(theUri, newRequest.getRequestUri());
Assert.assertEquals(3, newRequest.getHeaders().length);
Assertions.assertEquals(3, newRequest.getHeaders().length);
Assert.assertEquals("Accept-Encoding", newRequest.getHeaders()[0].getName());
Assert.assertEquals("gzip", newRequest.getHeaders()[0].getValue());
Assertions.assertEquals("Accept-Encoding", newRequest.getHeaders()[0].getName());
Assertions.assertEquals("gzip", newRequest.getHeaders()[0].getValue());
Assert.assertEquals("If-None-Match", newRequest.getHeaders()[1].getName());
Assert.assertEquals(theETag, newRequest.getHeaders()[1].getValue());
Assertions.assertEquals("If-None-Match", newRequest.getHeaders()[1].getName());
Assertions.assertEquals(theETag, newRequest.getHeaders()[1].getValue());
}
@Test
@ -160,7 +160,7 @@ public class TestConditionalRequestBuilder {
foundMaxAge0 = true;
}
}
Assert.assertTrue(foundMaxAge0);
Assertions.assertTrue(foundMaxAge0);
}
@Test
@ -187,14 +187,14 @@ public class TestConditionalRequestBuilder {
foundMaxAge0 = true;
}
}
Assert.assertTrue(foundMaxAge0);
Assertions.assertTrue(foundMaxAge0);
}
@Test
public void testBuildUnconditionalRequestUsesGETMethod()
throws Exception {
final HttpRequest result = impl.buildUnconditionalRequest(request);
Assert.assertEquals("GET", result.getMethod());
Assertions.assertEquals("GET", result.getMethod());
}
@Test
@ -203,7 +203,7 @@ public class TestConditionalRequestBuilder {
final String uri = "/theURI";
request = new BasicHttpRequest("GET", uri);
final HttpRequest result = impl.buildUnconditionalRequest(request);
Assert.assertEquals(uri, result.getRequestUri());
Assertions.assertEquals(uri, result.getRequestUri());
}
@Test
@ -218,7 +218,7 @@ public class TestConditionalRequestBuilder {
ccNoCacheFound = true;
}
}
Assert.assertTrue(ccNoCacheFound);
Assertions.assertTrue(ccNoCacheFound);
}
@Test
@ -233,7 +233,7 @@ public class TestConditionalRequestBuilder {
ccNoCacheFound = true;
}
}
Assert.assertTrue(ccNoCacheFound);
Assertions.assertTrue(ccNoCacheFound);
}
@Test
@ -241,7 +241,7 @@ public class TestConditionalRequestBuilder {
throws Exception {
request.addHeader("If-Range","\"etag\"");
final HttpRequest result = impl.buildUnconditionalRequest(request);
Assert.assertNull(result.getFirstHeader("If-Range"));
Assertions.assertNull(result.getFirstHeader("If-Range"));
}
@Test
@ -249,7 +249,7 @@ public class TestConditionalRequestBuilder {
throws Exception {
request.addHeader("If-Match","\"etag\"");
final HttpRequest result = impl.buildUnconditionalRequest(request);
Assert.assertNull(result.getFirstHeader("If-Match"));
Assertions.assertNull(result.getFirstHeader("If-Match"));
}
@Test
@ -257,7 +257,7 @@ public class TestConditionalRequestBuilder {
throws Exception {
request.addHeader("If-None-Match","\"etag\"");
final HttpRequest result = impl.buildUnconditionalRequest(request);
Assert.assertNull(result.getFirstHeader("If-None-Match"));
Assertions.assertNull(result.getFirstHeader("If-None-Match"));
}
@Test
@ -265,7 +265,7 @@ public class TestConditionalRequestBuilder {
throws Exception {
request.addHeader("If-Unmodified-Since", DateUtils.formatStandardDate(Instant.now()));
final HttpRequest result = impl.buildUnconditionalRequest(request);
Assert.assertNull(result.getFirstHeader("If-Unmodified-Since"));
Assertions.assertNull(result.getFirstHeader("If-Unmodified-Since"));
}
@Test
@ -273,7 +273,7 @@ public class TestConditionalRequestBuilder {
throws Exception {
request.addHeader("If-Modified-Since", DateUtils.formatStandardDate(Instant.now()));
final HttpRequest result = impl.buildUnconditionalRequest(request);
Assert.assertNull(result.getFirstHeader("If-Modified-Since"));
Assertions.assertNull(result.getFirstHeader("If-Modified-Since"));
}
@Test
@ -281,7 +281,7 @@ public class TestConditionalRequestBuilder {
throws Exception {
request.addHeader("User-Agent","MyBrowser/1.0");
final HttpRequest result = impl.buildUnconditionalRequest(request);
Assert.assertEquals("MyBrowser/1.0",
Assertions.assertEquals("MyBrowser/1.0",
result.getFirstHeader("User-Agent").getValue());
}
@ -300,15 +300,15 @@ public class TestConditionalRequestBuilder {
// seems like a lot of work, but necessary, check for existence and exclusiveness
String ifNoneMatch = conditional.getFirstHeader(HeaderConstants.IF_NONE_MATCH).getValue();
Assert.assertTrue(ifNoneMatch.contains(etag1));
Assert.assertTrue(ifNoneMatch.contains(etag2));
Assert.assertTrue(ifNoneMatch.contains(etag3));
Assertions.assertTrue(ifNoneMatch.contains(etag1));
Assertions.assertTrue(ifNoneMatch.contains(etag2));
Assertions.assertTrue(ifNoneMatch.contains(etag3));
ifNoneMatch = ifNoneMatch.replace(etag1, "");
ifNoneMatch = ifNoneMatch.replace(etag2, "");
ifNoneMatch = ifNoneMatch.replace(etag3, "");
ifNoneMatch = ifNoneMatch.replace(",","");
ifNoneMatch = ifNoneMatch.replace(" ", "");
Assert.assertEquals(ifNoneMatch, "");
Assertions.assertEquals(ifNoneMatch, "");
}
}

View File

@ -27,6 +27,8 @@
package org.apache.hc.client5.http.impl.cache;
import static org.hamcrest.MatcherAssert.assertThat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.Month;
@ -37,8 +39,7 @@ import org.apache.hc.core5.http.HttpHeaders;
import org.apache.hc.core5.http.message.BasicHeader;
import org.apache.hc.core5.http.message.HeaderGroup;
import org.hamcrest.CoreMatchers;
import org.hamcrest.MatcherAssert;
import org.junit.Test;
import org.junit.jupiter.api.Test;
/**
* Unit tests for {@link DateSupport}.
@ -53,48 +54,48 @@ public class TestDateSupport {
public void testIsBefore() throws Exception {
final HeaderGroup message1 = new HeaderGroup();
final HeaderGroup message2 = new HeaderGroup();
MatcherAssert.assertThat(DateSupport.isBefore(null, null, HttpHeaders.DATE), CoreMatchers.equalTo(false));
MatcherAssert.assertThat(DateSupport.isBefore(message1, message2, HttpHeaders.DATE), CoreMatchers.equalTo(false));
assertThat(DateSupport.isBefore(null, null, HttpHeaders.DATE), CoreMatchers.equalTo(false));
assertThat(DateSupport.isBefore(message1, message2, HttpHeaders.DATE), CoreMatchers.equalTo(false));
message1.setHeader(new BasicHeader(HttpHeaders.DATE, "huh?"));
message2.setHeader(new BasicHeader(HttpHeaders.DATE, "eh?"));
MatcherAssert.assertThat(DateSupport.isBefore(message1, message2, HttpHeaders.DATE), CoreMatchers.equalTo(false));
assertThat(DateSupport.isBefore(message1, message2, HttpHeaders.DATE), CoreMatchers.equalTo(false));
message1.setHeader(new BasicHeader(HttpHeaders.DATE, "huh?"));
message2.setHeader(new BasicHeader(HttpHeaders.DATE, DateUtils.formatStandardDate(createInstant(2017, Month.DECEMBER, 26))));
MatcherAssert.assertThat(DateSupport.isBefore(message1, message2, HttpHeaders.DATE), CoreMatchers.equalTo(false));
assertThat(DateSupport.isBefore(message1, message2, HttpHeaders.DATE), CoreMatchers.equalTo(false));
message1.setHeader(new BasicHeader(HttpHeaders.DATE, DateUtils.formatStandardDate(createInstant(2017, Month.DECEMBER, 25))));
message2.setHeader(new BasicHeader(HttpHeaders.DATE, DateUtils.formatStandardDate(createInstant(2017, Month.DECEMBER, 26))));
MatcherAssert.assertThat(DateSupport.isBefore(message1, message2, HttpHeaders.DATE), CoreMatchers.equalTo(true));
assertThat(DateSupport.isBefore(message1, message2, HttpHeaders.DATE), CoreMatchers.equalTo(true));
message1.setHeader(new BasicHeader(HttpHeaders.DATE, DateUtils.formatStandardDate(createInstant(2017, Month.DECEMBER, 27))));
message2.setHeader(new BasicHeader(HttpHeaders.DATE, DateUtils.formatStandardDate(createInstant(2017, Month.DECEMBER, 26))));
MatcherAssert.assertThat(DateSupport.isBefore(message1, message2, HttpHeaders.DATE), CoreMatchers.equalTo(false));
assertThat(DateSupport.isBefore(message1, message2, HttpHeaders.DATE), CoreMatchers.equalTo(false));
}
@Test
public void testIsAfter() throws Exception {
final HeaderGroup message1 = new HeaderGroup();
final HeaderGroup message2 = new HeaderGroup();
MatcherAssert.assertThat(DateSupport.isAfter(null, null, HttpHeaders.DATE), CoreMatchers.equalTo(false));
MatcherAssert.assertThat(DateSupport.isAfter(message1, message2, HttpHeaders.DATE), CoreMatchers.equalTo(false));
assertThat(DateSupport.isAfter(null, null, HttpHeaders.DATE), CoreMatchers.equalTo(false));
assertThat(DateSupport.isAfter(message1, message2, HttpHeaders.DATE), CoreMatchers.equalTo(false));
message1.setHeader(new BasicHeader(HttpHeaders.DATE, "huh?"));
message2.setHeader(new BasicHeader(HttpHeaders.DATE, "eh?"));
MatcherAssert.assertThat(DateSupport.isAfter(message1, message2, HttpHeaders.DATE), CoreMatchers.equalTo(false));
assertThat(DateSupport.isAfter(message1, message2, HttpHeaders.DATE), CoreMatchers.equalTo(false));
message1.setHeader(new BasicHeader(HttpHeaders.DATE, "huh?"));
message2.setHeader(new BasicHeader(HttpHeaders.DATE, DateUtils.formatStandardDate(createInstant(2017, Month.DECEMBER, 26))));
MatcherAssert.assertThat(DateSupport.isAfter(message1, message2, HttpHeaders.DATE), CoreMatchers.equalTo(false));
assertThat(DateSupport.isAfter(message1, message2, HttpHeaders.DATE), CoreMatchers.equalTo(false));
message1.setHeader(new BasicHeader(HttpHeaders.DATE, DateUtils.formatStandardDate(createInstant(2017, Month.DECEMBER, 27))));
message2.setHeader(new BasicHeader(HttpHeaders.DATE, DateUtils.formatStandardDate(createInstant(2017, Month.DECEMBER, 26))));
MatcherAssert.assertThat(DateSupport.isAfter(message1, message2, HttpHeaders.DATE), CoreMatchers.equalTo(true));
assertThat(DateSupport.isAfter(message1, message2, HttpHeaders.DATE), CoreMatchers.equalTo(true));
message1.setHeader(new BasicHeader(HttpHeaders.DATE, DateUtils.formatStandardDate(createInstant(2017, Month.DECEMBER, 25))));
message2.setHeader(new BasicHeader(HttpHeaders.DATE, DateUtils.formatStandardDate(createInstant(2017, Month.DECEMBER, 26))));
MatcherAssert.assertThat(DateSupport.isAfter(message1, message2, HttpHeaders.DATE), CoreMatchers.equalTo(false));
assertThat(DateSupport.isAfter(message1, message2, HttpHeaders.DATE), CoreMatchers.equalTo(false));
}
}

View File

@ -49,16 +49,14 @@ import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.message.BasicHeader;
import org.apache.hc.core5.http.message.BasicHttpRequest;
import org.apache.hc.core5.http.message.BasicHttpResponse;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentMatchers;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.MockitoAnnotations;
import org.mockito.stubbing.Answer;
@RunWith(MockitoJUnitRunner.class)
public class TestDefaultAsyncCacheInvalidator {
private DefaultAsyncCacheInvalidator impl;
@ -77,8 +75,9 @@ public class TestDefaultAsyncCacheInvalidator {
private Instant now;
private Instant tenSecondsAgo;
@Before
@BeforeEach
public void setUp() {
MockitoAnnotations.openMocks(this);
now = Instant.now();
tenSecondsAgo = now.minusSeconds(10);

View File

@ -48,15 +48,13 @@ import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.message.BasicHeader;
import org.apache.hc.core5.http.message.BasicHttpRequest;
import org.apache.hc.core5.http.message.BasicHttpResponse;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentMatchers;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.MockitoAnnotations;
import org.mockito.stubbing.Answer;
@RunWith(MockitoJUnitRunner.class)
public class TestDefaultCacheInvalidator {
private DefaultCacheInvalidator impl;
@ -71,8 +69,9 @@ public class TestDefaultCacheInvalidator {
private Instant now;
private Instant tenSecondsAgo;
@Before
@BeforeEach
public void setUp() {
MockitoAnnotations.openMocks(this);
now = Instant.now();
tenSecondsAgo = now.minusSeconds(10);

View File

@ -52,9 +52,9 @@ import org.apache.hc.core5.http.impl.io.AbstractMessageWriter;
import org.apache.hc.core5.http.io.SessionInputBuffer;
import org.apache.hc.core5.http.io.SessionOutputBuffer;
import org.apache.hc.core5.http.message.BasicHeader;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
public class TestHttpByteArrayCacheEntrySerializer {
@ -77,7 +77,7 @@ public class TestHttpByteArrayCacheEntrySerializer {
// Manually set this to true to re-generate all of the serialized files
private final boolean reserializeFiles = false;
@Before
@BeforeEach
public void before() {
serializer = HttpByteArrayCacheEntrySerializer.INSTANCE;
}
@ -202,7 +202,7 @@ public class TestHttpByteArrayCacheEntrySerializer {
cacheObjectValues.storageKey = null;
final HttpCacheStorageEntry testEntry = cacheObjectValues.toEntry();
Assert.assertThrows(IllegalStateException.class, () ->
Assertions.assertThrows(IllegalStateException.class, () ->
serializer.serialize(testEntry));
}
@ -300,7 +300,7 @@ public class TestHttpByteArrayCacheEntrySerializer {
public void testInvalidCacheEntry() throws Exception {
// This file is a JPEG not a cache entry, so should fail to deserialize
final byte[] bytes = readTestFileBytes(TEST_CONTENT_FILE_NAME);
Assert.assertThrows(ResourceIOException.class, () ->
Assertions.assertThrows(ResourceIOException.class, () ->
httpCacheStorageEntryFromBytes(serializer, bytes));
}
@ -313,7 +313,7 @@ public class TestHttpByteArrayCacheEntrySerializer {
public void testMissingHeaderCacheEntry() throws Exception {
// This file hand-edited to be missing a necessary header
final byte[] bytes = readTestFileBytes(MISSING_HEADER_TEST_SERIALIZED_NAME);
Assert.assertThrows(ResourceIOException.class, () ->
Assertions.assertThrows(ResourceIOException.class, () ->
httpCacheStorageEntryFromBytes(serializer, bytes));
}
@ -326,7 +326,7 @@ public class TestHttpByteArrayCacheEntrySerializer {
public void testInvalidHeaderCacheEntry() throws Exception {
// This file hand-edited to have an invalid header
final byte[] bytes = readTestFileBytes(INVALID_HEADER_TEST_SERIALIZED_NAME);
Assert.assertThrows(ResourceIOException.class, () ->
Assertions.assertThrows(ResourceIOException.class, () ->
httpCacheStorageEntryFromBytes(serializer, bytes));
}
@ -339,7 +339,7 @@ public class TestHttpByteArrayCacheEntrySerializer {
public void testVariantMapMissingKeyCacheEntry() throws Exception {
// This file hand-edited to be missing a VariantCache key
final byte[] bytes = readTestFileBytes(VARIANTMAP_MISSING_KEY_TEST_SERIALIZED_NAME);
Assert.assertThrows(ResourceIOException.class, () ->
Assertions.assertThrows(ResourceIOException.class, () ->
httpCacheStorageEntryFromBytes(serializer, bytes));
}
@ -352,7 +352,7 @@ public class TestHttpByteArrayCacheEntrySerializer {
public void testVariantMapMissingValueCacheEntry() throws Exception {
// This file hand-edited to be missing a VariantCache value
final byte[] bytes = readTestFileBytes(VARIANTMAP_MISSING_VALUE_TEST_SERIALIZED_NAME);
Assert.assertThrows(ResourceIOException.class, () ->
Assertions.assertThrows(ResourceIOException.class, () ->
httpCacheStorageEntryFromBytes(serializer, bytes));
}
@ -378,7 +378,7 @@ public class TestHttpByteArrayCacheEntrySerializer {
return throwyHttpWriter;
}
};
Assert.assertThrows(ResourceIOException.class, () ->
Assertions.assertThrows(ResourceIOException.class, () ->
testSerializer.serialize(testEntry));
}
@ -401,7 +401,7 @@ public class TestHttpByteArrayCacheEntrySerializer {
return throwyParser;
}
};
Assert.assertThrows(ResourceIOException.class, () ->
Assertions.assertThrows(ResourceIOException.class, () ->
testSerializer.deserialize(new byte[0]));
}
}

View File

@ -50,10 +50,10 @@ import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.message.BasicClassicHttpResponse;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
public class TestHttpCacheJiraNumber1147 {
@ -71,7 +71,7 @@ public class TestHttpCacheJiraNumber1147 {
}
}
@Before
@BeforeEach
public void setUp() throws Exception {
cacheDir = File.createTempFile("cachedir", "");
if (cacheDir.exists()) {
@ -80,7 +80,7 @@ public class TestHttpCacheJiraNumber1147 {
cacheDir.mkdir();
}
@After
@AfterEach
public void cleanUp() {
removeCache();
}
@ -121,7 +121,7 @@ public class TestHttpCacheJiraNumber1147 {
final ExecChain.Scope scope = new ExecChain.Scope("teset", route, get, mockEndpoint, context);
final ClassicHttpResponse response1 = t.execute(get, scope, mockExecChain);
Assert.assertEquals(200, response1.getCode());
Assertions.assertEquals(200, response1.getCode());
EntityUtils.consume(response1.getEntity());
verify(mockExecChain).proceed(isA(ClassicHttpRequest.class), isA(ExecChain.Scope.class));
@ -132,13 +132,13 @@ public class TestHttpCacheJiraNumber1147 {
when(mockExecChain.proceed(isA(ClassicHttpRequest.class), isA(ExecChain.Scope.class))).thenReturn(response);
final ClassicHttpResponse response2 = t.execute(get, scope, mockExecChain);
Assert.assertEquals(200, response2.getCode());
Assertions.assertEquals(200, response2.getCode());
EntityUtils.consume(response2.getEntity());
verify(mockExecChain, Mockito.times(1)).proceed(
isA(ClassicHttpRequest.class),
isA(ExecChain.Scope.class));
Assert.assertEquals(CacheResponseStatus.FAILURE, context.getCacheResponseStatus());
Assertions.assertEquals(CacheResponseStatus.FAILURE, context.getCacheResponseStatus());
}
protected ExecChainHandler createCachingExecChain(final BasicHttpCache cache, final CacheConfig config) {

View File

@ -43,19 +43,17 @@ import org.apache.hc.core5.http.HttpResponse;
import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.io.support.ClassicRequestBuilder;
import org.apache.hc.core5.http.message.BasicClassicHttpRequest;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.MockitoAnnotations;
/**
* This class tests behavior that is allowed (MAY) by the HTTP/1.1 protocol
* specification and for which we have implemented the behavior in HTTP cache.
*/
@RunWith(MockitoJUnitRunner.class)
public class TestProtocolAllowedBehavior {
static final int MAX_BYTES = 1024;
@ -77,8 +75,9 @@ public class TestProtocolAllowedBehavior {
CachingExec impl;
HttpCache cache;
@Before
@BeforeEach
public void setUp() throws Exception {
MockitoAnnotations.openMocks(this);
host = new HttpHost("foo.example.com", 80);
route = new HttpRoute(host);
@ -126,7 +125,7 @@ public class TestProtocolAllowedBehavior {
Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenThrow(new SocketTimeoutException());
final HttpResponse result = execute(req2);
Assert.assertEquals(HttpStatus.SC_OK, result.getCode());
Assertions.assertEquals(HttpStatus.SC_OK, result.getCode());
Mockito.verifyNoInteractions(mockCache);
}
@ -142,7 +141,7 @@ public class TestProtocolAllowedBehavior {
execute(req1);
final HttpResponse result = execute(req2);
Assert.assertEquals(HttpStatus.SC_OK, result.getCode());
Assertions.assertEquals(HttpStatus.SC_OK, result.getCode());
Mockito.verifyNoInteractions(mockCache);
}

View File

@ -47,13 +47,12 @@ import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.io.entity.ByteArrayEntity;
import org.apache.hc.core5.http.message.BasicClassicHttpRequest;
import org.apache.hc.core5.http.message.BasicClassicHttpResponse;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.MockitoAnnotations;
/**
* We are a conditionally-compliant HTTP/1.1 client with a cache. However, a lot
@ -70,7 +69,6 @@ import org.mockito.junit.MockitoJUnitRunner;
* document the places where we differ from the HTTP RFC.
*/
@SuppressWarnings("boxing") // test code
@RunWith(MockitoJUnitRunner.class)
public class TestProtocolDeviations {
private static final int MAX_BYTES = 1024;
@ -88,8 +86,9 @@ public class TestProtocolDeviations {
ExecChainHandler impl;
@Before
@BeforeEach
public void setUp() {
MockitoAnnotations.openMocks(this);
host = new HttpHost("foo.example.com", 80);
route = new HttpRoute(host);
@ -156,7 +155,7 @@ public class TestProtocolDeviations {
try {
final HttpResponse result = execute(request);
Assert.assertTrue(HttpStatus.SC_PARTIAL_CONTENT != result.getCode());
Assertions.assertTrue(HttpStatus.SC_PARTIAL_CONTENT != result.getCode());
} catch (final ClientProtocolException acceptableBehavior) {
// this is probably ok
}
@ -177,7 +176,7 @@ public class TestProtocolDeviations {
Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(originResponse);
final HttpResponse result = execute(request);
Assert.assertSame(originResponse, result);
Assertions.assertSame(originResponse, result);
}
/*
@ -193,7 +192,7 @@ public class TestProtocolDeviations {
Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(originResponse);
final HttpResponse result = execute(request);
Assert.assertSame(originResponse, result);
Assertions.assertSame(originResponse, result);
}
/*
@ -210,7 +209,7 @@ public class TestProtocolDeviations {
Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(originResponse);
final HttpResponse result = execute(request);
Assert.assertSame(originResponse, result);
Assertions.assertSame(originResponse, result);
}
}

View File

@ -26,12 +26,13 @@
*/
package org.apache.hc.client5.http.impl.cache;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.time.Instant;
@ -62,20 +63,18 @@ import org.apache.hc.core5.http.io.support.ClassicRequestBuilder;
import org.apache.hc.core5.http.message.BasicClassicHttpRequest;
import org.apache.hc.core5.http.message.BasicClassicHttpResponse;
import org.apache.hc.core5.http.message.MessageSupport;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.MockitoAnnotations;
/*
* This test class captures functionality required to achieve unconditional
* compliance with the HTTP/1.1 spec, i.e. all the SHOULD, SHOULD NOT,
* RECOMMENDED, and NOT RECOMMENDED behaviors.
*/
@RunWith(MockitoJUnitRunner.class)
public class TestProtocolRecommendations {
static final int MAX_BYTES = 1024;
@ -99,8 +98,9 @@ public class TestProtocolRecommendations {
Instant tenSecondsAgo;
Instant twoMinutesAgo;
@Before
@BeforeEach
public void setUp() throws Exception {
MockitoAnnotations.openMocks(this);
host = new HttpHost("foo.example.com", 80);
route = new HttpRoute(host);

View File

@ -26,9 +26,10 @@
*/
package org.apache.hc.client5.http.impl.cache;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayInputStream;
import java.io.IOException;
@ -52,20 +53,18 @@ import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.io.entity.InputStreamEntity;
import org.apache.hc.core5.http.io.support.ClassicRequestBuilder;
import org.apache.hc.core5.http.message.BasicClassicHttpRequest;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.MockitoAnnotations;
/**
* A suite of acceptance tests for compliance with RFC5861, which
* describes the stale-if-error and stale-while-revalidate
* Cache-Control extensions.
*/
@RunWith(MockitoJUnitRunner.class)
public class TestRFC5861Compliance {
static final int MAX_BYTES = 1024;
@ -87,8 +86,10 @@ public class TestRFC5861Compliance {
HttpCache cache;
ScheduledExecutorService executorService;
@Before
@BeforeEach
public void setUp() throws Exception {
MockitoAnnotations.openMocks(this);
host = new HttpHost("foo.example.com", 80);
route = new HttpRoute(host);
@ -115,7 +116,7 @@ public class TestRFC5861Compliance {
Mockito.when(mockExecRuntime.fork(null)).thenReturn(mockExecRuntime);
}
@After
@AfterEach
public void cleanup() {
executorService.shutdownNow();
}

View File

@ -26,8 +26,9 @@
*/
package org.apache.hc.client5.http.impl.cache;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Collections;
@ -36,14 +37,14 @@ import org.apache.hc.core5.http.HttpVersion;
import org.apache.hc.core5.http.ProtocolVersion;
import org.apache.hc.core5.http.message.BasicHttpRequest;
import org.apache.hc.core5.http.support.BasicRequestBuilder;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class TestRequestProtocolCompliance {
private RequestProtocolCompliance impl;
@Before
@BeforeEach
public void setUp() {
impl = new RequestProtocolCompliance(false);
}

View File

@ -39,9 +39,9 @@ import org.apache.hc.core5.http.HttpVersion;
import org.apache.hc.core5.http.ProtocolVersion;
import org.apache.hc.core5.http.message.BasicHttpRequest;
import org.apache.hc.core5.http.message.BasicHttpResponse;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class TestResponseCachingPolicy {
@ -56,7 +56,7 @@ public class TestResponseCachingPolicy {
private Instant tenSecondsFromNow;
private Instant sixSecondsAgo;
@Before
@BeforeEach
public void setUp() throws Exception {
now = Instant.now();
sixSecondsAgo = now.minusSeconds(6);
@ -71,20 +71,20 @@ public class TestResponseCachingPolicy {
@Test
public void testIsGetCacheable() {
Assert.assertTrue(policy.isResponseCacheable("GET", response));
Assertions.assertTrue(policy.isResponseCacheable("GET", response));
}
@Test
public void testIsHeadCacheable() {
policy = new ResponseCachingPolicy(0, true, false, false);
Assert.assertTrue(policy.isResponseCacheable("HEAD", response));
Assertions.assertTrue(policy.isResponseCacheable("HEAD", response));
}
@Test
public void testResponsesToRequestsWithAuthorizationHeadersAreNotCacheableBySharedCache() {
request = new BasicHttpRequest("GET","/");
request.setHeader("Authorization", StandardAuthScheme.BASIC + " dXNlcjpwYXNzd2Q=");
Assert.assertFalse(policy.isResponseCacheable(request,response));
Assertions.assertFalse(policy.isResponseCacheable(request,response));
}
@Test
@ -92,7 +92,7 @@ public class TestResponseCachingPolicy {
policy = new ResponseCachingPolicy(0, false, false, false);
request = new BasicHttpRequest("GET","/");
request.setHeader("Authorization", StandardAuthScheme.BASIC + " dXNlcjpwYXNzd2Q=");
Assert.assertTrue(policy.isResponseCacheable(request,response));
Assertions.assertTrue(policy.isResponseCacheable(request,response));
}
@Test
@ -100,7 +100,7 @@ public class TestResponseCachingPolicy {
request = new BasicHttpRequest("GET","/");
request.setHeader("Authorization", StandardAuthScheme.BASIC + " dXNlcjpwYXNzd2Q=");
response.setHeader("Cache-Control","s-maxage=3600");
Assert.assertTrue(policy.isResponseCacheable(request,response));
Assertions.assertTrue(policy.isResponseCacheable(request,response));
}
@Test
@ -108,7 +108,7 @@ public class TestResponseCachingPolicy {
request = new BasicHttpRequest("GET","/");
request.setHeader("Authorization", StandardAuthScheme.BASIC + " dXNlcjpwYXNzd2Q=");
response.setHeader("Cache-Control","must-revalidate");
Assert.assertTrue(policy.isResponseCacheable(request,response));
Assertions.assertTrue(policy.isResponseCacheable(request,response));
}
@Test
@ -116,7 +116,7 @@ public class TestResponseCachingPolicy {
request = new BasicHttpRequest("GET","/");
request.setHeader("Authorization", StandardAuthScheme.BASIC + " dXNlcjpwYXNzd2Q=");
response.setHeader("Cache-Control","public");
Assert.assertTrue(policy.isResponseCacheable(request,response));
Assertions.assertTrue(policy.isResponseCacheable(request,response));
}
@Test
@ -124,19 +124,19 @@ public class TestResponseCachingPolicy {
request = new BasicHttpRequest("GET","/");
request.setHeader("Authorization", StandardAuthScheme.BASIC + " dXNlcjpwYXNzd2Q=");
response.setHeader("Cache-Control","max-age=3600");
Assert.assertFalse(policy.isResponseCacheable(request,response));
Assertions.assertFalse(policy.isResponseCacheable(request,response));
}
@Test
public void test203ResponseCodeIsCacheable() {
response.setCode(HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION);
Assert.assertTrue(policy.isResponseCacheable("GET", response));
Assertions.assertTrue(policy.isResponseCacheable("GET", response));
}
@Test
public void test206ResponseCodeIsNotCacheable() {
response.setCode(HttpStatus.SC_PARTIAL_CONTENT);
Assert.assertFalse(policy.isResponseCacheable("GET", response));
Assertions.assertFalse(policy.isResponseCacheable("GET", response));
}
@Test
@ -146,25 +146,25 @@ public class TestResponseCachingPolicy {
request.setHeader("Authorization", StandardAuthScheme.BASIC + " QWxhZGRpbjpvcGVuIHNlc2FtZQ==");
response.setCode(HttpStatus.SC_PARTIAL_CONTENT);
response.setHeader("Cache-Control", "public");
Assert.assertFalse(policy.isResponseCacheable(request, response));
Assertions.assertFalse(policy.isResponseCacheable(request, response));
}
@Test
public void test300ResponseCodeIsCacheable() {
response.setCode(HttpStatus.SC_MULTIPLE_CHOICES);
Assert.assertTrue(policy.isResponseCacheable("GET", response));
Assertions.assertTrue(policy.isResponseCacheable("GET", response));
}
@Test
public void test301ResponseCodeIsCacheable() {
response.setCode(HttpStatus.SC_MOVED_PERMANENTLY);
Assert.assertTrue(policy.isResponseCacheable("GET", response));
Assertions.assertTrue(policy.isResponseCacheable("GET", response));
}
@Test
public void test410ResponseCodeIsCacheable() {
response.setCode(HttpStatus.SC_GONE);
Assert.assertTrue(policy.isResponseCacheable("GET", response));
Assertions.assertTrue(policy.isResponseCacheable("GET", response));
}
@Test
@ -172,7 +172,7 @@ public class TestResponseCachingPolicy {
response.setCode(HttpStatus.SC_MOVED_TEMPORARILY);
response.removeHeaders("Expires");
response.removeHeaders("Cache-Control");
Assert.assertFalse(policy.isResponseCacheable("GET", response));
Assertions.assertFalse(policy.isResponseCacheable("GET", response));
}
@Test
@ -180,7 +180,7 @@ public class TestResponseCachingPolicy {
response.setCode(HttpStatus.SC_SEE_OTHER);
response.removeHeaders("Expires");
response.removeHeaders("Cache-Control");
Assert.assertFalse(policy.isResponseCacheable("GET", response));
Assertions.assertFalse(policy.isResponseCacheable("GET", response));
}
@Test
@ -189,7 +189,7 @@ public class TestResponseCachingPolicy {
response.setCode(HttpStatus.SC_SEE_OTHER);
response.removeHeaders("Expires");
response.removeHeaders("Cache-Control");
Assert.assertFalse(policy.isResponseCacheable("GET", response));
Assertions.assertFalse(policy.isResponseCacheable("GET", response));
}
@ -198,7 +198,7 @@ public class TestResponseCachingPolicy {
response.setCode(HttpStatus.SC_TEMPORARY_REDIRECT);
response.removeHeaders("Expires");
response.removeHeaders("Cache-Control");
Assert.assertFalse(policy.isResponseCacheable("GET", response));
Assertions.assertFalse(policy.isResponseCacheable("GET", response));
}
@Test
@ -206,7 +206,7 @@ public class TestResponseCachingPolicy {
final int status = getRandomStatus();
response.setCode(status);
response.setHeader("Expires", DateUtils.formatStandardDate(Instant.now()));
Assert.assertTrue(policy.isResponseCacheable("GET", response));
Assertions.assertTrue(policy.isResponseCacheable("GET", response));
}
@Test
@ -214,7 +214,7 @@ public class TestResponseCachingPolicy {
final int status = getRandomStatus();
response.setCode(status);
response.setHeader("Cache-Control", "max-age=0");
Assert.assertTrue(policy.isResponseCacheable("GET", response));
Assertions.assertTrue(policy.isResponseCacheable("GET", response));
}
@Test
@ -222,7 +222,7 @@ public class TestResponseCachingPolicy {
final int status = getRandomStatus();
response.setCode(status);
response.setHeader("Cache-Control", "s-maxage=0");
Assert.assertTrue(policy.isResponseCacheable("GET", response));
Assertions.assertTrue(policy.isResponseCacheable("GET", response));
}
@Test
@ -230,7 +230,7 @@ public class TestResponseCachingPolicy {
final int status = getRandomStatus();
response.setCode(status);
response.setHeader("Cache-Control", "must-revalidate");
Assert.assertTrue(policy.isResponseCacheable("GET", response));
Assertions.assertTrue(policy.isResponseCacheable("GET", response));
}
@Test
@ -238,7 +238,7 @@ public class TestResponseCachingPolicy {
final int status = getRandomStatus();
response.setCode(status);
response.setHeader("Cache-Control", "proxy-revalidate");
Assert.assertTrue(policy.isResponseCacheable("GET", response));
Assertions.assertTrue(policy.isResponseCacheable("GET", response));
}
@Test
@ -246,7 +246,7 @@ public class TestResponseCachingPolicy {
final int status = getRandomStatus();
response.setCode(status);
response.setHeader("Cache-Control", "public");
Assert.assertTrue(policy.isResponseCacheable("GET", response));
Assertions.assertTrue(policy.isResponseCacheable("GET", response));
}
@Test
@ -254,7 +254,7 @@ public class TestResponseCachingPolicy {
final int status = getRandomStatus();
response.setCode(status);
response.setHeader("Cache-Control", "private");
Assert.assertFalse(policy.isResponseCacheable("GET", response));
Assertions.assertFalse(policy.isResponseCacheable("GET", response));
}
@Test
@ -262,63 +262,63 @@ public class TestResponseCachingPolicy {
policy = new ResponseCachingPolicy(0, false, false, false);
response.setCode(HttpStatus.SC_OK);
response.setHeader("Cache-Control", "private");
Assert.assertTrue(policy.isResponseCacheable("GET", response));
Assertions.assertTrue(policy.isResponseCacheable("GET", response));
}
@Test
public void testIsGetWithNoCacheCacheable() {
response.addHeader("Cache-Control", "no-cache");
Assert.assertFalse(policy.isResponseCacheable("GET", response));
Assertions.assertFalse(policy.isResponseCacheable("GET", response));
}
@Test
public void testIsHeadWithNoCacheCacheable() {
response.addHeader("Cache-Control", "no-cache");
Assert.assertFalse(policy.isResponseCacheable("HEAD", response));
Assertions.assertFalse(policy.isResponseCacheable("HEAD", response));
}
@Test
public void testIsGetWithNoStoreCacheable() {
response.addHeader("Cache-Control", "no-store");
Assert.assertFalse(policy.isResponseCacheable("GET", response));
Assertions.assertFalse(policy.isResponseCacheable("GET", response));
}
@Test
public void testIsHeadWithNoStoreCacheable() {
response.addHeader("Cache-Control", "no-store");
Assert.assertFalse(policy.isResponseCacheable("HEAD", response));
Assertions.assertFalse(policy.isResponseCacheable("HEAD", response));
}
@Test
public void testIsGetWithNoStoreEmbeddedInListCacheable() {
response.addHeader("Cache-Control", "public, no-store");
Assert.assertFalse(policy.isResponseCacheable("GET", response));
Assertions.assertFalse(policy.isResponseCacheable("GET", response));
}
@Test
public void testIsHeadWithNoStoreEmbeddedInListCacheable() {
response.addHeader("Cache-Control", "public, no-store");
Assert.assertFalse(policy.isResponseCacheable("HEAD", response));
Assertions.assertFalse(policy.isResponseCacheable("HEAD", response));
}
@Test
public void testIsGetWithNoCacheEmbeddedInListCacheable() {
response.addHeader("Cache-Control", "public, no-cache");
Assert.assertFalse(policy.isResponseCacheable("GET", response));
Assertions.assertFalse(policy.isResponseCacheable("GET", response));
}
@Test
public void testIsHeadWithNoCacheEmbeddedInListCacheable() {
response.addHeader("Cache-Control", "public, no-cache");
Assert.assertFalse(policy.isResponseCacheable("HEAD", response));
Assertions.assertFalse(policy.isResponseCacheable("HEAD", response));
}
@Test
@ -326,7 +326,7 @@ public class TestResponseCachingPolicy {
response.addHeader("Cache-Control", "max-age=20");
response.addHeader("Cache-Control", "public, no-cache");
Assert.assertFalse(policy.isResponseCacheable("GET", response));
Assertions.assertFalse(policy.isResponseCacheable("GET", response));
}
@Test
@ -334,7 +334,7 @@ public class TestResponseCachingPolicy {
response.addHeader("Cache-Control", "max-age=20");
response.addHeader("Cache-Control", "public, no-cache");
Assert.assertFalse(policy.isResponseCacheable("HEAD", response));
Assertions.assertFalse(policy.isResponseCacheable("HEAD", response));
}
@Test
@ -342,7 +342,7 @@ public class TestResponseCachingPolicy {
response.addHeader("Cache-Control", "max-age=20");
response.addHeader("Cache-Control", "public, no-store");
Assert.assertFalse(policy.isResponseCacheable("GET", response));
Assertions.assertFalse(policy.isResponseCacheable("GET", response));
}
@Test
@ -350,21 +350,21 @@ public class TestResponseCachingPolicy {
response.addHeader("Cache-Control", "max-age=20");
response.addHeader("Cache-Control", "public, no-store");
Assert.assertFalse(policy.isResponseCacheable("HEAD", response));
Assertions.assertFalse(policy.isResponseCacheable("HEAD", response));
}
@Test
public void testIsGetWithAnyCacheControlCacheable() {
response.addHeader("Cache-Control", "max=10");
Assert.assertTrue(policy.isResponseCacheable("GET", response));
Assertions.assertTrue(policy.isResponseCacheable("GET", response));
response = new BasicHttpResponse(HttpStatus.SC_OK, "");
response.setHeader("Date", DateUtils.formatStandardDate(Instant.now()));
response.addHeader("Cache-Control", "no-transform");
response.setHeader("Content-Length", "0");
Assert.assertTrue(policy.isResponseCacheable("GET", response));
Assertions.assertTrue(policy.isResponseCacheable("GET", response));
}
@Test
@ -372,42 +372,42 @@ public class TestResponseCachingPolicy {
policy = new ResponseCachingPolicy(0, true, false, false);
response.addHeader("Cache-Control", "max=10");
Assert.assertTrue(policy.isResponseCacheable("HEAD", response));
Assertions.assertTrue(policy.isResponseCacheable("HEAD", response));
response = new BasicHttpResponse(HttpStatus.SC_OK, "");
response.setHeader("Date", DateUtils.formatStandardDate(Instant.now()));
response.addHeader("Cache-Control", "no-transform");
response.setHeader("Content-Length", "0");
Assert.assertTrue(policy.isResponseCacheable("HEAD", response));
Assertions.assertTrue(policy.isResponseCacheable("HEAD", response));
}
@Test
public void testIsGetWithout200Cacheable() {
HttpResponse response404 = new BasicHttpResponse(HttpStatus.SC_NOT_FOUND, "");
Assert.assertFalse(policy.isResponseCacheable("GET", response404));
Assertions.assertFalse(policy.isResponseCacheable("GET", response404));
response404 = new BasicHttpResponse(HttpStatus.SC_GATEWAY_TIMEOUT, "");
Assert.assertFalse(policy.isResponseCacheable("GET", response404));
Assertions.assertFalse(policy.isResponseCacheable("GET", response404));
}
@Test
public void testIsHeadWithout200Cacheable() {
HttpResponse response404 = new BasicHttpResponse(HttpStatus.SC_NOT_FOUND, "");
Assert.assertFalse(policy.isResponseCacheable("HEAD", response404));
Assertions.assertFalse(policy.isResponseCacheable("HEAD", response404));
response404 = new BasicHttpResponse(HttpStatus.SC_GATEWAY_TIMEOUT, "");
Assert.assertFalse(policy.isResponseCacheable("HEAD", response404));
Assertions.assertFalse(policy.isResponseCacheable("HEAD", response404));
}
@Test
public void testVaryStarIsNotCacheable() {
response.setHeader("Vary", "*");
Assert.assertFalse(policy.isResponseCacheable("GET", response));
Assertions.assertFalse(policy.isResponseCacheable("GET", response));
}
@Test
@ -417,28 +417,28 @@ public class TestResponseCachingPolicy {
request.setHeader("Authorization", StandardAuthScheme.BASIC + " QWxhZGRpbjpvcGVuIHNlc2FtZQ==");
response.setHeader("Cache-Control", "public");
response.setHeader("Vary", "*");
Assert.assertFalse(policy.isResponseCacheable(request, response));
Assertions.assertFalse(policy.isResponseCacheable(request, response));
}
@Test
public void testIsGetWithVaryHeaderCacheable() {
response.addHeader("Vary", "Accept-Encoding");
Assert.assertTrue(policy.isResponseCacheable("GET", response));
Assertions.assertTrue(policy.isResponseCacheable("GET", response));
}
@Test
public void testIsHeadWithVaryHeaderCacheable() {
policy = new ResponseCachingPolicy(0, true, false, false);
response.addHeader("Vary", "Accept-Encoding");
Assert.assertTrue(policy.isResponseCacheable("HEAD", response));
Assertions.assertTrue(policy.isResponseCacheable("HEAD", response));
}
@Test
public void testIsArbitraryMethodCacheable() {
Assert.assertFalse(policy.isResponseCacheable("PUT", response));
Assertions.assertFalse(policy.isResponseCacheable("PUT", response));
Assert.assertFalse(policy.isResponseCacheable("get", response));
Assertions.assertFalse(policy.isResponseCacheable("get", response));
}
@Test
@ -450,21 +450,21 @@ public class TestResponseCachingPolicy {
response.setCode(HttpStatus.SC_NO_CONTENT);
response.setHeader("Cache-Control", "public");
Assert.assertFalse(policy.isResponseCacheable(request, response));
Assertions.assertFalse(policy.isResponseCacheable(request, response));
}
@Test
public void testResponsesToRequestsWithNoStoreAreNotCacheable() {
request.setHeader("Cache-Control","no-store");
response.setHeader("Cache-Control","public");
Assert.assertFalse(policy.isResponseCacheable(request,response));
Assertions.assertFalse(policy.isResponseCacheable(request,response));
}
@Test
public void testResponsesWithMultipleAgeHeadersAreNotCacheable() {
response.addHeader("Age", "3");
response.addHeader("Age", "5");
Assert.assertFalse(policy.isResponseCacheable("GET", response));
Assertions.assertFalse(policy.isResponseCacheable("GET", response));
}
@Test
@ -475,14 +475,14 @@ public class TestResponseCachingPolicy {
response.setHeader("Cache-Control", "public");
response.addHeader("Age", "3");
response.addHeader("Age", "5");
Assert.assertFalse(policy.isResponseCacheable(request, response));
Assertions.assertFalse(policy.isResponseCacheable(request, response));
}
@Test
public void testResponsesWithMultipleDateHeadersAreNotCacheable() {
response.addHeader("Date", DateUtils.formatStandardDate(now));
response.addHeader("Date", DateUtils.formatStandardDate(sixSecondsAgo));
Assert.assertFalse(policy.isResponseCacheable("GET", response));
Assertions.assertFalse(policy.isResponseCacheable("GET", response));
}
@Test
@ -493,13 +493,13 @@ public class TestResponseCachingPolicy {
response.setHeader("Cache-Control", "public");
response.addHeader("Date", DateUtils.formatStandardDate(now));
response.addHeader("Date", DateUtils.formatStandardDate(sixSecondsAgo));
Assert.assertFalse(policy.isResponseCacheable(request, response));
Assertions.assertFalse(policy.isResponseCacheable(request, response));
}
@Test
public void testResponsesWithMalformedDateHeadersAreNotCacheable() {
response.addHeader("Date", "garbage");
Assert.assertFalse(policy.isResponseCacheable("GET", response));
Assertions.assertFalse(policy.isResponseCacheable("GET", response));
}
@Test
@ -509,14 +509,14 @@ public class TestResponseCachingPolicy {
request.setHeader("Authorization", StandardAuthScheme.BASIC + " QWxhZGRpbjpvcGVuIHNlc2FtZQ==");
response.setHeader("Cache-Control", "public");
response.addHeader("Date", "garbage");
Assert.assertFalse(policy.isResponseCacheable(request, response));
Assertions.assertFalse(policy.isResponseCacheable(request, response));
}
@Test
public void testResponsesWithMultipleExpiresHeadersAreNotCacheable() {
response.addHeader("Expires", DateUtils.formatStandardDate(now));
response.addHeader("Expires", DateUtils.formatStandardDate(sixSecondsAgo));
Assert.assertFalse(policy.isResponseCacheable("GET", response));
Assertions.assertFalse(policy.isResponseCacheable("GET", response));
}
@Test
@ -527,19 +527,19 @@ public class TestResponseCachingPolicy {
response.setHeader("Cache-Control", "public");
response.addHeader("Expires", DateUtils.formatStandardDate(now));
response.addHeader("Expires", DateUtils.formatStandardDate(sixSecondsAgo));
Assert.assertFalse(policy.isResponseCacheable(request, response));
Assertions.assertFalse(policy.isResponseCacheable(request, response));
}
@Test
public void testResponsesWithoutDateHeadersAreNotCacheable() {
response.removeHeaders("Date");
Assert.assertFalse(policy.isResponseCacheable("GET", response));
Assertions.assertFalse(policy.isResponseCacheable("GET", response));
}
@Test
public void testResponseThatHasTooMuchContentIsNotCacheable() {
response.setHeader("Content-Length", "9000");
Assert.assertFalse(policy.isResponseCacheable("GET", response));
Assertions.assertFalse(policy.isResponseCacheable("GET", response));
}
@Test
@ -549,39 +549,39 @@ public class TestResponseCachingPolicy {
request.setHeader("Authorization", StandardAuthScheme.BASIC + " QWxhZGRpbjpvcGVuIHNlc2FtZQ==");
response.setHeader("Cache-Control", "public");
response.setHeader("Content-Length", "9000");
Assert.assertFalse(policy.isResponseCacheable(request, response));
Assertions.assertFalse(policy.isResponseCacheable(request, response));
}
@Test
public void testResponsesThatAreSmallEnoughAreCacheable() {
response.setHeader("Content-Length", "0");
Assert.assertTrue(policy.isResponseCacheable("GET", response));
Assertions.assertTrue(policy.isResponseCacheable("GET", response));
}
@Test
public void testResponsesToGETWithQueryParamsButNoExplicitCachingAreNotCacheable() {
request = new BasicHttpRequest("GET", "/foo?s=bar");
Assert.assertFalse(policy.isResponseCacheable(request, response));
Assertions.assertFalse(policy.isResponseCacheable(request, response));
}
@Test
public void testResponsesToHEADWithQueryParamsButNoExplicitCachingAreNotCacheable() {
request = new BasicHttpRequest("HEAD", "/foo?s=bar");
Assert.assertFalse(policy.isResponseCacheable(request, response));
Assertions.assertFalse(policy.isResponseCacheable(request, response));
}
@Test
public void testResponsesToGETWithQueryParamsButNoExplicitCachingAreNotCacheableEvenWhen1_0QueryCachingDisabled() {
policy = new ResponseCachingPolicy(0, true, true, false);
request = new BasicHttpRequest("GET", "/foo?s=bar");
Assert.assertFalse(policy.isResponseCacheable(request, response));
Assertions.assertFalse(policy.isResponseCacheable(request, response));
}
@Test
public void testResponsesToHEADWithQueryParamsButNoExplicitCachingAreNotCacheableEvenWhen1_0QueryCachingDisabled() {
policy = new ResponseCachingPolicy(0, true, true, false);
request = new BasicHttpRequest("HEAD", "/foo?s=bar");
Assert.assertFalse(policy.isResponseCacheable(request, response));
Assertions.assertFalse(policy.isResponseCacheable(request, response));
}
@Test
@ -589,7 +589,7 @@ public class TestResponseCachingPolicy {
request = new BasicHttpRequest("GET", "/foo?s=bar");
response.setHeader("Date", DateUtils.formatStandardDate(now));
response.setHeader("Expires", DateUtils.formatStandardDate(tenSecondsFromNow));
Assert.assertTrue(policy.isResponseCacheable(request, response));
Assertions.assertTrue(policy.isResponseCacheable(request, response));
}
@Test
@ -598,7 +598,7 @@ public class TestResponseCachingPolicy {
request = new BasicHttpRequest("HEAD", "/foo?s=bar");
response.setHeader("Date", DateUtils.formatStandardDate(now));
response.setHeader("Expires", DateUtils.formatStandardDate(tenSecondsFromNow));
Assert.assertTrue(policy.isResponseCacheable(request, response));
Assertions.assertTrue(policy.isResponseCacheable(request, response));
}
@Test
@ -607,7 +607,7 @@ public class TestResponseCachingPolicy {
request = new BasicHttpRequest("GET", "/foo?s=bar");
response.setHeader("Date", DateUtils.formatStandardDate(now));
response.setHeader("Expires", DateUtils.formatStandardDate(tenSecondsFromNow));
Assert.assertTrue(policy.isResponseCacheable(request, response));
Assertions.assertTrue(policy.isResponseCacheable(request, response));
}
@Test
@ -616,7 +616,7 @@ public class TestResponseCachingPolicy {
request = new BasicHttpRequest("HEAD", "/foo?s=bar");
response.setHeader("Date", DateUtils.formatStandardDate(now));
response.setHeader("Expires", DateUtils.formatStandardDate(tenSecondsFromNow));
Assert.assertTrue(policy.isResponseCacheable(request, response));
Assertions.assertTrue(policy.isResponseCacheable(request, response));
}
@Test
@ -624,7 +624,7 @@ public class TestResponseCachingPolicy {
request = new BasicHttpRequest("GET", "/foo?s=bar");
response = new BasicHttpResponse(HttpStatus.SC_OK, "OK");
response.setVersion(HttpVersion.HTTP_1_0);
Assert.assertFalse(policy.isResponseCacheable(request, response));
Assertions.assertFalse(policy.isResponseCacheable(request, response));
}
@Test
@ -632,7 +632,7 @@ public class TestResponseCachingPolicy {
request = new BasicHttpRequest("HEAD", "/foo?s=bar");
response = new BasicHttpResponse(HttpStatus.SC_OK, "OK");
response.setVersion(HttpVersion.HTTP_1_0);
Assert.assertFalse(policy.isResponseCacheable(request, response));
Assertions.assertFalse(policy.isResponseCacheable(request, response));
}
@Test
@ -641,7 +641,7 @@ public class TestResponseCachingPolicy {
request = new BasicHttpRequest("GET", "/foo?s=bar");
response = new BasicHttpResponse(HttpStatus.SC_OK, "OK");
response.setVersion(HttpVersion.HTTP_1_0);
Assert.assertFalse(policy.isResponseCacheable(request, response));
Assertions.assertFalse(policy.isResponseCacheable(request, response));
}
@Test
@ -650,7 +650,7 @@ public class TestResponseCachingPolicy {
request = new BasicHttpRequest("HEAD", "/foo?s=bar");
response = new BasicHttpResponse(HttpStatus.SC_OK, "OK");
response.setVersion(HttpVersion.HTTP_1_0);
Assert.assertFalse(policy.isResponseCacheable(request, response));
Assertions.assertFalse(policy.isResponseCacheable(request, response));
}
@Test
@ -660,7 +660,7 @@ public class TestResponseCachingPolicy {
response.setVersion(HttpVersion.HTTP_1_0);
response.setHeader("Date", DateUtils.formatStandardDate(now));
response.setHeader("Expires", DateUtils.formatStandardDate(tenSecondsFromNow));
Assert.assertTrue(policy.isResponseCacheable(request, response));
Assertions.assertTrue(policy.isResponseCacheable(request, response));
}
@Test
@ -671,7 +671,7 @@ public class TestResponseCachingPolicy {
response.setVersion(HttpVersion.HTTP_1_0);
response.setHeader("Date", DateUtils.formatStandardDate(now));
response.setHeader("Expires", DateUtils.formatStandardDate(tenSecondsFromNow));
Assert.assertTrue(policy.isResponseCacheable(request, response));
Assertions.assertTrue(policy.isResponseCacheable(request, response));
}
@Test
@ -682,7 +682,7 @@ public class TestResponseCachingPolicy {
response.setVersion(HttpVersion.HTTP_1_0);
response.setHeader("Date", DateUtils.formatStandardDate(now));
response.setHeader("Expires", DateUtils.formatStandardDate(tenSecondsFromNow));
Assert.assertFalse(policy.isResponseCacheable(request, response));
Assertions.assertFalse(policy.isResponseCacheable(request, response));
}
@Test
@ -693,21 +693,21 @@ public class TestResponseCachingPolicy {
response.setVersion(HttpVersion.HTTP_1_0);
response.setHeader("Date", DateUtils.formatStandardDate(now));
response.setHeader("Expires", DateUtils.formatStandardDate(tenSecondsFromNow));
Assert.assertFalse(policy.isResponseCacheable(request, response));
Assertions.assertFalse(policy.isResponseCacheable(request, response));
}
@Test
public void getsWithQueryParametersFrom1_0OriginsViaProxiesAreNotCacheable() {
request = new BasicHttpRequest("GET", "/foo?s=bar");
response.setHeader("Via", "1.0 someproxy");
Assert.assertFalse(policy.isResponseCacheable(request, response));
Assertions.assertFalse(policy.isResponseCacheable(request, response));
}
@Test
public void headsWithQueryParametersFrom1_0OriginsViaProxiesAreNotCacheable() {
request = new BasicHttpRequest("HEAD", "/foo?s=bar");
response.setHeader("Via", "1.0 someproxy");
Assert.assertFalse(policy.isResponseCacheable(request, response));
Assertions.assertFalse(policy.isResponseCacheable(request, response));
}
@Test
@ -716,7 +716,7 @@ public class TestResponseCachingPolicy {
response.setHeader("Date", DateUtils.formatStandardDate(now));
response.setHeader("Expires", DateUtils.formatStandardDate(tenSecondsFromNow));
response.setHeader("Via", "1.0 someproxy");
Assert.assertTrue(policy.isResponseCacheable(request, response));
Assertions.assertTrue(policy.isResponseCacheable(request, response));
}
@Test
@ -726,7 +726,7 @@ public class TestResponseCachingPolicy {
response.setHeader("Date", DateUtils.formatStandardDate(now));
response.setHeader("Expires", DateUtils.formatStandardDate(tenSecondsFromNow));
response.setHeader("Via", "1.0 someproxy");
Assert.assertTrue(policy.isResponseCacheable(request, response));
Assertions.assertTrue(policy.isResponseCacheable(request, response));
}
@Test
@ -736,7 +736,7 @@ public class TestResponseCachingPolicy {
response.setHeader("Date", DateUtils.formatStandardDate(now));
response.setHeader("Expires", DateUtils.formatStandardDate(tenSecondsFromNow));
response.setHeader("Via", "1.0 someproxy");
Assert.assertFalse(policy.isResponseCacheable(request, response));
Assertions.assertFalse(policy.isResponseCacheable(request, response));
}
@Test
@ -746,7 +746,7 @@ public class TestResponseCachingPolicy {
response.setHeader("Date", DateUtils.formatStandardDate(now));
response.setHeader("Expires", DateUtils.formatStandardDate(tenSecondsFromNow));
response.setHeader("Via", "1.0 someproxy");
Assert.assertFalse(policy.isResponseCacheable(request, response));
Assertions.assertFalse(policy.isResponseCacheable(request, response));
}
@Test
@ -755,7 +755,7 @@ public class TestResponseCachingPolicy {
response.setHeader("Date", DateUtils.formatStandardDate(now));
response.setHeader("Expires", DateUtils.formatStandardDate(tenSecondsFromNow));
response.setHeader("Via", "HTTP/1.0 someproxy");
Assert.assertTrue(policy.isResponseCacheable(request, response));
Assertions.assertTrue(policy.isResponseCacheable(request, response));
}
@Test
@ -765,7 +765,7 @@ public class TestResponseCachingPolicy {
response.setHeader("Date", DateUtils.formatStandardDate(now));
response.setHeader("Expires", DateUtils.formatStandardDate(tenSecondsFromNow));
response.setHeader("Via", "HTTP/1.0 someproxy");
Assert.assertTrue(policy.isResponseCacheable(request, response));
Assertions.assertTrue(policy.isResponseCacheable(request, response));
}
@Test
@ -775,7 +775,7 @@ public class TestResponseCachingPolicy {
response.setHeader("Date", DateUtils.formatStandardDate(now));
response.setHeader("Expires", DateUtils.formatStandardDate(tenSecondsFromNow));
response.setHeader("Via", "HTTP/1.0 someproxy");
Assert.assertFalse(policy.isResponseCacheable(request, response));
Assertions.assertFalse(policy.isResponseCacheable(request, response));
}
@Test
@ -785,7 +785,7 @@ public class TestResponseCachingPolicy {
response.setHeader("Date", DateUtils.formatStandardDate(now));
response.setHeader("Expires", DateUtils.formatStandardDate(tenSecondsFromNow));
response.setHeader("Via", "HTTP/1.0 someproxy");
Assert.assertFalse(policy.isResponseCacheable(request, response));
Assertions.assertFalse(policy.isResponseCacheable(request, response));
}
@Test
@ -796,7 +796,7 @@ public class TestResponseCachingPolicy {
response.setHeader("Date", DateUtils.formatStandardDate(now));
response.setHeader("Expires", DateUtils.formatStandardDate(tenSecondsFromNow));
response.setHeader("Via", "1.1 someproxy");
Assert.assertTrue(policy.isResponseCacheable(request, response));
Assertions.assertTrue(policy.isResponseCacheable(request, response));
}
@Test
@ -808,7 +808,7 @@ public class TestResponseCachingPolicy {
response.setHeader("Date", DateUtils.formatStandardDate(now));
response.setHeader("Expires", DateUtils.formatStandardDate(tenSecondsFromNow));
response.setHeader("Via", "1.1 someproxy");
Assert.assertTrue(policy.isResponseCacheable(request, response));
Assertions.assertTrue(policy.isResponseCacheable(request, response));
}
@Test
@ -816,7 +816,7 @@ public class TestResponseCachingPolicy {
response.setHeader("Date", DateUtils.formatStandardDate(now));
response.setHeader("Expires", DateUtils.formatStandardDate(now));
response.removeHeaders("Cache-Control");
Assert.assertFalse(policy.isResponseCacheable(request, response));
Assertions.assertFalse(policy.isResponseCacheable(request, response));
}
@Test
@ -824,7 +824,7 @@ public class TestResponseCachingPolicy {
response.setHeader("Date", DateUtils.formatStandardDate(now));
response.setHeader("Expires", DateUtils.formatStandardDate(sixSecondsAgo));
response.removeHeaders("Cache-Control");
Assert.assertFalse(policy.isResponseCacheable(request, response));
Assertions.assertFalse(policy.isResponseCacheable(request, response));
}
@Test
@ -832,7 +832,7 @@ public class TestResponseCachingPolicy {
response.setCode(HttpStatus.SC_MOVED_TEMPORARILY);
response.setHeader("Date", DateUtils.formatStandardDate(now));
response.setHeader("Cache-Control","max-age=300");
Assert.assertTrue(policy.isResponseCacheable(request, response));
Assertions.assertTrue(policy.isResponseCacheable(request, response));
}
@Test
@ -841,7 +841,7 @@ public class TestResponseCachingPolicy {
response.setCode(HttpStatus.SC_SEE_OTHER);
response.setHeader("Date", DateUtils.formatStandardDate(now));
response.setHeader("Cache-Control","max-age=300");
Assert.assertFalse(policy.isResponseCacheable(request, response));
Assertions.assertFalse(policy.isResponseCacheable(request, response));
}
@Test
@ -852,7 +852,7 @@ public class TestResponseCachingPolicy {
response.setCode(HttpStatus.SC_SEE_OTHER);
response.setHeader("Date", DateUtils.formatStandardDate(now));
response.setHeader("Cache-Control","max-age=300");
Assert.assertTrue(policy.isResponseCacheable(request, response));
Assertions.assertTrue(policy.isResponseCacheable(request, response));
}
@Test
@ -860,7 +860,7 @@ public class TestResponseCachingPolicy {
response.setCode(HttpStatus.SC_TEMPORARY_REDIRECT);
response.setHeader("Date", DateUtils.formatStandardDate(now));
response.setHeader("Cache-Control","max-age=300");
Assert.assertTrue(policy.isResponseCacheable(request, response));
Assertions.assertTrue(policy.isResponseCacheable(request, response));
}
@Test
@ -868,7 +868,7 @@ public class TestResponseCachingPolicy {
response.setCode(HttpStatus.SC_NOT_FOUND);
response.setHeader("Date", DateUtils.formatStandardDate(now));
response.setHeader("Cache-Control","max-age=300");
Assert.assertTrue(policy.isResponseCacheable(request, response));
Assertions.assertTrue(policy.isResponseCacheable(request, response));
}
private int getRandomStatus() {

View File

@ -36,15 +36,15 @@ import org.apache.hc.core5.http.HttpResponse;
import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.message.BasicHttpResponse;
import org.apache.hc.core5.http.support.BasicRequestBuilder;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class TestResponseProtocolCompliance {
private ResponseProtocolCompliance impl;
@Before
@BeforeEach
public void setUp() {
impl = new ResponseProtocolCompliance();
}
@ -69,7 +69,7 @@ public class TestResponseProtocolCompliance {
final int nbytes = 128;
final HttpResponse resp = makePartialResponse(nbytes);
Assert.assertThrows(ClientProtocolException.class, () ->
Assertions.assertThrows(ClientProtocolException.class, () ->
impl.ensureProtocolCompliance(wrapper, req, resp));
}

View File

@ -31,8 +31,8 @@ import java.time.Instant;
import org.apache.hc.client5.http.utils.DateUtils;
import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.http.message.BasicHeader;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class TestWarningValue {
@ -40,191 +40,191 @@ public class TestWarningValue {
public void testParseSingleWarnValue() {
final Header h = new BasicHeader("Warning","110 fred \"stale\"");
final WarningValue[] result = WarningValue.getWarningValues(h);
Assert.assertEquals(1, result.length);
Assertions.assertEquals(1, result.length);
final WarningValue wv = result[0];
Assert.assertEquals(110, wv.getWarnCode());
Assert.assertEquals("fred", wv.getWarnAgent());
Assert.assertEquals("\"stale\"", wv.getWarnText());
Assert.assertNull(wv.getWarnDate());
Assertions.assertEquals(110, wv.getWarnCode());
Assertions.assertEquals("fred", wv.getWarnAgent());
Assertions.assertEquals("\"stale\"", wv.getWarnText());
Assertions.assertNull(wv.getWarnDate());
}
@Test
public void testParseMultipleWarnValues() {
final Header h = new BasicHeader("Warning","110 fred \"stale\", 111 wilma \"other\"");
final WarningValue[] result = WarningValue.getWarningValues(h);
Assert.assertEquals(2, result.length);
Assertions.assertEquals(2, result.length);
WarningValue wv = result[0];
Assert.assertEquals(110, wv.getWarnCode());
Assert.assertEquals("fred", wv.getWarnAgent());
Assert.assertEquals("\"stale\"", wv.getWarnText());
Assert.assertNull(wv.getWarnDate());
Assertions.assertEquals(110, wv.getWarnCode());
Assertions.assertEquals("fred", wv.getWarnAgent());
Assertions.assertEquals("\"stale\"", wv.getWarnText());
Assertions.assertNull(wv.getWarnDate());
wv = result[1];
Assert.assertEquals(111, wv.getWarnCode());
Assert.assertEquals("wilma", wv.getWarnAgent());
Assert.assertEquals("\"other\"", wv.getWarnText());
Assert.assertNull(wv.getWarnDate());
Assertions.assertEquals(111, wv.getWarnCode());
Assertions.assertEquals("wilma", wv.getWarnAgent());
Assertions.assertEquals("\"other\"", wv.getWarnText());
Assertions.assertNull(wv.getWarnDate());
}
@Test
public void testMidHeaderParseErrorRecovery() {
final Header h = new BasicHeader("Warning","110 fred \"stale\", bogus, 111 wilma \"other\"");
final WarningValue[] result = WarningValue.getWarningValues(h);
Assert.assertEquals(2, result.length);
Assertions.assertEquals(2, result.length);
WarningValue wv = result[0];
Assert.assertEquals(110, wv.getWarnCode());
Assert.assertEquals("fred", wv.getWarnAgent());
Assert.assertEquals("\"stale\"", wv.getWarnText());
Assert.assertNull(wv.getWarnDate());
Assertions.assertEquals(110, wv.getWarnCode());
Assertions.assertEquals("fred", wv.getWarnAgent());
Assertions.assertEquals("\"stale\"", wv.getWarnText());
Assertions.assertNull(wv.getWarnDate());
wv = result[1];
Assert.assertEquals(111, wv.getWarnCode());
Assert.assertEquals("wilma", wv.getWarnAgent());
Assert.assertEquals("\"other\"", wv.getWarnText());
Assert.assertNull(wv.getWarnDate());
Assertions.assertEquals(111, wv.getWarnCode());
Assertions.assertEquals("wilma", wv.getWarnAgent());
Assertions.assertEquals("\"other\"", wv.getWarnText());
Assertions.assertNull(wv.getWarnDate());
}
@Test
public void testTrickyCommaMidHeaderParseErrorRecovery() {
final Header h = new BasicHeader("Warning","110 fred \"stale\", \"bogus, dude\", 111 wilma \"other\"");
final WarningValue[] result = WarningValue.getWarningValues(h);
Assert.assertEquals(2, result.length);
Assertions.assertEquals(2, result.length);
WarningValue wv = result[0];
Assert.assertEquals(110, wv.getWarnCode());
Assert.assertEquals("fred", wv.getWarnAgent());
Assert.assertEquals("\"stale\"", wv.getWarnText());
Assert.assertNull(wv.getWarnDate());
Assertions.assertEquals(110, wv.getWarnCode());
Assertions.assertEquals("fred", wv.getWarnAgent());
Assertions.assertEquals("\"stale\"", wv.getWarnText());
Assertions.assertNull(wv.getWarnDate());
wv = result[1];
Assert.assertEquals(111, wv.getWarnCode());
Assert.assertEquals("wilma", wv.getWarnAgent());
Assert.assertEquals("\"other\"", wv.getWarnText());
Assert.assertNull(wv.getWarnDate());
Assertions.assertEquals(111, wv.getWarnCode());
Assertions.assertEquals("wilma", wv.getWarnAgent());
Assertions.assertEquals("\"other\"", wv.getWarnText());
Assertions.assertNull(wv.getWarnDate());
}
@Test
public void testParseErrorRecoveryAtEndOfHeader() {
final Header h = new BasicHeader("Warning","110 fred \"stale\", 111 wilma \"other\", \"bogus, dude\"");
final WarningValue[] result = WarningValue.getWarningValues(h);
Assert.assertEquals(2, result.length);
Assertions.assertEquals(2, result.length);
WarningValue wv = result[0];
Assert.assertEquals(110, wv.getWarnCode());
Assert.assertEquals("fred", wv.getWarnAgent());
Assert.assertEquals("\"stale\"", wv.getWarnText());
Assert.assertNull(wv.getWarnDate());
Assertions.assertEquals(110, wv.getWarnCode());
Assertions.assertEquals("fred", wv.getWarnAgent());
Assertions.assertEquals("\"stale\"", wv.getWarnText());
Assertions.assertNull(wv.getWarnDate());
wv = result[1];
Assert.assertEquals(111, wv.getWarnCode());
Assert.assertEquals("wilma", wv.getWarnAgent());
Assert.assertEquals("\"other\"", wv.getWarnText());
Assert.assertNull(wv.getWarnDate());
Assertions.assertEquals(111, wv.getWarnCode());
Assertions.assertEquals("wilma", wv.getWarnAgent());
Assertions.assertEquals("\"other\"", wv.getWarnText());
Assertions.assertNull(wv.getWarnDate());
}
@Test
public void testConstructSingleWarnValue() {
final WarningValue impl = new WarningValue("110 fred \"stale\"");
Assert.assertEquals(110, impl.getWarnCode());
Assert.assertEquals("fred", impl.getWarnAgent());
Assert.assertEquals("\"stale\"", impl.getWarnText());
Assert.assertNull(impl.getWarnDate());
Assertions.assertEquals(110, impl.getWarnCode());
Assertions.assertEquals("fred", impl.getWarnAgent());
Assertions.assertEquals("\"stale\"", impl.getWarnText());
Assertions.assertNull(impl.getWarnDate());
}
@Test
public void testConstructWarnValueWithIPv4Address() {
final WarningValue impl = new WarningValue("110 192.168.1.1 \"stale\"");
Assert.assertEquals(110, impl.getWarnCode());
Assert.assertEquals("192.168.1.1", impl.getWarnAgent());
Assert.assertEquals("\"stale\"", impl.getWarnText());
Assert.assertNull(impl.getWarnDate());
Assertions.assertEquals(110, impl.getWarnCode());
Assertions.assertEquals("192.168.1.1", impl.getWarnAgent());
Assertions.assertEquals("\"stale\"", impl.getWarnText());
Assertions.assertNull(impl.getWarnDate());
}
@Test
public void testConstructWarnValueWithHostname() {
final WarningValue impl = new WarningValue("110 foo.example.com \"stale\"");
Assert.assertEquals(110, impl.getWarnCode());
Assert.assertEquals("foo.example.com", impl.getWarnAgent());
Assert.assertEquals("\"stale\"", impl.getWarnText());
Assert.assertNull(impl.getWarnDate());
Assertions.assertEquals(110, impl.getWarnCode());
Assertions.assertEquals("foo.example.com", impl.getWarnAgent());
Assertions.assertEquals("\"stale\"", impl.getWarnText());
Assertions.assertNull(impl.getWarnDate());
}
@Test
public void testConstructWarnValueWithHostnameAndPort() {
final WarningValue impl = new WarningValue("110 foo.example.com:8080 \"stale\"");
Assert.assertEquals(110, impl.getWarnCode());
Assert.assertEquals("foo.example.com:8080", impl.getWarnAgent());
Assert.assertEquals("\"stale\"", impl.getWarnText());
Assert.assertNull(impl.getWarnDate());
Assertions.assertEquals(110, impl.getWarnCode());
Assertions.assertEquals("foo.example.com:8080", impl.getWarnAgent());
Assertions.assertEquals("\"stale\"", impl.getWarnText());
Assertions.assertNull(impl.getWarnDate());
}
@Test
public void testConstructWarnValueWithIPv4AddressAndPort() {
final WarningValue impl = new WarningValue("110 192.168.1.1:8080 \"stale\"");
Assert.assertEquals(110, impl.getWarnCode());
Assert.assertEquals("192.168.1.1:8080", impl.getWarnAgent());
Assert.assertEquals("\"stale\"", impl.getWarnText());
Assert.assertNull(impl.getWarnDate());
Assertions.assertEquals(110, impl.getWarnCode());
Assertions.assertEquals("192.168.1.1:8080", impl.getWarnAgent());
Assertions.assertEquals("\"stale\"", impl.getWarnText());
Assertions.assertNull(impl.getWarnDate());
}
@Test
public void testConstructWarnValueWithPseudonym() {
final WarningValue impl = new WarningValue("110 ca$hm0ney \"stale\"");
Assert.assertEquals(110, impl.getWarnCode());
Assert.assertEquals("ca$hm0ney", impl.getWarnAgent());
Assert.assertEquals("\"stale\"", impl.getWarnText());
Assert.assertNull(impl.getWarnDate());
Assertions.assertEquals(110, impl.getWarnCode());
Assertions.assertEquals("ca$hm0ney", impl.getWarnAgent());
Assertions.assertEquals("\"stale\"", impl.getWarnText());
Assertions.assertNull(impl.getWarnDate());
}
@Test
public void testConstructWarnValueWithTextWithSpaces() {
final WarningValue impl = new WarningValue("110 fred \"stale stuff\"");
Assert.assertEquals(110, impl.getWarnCode());
Assert.assertEquals("fred", impl.getWarnAgent());
Assert.assertEquals("\"stale stuff\"", impl.getWarnText());
Assert.assertNull(impl.getWarnDate());
Assertions.assertEquals(110, impl.getWarnCode());
Assertions.assertEquals("fred", impl.getWarnAgent());
Assertions.assertEquals("\"stale stuff\"", impl.getWarnText());
Assertions.assertNull(impl.getWarnDate());
}
@Test
public void testConstructWarnValueWithTextWithCommas() {
final WarningValue impl = new WarningValue("110 fred \"stale, stuff\"");
Assert.assertEquals(110, impl.getWarnCode());
Assert.assertEquals("fred", impl.getWarnAgent());
Assert.assertEquals("\"stale, stuff\"", impl.getWarnText());
Assert.assertNull(impl.getWarnDate());
Assertions.assertEquals(110, impl.getWarnCode());
Assertions.assertEquals("fred", impl.getWarnAgent());
Assertions.assertEquals("\"stale, stuff\"", impl.getWarnText());
Assertions.assertNull(impl.getWarnDate());
}
@Test
public void testConstructWarnValueWithTextWithEscapedQuotes() {
final WarningValue impl = new WarningValue("110 fred \"stale\\\" stuff\"");
Assert.assertEquals(110, impl.getWarnCode());
Assert.assertEquals("fred", impl.getWarnAgent());
Assert.assertEquals("\"stale\\\" stuff\"", impl.getWarnText());
Assert.assertNull(impl.getWarnDate());
Assertions.assertEquals(110, impl.getWarnCode());
Assertions.assertEquals("fred", impl.getWarnAgent());
Assertions.assertEquals("\"stale\\\" stuff\"", impl.getWarnText());
Assertions.assertNull(impl.getWarnDate());
}
@Test
public void testConstructWarnValueWithAscTimeWarnDate() throws Exception {
final WarningValue impl = new WarningValue("110 fred \"stale\" \"Sun Nov 6 08:49:37 1994\"");
Assert.assertEquals(110, impl.getWarnCode());
Assert.assertEquals("fred", impl.getWarnAgent());
Assert.assertEquals("\"stale\"", impl.getWarnText());
Assertions.assertEquals(110, impl.getWarnCode());
Assertions.assertEquals("fred", impl.getWarnAgent());
Assertions.assertEquals("\"stale\"", impl.getWarnText());
final Instant target = DateUtils.parseStandardDate("Sun Nov 6 08:49:37 1994");
Assert.assertEquals(target, DateUtils.toInstant(impl.getWarnDate()));
Assertions.assertEquals(target, DateUtils.toInstant(impl.getWarnDate()));
}
@Test
public void testConstructWarnValueWithRFC850WarnDate() throws Exception {
final WarningValue impl = new WarningValue("110 fred \"stale\" \"Sunday, 06-Nov-94 08:49:37 GMT\"");
Assert.assertEquals(110, impl.getWarnCode());
Assert.assertEquals("fred", impl.getWarnAgent());
Assert.assertEquals("\"stale\"", impl.getWarnText());
Assertions.assertEquals(110, impl.getWarnCode());
Assertions.assertEquals("fred", impl.getWarnAgent());
Assertions.assertEquals("\"stale\"", impl.getWarnText());
final Instant target = DateUtils.parseStandardDate("Sunday, 06-Nov-94 08:49:37 GMT");
Assert.assertEquals(target, DateUtils.toInstant(impl.getWarnDate()));
Assertions.assertEquals(target, DateUtils.toInstant(impl.getWarnDate()));
}
@Test
public void testConstructWarnValueWithRFC1123WarnDate() throws Exception {
final WarningValue impl = new WarningValue("110 fred \"stale\" \"Sun, 06 Nov 1994 08:49:37 GMT\"");
Assert.assertEquals(110, impl.getWarnCode());
Assert.assertEquals("fred", impl.getWarnAgent());
Assert.assertEquals("\"stale\"", impl.getWarnText());
Assertions.assertEquals(110, impl.getWarnCode());
Assertions.assertEquals("fred", impl.getWarnAgent());
Assertions.assertEquals("\"stale\"", impl.getWarnText());
final Instant target = DateUtils.parseStandardDate("Sun, 06 Nov 1994 08:49:37 GMT");
Assert.assertEquals(target, DateUtils.toInstant(impl.getWarnDate()));
Assertions.assertEquals(target, DateUtils.toInstant(impl.getWarnDate()));
}
}

View File

@ -26,10 +26,11 @@
*/
package org.apache.hc.client5.http.impl.cache.memcached;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class TestPrefixKeyHashingScheme {
@ -39,7 +40,7 @@ public class TestPrefixKeyHashingScheme {
private PrefixKeyHashingScheme impl;
private KeyHashingScheme scheme;
@Before
@BeforeEach
public void setUp() {
scheme = storageKey -> {
assertEquals(KEY, storageKey);

View File

@ -26,9 +26,10 @@
*/
package org.apache.hc.client5.http.impl.cache.memcached;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
public class TestSHA256HashingScheme {

View File

@ -27,15 +27,15 @@
package org.apache.hc.client5.http.impl.schedule;
import org.apache.hc.core5.util.TimeValue;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class TestExponentialBackingOffSchedulingStrategy {
private ExponentialBackOffSchedulingStrategy impl;
@Before
@BeforeEach
public void setUp() {
impl = new ExponentialBackOffSchedulingStrategy(
ExponentialBackOffSchedulingStrategy.DEFAULT_BACK_OFF_RATE,
@ -46,14 +46,14 @@ public class TestExponentialBackingOffSchedulingStrategy {
@Test
public void testSchedule() {
Assert.assertEquals(TimeValue.ofMilliseconds(0), impl.schedule(0));
Assert.assertEquals(TimeValue.ofMilliseconds(6000), impl.schedule(1));
Assert.assertEquals(TimeValue.ofMilliseconds(60000), impl.schedule(2));
Assert.assertEquals(TimeValue.ofMilliseconds(600000), impl.schedule(3));
Assert.assertEquals(TimeValue.ofMilliseconds(6000000), impl.schedule(4));
Assert.assertEquals(TimeValue.ofMilliseconds(60000000), impl.schedule(5));
Assert.assertEquals(TimeValue.ofMilliseconds(86400000), impl.schedule(6));
Assert.assertEquals(TimeValue.ofMilliseconds(86400000), impl.schedule(Integer.MAX_VALUE));
Assertions.assertEquals(TimeValue.ofMilliseconds(0), impl.schedule(0));
Assertions.assertEquals(TimeValue.ofMilliseconds(6000), impl.schedule(1));
Assertions.assertEquals(TimeValue.ofMilliseconds(60000), impl.schedule(2));
Assertions.assertEquals(TimeValue.ofMilliseconds(600000), impl.schedule(3));
Assertions.assertEquals(TimeValue.ofMilliseconds(6000000), impl.schedule(4));
Assertions.assertEquals(TimeValue.ofMilliseconds(60000000), impl.schedule(5));
Assertions.assertEquals(TimeValue.ofMilliseconds(86400000), impl.schedule(6));
Assertions.assertEquals(TimeValue.ofMilliseconds(86400000), impl.schedule(Integer.MAX_VALUE));
}
}

View File

@ -28,24 +28,24 @@ package org.apache.hc.client5.http.impl.schedule;
import org.apache.hc.client5.http.schedule.SchedulingStrategy;
import org.apache.hc.core5.util.TimeValue;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class TestImmediateSchedulingStrategy {
private SchedulingStrategy impl;
@Before
@BeforeEach
public void setUp() {
impl = new ImmediateSchedulingStrategy();
}
@Test
public void testSchedule() {
Assert.assertEquals(TimeValue.ZERO_MILLISECONDS, impl.schedule(0));
Assert.assertEquals(TimeValue.ZERO_MILLISECONDS, impl.schedule(1));
Assert.assertEquals(TimeValue.ZERO_MILLISECONDS, impl.schedule(Integer.MAX_VALUE));
Assertions.assertEquals(TimeValue.ZERO_MILLISECONDS, impl.schedule(0));
Assertions.assertEquals(TimeValue.ZERO_MILLISECONDS, impl.schedule(1));
Assertions.assertEquals(TimeValue.ZERO_MILLISECONDS, impl.schedule(Integer.MAX_VALUE));
}
}

View File

@ -26,9 +26,10 @@
*/
package org.apache.hc.client5.http.schedule;
import static org.hamcrest.MatcherAssert.assertThat;
import org.hamcrest.CoreMatchers;
import org.hamcrest.MatcherAssert;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class TestConcurrentCountMap
{
@ -41,10 +42,10 @@ public class TestConcurrentCountMap
public void testBasics() {
map.increaseCount(IDENTIFIER);
map.increaseCount(IDENTIFIER);
MatcherAssert.assertThat(map.getCount(IDENTIFIER), CoreMatchers.equalTo(2));
assertThat(map.getCount(IDENTIFIER), CoreMatchers.equalTo(2));
map.resetCount(IDENTIFIER);
MatcherAssert.assertThat(map.getCount(IDENTIFIER), CoreMatchers.equalTo(0));
assertThat(map.getCount(IDENTIFIER), CoreMatchers.equalTo(0));
}
}

View File

@ -66,8 +66,13 @@
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest</artifactId>
<scope>test</scope>
</dependency>
<dependency>

View File

@ -29,58 +29,48 @@ package org.apache.hc.client5.http.fluent;
import java.lang.reflect.Method;
import java.net.URI;
import java.util.Arrays;
import java.util.stream.Stream;
import org.apache.hc.core5.http.ClassicHttpRequest;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
@RunWith(Parameterized.class)
public class TestRequest {
private static final String URI_STRING_FIXTURE = "http://localhost";
private static final URI URI_FIXTURE = URI.create(URI_STRING_FIXTURE);
@Parameterized.Parameters(name = "{index}: {0} => {1}")
public static Iterable<Object[]> data() {
return Arrays.asList(new Object[][]{
// @formatter:off
{"delete", "DELETE"},
{"get", "GET"},
{"head", "HEAD"},
{"options", "OPTIONS"},
{"patch", "PATCH"},
{"post", "POST"},
{"put", "PUT"},
{"trace", "TRACE"}
// @formatter:on
});
public static Stream<Arguments> data() {
return Stream.of(
Arguments.of("delete", "DELETE"),
Arguments.of("get", "GET"),
Arguments.of("head", "HEAD"),
Arguments.of("options", "OPTIONS"),
Arguments.of("patch", "PATCH"),
Arguments.of("post", "POST"),
Arguments.of("put", "PUT"),
Arguments.of("trace", "TRACE")
);
}
private final String methodName;
private final String expectedMethod;
public TestRequest(final String methodName, final String expectedMethod) {
this.methodName = methodName;
this.expectedMethod = expectedMethod;
}
@Test
public void testCreateFromString() throws Exception {
@ParameterizedTest(name = "{index}: {0} => {1}")
@MethodSource("data")
public void testCreateFromString(final String methodName, final String expectedMethod) throws Exception {
final Method method = Request.class.getMethod(methodName, String.class);
final Request request = (Request) method.invoke(null, URI_STRING_FIXTURE);
final ClassicHttpRequest classicHttpRequest = request.getRequest();
Assert.assertEquals(expectedMethod, classicHttpRequest.getMethod());
Assertions.assertEquals(expectedMethod, classicHttpRequest.getMethod());
}
@Test
public void testCreateFromURI() throws Exception {
@ParameterizedTest(name = "{index}: {0} => {1}")
@MethodSource("data")
public void testCreateFromURI(final String methodName, final String expectedMethod) throws Exception {
final Method method = Request.class.getMethod(methodName, URI.class);
final Request request = (Request) method.invoke(null, URI_FIXTURE);
final ClassicHttpRequest classicHttpRequest = request.getRequest();
Assert.assertEquals(expectedMethod, classicHttpRequest.getMethod());
Assertions.assertEquals(expectedMethod, classicHttpRequest.getMethod());
}
}

View File

@ -83,8 +83,13 @@
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-migrationsupport</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest</artifactId>
<scope>test</scope>
</dependency>
<dependency>

View File

@ -26,6 +26,8 @@
*/
package org.apache.hc.client5.testing.async;
import static org.hamcrest.MatcherAssert.assertThat;
import java.util.Arrays;
import java.util.Collections;
import java.util.Queue;
@ -76,9 +78,8 @@ import org.apache.hc.core5.http2.config.H2Config;
import org.apache.hc.core5.http2.impl.H2Processors;
import org.apache.hc.core5.net.URIAuthority;
import org.hamcrest.CoreMatchers;
import org.hamcrest.MatcherAssert;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.mockito.Mockito;
public abstract class AbstractHttpAsyncClientAuthentication<T extends CloseableHttpAsyncClient> extends AbstractIntegrationTestBase<T> {
@ -133,8 +134,8 @@ public abstract class AbstractHttpAsyncClientAuthentication<T extends CloseableH
.build(), context, null);
final HttpResponse response = future.get();
Assert.assertNotNull(response);
Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getCode());
Assertions.assertNotNull(response);
Assertions.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getCode());
Mockito.verify(credsProvider).getCredentials(
Mockito.eq(new AuthScope(target, "test realm", "basic")), Mockito.any());
}
@ -156,8 +157,8 @@ public abstract class AbstractHttpAsyncClientAuthentication<T extends CloseableH
.build(), context, null);
final HttpResponse response = future.get();
Assert.assertNotNull(response);
Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getCode());
Assertions.assertNotNull(response);
Assertions.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getCode());
Mockito.verify(credsProvider).getCredentials(
Mockito.eq(new AuthScope(target, "test realm", "basic")), Mockito.any());
}
@ -180,8 +181,8 @@ public abstract class AbstractHttpAsyncClientAuthentication<T extends CloseableH
.build(), context, null);
final HttpResponse response = future.get();
Assert.assertNotNull(response);
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assertions.assertNotNull(response);
Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
Mockito.verify(credsProvider).getCredentials(
Mockito.eq(new AuthScope(target, "test realm", "basic")), Mockito.any());
}
@ -204,8 +205,8 @@ public abstract class AbstractHttpAsyncClientAuthentication<T extends CloseableH
.build(), context, null);
final HttpResponse response = future.get();
Assert.assertNotNull(response);
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assertions.assertNotNull(response);
Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
Mockito.verify(credsProvider).getCredentials(
Mockito.eq(new AuthScope(target, "test realm", "basic")), Mockito.any());
}
@ -229,8 +230,8 @@ public abstract class AbstractHttpAsyncClientAuthentication<T extends CloseableH
.build(), context, null);
final HttpResponse response = future.get();
Assert.assertNotNull(response);
Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getCode());
Assertions.assertNotNull(response);
Assertions.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getCode());
}
@Test
@ -252,8 +253,8 @@ public abstract class AbstractHttpAsyncClientAuthentication<T extends CloseableH
.build(), context, null);
final HttpResponse response = future.get();
Assert.assertNotNull(response);
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assertions.assertNotNull(response);
Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
Mockito.verify(credsProvider).getCredentials(
Mockito.eq(new AuthScope(target, "test realm", "basic")), Mockito.any());
}
@ -277,8 +278,8 @@ public abstract class AbstractHttpAsyncClientAuthentication<T extends CloseableH
.setPath("/")
.build(), context, null);
final HttpResponse response = future.get();
Assert.assertNotNull(response);
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assertions.assertNotNull(response);
Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
}
Mockito.verify(authStrategy).select(Mockito.any(), Mockito.any(), Mockito.any());
@ -311,14 +312,14 @@ public abstract class AbstractHttpAsyncClientAuthentication<T extends CloseableH
.setPath(requestPath)
.build(), context, null);
final HttpResponse response = future.get();
Assert.assertNotNull(response);
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assertions.assertNotNull(response);
Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
}
// There should be only single auth strategy call for all successful message exchanges
Mockito.verify(authStrategy).select(Mockito.any(), Mockito.any(), Mockito.any());
MatcherAssert.assertThat(
assertThat(
responseQueue.stream().map(HttpResponse::getCode).collect(Collectors.toList()),
CoreMatchers.equalTo(Arrays.asList(401, 200, 200, 200, 200)));
@ -335,14 +336,14 @@ public abstract class AbstractHttpAsyncClientAuthentication<T extends CloseableH
.setPath(requestPath)
.build(), context, null);
final HttpResponse response = future.get();
Assert.assertNotNull(response);
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assertions.assertNotNull(response);
Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
}
// There should be an auth strategy call for all successful message exchanges
Mockito.verify(authStrategy, Mockito.times(3)).select(Mockito.any(), Mockito.any(), Mockito.any());
MatcherAssert.assertThat(
assertThat(
responseQueue.stream().map(HttpResponse::getCode).collect(Collectors.toList()),
CoreMatchers.equalTo(Arrays.asList(401, 200, 401, 200, 401, 200)));
}
@ -358,8 +359,8 @@ public abstract class AbstractHttpAsyncClientAuthentication<T extends CloseableH
.setAuthority(new URIAuthority("test:test", target.getHostName(), target.getPort()))
.setPath("/")
.build(), context, null);
final ExecutionException exception = Assert.assertThrows(ExecutionException.class, () -> future.get());
MatcherAssert.assertThat(exception.getCause(), CoreMatchers.instanceOf(ProtocolException.class));
final ExecutionException exception = Assertions.assertThrows(ExecutionException.class, () -> future.get());
assertThat(exception.getCause(), CoreMatchers.instanceOf(ProtocolException.class));
}
@Test
@ -422,8 +423,8 @@ public abstract class AbstractHttpAsyncClientAuthentication<T extends CloseableH
request.setConfig(config);
final Future<SimpleHttpResponse> future = httpclient.execute(request, context, null);
final SimpleHttpResponse response = future.get();
Assert.assertNotNull(response);
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assertions.assertNotNull(response);
Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
}
}
@ -451,8 +452,8 @@ public abstract class AbstractHttpAsyncClientAuthentication<T extends CloseableH
.setPath("/")
.build(), context, null);
final SimpleHttpResponse response = future.get();
Assert.assertNotNull(response);
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assertions.assertNotNull(response);
Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
Mockito.verify(credsProvider).getCredentials(
Mockito.eq(new AuthScope(target, "test realm", "basic")), Mockito.any());
}

View File

@ -26,6 +26,8 @@
*/
package org.apache.hc.client5.testing.async;
import static org.hamcrest.MatcherAssert.assertThat;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
@ -52,7 +54,6 @@ import org.apache.hc.core5.http.nio.entity.BasicAsyncEntityConsumer;
import org.apache.hc.core5.http.nio.support.BasicRequestProducer;
import org.apache.hc.core5.http.nio.support.BasicResponseConsumer;
import org.hamcrest.CoreMatchers;
import org.hamcrest.MatcherAssert;
import org.junit.Test;
public abstract class AbstractHttpAsyncFundamentalsTest<T extends CloseableHttpAsyncClient> extends AbstractIntegrationTestBase<T> {
@ -71,11 +72,11 @@ public abstract class AbstractHttpAsyncFundamentalsTest<T extends CloseableHttpA
.setPath("/random/2048")
.build(), null);
final SimpleHttpResponse response = future.get();
MatcherAssert.assertThat(response, CoreMatchers.notNullValue());
MatcherAssert.assertThat(response.getCode(), CoreMatchers.equalTo(200));
assertThat(response, CoreMatchers.notNullValue());
assertThat(response.getCode(), CoreMatchers.equalTo(200));
final String body = response.getBodyText();
MatcherAssert.assertThat(body, CoreMatchers.notNullValue());
MatcherAssert.assertThat(body.length(), CoreMatchers.equalTo(2048));
assertThat(body, CoreMatchers.notNullValue());
assertThat(body.length(), CoreMatchers.equalTo(2048));
}
}
@ -89,10 +90,10 @@ public abstract class AbstractHttpAsyncFundamentalsTest<T extends CloseableHttpA
.setPath("/random/2048")
.build(), null);
final SimpleHttpResponse response = future.get();
MatcherAssert.assertThat(response, CoreMatchers.notNullValue());
MatcherAssert.assertThat(response.getCode(), CoreMatchers.equalTo(200));
assertThat(response, CoreMatchers.notNullValue());
assertThat(response.getCode(), CoreMatchers.equalTo(200));
final String body = response.getBodyText();
MatcherAssert.assertThat(body, CoreMatchers.nullValue());
assertThat(body, CoreMatchers.nullValue());
}
}
@ -108,11 +109,11 @@ public abstract class AbstractHttpAsyncFundamentalsTest<T extends CloseableHttpA
AsyncEntityProducers.create(b1, ContentType.APPLICATION_OCTET_STREAM)),
new BasicResponseConsumer<>(new BasicAsyncEntityConsumer()), HttpClientContext.create(), null);
final Message<HttpResponse, byte[]> responseMessage = future.get();
MatcherAssert.assertThat(responseMessage, CoreMatchers.notNullValue());
assertThat(responseMessage, CoreMatchers.notNullValue());
final HttpResponse response = responseMessage.getHead();
MatcherAssert.assertThat(response.getCode(), CoreMatchers.equalTo(200));
assertThat(response.getCode(), CoreMatchers.equalTo(200));
final byte[] b2 = responseMessage.getBody();
MatcherAssert.assertThat(b1, CoreMatchers.equalTo(b2));
assertThat(b1, CoreMatchers.equalTo(b2));
}
}
@ -137,11 +138,11 @@ public abstract class AbstractHttpAsyncFundamentalsTest<T extends CloseableHttpA
while (!queue.isEmpty()) {
final Future<Message<HttpResponse, byte[]>> future = queue.remove();
final Message<HttpResponse, byte[]> responseMessage = future.get();
MatcherAssert.assertThat(responseMessage, CoreMatchers.notNullValue());
assertThat(responseMessage, CoreMatchers.notNullValue());
final HttpResponse response = responseMessage.getHead();
MatcherAssert.assertThat(response.getCode(), CoreMatchers.equalTo(200));
assertThat(response.getCode(), CoreMatchers.equalTo(200));
final byte[] b2 = responseMessage.getBody();
MatcherAssert.assertThat(b1, CoreMatchers.equalTo(b2));
assertThat(b1, CoreMatchers.equalTo(b2));
}
}
@ -196,7 +197,7 @@ public abstract class AbstractHttpAsyncFundamentalsTest<T extends CloseableHttpA
});
}
MatcherAssert.assertThat(countDownLatch.await(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit()), CoreMatchers.equalTo(true));
assertThat(countDownLatch.await(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit()), CoreMatchers.equalTo(true));
executorService.shutdownNow();
executorService.awaitTermination(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
@ -206,7 +207,7 @@ public abstract class AbstractHttpAsyncFundamentalsTest<T extends CloseableHttpA
if (response == null) {
break;
}
MatcherAssert.assertThat(response.getCode(), CoreMatchers.equalTo(200));
assertThat(response.getCode(), CoreMatchers.equalTo(200));
}
}
@ -219,8 +220,8 @@ public abstract class AbstractHttpAsyncFundamentalsTest<T extends CloseableHttpA
.setPath("/random/boom")
.build(), null);
final SimpleHttpResponse response = future.get();
MatcherAssert.assertThat(response, CoreMatchers.notNullValue());
MatcherAssert.assertThat(response.getCode(), CoreMatchers.equalTo(400));
assertThat(response, CoreMatchers.notNullValue());
assertThat(response.getCode(), CoreMatchers.equalTo(400));
}
}

View File

@ -26,6 +26,8 @@
*/
package org.apache.hc.client5.testing.async;
import static org.hamcrest.MatcherAssert.assertThat;
import java.net.InetSocketAddress;
import java.net.URI;
import java.util.concurrent.ExecutionException;
@ -67,9 +69,8 @@ import org.apache.hc.core5.testing.nio.H2TestServer;
import org.apache.hc.core5.testing.reactive.ReactiveRandomProcessor;
import org.apache.hc.core5.util.TimeValue;
import org.hamcrest.CoreMatchers;
import org.hamcrest.MatcherAssert;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
public abstract class AbstractHttpAsyncRedirectsTest <T extends CloseableHttpAsyncClient> extends AbstractIntegrationTestBase<T> {
@ -110,12 +111,12 @@ public abstract class AbstractHttpAsyncRedirectsTest <T extends CloseableHttpAsy
.setPath("/oldlocation/")
.build(), context, null);
final HttpResponse response = future.get();
Assert.assertNotNull(response);
Assertions.assertNotNull(response);
final HttpRequest request = context.getRequest();
Assert.assertEquals(HttpStatus.SC_MULTIPLE_CHOICES, response.getCode());
Assert.assertEquals("/oldlocation/", request.getRequestUri());
Assertions.assertEquals(HttpStatus.SC_MULTIPLE_CHOICES, response.getCode());
Assertions.assertEquals("/oldlocation/", request.getRequestUri());
}
@Test
@ -130,13 +131,13 @@ public abstract class AbstractHttpAsyncRedirectsTest <T extends CloseableHttpAsy
.setPath("/oldlocation/100")
.build(), context, null);
final HttpResponse response = future.get();
Assert.assertNotNull(response);
Assertions.assertNotNull(response);
final HttpRequest request = context.getRequest();
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assert.assertEquals("/random/100", request.getRequestUri());
Assert.assertEquals(target, new HttpHost(request.getScheme(), request.getAuthority()));
Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
Assertions.assertEquals("/random/100", request.getRequestUri());
Assertions.assertEquals(target, new HttpHost(request.getScheme(), request.getAuthority()));
}
@Test
@ -151,13 +152,13 @@ public abstract class AbstractHttpAsyncRedirectsTest <T extends CloseableHttpAsy
.setPath("/oldlocation/123")
.build(), context, null);
final HttpResponse response = future.get();
Assert.assertNotNull(response);
Assertions.assertNotNull(response);
final HttpRequest request = context.getRequest();
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assert.assertEquals("/random/123", request.getRequestUri());
Assert.assertEquals(target, new HttpHost(request.getScheme(), request.getAuthority()));
Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
Assertions.assertEquals("/random/123", request.getRequestUri());
Assertions.assertEquals(target, new HttpHost(request.getScheme(), request.getAuthority()));
}
@Test
@ -178,12 +179,12 @@ public abstract class AbstractHttpAsyncRedirectsTest <T extends CloseableHttpAsy
.setPath("/oldlocation/100")
.build(), context, null);
final HttpResponse response = future.get();
Assert.assertNotNull(response);
Assertions.assertNotNull(response);
final HttpRequest request = context.getRequest();
Assert.assertEquals(HttpStatus.SC_MOVED_TEMPORARILY, response.getCode());
Assert.assertEquals("/oldlocation/100", request.getRequestUri());
Assert.assertEquals(target, new HttpHost(request.getScheme(), request.getAuthority()));
Assertions.assertEquals(HttpStatus.SC_MOVED_TEMPORARILY, response.getCode());
Assertions.assertEquals("/oldlocation/100", request.getRequestUri());
Assertions.assertEquals(target, new HttpHost(request.getScheme(), request.getAuthority()));
}
@Test
@ -198,13 +199,13 @@ public abstract class AbstractHttpAsyncRedirectsTest <T extends CloseableHttpAsy
.setPath("/oldlocation/123")
.build(), context, null);
final HttpResponse response = future.get();
Assert.assertNotNull(response);
Assertions.assertNotNull(response);
final HttpRequest request = context.getRequest();
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assert.assertEquals("/random/123", request.getRequestUri());
Assert.assertEquals(target, new HttpHost(request.getScheme(), request.getAuthority()));
Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
Assertions.assertEquals("/random/123", request.getRequestUri());
Assertions.assertEquals(target, new HttpHost(request.getScheme(), request.getAuthority()));
}
@Test
@ -225,12 +226,12 @@ public abstract class AbstractHttpAsyncRedirectsTest <T extends CloseableHttpAsy
.setPath("/oldlocation/")
.build(), context, null);
final HttpResponse response = future.get();
Assert.assertNotNull(response);
Assertions.assertNotNull(response);
final HttpRequest request = context.getRequest();
Assert.assertEquals(HttpStatus.SC_NOT_MODIFIED, response.getCode());
Assert.assertEquals("/oldlocation/", request.getRequestUri());
Assertions.assertEquals(HttpStatus.SC_NOT_MODIFIED, response.getCode());
Assertions.assertEquals("/oldlocation/", request.getRequestUri());
}
@Test
@ -251,12 +252,12 @@ public abstract class AbstractHttpAsyncRedirectsTest <T extends CloseableHttpAsy
.setPath("/oldlocation/")
.build(), context, null);
final HttpResponse response = future.get();
Assert.assertNotNull(response);
Assertions.assertNotNull(response);
final HttpRequest request = context.getRequest();
Assert.assertEquals(HttpStatus.SC_USE_PROXY, response.getCode());
Assert.assertEquals("/oldlocation/", request.getRequestUri());
Assertions.assertEquals(HttpStatus.SC_USE_PROXY, response.getCode());
Assertions.assertEquals("/oldlocation/", request.getRequestUri());
}
@Test
@ -271,13 +272,13 @@ public abstract class AbstractHttpAsyncRedirectsTest <T extends CloseableHttpAsy
.setPath("/oldlocation/123")
.build(), context, null);
final HttpResponse response = future.get();
Assert.assertNotNull(response);
Assertions.assertNotNull(response);
final HttpRequest request = context.getRequest();
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assert.assertEquals("/random/123", request.getRequestUri());
Assert.assertEquals(target, new HttpHost(request.getScheme(), request.getAuthority()));
Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
Assertions.assertEquals("/random/123", request.getRequestUri());
Assertions.assertEquals(target, new HttpHost(request.getScheme(), request.getAuthority()));
}
@Test
@ -290,7 +291,7 @@ public abstract class AbstractHttpAsyncRedirectsTest <T extends CloseableHttpAsy
final RequestConfig config = RequestConfig.custom()
.setCircularRedirectsAllowed(true)
.setMaxRedirects(5).build();
final ExecutionException exception = Assert.assertThrows(ExecutionException.class, () -> {
final ExecutionException exception = Assertions.assertThrows(ExecutionException.class, () -> {
final Future<SimpleHttpResponse> future = httpclient.execute(SimpleRequestBuilder.get()
.setHttpHost(target)
.setPath("/circular-oldlocation/")
@ -298,7 +299,7 @@ public abstract class AbstractHttpAsyncRedirectsTest <T extends CloseableHttpAsy
.build(), null);
future.get();
});
MatcherAssert.assertThat(exception.getCause(), CoreMatchers.instanceOf(RedirectException.class));
assertThat(exception.getCause(), CoreMatchers.instanceOf(RedirectException.class));
}
@Test
@ -311,7 +312,7 @@ public abstract class AbstractHttpAsyncRedirectsTest <T extends CloseableHttpAsy
final RequestConfig config = RequestConfig.custom()
.setCircularRedirectsAllowed(false)
.build();
final ExecutionException exception = Assert.assertThrows(ExecutionException.class, () -> {
final ExecutionException exception = Assertions.assertThrows(ExecutionException.class, () -> {
final Future<SimpleHttpResponse> future = httpclient.execute(
SimpleRequestBuilder.get()
.setHttpHost(target)
@ -320,7 +321,7 @@ public abstract class AbstractHttpAsyncRedirectsTest <T extends CloseableHttpAsy
.build(), null);
future.get();
});
MatcherAssert.assertThat(exception.getCause(), CoreMatchers.instanceOf(CircularRedirectException.class));
assertThat(exception.getCause(), CoreMatchers.instanceOf(CircularRedirectException.class));
}
@Test
@ -337,13 +338,13 @@ public abstract class AbstractHttpAsyncRedirectsTest <T extends CloseableHttpAsy
.setBody("stuff", ContentType.TEXT_PLAIN)
.build(), context, null);
final HttpResponse response = future.get();
Assert.assertNotNull(response);
Assertions.assertNotNull(response);
final HttpRequest request = context.getRequest();
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assert.assertEquals("/echo/stuff", request.getRequestUri());
Assert.assertEquals("POST", request.getMethod());
Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
Assertions.assertEquals("/echo/stuff", request.getRequestUri());
Assertions.assertEquals("POST", request.getMethod());
}
@Test
@ -360,13 +361,13 @@ public abstract class AbstractHttpAsyncRedirectsTest <T extends CloseableHttpAsy
.setBody("stuff", ContentType.TEXT_PLAIN)
.build(), context, null);
final HttpResponse response = future.get();
Assert.assertNotNull(response);
Assertions.assertNotNull(response);
final HttpRequest request = context.getRequest();
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assert.assertEquals("/echo/stuff", request.getRequestUri());
Assert.assertEquals("GET", request.getMethod());
Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
Assertions.assertEquals("/echo/stuff", request.getRequestUri());
Assertions.assertEquals("GET", request.getMethod());
}
@Test
@ -390,13 +391,13 @@ public abstract class AbstractHttpAsyncRedirectsTest <T extends CloseableHttpAsy
.setPath("/oldlocation/stuff")
.build(), context, null);
final HttpResponse response = future.get();
Assert.assertNotNull(response);
Assertions.assertNotNull(response);
final HttpRequest request = context.getRequest();
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assert.assertEquals("/random/100", request.getRequestUri());
Assert.assertEquals(target, new HttpHost(request.getScheme(), request.getAuthority()));
Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
Assertions.assertEquals("/random/100", request.getRequestUri());
Assertions.assertEquals(target, new HttpHost(request.getScheme(), request.getAuthority()));
}
@Test
@ -420,13 +421,13 @@ public abstract class AbstractHttpAsyncRedirectsTest <T extends CloseableHttpAsy
.setPath("/random/oldlocation")
.build(), context, null);
final HttpResponse response = future.get();
Assert.assertNotNull(response);
Assertions.assertNotNull(response);
final HttpRequest request = context.getRequest();
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assert.assertEquals("/random/100", request.getRequestUri());
Assert.assertEquals(target, new HttpHost(request.getScheme(), request.getAuthority()));
Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
Assertions.assertEquals("/random/100", request.getRequestUri());
Assertions.assertEquals(target, new HttpHost(request.getScheme(), request.getAuthority()));
}
@Test
@ -442,7 +443,7 @@ public abstract class AbstractHttpAsyncRedirectsTest <T extends CloseableHttpAsy
return null;
}));
final ExecutionException exception = Assert.assertThrows(ExecutionException.class, () -> {
final ExecutionException exception = Assertions.assertThrows(ExecutionException.class, () -> {
final Future<SimpleHttpResponse> future = httpclient.execute(
SimpleRequestBuilder.get()
.setHttpHost(target)
@ -450,7 +451,7 @@ public abstract class AbstractHttpAsyncRedirectsTest <T extends CloseableHttpAsy
.build(), null);
future.get();
});
MatcherAssert.assertThat(exception.getCause(), CoreMatchers.instanceOf(HttpException.class));
assertThat(exception.getCause(), CoreMatchers.instanceOf(HttpException.class));
}
@Test
@ -466,7 +467,7 @@ public abstract class AbstractHttpAsyncRedirectsTest <T extends CloseableHttpAsy
return null;
}));
final ExecutionException exception = Assert.assertThrows(ExecutionException.class, () -> {
final ExecutionException exception = Assertions.assertThrows(ExecutionException.class, () -> {
final Future<SimpleHttpResponse> future = httpclient.execute(
SimpleRequestBuilder.get()
.setHttpHost(target)
@ -474,7 +475,7 @@ public abstract class AbstractHttpAsyncRedirectsTest <T extends CloseableHttpAsy
.build(), null);
future.get();
});
MatcherAssert.assertThat(exception.getCause(), CoreMatchers.instanceOf(ProtocolException.class));
assertThat(exception.getCause(), CoreMatchers.instanceOf(ProtocolException.class));
}
@Test
@ -499,15 +500,15 @@ public abstract class AbstractHttpAsyncRedirectsTest <T extends CloseableHttpAsy
.setPath("/oldlocation/100")
.build(), context, null);
final HttpResponse response = future.get();
Assert.assertNotNull(response);
Assertions.assertNotNull(response);
final HttpRequest request = context.getRequest();
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assert.assertEquals("/random/100", request.getRequestUri());
Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
Assertions.assertEquals("/random/100", request.getRequestUri());
final Header[] headers = request.getHeaders("Cookie");
Assert.assertEquals("There can only be one (cookie)", 1, headers.length);
Assertions.assertEquals(1, headers.length, "There can only be one (cookie)");
}
@Test
@ -551,13 +552,13 @@ public abstract class AbstractHttpAsyncRedirectsTest <T extends CloseableHttpAsy
.setPath("/oldlocation")
.build(), context, null);
final HttpResponse response = future.get();
Assert.assertNotNull(response);
Assertions.assertNotNull(response);
final HttpRequest request = context.getRequest();
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assert.assertEquals("/random/100", request.getRequestUri());
Assert.assertEquals(redirectTarget, new HttpHost(request.getScheme(), request.getAuthority()));
Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
Assertions.assertEquals("/random/100", request.getRequestUri());
Assertions.assertEquals(redirectTarget, new HttpHost(request.getScheme(), request.getAuthority()));
} finally {
server.shutdown(TimeValue.ofSeconds(5));
}

View File

@ -26,6 +26,9 @@
*/
package org.apache.hc.client5.testing.async;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.hamcrest.MatcherAssert.assertThat;
import java.io.ByteArrayOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
@ -62,9 +65,9 @@ import org.apache.hc.core5.testing.reactive.ReactiveTestUtils;
import org.apache.hc.core5.testing.reactive.ReactiveTestUtils.StreamDescription;
import org.apache.hc.core5.util.TextUtils;
import org.hamcrest.CoreMatchers;
import org.hamcrest.MatcherAssert;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Timeout;
import org.reactivestreams.Publisher;
import io.reactivex.Flowable;
@ -81,7 +84,8 @@ public abstract class AbstractHttpReactiveFundamentalsTest<T extends CloseableHt
return true;
}
@Test(timeout = 60_000)
@Test
@Timeout(value = 60_000, unit = MILLISECONDS)
public void testSequentialGetRequests() throws Exception {
final HttpHost target = start();
for (int i = 0; i < 3; i++) {
@ -90,16 +94,17 @@ public abstract class AbstractHttpReactiveFundamentalsTest<T extends CloseableHt
httpclient.execute(AsyncRequestBuilder.get(target + "/random/2048").build(), consumer, null);
final Message<HttpResponse, Publisher<ByteBuffer>> response = consumer.getResponseFuture().get();
MatcherAssert.assertThat(response, CoreMatchers.notNullValue());
MatcherAssert.assertThat(response.getHead().getCode(), CoreMatchers.equalTo(200));
assertThat(response, CoreMatchers.notNullValue());
assertThat(response.getHead().getCode(), CoreMatchers.equalTo(200));
final String body = publisherToString(response.getBody());
MatcherAssert.assertThat(body, CoreMatchers.notNullValue());
MatcherAssert.assertThat(body.length(), CoreMatchers.equalTo(2048));
assertThat(body, CoreMatchers.notNullValue());
assertThat(body.length(), CoreMatchers.equalTo(2048));
}
}
@Test(timeout = 2000)
@Test
@Timeout(value = 2000, unit = MILLISECONDS)
public void testSequentialHeadRequests() throws Exception {
final HttpHost target = start();
for (int i = 0; i < 3; i++) {
@ -108,15 +113,16 @@ public abstract class AbstractHttpReactiveFundamentalsTest<T extends CloseableHt
httpclient.execute(AsyncRequestBuilder.head(target + "/random/2048").build(), consumer, null);
final Message<HttpResponse, Publisher<ByteBuffer>> response = consumer.getResponseFuture().get();
MatcherAssert.assertThat(response, CoreMatchers.notNullValue());
MatcherAssert.assertThat(response.getHead().getCode(), CoreMatchers.equalTo(200));
assertThat(response, CoreMatchers.notNullValue());
assertThat(response.getHead().getCode(), CoreMatchers.equalTo(200));
final String body = publisherToString(response.getBody());
MatcherAssert.assertThat(body, CoreMatchers.nullValue());
assertThat(body, CoreMatchers.nullValue());
}
}
@Test(timeout = 60_000)
@Test
@Timeout(value = 60_000, unit = MILLISECONDS)
public void testSequentialPostRequests() throws Exception {
final HttpHost target = start();
for (int i = 0; i < 3; i++) {
@ -133,15 +139,16 @@ public abstract class AbstractHttpReactiveFundamentalsTest<T extends CloseableHt
final Future<Message<HttpResponse, Publisher<ByteBuffer>>> responseFuture = consumer.getResponseFuture();
final Message<HttpResponse, Publisher<ByteBuffer>> responseMessage = responseFuture.get();
MatcherAssert.assertThat(responseMessage, CoreMatchers.notNullValue());
assertThat(responseMessage, CoreMatchers.notNullValue());
final HttpResponse response = responseMessage.getHead();
MatcherAssert.assertThat(response.getCode(), CoreMatchers.equalTo(200));
assertThat(response.getCode(), CoreMatchers.equalTo(200));
final byte[] b2 = publisherToByteArray(responseMessage.getBody());
MatcherAssert.assertThat(b1, CoreMatchers.equalTo(b2));
assertThat(b1, CoreMatchers.equalTo(b2));
}
}
@Test(timeout = 60_000)
@Test
@Timeout(value = 60_000, unit = MILLISECONDS)
public void testConcurrentPostRequests() throws Exception {
final HttpHost target = start();
@ -178,15 +185,16 @@ public abstract class AbstractHttpReactiveFundamentalsTest<T extends CloseableHt
final StreamingTestCase streamingTestCase = testCases.get(streamDescription.length);
final long expectedLength = streamingTestCase.length;
final long actualLength = streamDescription.length;
Assert.assertEquals(expectedLength, actualLength);
Assertions.assertEquals(expectedLength, actualLength);
final String expectedHash = streamingTestCase.expectedHash.get();
final String actualHash = TextUtils.toHexString(streamDescription.md.digest());
Assert.assertEquals(expectedHash, actualHash);
Assertions.assertEquals(expectedHash, actualHash);
}
}
@Test(timeout = 60_000)
@Test
@Timeout(value = 60_000, unit = MILLISECONDS)
public void testRequestExecutionFromCallback() throws Exception {
final HttpHost target = start();
final int requestNum = 50;
@ -230,7 +238,7 @@ public abstract class AbstractHttpReactiveFundamentalsTest<T extends CloseableHt
});
}
MatcherAssert.assertThat(countDownLatch.await(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit()), CoreMatchers.equalTo(true));
assertThat(countDownLatch.await(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit()), CoreMatchers.equalTo(true));
executorService.shutdownNow();
executorService.awaitTermination(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
@ -240,7 +248,7 @@ public abstract class AbstractHttpReactiveFundamentalsTest<T extends CloseableHt
if (response == null) {
break;
}
MatcherAssert.assertThat(response.getHead().getCode(), CoreMatchers.equalTo(200));
assertThat(response.getHead().getCode(), CoreMatchers.equalTo(200));
}
}
@ -254,8 +262,8 @@ public abstract class AbstractHttpReactiveFundamentalsTest<T extends CloseableHt
final Future<Message<HttpResponse, Publisher<ByteBuffer>>> future = consumer.getResponseFuture();
final HttpResponse response = future.get().getHead();
MatcherAssert.assertThat(response, CoreMatchers.notNullValue());
MatcherAssert.assertThat(response.getCode(), CoreMatchers.equalTo(400));
assertThat(response, CoreMatchers.notNullValue());
assertThat(response.getCode(), CoreMatchers.equalTo(400));
}
static String publisherToString(final Publisher<ByteBuffer> publisher) throws Exception {

View File

@ -39,10 +39,12 @@ import org.apache.hc.core5.http.URIScheme;
import org.apache.hc.core5.http.nio.ssl.BasicClientTlsStrategy;
import org.apache.hc.core5.http2.config.H2Config;
import org.junit.Rule;
import org.junit.jupiter.migrationsupport.rules.EnableRuleMigrationSupport;
import org.junit.rules.ExternalResource;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@EnableRuleMigrationSupport
@RunWith(Parameterized.class)
public class TestH2Async extends AbstractHttpAsyncFundamentalsTest<CloseableHttpAsyncClient> {

View File

@ -37,9 +37,11 @@ import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.http.URIScheme;
import org.apache.hc.core5.http2.config.H2Config;
import org.apache.hc.core5.reactor.IOReactorConfig;
import org.junit.jupiter.migrationsupport.rules.EnableRuleMigrationSupport;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@EnableRuleMigrationSupport
@RunWith(Parameterized.class)
public class TestH2AsyncMinimal extends AbstractHttpAsyncFundamentalsTest<MinimalH2AsyncClient> {

View File

@ -38,10 +38,12 @@ import org.apache.hc.client5.testing.SSLTestContexts;
import org.apache.hc.core5.http.HttpVersion;
import org.apache.hc.core5.http.URIScheme;
import org.junit.Rule;
import org.junit.jupiter.migrationsupport.rules.EnableRuleMigrationSupport;
import org.junit.rules.ExternalResource;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@EnableRuleMigrationSupport
@RunWith(Parameterized.class)
public class TestH2AsyncRedirect extends AbstractHttpAsyncRedirectsTest<CloseableHttpAsyncClient> {

View File

@ -44,10 +44,12 @@ import org.apache.hc.core5.http.HttpVersion;
import org.apache.hc.core5.http.URIScheme;
import org.apache.hc.core5.http.config.Lookup;
import org.junit.Rule;
import org.junit.jupiter.migrationsupport.rules.EnableRuleMigrationSupport;
import org.junit.rules.ExternalResource;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@EnableRuleMigrationSupport
@RunWith(Parameterized.class)
public class TestH2ClientAuthentication extends AbstractHttpAsyncClientAuthentication<CloseableHttpAsyncClient> {

View File

@ -26,6 +26,8 @@
*/
package org.apache.hc.client5.testing.async;
import static org.hamcrest.MatcherAssert.assertThat;
import java.util.Arrays;
import java.util.Collection;
import java.util.Random;
@ -52,13 +54,14 @@ import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.http.URIScheme;
import org.apache.hc.core5.http.config.Http1Config;
import org.hamcrest.CoreMatchers;
import org.hamcrest.MatcherAssert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.jupiter.migrationsupport.rules.EnableRuleMigrationSupport;
import org.junit.rules.ExternalResource;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@EnableRuleMigrationSupport
@RunWith(Parameterized.class)
public class TestHttp1Async extends AbstractHttpAsyncFundamentalsTest<CloseableHttpAsyncClient> {
@ -136,11 +139,11 @@ public class TestHttp1Async extends AbstractHttpAsyncFundamentalsTest<CloseableH
.addHeader(HttpHeaders.CONNECTION, HeaderElements.CLOSE)
.build(), null);
final SimpleHttpResponse response = future.get();
MatcherAssert.assertThat(response, CoreMatchers.notNullValue());
MatcherAssert.assertThat(response.getCode(), CoreMatchers.equalTo(200));
assertThat(response, CoreMatchers.notNullValue());
assertThat(response.getCode(), CoreMatchers.equalTo(200));
final String body = response.getBodyText();
MatcherAssert.assertThat(body, CoreMatchers.notNullValue());
MatcherAssert.assertThat(body.length(), CoreMatchers.equalTo(2048));
assertThat(body, CoreMatchers.notNullValue());
assertThat(body.length(), CoreMatchers.equalTo(2048));
}
}
@ -167,11 +170,11 @@ public class TestHttp1Async extends AbstractHttpAsyncFundamentalsTest<CloseableH
.setPath("/random/2048")
.build(), null);
final SimpleHttpResponse response1 = future1.get();
MatcherAssert.assertThat(response1, CoreMatchers.notNullValue());
MatcherAssert.assertThat(response1.getCode(), CoreMatchers.equalTo(200));
assertThat(response1, CoreMatchers.notNullValue());
assertThat(response1.getCode(), CoreMatchers.equalTo(200));
final String body1 = response1.getBodyText();
MatcherAssert.assertThat(body1, CoreMatchers.notNullValue());
MatcherAssert.assertThat(body1.length(), CoreMatchers.equalTo(2048));
assertThat(body1, CoreMatchers.notNullValue());
assertThat(body1.length(), CoreMatchers.equalTo(2048));
try (final CloseableHttpAsyncClient httpclient2 = HttpAsyncClients.custom()
@ -185,11 +188,11 @@ public class TestHttp1Async extends AbstractHttpAsyncFundamentalsTest<CloseableH
.setPath("/random/2048")
.build(), null);
final SimpleHttpResponse response2 = future2.get();
MatcherAssert.assertThat(response2, CoreMatchers.notNullValue());
MatcherAssert.assertThat(response2.getCode(), CoreMatchers.equalTo(200));
assertThat(response2, CoreMatchers.notNullValue());
assertThat(response2.getCode(), CoreMatchers.equalTo(200));
final String body2 = response2.getBodyText();
MatcherAssert.assertThat(body2, CoreMatchers.notNullValue());
MatcherAssert.assertThat(body2.length(), CoreMatchers.equalTo(2048));
assertThat(body2, CoreMatchers.notNullValue());
assertThat(body2.length(), CoreMatchers.equalTo(2048));
}
final Future<SimpleHttpResponse> future3 = httpclient.execute(
@ -198,11 +201,11 @@ public class TestHttp1Async extends AbstractHttpAsyncFundamentalsTest<CloseableH
.setPath("/random/2048")
.build(), null);
final SimpleHttpResponse response3 = future3.get();
MatcherAssert.assertThat(response3, CoreMatchers.notNullValue());
MatcherAssert.assertThat(response3.getCode(), CoreMatchers.equalTo(200));
assertThat(response3, CoreMatchers.notNullValue());
assertThat(response3.getCode(), CoreMatchers.equalTo(200));
final String body3 = response3.getBodyText();
MatcherAssert.assertThat(body3, CoreMatchers.notNullValue());
MatcherAssert.assertThat(body3.length(), CoreMatchers.equalTo(2048));
assertThat(body3, CoreMatchers.notNullValue());
assertThat(body3.length(), CoreMatchers.equalTo(2048));
}
@Test
@ -269,8 +272,8 @@ public class TestHttp1Async extends AbstractHttpAsyncFundamentalsTest<CloseableH
.setPath("/random/1000")
.build(), null);
final SimpleHttpResponse response = future.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
MatcherAssert.assertThat(response, CoreMatchers.notNullValue());
MatcherAssert.assertThat(response.getCode(), CoreMatchers.equalTo(200));
assertThat(response, CoreMatchers.notNullValue());
assertThat(response.getCode(), CoreMatchers.equalTo(200));
}
} finally {

View File

@ -54,9 +54,10 @@ import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.HttpVersion;
import org.apache.hc.core5.http.URIScheme;
import org.apache.hc.core5.http.message.BasicHeader;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.Rule;
import org.junit.jupiter.migrationsupport.rules.EnableRuleMigrationSupport;
import org.junit.rules.ExternalResource;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@ -64,6 +65,7 @@ import org.junit.runners.Parameterized;
/**
* Redirection test cases.
*/
@EnableRuleMigrationSupport
@RunWith(Parameterized.class)
public class TestHttp1AsyncRedirects extends AbstractHttpAsyncRedirectsTest<CloseableHttpAsyncClient> {
@ -137,12 +139,12 @@ public class TestHttp1AsyncRedirects extends AbstractHttpAsyncRedirectsTest<Clos
.setPath("/oldlocation/")
.build(), context, null);
final HttpResponse response = future.get();
Assert.assertNotNull(response);
Assertions.assertNotNull(response);
final HttpRequest request = context.getRequest();
Assert.assertEquals(HttpStatus.SC_MULTIPLE_CHOICES, response.getCode());
Assert.assertEquals("/oldlocation/", request.getRequestUri());
Assertions.assertEquals(HttpStatus.SC_MULTIPLE_CHOICES, response.getCode());
Assertions.assertEquals("/oldlocation/", request.getRequestUri());
}
@Test
@ -157,13 +159,13 @@ public class TestHttp1AsyncRedirects extends AbstractHttpAsyncRedirectsTest<Clos
.setPath("/oldlocation/100")
.build(), context, null);
final HttpResponse response = future.get();
Assert.assertNotNull(response);
Assertions.assertNotNull(response);
final HttpRequest request = context.getRequest();
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assert.assertEquals("/random/100", request.getRequestUri());
Assert.assertEquals(target, new HttpHost(request.getScheme(), request.getAuthority()));
Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
Assertions.assertEquals("/random/100", request.getRequestUri());
Assertions.assertEquals(target, new HttpHost(request.getScheme(), request.getAuthority()));
}
@Test
@ -184,15 +186,15 @@ public class TestHttp1AsyncRedirects extends AbstractHttpAsyncRedirectsTest<Clos
.setPath("/oldlocation/123")
.build(), context, null);
final HttpResponse response = future.get();
Assert.assertNotNull(response);
Assertions.assertNotNull(response);
final HttpRequest request = context.getRequest();
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assert.assertEquals("/random/123", request.getRequestUri());
Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
Assertions.assertEquals("/random/123", request.getRequestUri());
final Header header = request.getFirstHeader(HttpHeaders.USER_AGENT);
Assert.assertEquals("my-test-client", header.getValue());
Assertions.assertEquals("my-test-client", header.getValue());
}
}

View File

@ -52,7 +52,7 @@ import org.apache.hc.core5.http.protocol.BasicHttpContext;
import org.apache.hc.core5.http.protocol.HttpContext;
import org.apache.hc.core5.http.protocol.HttpCoreContext;
import org.apache.hc.core5.net.URIAuthority;
import org.junit.Assert;
import org.junit.jupiter.api.Assertions;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExternalResource;
@ -152,14 +152,14 @@ public class TestHttp1AsyncStatefulConnManagement extends AbstractIntegrationTes
if (ex != null) {
throw ex;
}
Assert.assertEquals(requestCount, worker.getCount());
Assertions.assertEquals(requestCount, worker.getCount());
}
for (final HttpContext context : contexts) {
final String state0 = (String) context.getAttribute("r0");
Assert.assertNotNull(state0);
Assertions.assertNotNull(state0);
for (int r = 1; r < requestCount; r++) {
Assert.assertEquals(state0, context.getAttribute("r" + r));
Assertions.assertEquals(state0, context.getAttribute("r" + r));
}
}
@ -260,8 +260,8 @@ public class TestHttp1AsyncStatefulConnManagement extends AbstractIntegrationTes
.build();
final Future<SimpleHttpResponse> future1 = httpclient.execute(request1, context1, null);
final HttpResponse response1 = future1.get();
Assert.assertNotNull(response1);
Assert.assertEquals(200, response1.getCode());
Assertions.assertNotNull(response1);
Assertions.assertEquals(200, response1.getCode());
// The ConnPoolByRoute now has 1 free connection, out of 2 max
// The ConnPoolByRoute has one RouteSpcfcPool, that has one free connection
@ -280,8 +280,8 @@ public class TestHttp1AsyncStatefulConnManagement extends AbstractIntegrationTes
.build();
final Future<SimpleHttpResponse> future2 = httpclient.execute(request2, context2, null);
final HttpResponse response2 = future2.get();
Assert.assertNotNull(response2);
Assert.assertEquals(200, response2.getCode());
Assertions.assertNotNull(response2);
Assertions.assertEquals(200, response2.getCode());
// ConnPoolByRoute now has 2 free connexions, out of its 2 max.
// The [localhost][stuff] RouteSpcfcPool is the same as earlier
@ -302,8 +302,8 @@ public class TestHttp1AsyncStatefulConnManagement extends AbstractIntegrationTes
.build();
final Future<SimpleHttpResponse> future3 = httpclient.execute(request3, context3, null);
final HttpResponse response3 = future3.get();
Assert.assertNotNull(response3);
Assert.assertEquals(200, response3.getCode());
Assertions.assertNotNull(response3);
Assertions.assertEquals(200, response3.getCode());
}
}

View File

@ -60,14 +60,16 @@ import org.apache.hc.core5.http.URIScheme;
import org.apache.hc.core5.http.config.Http1Config;
import org.apache.hc.core5.http.config.Lookup;
import org.apache.hc.core5.http.impl.HttpProcessors;
import org.junit.Assert;
import org.junit.jupiter.api.Assertions;
import org.junit.Rule;
import org.junit.Test;
import org.junit.jupiter.migrationsupport.rules.EnableRuleMigrationSupport;
import org.junit.rules.ExternalResource;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.mockito.Mockito;
@EnableRuleMigrationSupport
@RunWith(Parameterized.class)
public class TestHttp1ClientAuthentication extends AbstractHttpAsyncClientAuthentication<CloseableHttpAsyncClient> {
@ -176,8 +178,8 @@ public class TestHttp1ClientAuthentication extends AbstractHttpAsyncClientAuthen
final Future<SimpleHttpResponse> future = httpclient.execute(request, context, null);
final HttpResponse response = future.get();
Assert.assertNotNull(response);
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assertions.assertNotNull(response);
Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
Mockito.verify(credsProvider).getCredentials(
Mockito.eq(new AuthScope(target, "test realm", "basic")), Mockito.any());
}

View File

@ -26,6 +26,9 @@
*/
package org.apache.hc.client5.testing.async;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.hamcrest.MatcherAssert.assertThat;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Collection;
@ -52,9 +55,9 @@ import org.apache.hc.core5.http.nio.AsyncRequestProducer;
import org.apache.hc.core5.http.nio.support.AsyncRequestBuilder;
import org.apache.hc.core5.reactive.ReactiveResponseConsumer;
import org.hamcrest.CoreMatchers;
import org.hamcrest.MatcherAssert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.jupiter.api.Timeout;
import org.junit.rules.ExternalResource;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@ -126,7 +129,8 @@ public class TestHttp1Reactive extends AbstractHttpReactiveFundamentalsTest<Clos
return super.start(null, Http1Config.DEFAULT);
}
@Test(timeout = 60_000)
@Test
@Timeout(value = 60_000, unit = MILLISECONDS)
public void testSequentialGetRequestsCloseConnection() throws Exception {
final HttpHost target = start();
for (int i = 0; i < 3; i++) {
@ -141,29 +145,32 @@ public class TestHttp1Reactive extends AbstractHttpReactiveFundamentalsTest<Clos
httpclient.execute(request, consumer, null);
final Message<HttpResponse, Publisher<ByteBuffer>> response = consumer.getResponseFuture().get();
MatcherAssert.assertThat(response, CoreMatchers.notNullValue());
MatcherAssert.assertThat(response.getHead().getCode(), CoreMatchers.equalTo(200));
assertThat(response, CoreMatchers.notNullValue());
assertThat(response.getHead().getCode(), CoreMatchers.equalTo(200));
final String body = publisherToString(response.getBody());
MatcherAssert.assertThat(body, CoreMatchers.notNullValue());
MatcherAssert.assertThat(body.length(), CoreMatchers.equalTo(2048));
assertThat(body, CoreMatchers.notNullValue());
assertThat(body.length(), CoreMatchers.equalTo(2048));
}
}
@Test(timeout = 60_000)
@Test
@Timeout(value = 60_000, unit = MILLISECONDS)
public void testConcurrentPostsOverMultipleConnections() throws Exception {
connManager.setDefaultMaxPerRoute(20);
connManager.setMaxTotal(100);
super.testConcurrentPostRequests();
}
@Test(timeout = 60_000)
@Test
@Timeout(value = 60_000, unit = MILLISECONDS)
public void testConcurrentPostsOverSingleConnection() throws Exception {
connManager.setDefaultMaxPerRoute(1);
connManager.setMaxTotal(100);
super.testConcurrentPostRequests();
}
@Test(timeout = 60_000)
@Test
@Timeout(value = 60_000, unit = MILLISECONDS)
public void testSharedPool() throws Exception {
final HttpHost target = start();
final AsyncRequestProducer request1 = AsyncRequestBuilder.get(target + "/random/2048").build();
@ -172,12 +179,12 @@ public class TestHttp1Reactive extends AbstractHttpReactiveFundamentalsTest<Clos
httpclient.execute(request1, consumer1, null);
final Message<HttpResponse, Publisher<ByteBuffer>> response1 = consumer1.getResponseFuture().get();
MatcherAssert.assertThat(response1, CoreMatchers.notNullValue());
MatcherAssert.assertThat(response1.getHead(), CoreMatchers.notNullValue());
MatcherAssert.assertThat(response1.getHead().getCode(), CoreMatchers.equalTo(200));
assertThat(response1, CoreMatchers.notNullValue());
assertThat(response1.getHead(), CoreMatchers.notNullValue());
assertThat(response1.getHead().getCode(), CoreMatchers.equalTo(200));
final String body1 = publisherToString(response1.getBody());
MatcherAssert.assertThat(body1, CoreMatchers.notNullValue());
MatcherAssert.assertThat(body1.length(), CoreMatchers.equalTo(2048));
assertThat(body1, CoreMatchers.notNullValue());
assertThat(body1.length(), CoreMatchers.equalTo(2048));
try (final CloseableHttpAsyncClient httpclient2 = HttpAsyncClients.custom()
@ -191,11 +198,11 @@ public class TestHttp1Reactive extends AbstractHttpReactiveFundamentalsTest<Clos
httpclient2.execute(request2, consumer2, null);
final Message<HttpResponse, Publisher<ByteBuffer>> response2 = consumer2.getResponseFuture().get();
MatcherAssert.assertThat(response2, CoreMatchers.notNullValue());
MatcherAssert.assertThat(response2.getHead().getCode(), CoreMatchers.equalTo(200));
assertThat(response2, CoreMatchers.notNullValue());
assertThat(response2.getHead().getCode(), CoreMatchers.equalTo(200));
final String body2 = publisherToString(response2.getBody());
MatcherAssert.assertThat(body2, CoreMatchers.notNullValue());
MatcherAssert.assertThat(body2.length(), CoreMatchers.equalTo(2048));
assertThat(body2, CoreMatchers.notNullValue());
assertThat(body2.length(), CoreMatchers.equalTo(2048));
}
final AsyncRequestProducer request3 = AsyncRequestBuilder.get(target + "/random/2048").build();
@ -204,11 +211,11 @@ public class TestHttp1Reactive extends AbstractHttpReactiveFundamentalsTest<Clos
httpclient.execute(request3, consumer3, null);
final Message<HttpResponse, Publisher<ByteBuffer>> response3 = consumer3.getResponseFuture().get();
MatcherAssert.assertThat(response3, CoreMatchers.notNullValue());
MatcherAssert.assertThat(response3.getHead().getCode(), CoreMatchers.equalTo(200));
assertThat(response3, CoreMatchers.notNullValue());
assertThat(response3.getHead().getCode(), CoreMatchers.equalTo(200));
final String body3 = publisherToString(response3.getBody());
MatcherAssert.assertThat(body3, CoreMatchers.notNullValue());
MatcherAssert.assertThat(body3.length(), CoreMatchers.equalTo(2048));
assertThat(body3, CoreMatchers.notNullValue());
assertThat(body3.length(), CoreMatchers.equalTo(2048));
}
}

View File

@ -26,6 +26,8 @@
*/
package org.apache.hc.client5.testing.async;
import static org.hamcrest.MatcherAssert.assertThat;
import java.util.Arrays;
import java.util.Collection;
import java.util.concurrent.Future;
@ -51,13 +53,14 @@ import org.apache.hc.core5.http2.HttpVersionPolicy;
import org.apache.hc.core5.http2.config.H2Config;
import org.apache.hc.core5.util.TimeValue;
import org.hamcrest.CoreMatchers;
import org.hamcrest.MatcherAssert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.jupiter.migrationsupport.rules.EnableRuleMigrationSupport;
import org.junit.rules.ExternalResource;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@EnableRuleMigrationSupport
@RunWith(Parameterized.class)
public class TestHttp1RequestReExecution extends AbstractIntegrationTestBase<CloseableHttpAsyncClient> {
@ -152,8 +155,8 @@ public class TestHttp1RequestReExecution extends AbstractIntegrationTestBase<Clo
.setPath("/random/2048")
.build(), null);
final SimpleHttpResponse response = future.get();
MatcherAssert.assertThat(response, CoreMatchers.notNullValue());
MatcherAssert.assertThat(response.getCode(), CoreMatchers.equalTo(HttpStatus.SC_SERVICE_UNAVAILABLE));
assertThat(response, CoreMatchers.notNullValue());
assertThat(response.getCode(), CoreMatchers.equalTo(HttpStatus.SC_SERVICE_UNAVAILABLE));
}
@Test
@ -166,8 +169,8 @@ public class TestHttp1RequestReExecution extends AbstractIntegrationTestBase<Clo
.setPath("/random/2048")
.build(), null);
final SimpleHttpResponse response = future.get();
MatcherAssert.assertThat(response, CoreMatchers.notNullValue());
MatcherAssert.assertThat(response.getCode(), CoreMatchers.equalTo(HttpStatus.SC_OK));
assertThat(response, CoreMatchers.notNullValue());
assertThat(response.getCode(), CoreMatchers.equalTo(HttpStatus.SC_OK));
}
}

View File

@ -26,6 +26,8 @@
*/
package org.apache.hc.client5.testing.async;
import static org.hamcrest.MatcherAssert.assertThat;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedList;
@ -58,11 +60,12 @@ import org.apache.hc.core5.http2.HttpVersionPolicy;
import org.apache.hc.core5.http2.config.H2Config;
import org.apache.hc.core5.reactor.IOReactorConfig;
import org.hamcrest.CoreMatchers;
import org.hamcrest.MatcherAssert;
import org.junit.Test;
import org.junit.jupiter.migrationsupport.rules.EnableRuleMigrationSupport;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@EnableRuleMigrationSupport
@RunWith(Parameterized.class)
public class TestHttpAsyncMinimal extends AbstractHttpAsyncFundamentalsTest<MinimalHttpAsyncClient> {
@ -132,11 +135,11 @@ public class TestHttpAsyncMinimal extends AbstractHttpAsyncFundamentalsTest<Mini
while (!queue.isEmpty()) {
final Future<Message<HttpResponse, byte[]>> future = queue.remove();
final Message<HttpResponse, byte[]> responseMessage = future.get();
MatcherAssert.assertThat(responseMessage, CoreMatchers.notNullValue());
assertThat(responseMessage, CoreMatchers.notNullValue());
final HttpResponse response = responseMessage.getHead();
MatcherAssert.assertThat(response.getCode(), CoreMatchers.equalTo(200));
assertThat(response.getCode(), CoreMatchers.equalTo(200));
final byte[] b2 = responseMessage.getBody();
MatcherAssert.assertThat(b1, CoreMatchers.equalTo(b2));
assertThat(b1, CoreMatchers.equalTo(b2));
endpoint.releaseAndReuse();
}
} finally {

View File

@ -26,6 +26,8 @@
*/
package org.apache.hc.client5.testing.async;
import static org.hamcrest.MatcherAssert.assertThat;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedList;
@ -58,11 +60,12 @@ import org.apache.hc.core5.http2.HttpVersionPolicy;
import org.apache.hc.core5.http2.config.H2Config;
import org.apache.hc.core5.reactor.IOReactorConfig;
import org.hamcrest.CoreMatchers;
import org.hamcrest.MatcherAssert;
import org.junit.Test;
import org.junit.jupiter.migrationsupport.rules.EnableRuleMigrationSupport;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@EnableRuleMigrationSupport
@RunWith(Parameterized.class)
public class TestHttpMinimalReactive extends AbstractHttpReactiveFundamentalsTest<MinimalHttpAsyncClient> {
@ -132,11 +135,11 @@ public class TestHttpMinimalReactive extends AbstractHttpReactiveFundamentalsTes
while (!queue.isEmpty()) {
final Future<Message<HttpResponse, byte[]>> future = queue.remove();
final Message<HttpResponse, byte[]> responseMessage = future.get();
MatcherAssert.assertThat(responseMessage, CoreMatchers.notNullValue());
assertThat(responseMessage, CoreMatchers.notNullValue());
final HttpResponse response = responseMessage.getHead();
MatcherAssert.assertThat(response.getCode(), CoreMatchers.equalTo(200));
assertThat(response.getCode(), CoreMatchers.equalTo(200));
final byte[] b2 = responseMessage.getBody();
MatcherAssert.assertThat(b1, CoreMatchers.equalTo(b2));
assertThat(b1, CoreMatchers.equalTo(b2));
endpoint.releaseAndReuse();
}
} finally {

View File

@ -39,8 +39,8 @@ import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.junit.Assert;
import org.junit.Before;
import org.junit.jupiter.api.Assertions;
import org.junit.Test;
public class TestFluent extends LocalServerTestBase {
@ -71,7 +71,7 @@ public class TestFluent extends LocalServerTestBase {
final HttpHost target = start();
final String baseURL = "http://localhost:" + target.getPort();
final String message = Request.get(baseURL + "/").execute().returnContent().asString();
Assert.assertEquals("All is well", message);
Assertions.assertEquals("All is well", message);
}
@Test
@ -79,7 +79,7 @@ public class TestFluent extends LocalServerTestBase {
final HttpHost target = start();
final String baseURL = "http://localhost:" + target.getPort();
final String message = Request.create("GET", baseURL + "/").execute().returnContent().asString();
Assert.assertEquals("All is well", message);
Assertions.assertEquals("All is well", message);
}
@Test
@ -87,14 +87,14 @@ public class TestFluent extends LocalServerTestBase {
final HttpHost target = start();
final String baseURL = "http://localhost:" + target.getPort();
final String message = Request.create("GET", new URI(baseURL + "/")).execute().returnContent().asString();
Assert.assertEquals("All is well", message);
Assertions.assertEquals("All is well", message);
}
@Test
public void testGetRequestFailure() throws Exception {
final HttpHost target = start();
final String baseURL = "http://localhost:" + target.getPort();
Assert.assertThrows(ClientProtocolException.class, () ->
Assertions.assertThrows(ClientProtocolException.class, () ->
Request.get(baseURL + "/boom").execute().returnContent().asString());
}
@ -105,11 +105,11 @@ public class TestFluent extends LocalServerTestBase {
final String message1 = Request.post(baseURL + "/echo")
.bodyString("what is up?", ContentType.TEXT_PLAIN)
.execute().returnContent().asString();
Assert.assertEquals("what is up?", message1);
Assertions.assertEquals("what is up?", message1);
final String message2 = Request.post(baseURL + "/echo")
.bodyByteArray(new byte[]{1, 2, 3}, ContentType.APPLICATION_OCTET_STREAM)
.execute().returnContent().asString();
Assert.assertEquals("echo", message2);
Assertions.assertEquals("echo", message2);
}
@Test
@ -118,9 +118,9 @@ public class TestFluent extends LocalServerTestBase {
final String baseURL = "http://localhost:" + target.getPort();
final Content content = Request.post(baseURL + "/echo").bodyByteArray("Ü".getBytes(StandardCharsets.UTF_8)).execute()
.returnContent();
Assert.assertEquals((byte)-61, content.asBytes()[0]);
Assert.assertEquals((byte)-100, content.asBytes()[1]);
Assert.assertEquals("Ü", content.asString(StandardCharsets.UTF_8));
Assertions.assertEquals((byte)-61, content.asBytes()[0]);
Assertions.assertEquals((byte)-100, content.asBytes()[1]);
Assertions.assertEquals("Ü", content.asString(StandardCharsets.UTF_8));
}
@Test

View File

@ -30,7 +30,7 @@ import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.io.BasicHttpClientConnectionManager;
import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.junit.Assert;
import org.junit.jupiter.api.Assertions;
import org.junit.Test;
public class TestBasicConnectionManager extends LocalServerTestBase {
@ -42,7 +42,7 @@ public class TestBasicConnectionManager extends LocalServerTestBase {
final HttpHost target = start();
final HttpGet get = new HttpGet("/random/1024");
this.httpclient.execute(target, get, response -> {
Assert.assertEquals(200, response.getCode());
Assertions.assertEquals(200, response.getCode());
EntityUtils.consume(response.getEntity());
return null;
});
@ -56,7 +56,7 @@ public class TestBasicConnectionManager extends LocalServerTestBase {
final HttpGet get1 = new HttpGet("/random/1024");
this.httpclient.execute(target, get1);
final HttpGet get2 = new HttpGet("/random/1024");
Assert.assertThrows(IllegalStateException.class, () ->
Assertions.assertThrows(IllegalStateException.class, () ->
this.httpclient.execute(target, get2));
}

View File

@ -26,6 +26,8 @@
*/
package org.apache.hc.client5.testing.sync;
import static org.hamcrest.MatcherAssert.assertThat;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
@ -78,8 +80,7 @@ import org.apache.hc.core5.http.protocol.HttpContext;
import org.apache.hc.core5.http.support.BasicResponseBuilder;
import org.apache.hc.core5.net.URIAuthority;
import org.hamcrest.CoreMatchers;
import org.hamcrest.MatcherAssert;
import org.junit.Assert;
import org.junit.jupiter.api.Assertions;
import org.junit.Test;
import org.mockito.Mockito;
@ -109,8 +110,8 @@ public class TestClientAuthentication extends LocalServerTestBase {
this.httpclient.execute(target, httpget, context, response -> {
final HttpEntity entity = response.getEntity();
Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getCode());
Assert.assertNotNull(entity);
Assertions.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getCode());
Assertions.assertNotNull(entity);
EntityUtils.consume(entity);
return null;
});
@ -132,8 +133,8 @@ public class TestClientAuthentication extends LocalServerTestBase {
this.httpclient.execute(target, httpget, context, response -> {
final HttpEntity entity = response.getEntity();
Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getCode());
Assert.assertNotNull(entity);
Assertions.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getCode());
Assertions.assertNotNull(entity);
EntityUtils.consume(entity);
return null;
});
@ -155,8 +156,8 @@ public class TestClientAuthentication extends LocalServerTestBase {
this.httpclient.execute(target, httpget, context, response -> {
final HttpEntity entity = response.getEntity();
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assert.assertNotNull(entity);
Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
Assertions.assertNotNull(entity);
EntityUtils.consume(entity);
return null;
});
@ -186,8 +187,8 @@ public class TestClientAuthentication extends LocalServerTestBase {
this.httpclient.execute(target, httpput, context, response -> {
final HttpEntity entity = response.getEntity();
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assert.assertNotNull(entity);
Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
Assertions.assertNotNull(entity);
return null;
});
}
@ -213,8 +214,8 @@ public class TestClientAuthentication extends LocalServerTestBase {
this.httpclient.execute(target, httpput, context, response -> {
final HttpEntity entity = response.getEntity();
Assert.assertEquals(401, response.getCode());
Assert.assertNotNull(entity);
Assertions.assertEquals(401, response.getCode());
Assertions.assertNotNull(entity);
EntityUtils.consume(entity);
return null;
});
@ -236,8 +237,8 @@ public class TestClientAuthentication extends LocalServerTestBase {
this.httpclient.execute(target, httppost, context, response -> {
final HttpEntity entity = response.getEntity();
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assert.assertNotNull(entity);
Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
Assertions.assertNotNull(entity);
EntityUtils.consume(entity);
return null;
});
@ -266,8 +267,8 @@ public class TestClientAuthentication extends LocalServerTestBase {
this.httpclient.execute(target, httppost, context, response -> {
final HttpEntity entity = response.getEntity();
Assert.assertEquals(401, response.getCode());
Assert.assertNotNull(entity);
Assertions.assertEquals(401, response.getCode());
Assertions.assertNotNull(entity);
EntityUtils.consume(entity);
return null;
});
@ -293,8 +294,8 @@ public class TestClientAuthentication extends LocalServerTestBase {
final HttpGet httpget = new HttpGet("/");
this.httpclient.execute(target, httpget, context, response -> {
final HttpEntity entity1 = response.getEntity();
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assert.assertNotNull(entity1);
Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
Assertions.assertNotNull(entity1);
EntityUtils.consume(entity1);
return null;
});
@ -302,7 +303,7 @@ public class TestClientAuthentication extends LocalServerTestBase {
Mockito.verify(authStrategy).select(Mockito.any(), Mockito.any(), Mockito.any());
MatcherAssert.assertThat(
assertThat(
responseQueue.stream().map(HttpResponse::getCode).collect(Collectors.toList()),
CoreMatchers.equalTo(Arrays.asList(401, 200, 200, 200, 200, 200)));
}
@ -331,8 +332,8 @@ public class TestClientAuthentication extends LocalServerTestBase {
final HttpGet httpget = new HttpGet(requestPath);
this.httpclient.execute(target, httpget, context, response -> {
final HttpEntity entity1 = response.getEntity();
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assert.assertNotNull(entity1);
Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
Assertions.assertNotNull(entity1);
EntityUtils.consume(entity1);
return null;
});
@ -341,7 +342,7 @@ public class TestClientAuthentication extends LocalServerTestBase {
// There should be only single auth strategy call for all successful message exchanges
Mockito.verify(authStrategy).select(Mockito.any(), Mockito.any(), Mockito.any());
MatcherAssert.assertThat(
assertThat(
responseQueue.stream().map(HttpResponse::getCode).collect(Collectors.toList()),
CoreMatchers.equalTo(Arrays.asList(401, 200, 200, 200, 200)));
@ -353,8 +354,8 @@ public class TestClientAuthentication extends LocalServerTestBase {
final HttpGet httpget = new HttpGet(requestPath);
this.httpclient.execute(target, httpget, context, response -> {
final HttpEntity entity1 = response.getEntity();
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assert.assertNotNull(entity1);
Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
Assertions.assertNotNull(entity1);
EntityUtils.consume(entity1);
return null;
});
@ -363,7 +364,7 @@ public class TestClientAuthentication extends LocalServerTestBase {
// There should be an auth strategy call for all successful message exchanges
Mockito.verify(authStrategy, Mockito.times(2)).select(Mockito.any(), Mockito.any(), Mockito.any());
MatcherAssert.assertThat(
assertThat(
responseQueue.stream().map(HttpResponse::getCode).collect(Collectors.toList()),
CoreMatchers.equalTo(Arrays.asList(200, 401, 200, 200, 401, 200)));
}
@ -413,8 +414,8 @@ public class TestClientAuthentication extends LocalServerTestBase {
this.httpclient.execute(target, httpget1, context, response -> {
final HttpEntity entity1 = response.getEntity();
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assert.assertNotNull(entity1);
Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
Assertions.assertNotNull(entity1);
EntityUtils.consume(entity1);
return null;
});
@ -423,8 +424,8 @@ public class TestClientAuthentication extends LocalServerTestBase {
this.httpclient.execute(target, httpget2, context, response -> {
final HttpEntity entity2 = response.getEntity();
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assert.assertNotNull(entity2);
Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
Assertions.assertNotNull(entity2);
EntityUtils.consume(entity2);
return null;
});
@ -433,8 +434,8 @@ public class TestClientAuthentication extends LocalServerTestBase {
this.httpclient.execute(target, httpget3, context, response -> {
final HttpEntity entity3 = response.getEntity();
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assert.assertNotNull(entity3);
Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
Assertions.assertNotNull(entity3);
EntityUtils.consume(entity3);
return null;
});
@ -449,7 +450,7 @@ public class TestClientAuthentication extends LocalServerTestBase {
final HttpGet httpget = new HttpGet("http://test:test@" + target.toHostString() + "/");
final HttpClientContext context = HttpClientContext.create();
Assert.assertThrows(ClientProtocolException.class, () -> this.httpclient.execute(target, httpget, context, response -> null));
Assertions.assertThrows(ClientProtocolException.class, () -> this.httpclient.execute(target, httpget, context, response -> null));
}
@Test
@ -468,8 +469,8 @@ public class TestClientAuthentication extends LocalServerTestBase {
final HttpGet httpget = new HttpGet("/");
this.httpclient.execute(target, httpget, context, response -> {
final HttpEntity entity1 = response.getEntity();
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assert.assertNotNull(entity1);
Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
Assertions.assertNotNull(entity1);
EntityUtils.consume(entity1);
return null;
});
@ -494,8 +495,8 @@ public class TestClientAuthentication extends LocalServerTestBase {
final HttpGet httpget = new HttpGet("/");
this.httpclient.execute(target, httpget, context, response -> {
final HttpEntity entity1 = response.getEntity();
Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getCode());
Assert.assertNotNull(entity1);
Assertions.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getCode());
Assertions.assertNotNull(entity1);
EntityUtils.consume(entity1);
return null;
});
@ -535,7 +536,7 @@ public class TestClientAuthentication extends LocalServerTestBase {
final HttpGet httpget = new HttpGet("/");
this.httpclient.execute(target, httpget, context, response -> {
final HttpEntity entity = response.getEntity();
Assert.assertEquals(HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED, response.getCode());
Assertions.assertEquals(HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED, response.getCode());
EntityUtils.consume(entity);
return null;
});
@ -567,7 +568,7 @@ public class TestClientAuthentication extends LocalServerTestBase {
this.httpclient.execute(target, httpget, context, response -> {
EntityUtils.consume(response.getEntity());
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
return null;
});
}
@ -641,8 +642,8 @@ public class TestClientAuthentication extends LocalServerTestBase {
httpget.setConfig(config);
this.httpclient.execute(target, httpget, context, response -> {
final HttpEntity entity = response.getEntity();
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assert.assertNotNull(entity);
Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
Assertions.assertNotNull(entity);
EntityUtils.consume(entity);
return null;
});
@ -673,8 +674,8 @@ public class TestClientAuthentication extends LocalServerTestBase {
this.httpclient.execute(target, httpget, context, response -> {
final HttpEntity entity = response.getEntity();
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assert.assertNotNull(entity);
Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
Assertions.assertNotNull(entity);
EntityUtils.consume(entity);
return null;
});

View File

@ -44,7 +44,7 @@ import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.io.HttpRequestHandler;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.protocol.HttpContext;
import org.junit.Assert;
import org.junit.jupiter.api.Assertions;
import org.junit.Test;
/**
@ -84,7 +84,7 @@ public class TestClientAuthenticationFakeNTLM extends LocalServerTestBase {
this.httpclient.execute(target, httpget, context, response -> {
EntityUtils.consume(response.getEntity());
Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getCode());
Assertions.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getCode());
return null;
});
}
@ -132,7 +132,7 @@ public class TestClientAuthenticationFakeNTLM extends LocalServerTestBase {
this.httpclient.execute(target, httpget, context, response -> {
EntityUtils.consume(response.getEntity());
Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getCode());
Assertions.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getCode());
return null;
});
}
@ -157,7 +157,7 @@ public class TestClientAuthenticationFakeNTLM extends LocalServerTestBase {
this.httpclient.execute(target, httpget, context, response -> {
EntityUtils.consume(response.getEntity());
Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getCode());
Assertions.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getCode());
return null;
});
}
@ -197,7 +197,7 @@ public class TestClientAuthenticationFakeNTLM extends LocalServerTestBase {
this.httpclient.execute(target, httpget, context, response -> {
EntityUtils.consume(response.getEntity());
Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getCode());
Assertions.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getCode());
return null;
});
}
@ -218,7 +218,7 @@ public class TestClientAuthenticationFakeNTLM extends LocalServerTestBase {
this.httpclient.execute(target, httpget, context, response -> {
EntityUtils.consume(response.getEntity());
Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getCode());
Assertions.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getCode());
return null;
});
}

View File

@ -59,7 +59,7 @@ import org.apache.hc.core5.http.message.BasicClassicHttpRequest;
import org.apache.hc.core5.http.protocol.HttpContext;
import org.apache.hc.core5.net.URIBuilder;
import org.apache.hc.core5.util.TimeValue;
import org.junit.Assert;
import org.junit.jupiter.api.Assertions;
import org.junit.Test;
/**
@ -162,11 +162,11 @@ public class TestClientRequestExecution extends LocalServerTestBase {
EntityUtils.consume(response.getEntity());
final HttpRequest reqWrapper = context.getRequest();
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
final Header[] myheaders = reqWrapper.getHeaders("my-header");
Assert.assertNotNull(myheaders);
Assert.assertEquals(1, myheaders.length);
Assertions.assertNotNull(myheaders);
Assertions.assertEquals(1, myheaders.length);
return null;
});
}
@ -218,7 +218,7 @@ public class TestClientRequestExecution extends LocalServerTestBase {
new ByteArrayInputStream(
new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 } ),
-1, null));
Assert.assertThrows(IOException.class, () ->
Assertions.assertThrows(IOException.class, () ->
this.httpclient.execute(target, httppost, context, response -> null));
}
@ -231,14 +231,14 @@ public class TestClientRequestExecution extends LocalServerTestBase {
final HttpClientContext context = HttpClientContext.create();
final ClassicHttpRequest request = new BasicClassicHttpRequest("GET", "{{|boom|}}");
this.httpclient.execute(target, request, context, response -> {
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
EntityUtils.consume(response.getEntity());
return null;
});
final HttpRequest reqWrapper = context.getRequest();
Assert.assertEquals("{{|boom|}}", reqWrapper.getRequestUri());
Assertions.assertEquals("{{|boom|}}", reqWrapper.getRequestUri());
}
@Test
@ -251,13 +251,13 @@ public class TestClientRequestExecution extends LocalServerTestBase {
final HttpClientContext context = HttpClientContext.create();
this.httpclient.execute(target, httpget, context, response -> {
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
EntityUtils.consume(response.getEntity());
return null;
});
final HttpRequest request = context.getRequest();
Assert.assertEquals("/stuff", request.getRequestUri());
Assertions.assertEquals("/stuff", request.getRequestUri());
}
@Test
@ -278,16 +278,16 @@ public class TestClientRequestExecution extends LocalServerTestBase {
final HttpClientContext context = HttpClientContext.create();
this.httpclient.execute(httpget, context, response -> {
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
return null;
});
final HttpRequest request = context.getRequest();
Assert.assertEquals("/stuff", request.getRequestUri());
Assertions.assertEquals("/stuff", request.getRequestUri());
final RedirectLocations redirectLocations = context.getRedirectLocations();
final URI location = URIUtils.resolve(uri, target, redirectLocations.getAll());
Assert.assertEquals(uri, location);
Assertions.assertEquals(uri, location);
}
@Test

View File

@ -54,8 +54,8 @@ import org.apache.hc.core5.pool.PoolConcurrencyPolicy;
import org.apache.hc.core5.pool.PoolReusePolicy;
import org.apache.hc.core5.util.TimeValue;
import org.apache.hc.core5.util.Timeout;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
/**
* Tests for {@code PoolingHttpClientConnectionManager} that do require a server
@ -90,24 +90,24 @@ public class TestConnectionManagement extends LocalServerTestBase {
final HttpRequestExecutor exec = new HttpRequestExecutor();
exec.preProcess(request, httpProcessor, context);
try (final ClassicHttpResponse response1 = endpoint1.execute("id1", request, exec, context)) {
Assert.assertEquals(HttpStatus.SC_OK, response1.getCode());
Assertions.assertEquals(HttpStatus.SC_OK, response1.getCode());
}
// check that there is no auto-release by default
// this should fail quickly, connection has not been released
final LeaseRequest leaseRequest2 = this.connManager.lease("id2", route,null);
Assert.assertThrows(TimeoutException.class, () -> leaseRequest2.get(Timeout.ofMilliseconds(10)));
Assertions.assertThrows(TimeoutException.class, () -> leaseRequest2.get(Timeout.ofMilliseconds(10)));
endpoint1.close();
this.connManager.release(endpoint1, null, TimeValue.NEG_ONE_MILLISECOND);
final LeaseRequest leaseRequest3 = this.connManager.lease("id2", route,null);
final ConnectionEndpoint endpoint2 = leaseRequest3.get(Timeout.ZERO_MILLISECONDS);
Assert.assertFalse(endpoint2.isConnected());
Assertions.assertFalse(endpoint2.isConnected());
this.connManager.connect(endpoint2, null, context);
try (final ClassicHttpResponse response2 = endpoint2.execute("id2", request, exec, context)) {
Assert.assertEquals(HttpStatus.SC_OK, response2.getCode());
Assertions.assertEquals(HttpStatus.SC_OK, response2.getCode());
}
// release connection after marking it for re-use
@ -116,11 +116,11 @@ public class TestConnectionManagement extends LocalServerTestBase {
final LeaseRequest leaseRequest4 = this.connManager.lease("id3", route,null);
final ConnectionEndpoint endpoint3 = leaseRequest4.get(Timeout.ZERO_MILLISECONDS);
Assert.assertTrue(endpoint3.isConnected());
Assertions.assertTrue(endpoint3.isConnected());
// repeat the communication, no need to prepare the request again
try (final ClassicHttpResponse response3 = endpoint3.execute("id3", request, exec, context)) {
Assert.assertEquals(HttpStatus.SC_OK, response3.getCode());
Assertions.assertEquals(HttpStatus.SC_OK, response3.getCode());
}
this.connManager.release(endpoint3, null, TimeValue.NEG_ONE_MILLISECOND);
@ -153,36 +153,36 @@ public class TestConnectionManagement extends LocalServerTestBase {
final HttpRequestExecutor exec = new HttpRequestExecutor();
exec.preProcess(request, httpProcessor, context);
try (final ClassicHttpResponse response1 = endpoint1.execute("id1", request, exec, context)) {
Assert.assertEquals(HttpStatus.SC_OK, response1.getCode());
Assertions.assertEquals(HttpStatus.SC_OK, response1.getCode());
}
// check that there is no auto-release by default
final LeaseRequest leaseRequest2 = this.connManager.lease("id2", route,null);
// this should fail quickly, connection has not been released
Assert.assertThrows(TimeoutException.class, () -> leaseRequest2.get(Timeout.ofMilliseconds(10)));
Assertions.assertThrows(TimeoutException.class, () -> leaseRequest2.get(Timeout.ofMilliseconds(10)));
endpoint1.close();
this.connManager.release(endpoint1, null, TimeValue.ofMilliseconds(100));
final LeaseRequest leaseRequest3 = this.connManager.lease("id2", route,null);
final ConnectionEndpoint endpoint2 = leaseRequest3.get(Timeout.ZERO_MILLISECONDS);
Assert.assertFalse(endpoint2.isConnected());
Assertions.assertFalse(endpoint2.isConnected());
this.connManager.connect(endpoint2, null, context);
try (final ClassicHttpResponse response2 = endpoint2.execute("id2", request, exec, context)) {
Assert.assertEquals(HttpStatus.SC_OK, response2.getCode());
Assertions.assertEquals(HttpStatus.SC_OK, response2.getCode());
}
this.connManager.release(endpoint2, null, TimeValue.ofMilliseconds(100));
final LeaseRequest leaseRequest4 = this.connManager.lease("id3", route,null);
final ConnectionEndpoint endpoint3 = leaseRequest4.get(Timeout.ZERO_MILLISECONDS);
Assert.assertTrue(endpoint3.isConnected());
Assertions.assertTrue(endpoint3.isConnected());
// repeat the communication, no need to prepare the request again
try (final ClassicHttpResponse response3 = endpoint3.execute("id3", request, exec, context)) {
Assert.assertEquals(HttpStatus.SC_OK, response3.getCode());
Assertions.assertEquals(HttpStatus.SC_OK, response3.getCode());
}
this.connManager.release(endpoint3, null, TimeValue.ofMilliseconds(100));
@ -190,13 +190,13 @@ public class TestConnectionManagement extends LocalServerTestBase {
final LeaseRequest leaseRequest5 = this.connManager.lease("id4", route,null);
final ConnectionEndpoint endpoint4 = leaseRequest5.get(Timeout.ZERO_MILLISECONDS);
Assert.assertFalse(endpoint4.isConnected());
Assertions.assertFalse(endpoint4.isConnected());
// repeat the communication, no need to prepare the request again
this.connManager.connect(endpoint4, null, context);
try (final ClassicHttpResponse response4 = endpoint4.execute("id4", request, exec, context)) {
Assert.assertEquals(HttpStatus.SC_OK, response4.getCode());
Assertions.assertEquals(HttpStatus.SC_OK, response4.getCode());
}
this.connManager.close();
@ -215,28 +215,28 @@ public class TestConnectionManagement extends LocalServerTestBase {
final ConnectionEndpoint endpoint1 = leaseRequest1.get(Timeout.ZERO_MILLISECONDS);
this.connManager.connect(endpoint1, null, context);
Assert.assertEquals(1, this.connManager.getTotalStats().getLeased());
Assert.assertEquals(1, this.connManager.getStats(route).getLeased());
Assertions.assertEquals(1, this.connManager.getTotalStats().getLeased());
Assertions.assertEquals(1, this.connManager.getStats(route).getLeased());
this.connManager.release(endpoint1, null, TimeValue.ofMilliseconds(100));
// Released, still active.
Assert.assertEquals(1, this.connManager.getTotalStats().getAvailable());
Assert.assertEquals(1, this.connManager.getStats(route).getAvailable());
Assertions.assertEquals(1, this.connManager.getTotalStats().getAvailable());
Assertions.assertEquals(1, this.connManager.getStats(route).getAvailable());
this.connManager.closeExpired();
// Time has not expired yet.
Assert.assertEquals(1, this.connManager.getTotalStats().getAvailable());
Assert.assertEquals(1, this.connManager.getStats(route).getAvailable());
Assertions.assertEquals(1, this.connManager.getTotalStats().getAvailable());
Assertions.assertEquals(1, this.connManager.getStats(route).getAvailable());
Thread.sleep(150);
this.connManager.closeExpired();
// Time expired now, connections are destroyed.
Assert.assertEquals(0, this.connManager.getTotalStats().getAvailable());
Assert.assertEquals(0, this.connManager.getStats(route).getAvailable());
Assertions.assertEquals(0, this.connManager.getTotalStats().getAvailable());
Assertions.assertEquals(0, this.connManager.getStats(route).getAvailable());
this.connManager.close();
}
@ -264,28 +264,28 @@ public class TestConnectionManagement extends LocalServerTestBase {
final ConnectionEndpoint endpoint1 = leaseRequest1.get(Timeout.ZERO_MILLISECONDS);
this.connManager.connect(endpoint1, null, context);
Assert.assertEquals(1, this.connManager.getTotalStats().getLeased());
Assert.assertEquals(1, this.connManager.getStats(route).getLeased());
Assertions.assertEquals(1, this.connManager.getTotalStats().getLeased());
Assertions.assertEquals(1, this.connManager.getStats(route).getLeased());
// Release, let remain idle for forever
this.connManager.release(endpoint1, null, TimeValue.NEG_ONE_MILLISECOND);
// Released, still active.
Assert.assertEquals(1, this.connManager.getTotalStats().getAvailable());
Assert.assertEquals(1, this.connManager.getStats(route).getAvailable());
Assertions.assertEquals(1, this.connManager.getTotalStats().getAvailable());
Assertions.assertEquals(1, this.connManager.getStats(route).getAvailable());
this.connManager.closeExpired();
// Time has not expired yet.
Assert.assertEquals(1, this.connManager.getTotalStats().getAvailable());
Assert.assertEquals(1, this.connManager.getStats(route).getAvailable());
Assertions.assertEquals(1, this.connManager.getTotalStats().getAvailable());
Assertions.assertEquals(1, this.connManager.getStats(route).getAvailable());
Thread.sleep(150);
this.connManager.closeExpired();
// TTL expired now, connections are destroyed.
Assert.assertEquals(0, this.connManager.getTotalStats().getAvailable());
Assert.assertEquals(0, this.connManager.getStats(route).getAvailable());
Assertions.assertEquals(0, this.connManager.getTotalStats().getAvailable());
Assertions.assertEquals(0, this.connManager.getStats(route).getAvailable());
this.connManager.close();
}

View File

@ -52,7 +52,7 @@ import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.InputStreamEntity;
import org.apache.hc.core5.http.protocol.HttpContext;
import org.apache.hc.core5.http.protocol.HttpProcessor;
import org.junit.Assert;
import org.junit.jupiter.api.Assertions;
import org.junit.Test;
public class TestConnectionReuse extends LocalServerTestBase {
@ -85,7 +85,7 @@ public class TestConnectionReuse extends LocalServerTestBase {
}
// Expect some connection in the pool
Assert.assertTrue(this.connManager.getTotalStats().getAvailable() > 0);
Assertions.assertTrue(this.connManager.getTotalStats().getAvailable() > 0);
}
@Test
@ -121,7 +121,7 @@ public class TestConnectionReuse extends LocalServerTestBase {
}
// Expect some connection in the pool
Assert.assertTrue(this.connManager.getTotalStats().getAvailable() > 0);
Assertions.assertTrue(this.connManager.getTotalStats().getAvailable() > 0);
}
private static class AlwaysCloseConn implements HttpResponseInterceptor {
@ -167,7 +167,7 @@ public class TestConnectionReuse extends LocalServerTestBase {
}
// Expect zero connections in the pool
Assert.assertEquals(0, this.connManager.getTotalStats().getAvailable());
Assertions.assertEquals(0, this.connManager.getTotalStats().getAvailable());
}
@Test
@ -198,7 +198,7 @@ public class TestConnectionReuse extends LocalServerTestBase {
}
// Expect zero connections in the pool
Assert.assertEquals(0, this.connManager.getTotalStats().getAvailable());
Assertions.assertEquals(0, this.connManager.getTotalStats().getAvailable());
}
@Test
@ -216,14 +216,14 @@ public class TestConnectionReuse extends LocalServerTestBase {
return null;
});
Assert.assertEquals(1, this.connManager.getTotalStats().getAvailable());
Assertions.assertEquals(1, this.connManager.getTotalStats().getAvailable());
this.httpclient.execute(target, new HttpGet("/random/2000"), response -> {
EntityUtils.consume(response.getEntity());
return null;
});
Assert.assertEquals(1, this.connManager.getTotalStats().getAvailable());
Assertions.assertEquals(1, this.connManager.getTotalStats().getAvailable());
// Now sleep for 1.1 seconds and let the timeout do its work
Thread.sleep(1100);
@ -232,7 +232,7 @@ public class TestConnectionReuse extends LocalServerTestBase {
return null;
});
Assert.assertEquals(1, this.connManager.getTotalStats().getAvailable());
Assertions.assertEquals(1, this.connManager.getTotalStats().getAvailable());
// Do another request just under the 1 second limit & make
// sure we reuse that connection.
@ -242,7 +242,7 @@ public class TestConnectionReuse extends LocalServerTestBase {
return null;
});
Assert.assertEquals(1, this.connManager.getTotalStats().getAvailable());
Assertions.assertEquals(1, this.connManager.getTotalStats().getAvailable());
}
private static class WorkerThread extends Thread {

View File

@ -56,8 +56,8 @@ import org.apache.hc.core5.http.io.entity.InputStreamEntity;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.http.message.MessageSupport;
import org.apache.hc.core5.http.protocol.HttpContext;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
/**
* Test case for how Content Codings are processed. By default, we want to do the right thing and
@ -93,8 +93,8 @@ public class TestContentCodings extends LocalServerTestBase {
final HttpGet request = new HttpGet("/some-resource");
this.httpclient.execute(target, request, response -> {
Assert.assertEquals(HttpStatus.SC_NO_CONTENT, response.getCode());
Assert.assertNull(response.getEntity());
Assertions.assertEquals(HttpStatus.SC_NO_CONTENT, response.getCode());
Assertions.assertNull(response.getEntity());
return null;
});
}
@ -115,8 +115,8 @@ public class TestContentCodings extends LocalServerTestBase {
final HttpGet request = new HttpGet("/some-resource");
this.httpclient.execute(target, request, response -> {
Assert.assertEquals("The entity text is correctly transported", entityText,
EntityUtils.toString(response.getEntity()));
Assertions.assertEquals(entityText, EntityUtils.toString(response.getEntity()),
"The entity text is correctly transported");
return null;
});
}
@ -137,8 +137,8 @@ public class TestContentCodings extends LocalServerTestBase {
final HttpGet request = new HttpGet("/some-resource");
this.httpclient.execute(target, request, response -> {
Assert.assertEquals("The entity text is correctly transported", entityText,
EntityUtils.toString(response.getEntity()));
Assertions.assertEquals(entityText, EntityUtils.toString(response.getEntity()),
"The entity text is correctly transported");
return null;
});
}
@ -158,8 +158,8 @@ public class TestContentCodings extends LocalServerTestBase {
final HttpGet request = new HttpGet("/some-resource");
this.httpclient.execute(target, request, response -> {
Assert.assertEquals("The entity text is correctly transported", entityText,
EntityUtils.toString(response.getEntity()));
Assertions.assertEquals(entityText, EntityUtils.toString(response.getEntity()),
"The entity text is correctly transported");
return null;
});
}
@ -210,9 +210,9 @@ public class TestContentCodings extends LocalServerTestBase {
for (final WorkerTask workerTask : workers) {
if (workerTask.isFailed()) {
Assert.fail("A worker failed");
Assertions.fail("A worker failed");
}
Assert.assertEquals(entityText, workerTask.getText());
Assertions.assertEquals(entityText, workerTask.getText());
}
}
@ -228,7 +228,7 @@ public class TestContentCodings extends LocalServerTestBase {
this.httpclient.execute(target, request, response -> {
final ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
Assert.assertEquals(entityText, out.toString("utf-8"));
Assertions.assertEquals(entityText, out.toString("utf-8"));
return null;
});
@ -246,7 +246,7 @@ public class TestContentCodings extends LocalServerTestBase {
this.httpclient.execute(target, request, response -> {
final ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
Assert.assertEquals(entityText, out.toString("utf-8"));
Assertions.assertEquals(entityText, out.toString("utf-8"));
return out;
});
}
@ -261,7 +261,7 @@ public class TestContentCodings extends LocalServerTestBase {
final HttpGet request = new HttpGet("/some-resource");
final String response = this.httpclient.execute(target, request, new BasicHttpClientResponseHandler());
Assert.assertEquals("The entity text is correctly transported", entityText, response);
Assertions.assertEquals(entityText, response, "The entity text is correctly transported");
}
@Test
@ -274,7 +274,7 @@ public class TestContentCodings extends LocalServerTestBase {
final HttpGet request = new HttpGet("/some-resource");
final String response = this.httpclient.execute(target, request, new BasicHttpClientResponseHandler());
Assert.assertEquals("The entity text is correctly transported", entityText, response);
Assertions.assertEquals(entityText, response, "The entity text is correctly transported");
}
/**

View File

@ -38,7 +38,7 @@ import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.message.BasicHeader;
import org.junit.Assert;
import org.junit.jupiter.api.Assertions;
import org.junit.Test;
/**
@ -54,7 +54,7 @@ public class TestCookieVirtualHost extends LocalServerTestBase {
switch (n) {
case 1:
// Assert Host is forwarded from URI
Assert.assertEquals("app.mydomain.fr", request
Assertions.assertEquals("app.mydomain.fr", request
.getFirstHeader("Host").getValue());
response.setCode(HttpStatus.SC_OK);
@ -66,24 +66,23 @@ public class TestCookieVirtualHost extends LocalServerTestBase {
case 2:
// Assert Host is still forwarded from URI
Assert.assertEquals("app.mydomain.fr", request
Assertions.assertEquals("app.mydomain.fr", request
.getFirstHeader("Host").getValue());
// We should get our cookie back.
Assert.assertNotNull("We must get a cookie header",
request.getFirstHeader("Cookie"));
Assertions.assertNotNull(request.getFirstHeader("Cookie"), "We must get a cookie header");
response.setCode(HttpStatus.SC_OK);
break;
case 3:
// Assert Host is forwarded from URI
Assert.assertEquals("app.mydomain.fr", request
Assertions.assertEquals("app.mydomain.fr", request
.getFirstHeader("Host").getValue());
response.setCode(HttpStatus.SC_OK);
break;
default:
Assert.fail("Unexpected value: " + n);
Assertions.fail("Unexpected value: " + n);
break;
}
});
@ -104,9 +103,9 @@ public class TestCookieVirtualHost extends LocalServerTestBase {
// We should have one cookie set on domain.
final List<Cookie> cookies = cookieStore.getCookies();
Assert.assertNotNull(cookies);
Assert.assertEquals(1, cookies.size());
Assert.assertEquals("name1", cookies.get(0).getName());
Assertions.assertNotNull(cookies);
Assertions.assertEquals(1, cookies.size());
Assertions.assertEquals("name1", cookies.get(0).getName());
// Second request : send the cookie back.
final HttpGet request2 = new HttpGet(new URI("http://app.mydomain.fr"));

View File

@ -43,8 +43,8 @@ import org.apache.hc.core5.http.impl.io.DefaultBHttpServerConnection;
import org.apache.hc.core5.http.io.HttpConnectionFactory;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class TestMalformedServerResponse {
@ -98,13 +98,13 @@ public class TestMalformedServerResponse {
try (final CloseableHttpClient httpclient = HttpClientBuilder.create().build()) {
final HttpGet get1 = new HttpGet("/nostuff");
httpclient.execute(target, get1, response -> {
Assert.assertEquals(HttpStatus.SC_NO_CONTENT, response.getCode());
Assertions.assertEquals(HttpStatus.SC_NO_CONTENT, response.getCode());
EntityUtils.consume(response.getEntity());
return null;
});
final HttpGet get2 = new HttpGet("/stuff");
httpclient.execute(target, get2, response -> {
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
EntityUtils.consume(response.getEntity());
return null;
});

View File

@ -45,7 +45,7 @@ import org.apache.hc.core5.http.io.HttpRequestHandler;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.http.protocol.HttpContext;
import org.junit.Assert;
import org.junit.jupiter.api.Assertions;
import org.junit.Test;
/**
@ -81,22 +81,22 @@ public class TestMinimalClientRequestExecution extends LocalServerTestBase {
final HttpGet request = new HttpGet("/");
this.httpclient.execute(target, request, context, response -> {
EntityUtils.consume(response.getEntity());
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
return null;
});
final HttpRequest reqWrapper = context.getRequest();
Assert.assertNotNull(reqWrapper);
Assertions.assertNotNull(reqWrapper);
final Header[] headers = reqWrapper.getHeaders();
final Set<String> headerSet = new HashSet<>();
for (final Header header: headers) {
headerSet.add(header.getName().toLowerCase(Locale.ROOT));
}
Assert.assertEquals(3, headerSet.size());
Assert.assertTrue(headerSet.contains("connection"));
Assert.assertTrue(headerSet.contains("host"));
Assert.assertTrue(headerSet.contains("user-agent"));
Assertions.assertEquals(3, headerSet.size());
Assertions.assertTrue(headerSet.contains("connection"));
Assertions.assertTrue(headerSet.contains("host"));
Assertions.assertTrue(headerSet.contains("user-agent"));
}
}
@ -110,7 +110,7 @@ public class TestMinimalClientRequestExecution extends LocalServerTestBase {
final HttpGet request = new HttpGet("/");
this.httpclient.execute(target, request, response -> {
EntityUtils.consume(response.getEntity());
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
return null;
});
}

View File

@ -26,6 +26,8 @@
*/
package org.apache.hc.client5.testing.sync;
import static org.hamcrest.MatcherAssert.assertThat;
import java.io.IOException;
import java.net.URI;
import java.util.Collections;
@ -62,8 +64,7 @@ import org.apache.hc.core5.http.message.BasicHeader;
import org.apache.hc.core5.http.protocol.HttpContext;
import org.apache.hc.core5.net.URIBuilder;
import org.hamcrest.CoreMatchers;
import org.hamcrest.MatcherAssert;
import org.junit.Assert;
import org.junit.jupiter.api.Assertions;
import org.junit.Test;
/**
@ -80,17 +81,17 @@ public class TestRedirects extends LocalServerTestBase {
final HttpClientContext context = HttpClientContext.create();
final HttpGet httpget = new HttpGet("/oldlocation/100");
this.httpclient.execute(target, httpget, context, response -> {
Assert.assertEquals(HttpStatus.SC_MULTIPLE_CHOICES, response.getCode());
Assertions.assertEquals(HttpStatus.SC_MULTIPLE_CHOICES, response.getCode());
EntityUtils.consume(response.getEntity());
return null;
});
final HttpRequest reqWrapper = context.getRequest();
Assert.assertEquals(new URIBuilder().setHttpHost(target).setPath("/oldlocation/100").build(),
Assertions.assertEquals(new URIBuilder().setHttpHost(target).setPath("/oldlocation/100").build(),
reqWrapper.getUri());
final RedirectLocations redirects = context.getRedirectLocations();
Assert.assertNotNull(redirects);
Assert.assertEquals(0, redirects.size());
Assertions.assertNotNull(redirects);
Assertions.assertEquals(0, redirects.size());
}
@Test
@ -103,18 +104,18 @@ public class TestRedirects extends LocalServerTestBase {
final HttpClientContext context = HttpClientContext.create();
final HttpGet httpget = new HttpGet("/oldlocation/100");
this.httpclient.execute(target, httpget, context, response -> {
Assert.assertEquals(HttpStatus.SC_MULTIPLE_CHOICES, response.getCode());
Assertions.assertEquals(HttpStatus.SC_MULTIPLE_CHOICES, response.getCode());
EntityUtils.consume(response.getEntity());
return null;
});
final HttpRequest reqWrapper = context.getRequest();
Assert.assertEquals(new URIBuilder().setHttpHost(target).setPath("/oldlocation/100").build(),
Assertions.assertEquals(new URIBuilder().setHttpHost(target).setPath("/oldlocation/100").build(),
reqWrapper.getUri());
final RedirectLocations redirects = context.getRedirectLocations();
Assert.assertNotNull(redirects);
Assert.assertEquals(0, redirects.size());
Assertions.assertNotNull(redirects);
Assertions.assertEquals(0, redirects.size());
}
@Test
@ -128,21 +129,21 @@ public class TestRedirects extends LocalServerTestBase {
final HttpGet httpget = new HttpGet("/oldlocation/100");
this.httpclient.execute(target, httpget, context, response -> {
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
EntityUtils.consume(response.getEntity());
return null;
});
final HttpRequest reqWrapper = context.getRequest();
Assert.assertEquals(new URIBuilder().setHttpHost(target).setPath("/random/100").build(),
Assertions.assertEquals(new URIBuilder().setHttpHost(target).setPath("/random/100").build(),
reqWrapper.getUri());
final RedirectLocations redirects = context.getRedirectLocations();
Assert.assertNotNull(redirects);
Assert.assertEquals(1, redirects.size());
Assertions.assertNotNull(redirects);
Assertions.assertEquals(1, redirects.size());
final URI redirect = new URIBuilder().setHttpHost(target).setPath("/random/100").build();
Assert.assertTrue(redirects.contains(redirect));
Assertions.assertTrue(redirects.contains(redirect));
}
@Test
@ -156,13 +157,13 @@ public class TestRedirects extends LocalServerTestBase {
final HttpGet httpget = new HttpGet("/oldlocation/50");
this.httpclient.execute(target, httpget, context, response -> {
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
EntityUtils.consume(response.getEntity());
return null;
});
final HttpRequest reqWrapper = context.getRequest();
Assert.assertEquals(new URIBuilder().setHttpHost(target).setPath("/random/50").build(),
Assertions.assertEquals(new URIBuilder().setHttpHost(target).setPath("/random/50").build(),
reqWrapper.getUri());
}
@ -186,8 +187,8 @@ public class TestRedirects extends LocalServerTestBase {
this.httpclient.execute(target, httpget, context, response -> {
final HttpRequest reqWrapper = context.getRequest();
Assert.assertEquals(HttpStatus.SC_MOVED_TEMPORARILY, response.getCode());
Assert.assertEquals("/oldlocation/100", reqWrapper.getRequestUri());
Assertions.assertEquals(HttpStatus.SC_MOVED_TEMPORARILY, response.getCode());
Assertions.assertEquals("/oldlocation/100", reqWrapper.getRequestUri());
EntityUtils.consume(response.getEntity());
return null;
@ -205,13 +206,13 @@ public class TestRedirects extends LocalServerTestBase {
final HttpGet httpget = new HttpGet("/oldlocation/123");
this.httpclient.execute(target, httpget, context, response -> {
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
EntityUtils.consume(response.getEntity());
return null;
});
final HttpRequest reqWrapper = context.getRequest();
Assert.assertEquals(new URIBuilder().setHttpHost(target).setPath("/random/123").build(),
Assertions.assertEquals(new URIBuilder().setHttpHost(target).setPath("/random/123").build(),
reqWrapper.getUri());
}
@ -229,18 +230,18 @@ public class TestRedirects extends LocalServerTestBase {
final HttpGet httpget = new HttpGet("/oldlocation/stuff");
this.httpclient.execute(target, httpget, context, response -> {
Assert.assertEquals(HttpStatus.SC_NOT_MODIFIED, response.getCode());
Assertions.assertEquals(HttpStatus.SC_NOT_MODIFIED, response.getCode());
EntityUtils.consume(response.getEntity());
return null;
});
final HttpRequest reqWrapper = context.getRequest();
Assert.assertEquals(new URIBuilder().setHttpHost(target).setPath("/oldlocation/stuff").build(),
Assertions.assertEquals(new URIBuilder().setHttpHost(target).setPath("/oldlocation/stuff").build(),
reqWrapper.getUri());
final RedirectLocations redirects = context.getRedirectLocations();
Assert.assertNotNull(redirects);
Assert.assertEquals(0, redirects.size());
Assertions.assertNotNull(redirects);
Assertions.assertEquals(0, redirects.size());
}
@Test
@ -257,18 +258,18 @@ public class TestRedirects extends LocalServerTestBase {
final HttpGet httpget = new HttpGet("/oldlocation/stuff");
this.httpclient.execute(target, httpget, context, response -> {
Assert.assertEquals(HttpStatus.SC_USE_PROXY, response.getCode());
Assertions.assertEquals(HttpStatus.SC_USE_PROXY, response.getCode());
EntityUtils.consume(response.getEntity());
return null;
});
final HttpRequest reqWrapper = context.getRequest();
Assert.assertEquals(new URIBuilder().setHttpHost(target).setPath("/oldlocation/stuff").build(),
Assertions.assertEquals(new URIBuilder().setHttpHost(target).setPath("/oldlocation/stuff").build(),
reqWrapper.getUri());
final RedirectLocations redirects = context.getRedirectLocations();
Assert.assertNotNull(redirects);
Assert.assertEquals(0, redirects.size());
Assertions.assertNotNull(redirects);
Assertions.assertEquals(0, redirects.size());
}
@Test
@ -282,13 +283,13 @@ public class TestRedirects extends LocalServerTestBase {
final HttpGet httpget = new HttpGet("/oldlocation/123");
this.httpclient.execute(target, httpget, context, response -> {
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
EntityUtils.consume(response.getEntity());
return null;
});
final HttpRequest reqWrapper = context.getRequest();
Assert.assertEquals(new URIBuilder().setHttpHost(target).setPath("/random/123").build(),
Assertions.assertEquals(new URIBuilder().setHttpHost(target).setPath("/random/123").build(),
reqWrapper.getUri());
}
@ -306,9 +307,9 @@ public class TestRedirects extends LocalServerTestBase {
final HttpGet httpget = new HttpGet("/circular-oldlocation/123");
httpget.setConfig(config);
final ClientProtocolException exception = Assert.assertThrows(ClientProtocolException.class, () ->
final ClientProtocolException exception = Assertions.assertThrows(ClientProtocolException.class, () ->
this.httpclient.execute(target, httpget, response -> null));
Assert.assertTrue(exception.getCause() instanceof RedirectException);
Assertions.assertTrue(exception.getCause() instanceof RedirectException);
}
@Test
@ -324,9 +325,9 @@ public class TestRedirects extends LocalServerTestBase {
final HttpGet httpget = new HttpGet("/circular-oldlocation/123");
httpget.setConfig(config);
final ClientProtocolException exception = Assert.assertThrows(ClientProtocolException.class, () ->
final ClientProtocolException exception = Assertions.assertThrows(ClientProtocolException.class, () ->
this.httpclient.execute(target, httpget, response -> null));
Assert.assertTrue(exception.getCause() instanceof CircularRedirectException);
Assertions.assertTrue(exception.getCause() instanceof CircularRedirectException);
}
@Test
@ -341,15 +342,15 @@ public class TestRedirects extends LocalServerTestBase {
httppost.setEntity(new StringEntity("stuff"));
this.httpclient.execute(target, httppost, context, response -> {
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
EntityUtils.consume(response.getEntity());
return null;
});
final HttpRequest reqWrapper = context.getRequest();
Assert.assertEquals(new URIBuilder().setHttpHost(target).setPath("/echo/stuff").build(),
Assertions.assertEquals(new URIBuilder().setHttpHost(target).setPath("/echo/stuff").build(),
reqWrapper.getUri());
Assert.assertEquals("GET", reqWrapper.getMethod());
Assertions.assertEquals("GET", reqWrapper.getMethod());
}
@Test
@ -369,13 +370,13 @@ public class TestRedirects extends LocalServerTestBase {
final HttpGet httpget = new HttpGet("/oldlocation/stuff");
this.httpclient.execute(target, httpget, context, response -> {
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
EntityUtils.consume(response.getEntity());
return null;
});
final HttpRequest reqWrapper = context.getRequest();
Assert.assertEquals(new URIBuilder().setHttpHost(target).setPath("/random/100").build(),
Assertions.assertEquals(new URIBuilder().setHttpHost(target).setPath("/random/100").build(),
reqWrapper.getUri());
}
@ -397,13 +398,13 @@ public class TestRedirects extends LocalServerTestBase {
final HttpGet httpget = new HttpGet("/random/oldlocation");
this.httpclient.execute(target, httpget, context, response -> {
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
EntityUtils.consume(response.getEntity());
return null;
});
final HttpRequest reqWrapper = context.getRequest();
Assert.assertEquals(new URIBuilder().setHttpHost(target).setPath("/random/100").build(),
Assertions.assertEquals(new URIBuilder().setHttpHost(target).setPath("/random/100").build(),
reqWrapper.getUri());
}
@ -422,9 +423,9 @@ public class TestRedirects extends LocalServerTestBase {
final HttpGet httpget = new HttpGet("/oldlocation");
final ClientProtocolException exception = Assert.assertThrows(ClientProtocolException.class, () ->
final ClientProtocolException exception = Assertions.assertThrows(ClientProtocolException.class, () ->
this.httpclient.execute(target, httpget, response -> null));
MatcherAssert.assertThat(exception.getCause(), CoreMatchers.instanceOf(HttpException.class));
assertThat(exception.getCause(), CoreMatchers.instanceOf(HttpException.class));
}
@Test
@ -442,9 +443,9 @@ public class TestRedirects extends LocalServerTestBase {
final HttpGet httpget = new HttpGet("/oldlocation");
final ClientProtocolException exception = Assert.assertThrows(ClientProtocolException.class, () ->
final ClientProtocolException exception = Assertions.assertThrows(ClientProtocolException.class, () ->
this.httpclient.execute(target, httpget, response -> null));
MatcherAssert.assertThat(exception.getCause(), CoreMatchers.instanceOf(ProtocolException.class));
assertThat(exception.getCause(), CoreMatchers.instanceOf(ProtocolException.class));
}
@Test
@ -466,17 +467,17 @@ public class TestRedirects extends LocalServerTestBase {
final HttpGet httpget = new HttpGet("/oldlocation/100");
this.httpclient.execute(target, httpget, context, response -> {
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
EntityUtils.consume(response.getEntity());
return null;
});
final HttpRequest reqWrapper = context.getRequest();
Assert.assertEquals(new URIBuilder().setHttpHost(target).setPath("/random/100").build(),
Assertions.assertEquals(new URIBuilder().setHttpHost(target).setPath("/random/100").build(),
reqWrapper.getUri());
final Header[] headers = reqWrapper.getHeaders("Cookie");
Assert.assertEquals("There can only be one (cookie)", 1, headers.length);
Assertions.assertEquals(1, headers.length, "There can only be one (cookie)");
}
@Test
@ -492,17 +493,17 @@ public class TestRedirects extends LocalServerTestBase {
final HttpGet httpget = new HttpGet("/oldlocation/100");
this.httpclient.execute(target, httpget, context, response -> {
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
EntityUtils.consume(response.getEntity());
return null;
});
final HttpRequest reqWrapper = context.getRequest();
Assert.assertEquals(new URIBuilder().setHttpHost(target).setPath("/random/100").build(),
Assertions.assertEquals(new URIBuilder().setHttpHost(target).setPath("/random/100").build(),
reqWrapper.getUri());
final Header header = reqWrapper.getFirstHeader(HttpHeaders.USER_AGENT);
Assert.assertEquals("my-test-client", header.getValue());
Assertions.assertEquals("my-test-client", header.getValue());
}
@Test
@ -537,18 +538,18 @@ public class TestRedirects extends LocalServerTestBase {
final HttpGet httpget = new HttpGet("/oldlocation/100");
this.httpclient.execute(target, httpget, context, response -> {
Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
EntityUtils.consume(response.getEntity());
return null;
});
final HttpRequest reqWrapper = context.getRequest();
Assert.assertEquals(new URIBuilder().setHttpHost(target).setPath("/random/100").build(),
Assertions.assertEquals(new URIBuilder().setHttpHost(target).setPath("/random/100").build(),
reqWrapper.getUri());
MatcherAssert.assertThat(values.poll(), CoreMatchers.equalTo("gzip, x-gzip, deflate"));
MatcherAssert.assertThat(values.poll(), CoreMatchers.equalTo("gzip, x-gzip, deflate"));
MatcherAssert.assertThat(values.poll(), CoreMatchers.nullValue());
assertThat(values.poll(), CoreMatchers.equalTo("gzip, x-gzip, deflate"));
assertThat(values.poll(), CoreMatchers.equalTo("gzip, x-gzip, deflate"));
assertThat(values.poll(), CoreMatchers.nullValue());
}
}

View File

@ -56,7 +56,7 @@ import org.apache.hc.core5.http.protocol.HttpContext;
import org.ietf.jgss.GSSContext;
import org.ietf.jgss.GSSManager;
import org.ietf.jgss.GSSName;
import org.junit.Assert;
import org.junit.jupiter.api.Assertions;
import org.junit.Test;
import org.mockito.ArgumentMatchers;
import org.mockito.Mockito;
@ -170,7 +170,7 @@ public class TestSPNegoScheme extends LocalServerTestBase {
final HttpGet httpget = new HttpGet(s);
this.httpclient.execute(target, httpget, response -> {
EntityUtils.consume(response.getEntity());
Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getCode());
Assertions.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getCode());
return null;
});
}
@ -202,7 +202,7 @@ public class TestSPNegoScheme extends LocalServerTestBase {
final HttpGet httpget = new HttpGet(s);
this.httpclient.execute(target, httpget, response -> {
EntityUtils.consume(response.getEntity());
Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getCode());
Assertions.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getCode());
return null;
});

View File

@ -27,6 +27,8 @@
package org.apache.hc.client5.testing.sync;
import static org.hamcrest.MatcherAssert.assertThat;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
@ -56,10 +58,9 @@ import org.apache.hc.core5.ssl.SSLContexts;
import org.apache.hc.core5.ssl.TrustStrategy;
import org.apache.hc.core5.util.TimeValue;
import org.hamcrest.CoreMatchers;
import org.hamcrest.MatcherAssert;
import org.junit.After;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
/**
* Unit tests for {@link SSLConnectionSocketFactory}.
@ -68,7 +69,7 @@ public class TestSSLSocketFactory {
private HttpServer server;
@After
@AfterEach
public void shutDown() throws Exception {
if (this.server != null) {
this.server.close(CloseMode.GRACEFUL);
@ -116,8 +117,8 @@ public class TestSSLSocketFactory {
context)) {
final SSLSession sslsession = sslSocket.getSession();
Assert.assertNotNull(sslsession);
Assert.assertTrue(hostVerifier.isFired());
Assertions.assertNotNull(sslsession);
Assertions.assertTrue(hostVerifier.isFired());
}
}
}
@ -147,7 +148,7 @@ public class TestSSLSocketFactory {
context)) {
final SSLSession sslsession = sslSocket.getSession();
Assert.assertNotNull(sslsession);
Assertions.assertNotNull(sslsession);
}
}
}
@ -177,8 +178,8 @@ public class TestSSLSocketFactory {
context)) {
final SSLSession sslsession = sslSocket.getSession();
Assert.assertNotNull(sslsession);
Assert.assertTrue(hostVerifier.isFired());
Assertions.assertNotNull(sslsession);
Assertions.assertTrue(hostVerifier.isFired());
}
}
}
@ -200,7 +201,7 @@ public class TestSSLSocketFactory {
try (final Socket socket = socketFactory.createSocket(context)) {
final InetSocketAddress remoteAddress = new InetSocketAddress("localhost", this.server.getLocalPort());
final HttpHost target = new HttpHost("https", "localhost", this.server.getLocalPort());
Assert.assertThrows(IOException.class, () -> {
Assertions.assertThrows(IOException.class, () -> {
try (final SSLSocket sslSocket = (SSLSocket) socketFactory.connectSocket(
TimeValue.ZERO_MILLISECONDS,
socket, target,
@ -209,8 +210,8 @@ public class TestSSLSocketFactory {
context)) {
final SSLSession sslsession = sslSocket.getSession();
Assert.assertNotNull(sslsession);
Assert.assertTrue(hostVerifier.isFired());
Assertions.assertNotNull(sslsession);
Assertions.assertTrue(hostVerifier.isFired());
sslSocket.getInputStream().read();
}
});
@ -236,7 +237,7 @@ public class TestSSLSocketFactory {
try (final Socket socket = socketFactory.createSocket(context)) {
final InetSocketAddress remoteAddress = new InetSocketAddress("localhost", this.server.getLocalPort());
final HttpHost target = new HttpHost("https", "localhost", this.server.getLocalPort());
Assert.assertThrows(SSLException.class, () -> {
Assertions.assertThrows(SSLException.class, () -> {
try (final SSLSocket sslSocket = (SSLSocket) socketFactory.connectSocket(
TimeValue.ZERO_MILLISECONDS, socket, target, remoteAddress, null, context)) {
// empty for now
@ -306,7 +307,7 @@ public class TestSSLSocketFactory {
try (final Socket socket = socketFactory.createSocket(context)) {
final InetSocketAddress remoteAddress = new InetSocketAddress("localhost", this.server.getLocalPort());
final HttpHost target = new HttpHost("https", "localhost", this.server.getLocalPort());
Assert.assertThrows(IOException.class, () ->
Assertions.assertThrows(IOException.class, () ->
socketFactory.connectSocket(
TimeValue.ZERO_MILLISECONDS, socket, target, remoteAddress, null, context));
}
@ -332,9 +333,9 @@ public class TestSSLSocketFactory {
"SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5"
};
for (final String cipherSuite : weakCiphersSuites) {
final Exception exception = Assert.assertThrows(Exception.class, () ->
final Exception exception = Assertions.assertThrows(Exception.class, () ->
testWeakCipherDisabledByDefault(cipherSuite));
MatcherAssert.assertThat(exception, CoreMatchers.anyOf(
assertThat(exception, CoreMatchers.anyOf(
CoreMatchers.instanceOf(IOException.class),
CoreMatchers.instanceOf(IllegalArgumentException.class)));
}

View File

@ -43,7 +43,7 @@ import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.http.protocol.BasicHttpContext;
import org.apache.hc.core5.http.protocol.HttpContext;
import org.junit.Assert;
import org.junit.jupiter.api.Assertions;
import org.junit.Test;
/**
@ -108,14 +108,14 @@ public class TestStatefulConnManagement extends LocalServerTestBase {
if (ex != null) {
throw ex;
}
Assert.assertEquals(requestCount, worker.getCount());
Assertions.assertEquals(requestCount, worker.getCount());
}
for (final HttpContext context : contexts) {
final String state0 = (String) context.getAttribute("r0");
Assert.assertNotNull(state0);
Assertions.assertNotNull(state0);
for (int r = 1; r < requestCount; r++) {
Assert.assertEquals(state0, context.getAttribute("r" + r));
Assertions.assertEquals(state0, context.getAttribute("r" + r));
}
}

View File

@ -26,6 +26,8 @@
*/
package org.apache.hc.client5.testing.sync;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import org.apache.hc.client5.http.auth.AuthSchemeFactory;
import org.apache.hc.client5.http.auth.StandardAuthScheme;
import org.apache.hc.client5.http.classic.methods.HttpGet;
@ -41,13 +43,15 @@ import org.apache.hc.core5.http.config.RegistryBuilder;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.junit.Assume;
import org.junit.Test;
import org.junit.jupiter.api.Timeout;
/**
* Unit tests for Windows negotiate authentication.
*/
public class TestWindowsNegotiateScheme extends LocalServerTestBase {
@Test(timeout=30000) // this timeout (in ms) needs to be extended if you're actively debugging the code
@Test // this timeout (in ms) needs to be extended if you're actively debugging the code
@Timeout(value = 30000, unit = MILLISECONDS)
public void testNoInfiniteLoopOnSPNOutsideDomain() throws Exception {
this.server.registerHandler("/", (request, response, context) -> {
response.addHeader(HttpHeaders.WWW_AUTHENTICATE, StandardAuthScheme.SPNEGO);

View File

@ -74,8 +74,13 @@
<artifactId>jna-platform</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-migrationsupport</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

View File

@ -82,8 +82,13 @@
<artifactId>commons-codec</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest</artifactId>
<scope>test</scope>
</dependency>
<dependency>

View File

@ -31,8 +31,8 @@ import java.io.IOException;
import java.net.InetAddress;
import org.apache.hc.core5.http.HttpHost;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
/**
* Unit tests for exceptions.
@ -43,14 +43,14 @@ public class ConnectExceptionSupportTest {
@Test
public void testConnectTimeoutExceptionFromNullMessageAndHost() {
final ConnectTimeoutException ctx = ConnectExceptionSupport.createConnectTimeoutException(null, null);
Assert.assertEquals("Connect to remote endpoint timed out", ctx.getMessage());
Assertions.assertEquals("Connect to remote endpoint timed out", ctx.getMessage());
}
@Test
public void testConnectTimeoutExceptionFromCause() {
final IOException cause = new IOException("something awful");
final ConnectTimeoutException ctx = ConnectExceptionSupport.createConnectTimeoutException(cause, null);
Assert.assertEquals("Connect to remote endpoint failed: something awful", ctx.getMessage());
Assertions.assertEquals("Connect to remote endpoint failed: something awful", ctx.getMessage());
}
@Test
@ -58,7 +58,7 @@ public class ConnectExceptionSupportTest {
final HttpHost target = new HttpHost("localhost");
final IOException cause = new IOException();
final ConnectTimeoutException ctx = ConnectExceptionSupport.createConnectTimeoutException(cause, target);
Assert.assertEquals("Connect to http://localhost timed out", ctx.getMessage());
Assertions.assertEquals("Connect to http://localhost timed out", ctx.getMessage());
}
@Test
@ -67,21 +67,21 @@ public class ConnectExceptionSupportTest {
final InetAddress remoteAddress = InetAddress.getByAddress(new byte[] {1,2,3,4});
final IOException cause = new IOException();
final ConnectTimeoutException ctx = ConnectExceptionSupport.createConnectTimeoutException(cause, target, remoteAddress);
Assert.assertEquals("Connect to http://localhost [/1.2.3.4] timed out", ctx.getMessage());
Assertions.assertEquals("Connect to http://localhost [/1.2.3.4] timed out", ctx.getMessage());
}
@Test
public void testHttpHostConnectExceptionFromNullCause() {
final HttpHostConnectException ctx = ConnectExceptionSupport.createHttpHostConnectException(null, null,
(InetAddress [])null);
Assert.assertEquals("Connect to remote endpoint refused", ctx.getMessage());
Assertions.assertEquals("Connect to remote endpoint refused", ctx.getMessage());
}
@Test
public void testHttpHostConnectExceptionFromCause() {
final IOException cause = new IOException("something awful");
final HttpHostConnectException ctx = ConnectExceptionSupport.createHttpHostConnectException(cause, null);
Assert.assertEquals("Connect to remote endpoint failed: something awful", ctx.getMessage());
Assertions.assertEquals("Connect to remote endpoint failed: something awful", ctx.getMessage());
}
@Test
@ -89,7 +89,7 @@ public class ConnectExceptionSupportTest {
final HttpHost target = new HttpHost("localhost");
final IOException cause = new IOException();
final HttpHostConnectException ctx = ConnectExceptionSupport.createHttpHostConnectException(cause, target);
Assert.assertEquals("Connect to http://localhost refused", ctx.getMessage());
Assertions.assertEquals("Connect to http://localhost refused", ctx.getMessage());
}
@Test
@ -100,7 +100,7 @@ public class ConnectExceptionSupportTest {
final IOException cause = new IOException();
final HttpHostConnectException ctx = ConnectExceptionSupport.createHttpHostConnectException(cause, target,
remoteAddress1, remoteAddress2);
Assert.assertEquals("Connect to http://localhost [/1.2.3.4, /5.6.7.8] refused", ctx.getMessage());
Assertions.assertEquals("Connect to http://localhost [/1.2.3.4, /5.6.7.8] refused", ctx.getMessage());
}
}

View File

@ -29,7 +29,6 @@ package org.apache.hc.client5.http;
import org.apache.hc.core5.http.ContentType;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.hamcrest.Factory;
import org.hamcrest.Matcher;
public class ContentTypeMatcher extends BaseMatcher<ContentType> {
@ -54,7 +53,6 @@ public class ContentTypeMatcher extends BaseMatcher<ContentType> {
description.appendText("same MIME type as ").appendValue(expectedContentType);
}
@Factory
public static Matcher<ContentType> sameMimeType(final ContentType contentType) {
return new ContentTypeMatcher(contentType);
}

View File

@ -30,7 +30,6 @@ import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.util.LangUtils;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.hamcrest.Factory;
import org.hamcrest.Matcher;
public class HeaderMatcher extends BaseMatcher<Header> {
@ -57,7 +56,6 @@ public class HeaderMatcher extends BaseMatcher<Header> {
description.appendText("same header as ").appendValue(headerValue).appendText(": ").appendValue(headerValue);
}
@Factory
public static Matcher<Header> same(final String headerName, final Object headerValue) {
return new HeaderMatcher(headerName, headerValue);
}

View File

@ -30,7 +30,6 @@ import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.util.LangUtils;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.hamcrest.Factory;
import org.hamcrest.Matcher;
public class HeadersMatcher extends BaseMatcher<Header[]> {
@ -65,7 +64,6 @@ public class HeadersMatcher extends BaseMatcher<Header[]> {
description.appendText("same headers as ").appendValueList("[", ", ", "]", expectedHeaders);
}
@Factory
public static Matcher<Header[]> same(final Header... headers) {
return new HeadersMatcher(headers);
}

View File

@ -30,7 +30,6 @@ import org.apache.hc.core5.http.NameValuePair;
import org.apache.hc.core5.util.LangUtils;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.hamcrest.Factory;
import org.hamcrest.Matcher;
public class NameValuePairMatcher extends BaseMatcher<NameValuePair> {
@ -57,12 +56,10 @@ public class NameValuePairMatcher extends BaseMatcher<NameValuePair> {
description.appendText("equals ").appendValue(name).appendText("=").appendValue(value);
}
@Factory
public static Matcher<NameValuePair> equals(final String name, final String value) {
return new NameValuePairMatcher(name, value);
}
@Factory
public static Matcher<NameValuePair> same(final String name, final String value) {
return new NameValuePairMatcher(name, value);
}

View File

@ -35,7 +35,6 @@ import org.apache.hc.core5.http.NameValuePair;
import org.apache.hc.core5.util.LangUtils;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.hamcrest.Factory;
import org.hamcrest.Matcher;
public class NameValuePairsMatcher extends BaseMatcher<Collection<? extends NameValuePair>> {
@ -74,12 +73,10 @@ public class NameValuePairsMatcher extends BaseMatcher<Collection<? extends Name
description.appendText("same name/value pairs as ").appendValueList("[", ", ", "]", expectedNameValuePairList);
}
@Factory
public static Matcher<Collection<? extends NameValuePair>> same(final Collection<? extends NameValuePair> nameValuePairs) {
return new NameValuePairsMatcher(new ArrayList<>(nameValuePairs));
}
@Factory
public static Matcher<Collection<? extends NameValuePair>> same(final NameValuePair... nameValuePairs) {
return new NameValuePairsMatcher(Arrays.asList(nameValuePairs));
}

View File

@ -27,6 +27,8 @@
package org.apache.hc.client5.http.async.methods;
import static org.hamcrest.MatcherAssert.assertThat;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
@ -42,9 +44,8 @@ import org.apache.hc.core5.http.message.BasicHeader;
import org.apache.hc.core5.http.message.BasicNameValuePair;
import org.apache.hc.core5.net.URIAuthority;
import org.hamcrest.CoreMatchers;
import org.hamcrest.MatcherAssert;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
/**
* Simple tests for {@link SimpleResponseBuilder} and {@link SimpleRequestBuilder}.
@ -54,153 +55,153 @@ public class TestSimpleMessageBuilders {
@Test
public void testResponseBasics() throws Exception {
final SimpleResponseBuilder builder = SimpleResponseBuilder.create(200);
Assert.assertEquals(200, builder.getStatus());
Assert.assertNull(builder.getHeaders());
Assert.assertNull(builder.getVersion());
Assertions.assertEquals(200, builder.getStatus());
Assertions.assertNull(builder.getHeaders());
Assertions.assertNull(builder.getVersion());
final SimpleHttpResponse r1 = builder.build();
Assert.assertNotNull(r1);
Assert.assertEquals(200, r1.getCode());
Assert.assertNull(r1.getVersion());
Assertions.assertNotNull(r1);
Assertions.assertEquals(200, r1.getCode());
Assertions.assertNull(r1.getVersion());
builder.setStatus(500);
builder.setVersion(HttpVersion.HTTP_1_0);
Assert.assertEquals(500, builder.getStatus());
Assert.assertEquals(HttpVersion.HTTP_1_0, builder.getVersion());
Assertions.assertEquals(500, builder.getStatus());
Assertions.assertEquals(HttpVersion.HTTP_1_0, builder.getVersion());
final SimpleHttpResponse r2 = builder.build();
Assert.assertEquals(500, r2.getCode());
Assert.assertEquals(HttpVersion.HTTP_1_0, r2.getVersion());
Assertions.assertEquals(500, r2.getCode());
Assertions.assertEquals(HttpVersion.HTTP_1_0, r2.getVersion());
builder.addHeader("h1", "v1");
builder.addHeader("h1", "v2");
builder.addHeader("h2", "v2");
MatcherAssert.assertThat(builder.getHeaders(), HeadersMatcher.same(
assertThat(builder.getHeaders(), HeadersMatcher.same(
new BasicHeader("h1", "v1"), new BasicHeader("h1", "v2"), new BasicHeader("h2", "v2")));
MatcherAssert.assertThat(builder.getHeaders("h1"), HeadersMatcher.same(
assertThat(builder.getHeaders("h1"), HeadersMatcher.same(
new BasicHeader("h1", "v1"), new BasicHeader("h1", "v2")));
MatcherAssert.assertThat(builder.getFirstHeader("h1"), HeaderMatcher.same("h1", "v1"));
MatcherAssert.assertThat(builder.getLastHeader("h1"), HeaderMatcher.same("h1", "v2"));
assertThat(builder.getFirstHeader("h1"), HeaderMatcher.same("h1", "v1"));
assertThat(builder.getLastHeader("h1"), HeaderMatcher.same("h1", "v2"));
final SimpleHttpResponse r3 = builder.build();
MatcherAssert.assertThat(r3.getHeaders(), HeadersMatcher.same(
assertThat(r3.getHeaders(), HeadersMatcher.same(
new BasicHeader("h1", "v1"), new BasicHeader("h1", "v2"), new BasicHeader("h2", "v2")));
MatcherAssert.assertThat(r3.getHeaders("h1"), HeadersMatcher.same(
assertThat(r3.getHeaders("h1"), HeadersMatcher.same(
new BasicHeader("h1", "v1"), new BasicHeader("h1", "v2")));
MatcherAssert.assertThat(r3.getFirstHeader("h1"), HeaderMatcher.same("h1", "v1"));
MatcherAssert.assertThat(r3.getLastHeader("h1"), HeaderMatcher.same("h1", "v2"));
assertThat(r3.getFirstHeader("h1"), HeaderMatcher.same("h1", "v1"));
assertThat(r3.getLastHeader("h1"), HeaderMatcher.same("h1", "v2"));
builder.removeHeader(new BasicHeader("h1", "v2"));
MatcherAssert.assertThat(builder.getHeaders("h1"), HeadersMatcher.same(new BasicHeader("h1", "v1")));
MatcherAssert.assertThat(builder.getHeaders(), HeadersMatcher.same(
assertThat(builder.getHeaders("h1"), HeadersMatcher.same(new BasicHeader("h1", "v1")));
assertThat(builder.getHeaders(), HeadersMatcher.same(
new BasicHeader("h1", "v1"), new BasicHeader("h2", "v2")));
final SimpleHttpResponse r4 = builder.build();
MatcherAssert.assertThat(r4.getHeaders("h1"), HeadersMatcher.same(new BasicHeader("h1", "v1")));
MatcherAssert.assertThat(r4.getHeaders(), HeadersMatcher.same(
assertThat(r4.getHeaders("h1"), HeadersMatcher.same(new BasicHeader("h1", "v1")));
assertThat(r4.getHeaders(), HeadersMatcher.same(
new BasicHeader("h1", "v1"), new BasicHeader("h2", "v2")));
builder.removeHeaders("h1");
MatcherAssert.assertThat(builder.getHeaders("h1"), HeadersMatcher.same());
MatcherAssert.assertThat(builder.getHeaders(), HeadersMatcher.same(new BasicHeader("h2", "v2")));
assertThat(builder.getHeaders("h1"), HeadersMatcher.same());
assertThat(builder.getHeaders(), HeadersMatcher.same(new BasicHeader("h2", "v2")));
final SimpleHttpResponse r5 = builder.build();
MatcherAssert.assertThat(r5.getHeaders("h1"), HeadersMatcher.same());
MatcherAssert.assertThat(r5.getHeaders(), HeadersMatcher.same(new BasicHeader("h2", "v2")));
assertThat(r5.getHeaders("h1"), HeadersMatcher.same());
assertThat(r5.getHeaders(), HeadersMatcher.same(new BasicHeader("h2", "v2")));
}
@Test
public void testRequestBasics() throws Exception {
final SimpleRequestBuilder builder = SimpleRequestBuilder.get();
Assert.assertEquals(URI.create("/"), builder.getUri());
Assert.assertEquals("GET", builder.getMethod());
Assert.assertNull(builder.getScheme());
Assert.assertNull(builder.getAuthority());
Assert.assertNull(builder.getPath());
Assert.assertNull(builder.getHeaders());
Assert.assertNull(builder.getVersion());
Assert.assertNull(builder.getCharset());
Assert.assertNull(builder.getParameters());
Assertions.assertEquals(URI.create("/"), builder.getUri());
Assertions.assertEquals("GET", builder.getMethod());
Assertions.assertNull(builder.getScheme());
Assertions.assertNull(builder.getAuthority());
Assertions.assertNull(builder.getPath());
Assertions.assertNull(builder.getHeaders());
Assertions.assertNull(builder.getVersion());
Assertions.assertNull(builder.getCharset());
Assertions.assertNull(builder.getParameters());
final SimpleHttpRequest r1 = builder.build();
Assert.assertNotNull(r1);
Assert.assertEquals("GET", r1.getMethod());
Assert.assertNull(r1.getScheme());
Assert.assertNull(r1.getAuthority());
Assert.assertNull(r1.getPath());
Assert.assertEquals(URI.create("/"), r1.getUri());
Assert.assertNull(r1.getVersion());
Assertions.assertNotNull(r1);
Assertions.assertEquals("GET", r1.getMethod());
Assertions.assertNull(r1.getScheme());
Assertions.assertNull(r1.getAuthority());
Assertions.assertNull(r1.getPath());
Assertions.assertEquals(URI.create("/"), r1.getUri());
Assertions.assertNull(r1.getVersion());
builder.setUri(URI.create("http://host:1234/blah?param=value"));
builder.setVersion(HttpVersion.HTTP_1_1);
Assert.assertEquals("http", builder.getScheme());
Assert.assertEquals(new URIAuthority("host", 1234), builder.getAuthority());
Assert.assertEquals("/blah?param=value", builder.getPath());
Assert.assertEquals(URI.create("http://host:1234/blah?param=value"), builder.getUri());
Assert.assertEquals(HttpVersion.HTTP_1_1, builder.getVersion());
Assertions.assertEquals("http", builder.getScheme());
Assertions.assertEquals(new URIAuthority("host", 1234), builder.getAuthority());
Assertions.assertEquals("/blah?param=value", builder.getPath());
Assertions.assertEquals(URI.create("http://host:1234/blah?param=value"), builder.getUri());
Assertions.assertEquals(HttpVersion.HTTP_1_1, builder.getVersion());
final SimpleHttpRequest r2 = builder.build();
Assert.assertEquals("GET", r2.getMethod());
Assert.assertEquals("http", r2.getScheme());
Assert.assertEquals(new URIAuthority("host", 1234), r2.getAuthority());
Assert.assertEquals("/blah?param=value", r2.getPath());
Assert.assertEquals(URI.create("http://host:1234/blah?param=value"), r2.getUri());
Assert.assertEquals(HttpVersion.HTTP_1_1, builder.getVersion());
Assertions.assertEquals("GET", r2.getMethod());
Assertions.assertEquals("http", r2.getScheme());
Assertions.assertEquals(new URIAuthority("host", 1234), r2.getAuthority());
Assertions.assertEquals("/blah?param=value", r2.getPath());
Assertions.assertEquals(URI.create("http://host:1234/blah?param=value"), r2.getUri());
Assertions.assertEquals(HttpVersion.HTTP_1_1, builder.getVersion());
builder.setCharset(StandardCharsets.US_ASCII);
builder.addParameter("param1", "value1");
builder.addParameter("param2", null);
builder.addParameters(new BasicNameValuePair("param3", "value3"), new BasicNameValuePair("param4", null));
Assert.assertEquals(builder.getParameters(), Arrays.asList(
Assertions.assertEquals(builder.getParameters(), Arrays.asList(
new BasicNameValuePair("param1", "value1"), new BasicNameValuePair("param2", null),
new BasicNameValuePair("param3", "value3"), new BasicNameValuePair("param4", null)
));
Assert.assertEquals(URI.create("http://host:1234/blah?param=value"), builder.getUri());
Assertions.assertEquals(URI.create("http://host:1234/blah?param=value"), builder.getUri());
final SimpleHttpRequest r3 = builder.build();
Assert.assertEquals("GET", r3.getMethod());
Assert.assertEquals("http", r3.getScheme());
Assert.assertEquals(new URIAuthority("host", 1234), r3.getAuthority());
Assert.assertEquals("/blah?param=value&param1=value1&param2&param3=value3&param4", r3.getPath());
Assert.assertEquals(URI.create("http://host:1234/blah?param=value&param1=value1&param2&param3=value3&param4"),
Assertions.assertEquals("GET", r3.getMethod());
Assertions.assertEquals("http", r3.getScheme());
Assertions.assertEquals(new URIAuthority("host", 1234), r3.getAuthority());
Assertions.assertEquals("/blah?param=value&param1=value1&param2&param3=value3&param4", r3.getPath());
Assertions.assertEquals(URI.create("http://host:1234/blah?param=value&param1=value1&param2&param3=value3&param4"),
r3.getUri());
builder.addHeader("h1", "v1");
builder.addHeader("h1", "v2");
builder.addHeader("h2", "v2");
MatcherAssert.assertThat(builder.getHeaders(), HeadersMatcher.same(
assertThat(builder.getHeaders(), HeadersMatcher.same(
new BasicHeader("h1", "v1"), new BasicHeader("h1", "v2"), new BasicHeader("h2", "v2")));
MatcherAssert.assertThat(builder.getHeaders("h1"), HeadersMatcher.same(
assertThat(builder.getHeaders("h1"), HeadersMatcher.same(
new BasicHeader("h1", "v1"), new BasicHeader("h1", "v2")));
MatcherAssert.assertThat(builder.getFirstHeader("h1"), HeaderMatcher.same("h1", "v1"));
MatcherAssert.assertThat(builder.getLastHeader("h1"), HeaderMatcher.same("h1", "v2"));
assertThat(builder.getFirstHeader("h1"), HeaderMatcher.same("h1", "v1"));
assertThat(builder.getLastHeader("h1"), HeaderMatcher.same("h1", "v2"));
final SimpleHttpRequest r4 = builder.build();
MatcherAssert.assertThat(r4.getHeaders(), HeadersMatcher.same(
assertThat(r4.getHeaders(), HeadersMatcher.same(
new BasicHeader("h1", "v1"), new BasicHeader("h1", "v2"), new BasicHeader("h2", "v2")));
MatcherAssert.assertThat(r4.getHeaders("h1"), HeadersMatcher.same(
assertThat(r4.getHeaders("h1"), HeadersMatcher.same(
new BasicHeader("h1", "v1"), new BasicHeader("h1", "v2")));
MatcherAssert.assertThat(r4.getFirstHeader("h1"), HeaderMatcher.same("h1", "v1"));
MatcherAssert.assertThat(r4.getLastHeader("h1"), HeaderMatcher.same("h1", "v2"));
assertThat(r4.getFirstHeader("h1"), HeaderMatcher.same("h1", "v1"));
assertThat(r4.getLastHeader("h1"), HeaderMatcher.same("h1", "v2"));
builder.removeHeader(new BasicHeader("h1", "v2"));
MatcherAssert.assertThat(builder.getHeaders("h1"), HeadersMatcher.same(new BasicHeader("h1", "v1")));
MatcherAssert.assertThat(builder.getHeaders(), HeadersMatcher.same(
assertThat(builder.getHeaders("h1"), HeadersMatcher.same(new BasicHeader("h1", "v1")));
assertThat(builder.getHeaders(), HeadersMatcher.same(
new BasicHeader("h1", "v1"), new BasicHeader("h2", "v2")));
final SimpleHttpRequest r5 = builder.build();
MatcherAssert.assertThat(r5.getHeaders("h1"), HeadersMatcher.same(new BasicHeader("h1", "v1")));
MatcherAssert.assertThat(r5.getHeaders(), HeadersMatcher.same(
assertThat(r5.getHeaders("h1"), HeadersMatcher.same(new BasicHeader("h1", "v1")));
assertThat(r5.getHeaders(), HeadersMatcher.same(
new BasicHeader("h1", "v1"), new BasicHeader("h2", "v2")));
builder.removeHeaders("h1");
MatcherAssert.assertThat(builder.getHeaders("h1"), HeadersMatcher.same());
MatcherAssert.assertThat(builder.getHeaders(), HeadersMatcher.same(new BasicHeader("h2", "v2")));
assertThat(builder.getHeaders("h1"), HeadersMatcher.same());
assertThat(builder.getHeaders(), HeadersMatcher.same(new BasicHeader("h2", "v2")));
final SimpleHttpRequest r6 = builder.build();
MatcherAssert.assertThat(r6.getHeaders("h1"), HeadersMatcher.same());
MatcherAssert.assertThat(r6.getHeaders(), HeadersMatcher.same(new BasicHeader("h2", "v2")));
assertThat(r6.getHeaders("h1"), HeadersMatcher.same());
assertThat(r6.getHeaders(), HeadersMatcher.same(new BasicHeader("h2", "v2")));
}
@Test
@ -212,9 +213,9 @@ public class TestSimpleMessageBuilders {
response.setVersion(HttpVersion.HTTP_2);
final SimpleResponseBuilder builder = SimpleResponseBuilder.copy(response);
Assert.assertEquals(400, builder.getStatus());
Assert.assertEquals(HttpVersion.HTTP_2, builder.getVersion());
MatcherAssert.assertThat(builder.getHeaders(), HeadersMatcher.same(
Assertions.assertEquals(400, builder.getStatus());
Assertions.assertEquals(HttpVersion.HTTP_2, builder.getVersion());
assertThat(builder.getHeaders(), HeadersMatcher.same(
new BasicHeader("h1", "v1"), new BasicHeader("h1", "v2"), new BasicHeader("h2", "v2")));
}
@ -227,12 +228,12 @@ public class TestSimpleMessageBuilders {
request.setVersion(HttpVersion.HTTP_2);
final SimpleRequestBuilder builder = SimpleRequestBuilder.copy(request);
Assert.assertEquals("GET", builder.getMethod());
Assert.assertEquals("https", builder.getScheme());
Assert.assertEquals(new URIAuthority("host", 3456), builder.getAuthority());
Assert.assertEquals("/stuff?blah", builder.getPath());
Assert.assertEquals(HttpVersion.HTTP_2, builder.getVersion());
MatcherAssert.assertThat(builder.getHeaders(), HeadersMatcher.same(
Assertions.assertEquals("GET", builder.getMethod());
Assertions.assertEquals("https", builder.getScheme());
Assertions.assertEquals(new URIAuthority("host", 3456), builder.getAuthority());
Assertions.assertEquals("/stuff?blah", builder.getPath());
Assertions.assertEquals(HttpVersion.HTTP_2, builder.getVersion());
assertThat(builder.getHeaders(), HeadersMatcher.same(
new BasicHeader("h1", "v1"), new BasicHeader("h1", "v2"), new BasicHeader("h2", "v2")));
}
@ -242,16 +243,16 @@ public class TestSimpleMessageBuilders {
builder.addParameter("p1", "v1");
builder.addParameters(new BasicNameValuePair("p2", "v2"), new BasicNameValuePair("p3", "v3"));
builder.addParameter(new BasicNameValuePair("p3", "v3.1"));
Assert.assertEquals("GET", builder.getMethod());
Assert.assertEquals("https", builder.getScheme());
Assert.assertEquals(new URIAuthority("host", 3456), builder.getAuthority());
Assert.assertEquals("/stuff?p0=p0", builder.getPath());
MatcherAssert.assertThat(builder.getParameters(), NameValuePairsMatcher.same(
Assertions.assertEquals("GET", builder.getMethod());
Assertions.assertEquals("https", builder.getScheme());
Assertions.assertEquals(new URIAuthority("host", 3456), builder.getAuthority());
Assertions.assertEquals("/stuff?p0=p0", builder.getPath());
assertThat(builder.getParameters(), NameValuePairsMatcher.same(
new BasicNameValuePair("p1", "v1"), new BasicNameValuePair("p2", "v2"),
new BasicNameValuePair("p3", "v3"), new BasicNameValuePair("p3", "v3.1")));
final SimpleHttpRequest request = builder.build();
MatcherAssert.assertThat(request.getPath(), CoreMatchers.equalTo("/stuff?p0=p0&p1=v1&p2=v2&p3=v3&p3=v3.1"));
Assert.assertNull(request.getBody());
assertThat(request.getPath(), CoreMatchers.equalTo("/stuff?p0=p0&p1=v1&p2=v2&p3=v3&p3=v3.1"));
Assertions.assertNull(request.getBody());
}
@Test
@ -260,19 +261,19 @@ public class TestSimpleMessageBuilders {
builder.addParameter("p1", "v1");
builder.addParameters(new BasicNameValuePair("p2", "v2"), new BasicNameValuePair("p3", "v3"));
builder.addParameter(new BasicNameValuePair("p3", "v3.1"));
Assert.assertEquals("POST", builder.getMethod());
Assert.assertEquals("https", builder.getScheme());
Assert.assertEquals(new URIAuthority("host", 3456), builder.getAuthority());
Assert.assertEquals("/stuff?p0=p0", builder.getPath());
MatcherAssert.assertThat(builder.getParameters(), NameValuePairsMatcher.same(
Assertions.assertEquals("POST", builder.getMethod());
Assertions.assertEquals("https", builder.getScheme());
Assertions.assertEquals(new URIAuthority("host", 3456), builder.getAuthority());
Assertions.assertEquals("/stuff?p0=p0", builder.getPath());
assertThat(builder.getParameters(), NameValuePairsMatcher.same(
new BasicNameValuePair("p1", "v1"), new BasicNameValuePair("p2", "v2"),
new BasicNameValuePair("p3", "v3"), new BasicNameValuePair("p3", "v3.1")));
final SimpleHttpRequest request = builder.build();
MatcherAssert.assertThat(request.getPath(), CoreMatchers.equalTo("/stuff?p0=p0"));
Assert.assertNotNull(request.getBody());
MatcherAssert.assertThat(request.getBody().getContentType(),
assertThat(request.getPath(), CoreMatchers.equalTo("/stuff?p0=p0"));
Assertions.assertNotNull(request.getBody());
assertThat(request.getBody().getContentType(),
ContentTypeMatcher.sameMimeType(ContentType.APPLICATION_FORM_URLENCODED));
MatcherAssert.assertThat(request.getBody().getBodyText(),
assertThat(request.getBody().getBodyText(),
CoreMatchers.equalTo("p1=v1&p2=v2&p3=v3&p3=v3.1"));
}

View File

@ -30,28 +30,28 @@ package org.apache.hc.client5.http.auth;
import java.util.Arrays;
import org.apache.hc.core5.http.message.BasicNameValuePair;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class TestAuthChallenge {
@Test
public void testAuthChallengeWithValue() {
final AuthChallenge authChallenge = new AuthChallenge(ChallengeType.TARGET, StandardAuthScheme.BASIC, "blah", null);
Assert.assertEquals(StandardAuthScheme.BASIC, authChallenge.getSchemeName());
Assert.assertEquals("blah", authChallenge.getValue());
Assert.assertNull(authChallenge.getParams());
Assert.assertEquals(StandardAuthScheme.BASIC + " blah", authChallenge.toString());
Assertions.assertEquals(StandardAuthScheme.BASIC, authChallenge.getSchemeName());
Assertions.assertEquals("blah", authChallenge.getValue());
Assertions.assertNull(authChallenge.getParams());
Assertions.assertEquals(StandardAuthScheme.BASIC + " blah", authChallenge.toString());
}
@Test
public void testAuthChallengeWithParams() {
final AuthChallenge authChallenge = new AuthChallenge(ChallengeType.TARGET, StandardAuthScheme.BASIC, null,
Arrays.asList(new BasicNameValuePair("blah", "this"), new BasicNameValuePair("blah", "that")));
Assert.assertEquals(StandardAuthScheme.BASIC, authChallenge.getSchemeName());
Assert.assertNull(authChallenge.getValue());
Assert.assertNotNull(authChallenge.getParams());
Assert.assertEquals(StandardAuthScheme.BASIC + " [blah=this, blah=that]", authChallenge.toString());
Assertions.assertEquals(StandardAuthScheme.BASIC, authChallenge.getSchemeName());
Assertions.assertNull(authChallenge.getValue());
Assertions.assertNotNull(authChallenge.getParams());
Assertions.assertEquals(StandardAuthScheme.BASIC + " [blah=this, blah=that]", authChallenge.toString());
}
}

View File

@ -27,8 +27,8 @@
package org.apache.hc.client5.http.auth;
import org.apache.hc.core5.http.HttpHost;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
/**
* Tests for {@link org.apache.hc.client5.http.auth.AuthScope}.
@ -38,82 +38,82 @@ public class TestAuthScope {
@Test
public void testBasics() {
final AuthScope authscope = new AuthScope("http", "somehost", 80, "somerealm", "SomeScheme");
Assert.assertEquals("SomeScheme", authscope.getSchemeName());
Assert.assertEquals("http", authscope.getProtocol());
Assert.assertEquals("somehost", authscope.getHost());
Assert.assertEquals(80, authscope.getPort());
Assert.assertEquals("somerealm", authscope.getRealm());
Assert.assertEquals("SomeScheme 'somerealm' http://somehost:80", authscope.toString());
Assertions.assertEquals("SomeScheme", authscope.getSchemeName());
Assertions.assertEquals("http", authscope.getProtocol());
Assertions.assertEquals("somehost", authscope.getHost());
Assertions.assertEquals(80, authscope.getPort());
Assertions.assertEquals("somerealm", authscope.getRealm());
Assertions.assertEquals("SomeScheme 'somerealm' http://somehost:80", authscope.toString());
}
@Test
public void testByOrigin() {
final HttpHost host = new HttpHost("http", "somehost", 8080);
final AuthScope authscope = new AuthScope(host);
Assert.assertNull(authscope.getSchemeName());
Assert.assertEquals("somehost", authscope.getHost());
Assert.assertEquals(8080, authscope.getPort());
Assert.assertNull(authscope.getRealm());
Assert.assertEquals("http", authscope.getProtocol());
Assert.assertEquals("<any auth scheme> <any realm> http://somehost:8080", authscope.toString());
Assertions.assertNull(authscope.getSchemeName());
Assertions.assertEquals("somehost", authscope.getHost());
Assertions.assertEquals(8080, authscope.getPort());
Assertions.assertNull(authscope.getRealm());
Assertions.assertEquals("http", authscope.getProtocol());
Assertions.assertEquals("<any auth scheme> <any realm> http://somehost:8080", authscope.toString());
}
@Test
public void testMixedCaseHostname() {
final AuthScope authscope = new AuthScope("SomeHost", 80);
Assert.assertNull(authscope.getSchemeName());
Assert.assertEquals("somehost", authscope.getHost());
Assert.assertEquals(80, authscope.getPort());
Assert.assertNull(authscope.getRealm());
Assert.assertEquals("<any auth scheme> <any realm> <any protocol>://somehost:80", authscope.toString());
Assertions.assertNull(authscope.getSchemeName());
Assertions.assertEquals("somehost", authscope.getHost());
Assertions.assertEquals(80, authscope.getPort());
Assertions.assertNull(authscope.getRealm());
Assertions.assertEquals("<any auth scheme> <any realm> <any protocol>://somehost:80", authscope.toString());
}
@Test
public void testByOriginMixedCaseHostname() throws Exception {
final HttpHost host = new HttpHost("http", "SomeHost", 8080);
final AuthScope authscope = new AuthScope(host);
Assert.assertEquals("somehost", authscope.getHost());
Assertions.assertEquals("somehost", authscope.getHost());
}
@Test
public void testBasicsAllOptional() {
final AuthScope authscope = new AuthScope(null, null, -1, null, null);
Assert.assertNull(authscope.getSchemeName());
Assert.assertNull(authscope.getHost());
Assert.assertEquals(-1, authscope.getPort());
Assert.assertNull(authscope.getRealm());
Assert.assertEquals("<any auth scheme> <any realm> <any protocol>://<any host>:<any port>", authscope.toString());
Assertions.assertNull(authscope.getSchemeName());
Assertions.assertNull(authscope.getHost());
Assertions.assertEquals(-1, authscope.getPort());
Assertions.assertNull(authscope.getRealm());
Assertions.assertEquals("<any auth scheme> <any realm> <any protocol>://<any host>:<any port>", authscope.toString());
}
@Test
public void testScopeMatching() {
final AuthScope authscope1 = new AuthScope("http", "somehost", 80, "somerealm", "somescheme");
final AuthScope authscope2 = new AuthScope("http", "someotherhost", 80, "somerealm", "somescheme");
Assert.assertTrue(authscope1.match(authscope2) < 0);
Assertions.assertTrue(authscope1.match(authscope2) < 0);
int m1 = authscope1.match(new AuthScope(null, null, -1, null, "somescheme"));
int m2 = authscope1.match(new AuthScope(null, null, -1, "somerealm", null));
Assert.assertTrue(m2 > m1);
Assertions.assertTrue(m2 > m1);
m1 = authscope1.match(new AuthScope(null, null, -1, null, "somescheme"));
m2 = authscope1.match(new AuthScope(null, null, -1, "somerealm", null));
Assert.assertTrue(m2 > m1);
Assertions.assertTrue(m2 > m1);
m1 = authscope1.match(new AuthScope(null, null, -1, "somerealm", "somescheme"));
m2 = authscope1.match(new AuthScope(null, null, 80, null, null));
Assert.assertTrue(m2 > m1);
Assertions.assertTrue(m2 > m1);
m1 = authscope1.match(new AuthScope(null, null, 80, "somerealm", "somescheme"));
m2 = authscope1.match(new AuthScope(null, "somehost", -1, null, null));
Assert.assertTrue(m2 > m1);
Assertions.assertTrue(m2 > m1);
m1 = authscope1.match(new AuthScope(null, null, 80, "somerealm", "somescheme"));
m2 = authscope1.match(new AuthScope(null, "somehost", -1, null, null));
Assert.assertTrue(m2 > m1);
Assertions.assertTrue(m2 > m1);
m1 = authscope1.match(new AuthScope(null, null, -1, null, null));
m2 = authscope1.match(new AuthScope(null, null, -1, null, "somescheme"));
Assert.assertTrue(m2 > m1);
Assertions.assertTrue(m2 > m1);
}
@Test
@ -126,14 +126,14 @@ public class TestAuthScope {
final AuthScope authscope6 = new AuthScope("http", "somehost", 80, "somerealm", "someotherscheme");
final AuthScope authscope7 = new AuthScope("https", "somehost", 80, "somerealm", "somescheme");
final AuthScope authscope8 = new AuthScope("https", "somehost", 80, "somerealm", "SomeScheme");
Assert.assertEquals(authscope1, authscope1);
Assert.assertNotEquals(authscope1, authscope2);
Assert.assertEquals(authscope1, authscope3);
Assert.assertNotEquals(authscope1, authscope4);
Assert.assertNotEquals(authscope1, authscope5);
Assert.assertNotEquals(authscope1, authscope6);
Assert.assertNotEquals(authscope1, authscope7);
Assert.assertEquals(authscope7, authscope8);
Assertions.assertEquals(authscope1, authscope1);
Assertions.assertNotEquals(authscope1, authscope2);
Assertions.assertEquals(authscope1, authscope3);
Assertions.assertNotEquals(authscope1, authscope4);
Assertions.assertNotEquals(authscope1, authscope5);
Assertions.assertNotEquals(authscope1, authscope6);
Assertions.assertNotEquals(authscope1, authscope7);
Assertions.assertEquals(authscope7, authscope8);
}
@Test
@ -146,14 +146,14 @@ public class TestAuthScope {
final AuthScope authscope6 = new AuthScope("http", "somehost", 80, "somerealm", "someotherscheme");
final AuthScope authscope7 = new AuthScope("https", "somehost", 80, "somerealm", "somescheme");
final AuthScope authscope8 = new AuthScope("https", "somehost", 80, "somerealm", "SomeScheme");
Assert.assertEquals(authscope1.hashCode(), authscope1.hashCode());
Assert.assertNotEquals(authscope1.hashCode(), authscope2.hashCode());
Assert.assertEquals(authscope1.hashCode(), authscope3.hashCode());
Assert.assertNotEquals(authscope1.hashCode(), authscope4.hashCode());
Assert.assertNotEquals(authscope1.hashCode(), authscope5.hashCode());
Assert.assertNotEquals(authscope1.hashCode(), authscope6.hashCode());
Assert.assertNotEquals(authscope1.hashCode(), authscope7.hashCode());
Assert.assertEquals(authscope7.hashCode(), authscope8.hashCode());
Assertions.assertEquals(authscope1.hashCode(), authscope1.hashCode());
Assertions.assertNotEquals(authscope1.hashCode(), authscope2.hashCode());
Assertions.assertEquals(authscope1.hashCode(), authscope3.hashCode());
Assertions.assertNotEquals(authscope1.hashCode(), authscope4.hashCode());
Assertions.assertNotEquals(authscope1.hashCode(), authscope5.hashCode());
Assertions.assertNotEquals(authscope1.hashCode(), authscope6.hashCode());
Assertions.assertNotEquals(authscope1.hashCode(), authscope7.hashCode());
Assertions.assertEquals(authscope7.hashCode(), authscope8.hashCode());
}
}

View File

@ -32,8 +32,8 @@ import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class TestCredentials {
@ -41,37 +41,37 @@ public class TestCredentials {
public void testUsernamePasswordCredentialsBasics() {
final UsernamePasswordCredentials creds1 = new UsernamePasswordCredentials(
"name","pwd".toCharArray());
Assert.assertEquals("name", creds1.getUserName());
Assert.assertEquals(new BasicUserPrincipal("name"),
Assertions.assertEquals("name", creds1.getUserName());
Assertions.assertEquals(new BasicUserPrincipal("name"),
creds1.getUserPrincipal());
Assert.assertArrayEquals("pwd".toCharArray(), creds1.getPassword());
Assert.assertEquals("[principal: name]", creds1.toString());
Assertions.assertArrayEquals("pwd".toCharArray(), creds1.getPassword());
Assertions.assertEquals("[principal: name]", creds1.toString());
final UsernamePasswordCredentials creds2 = new UsernamePasswordCredentials(
"name", null);
Assert.assertEquals("name", creds2.getUserName());
Assert.assertEquals(new BasicUserPrincipal("name"),
Assertions.assertEquals("name", creds2.getUserName());
Assertions.assertEquals(new BasicUserPrincipal("name"),
creds2.getUserPrincipal());
Assert.assertNull(creds2.getPassword());
Assert.assertEquals("[principal: name]", creds2.toString());
Assertions.assertNull(creds2.getPassword());
Assertions.assertEquals("[principal: name]", creds2.toString());
}
@Test
public void testNTCredentialsBasics() {
final NTCredentials creds1 = new NTCredentials(
"name","pwd".toCharArray(), "localhost", "domain");
Assert.assertEquals("name", creds1.getUserName());
Assert.assertEquals(new NTUserPrincipal("DOMAIN", "name"),
Assertions.assertEquals("name", creds1.getUserName());
Assertions.assertEquals(new NTUserPrincipal("DOMAIN", "name"),
creds1.getUserPrincipal());
Assert.assertArrayEquals("pwd".toCharArray(), creds1.getPassword());
Assert.assertEquals("[principal: DOMAIN\\name][workstation: LOCALHOST][netbiosDomain: DOMAIN]",
Assertions.assertArrayEquals("pwd".toCharArray(), creds1.getPassword());
Assertions.assertEquals("[principal: DOMAIN\\name][workstation: LOCALHOST][netbiosDomain: DOMAIN]",
creds1.toString());
final NTCredentials creds2 = new NTCredentials(
"name", null, null, null);
Assert.assertEquals("name", creds2.getUserName());
Assert.assertEquals(new NTUserPrincipal(null, "name"),
Assertions.assertEquals("name", creds2.getUserName());
Assertions.assertEquals(new NTUserPrincipal(null, "name"),
creds2.getUserPrincipal());
Assert.assertNull(creds2.getPassword());
Assert.assertEquals("[principal: name][workstation: null][netbiosDomain: null]",
Assertions.assertNull(creds2.getPassword());
Assertions.assertEquals("[principal: name][workstation: null][netbiosDomain: null]",
creds2.toString());
}
@ -84,9 +84,9 @@ public class TestCredentials {
final UsernamePasswordCredentials creds3 = new UsernamePasswordCredentials(
"name", "otherpwd".toCharArray());
Assert.assertTrue(creds1.hashCode() == creds1.hashCode());
Assert.assertTrue(creds1.hashCode() != creds2.hashCode());
Assert.assertTrue(creds1.hashCode() == creds3.hashCode());
Assertions.assertTrue(creds1.hashCode() == creds1.hashCode());
Assertions.assertTrue(creds1.hashCode() != creds2.hashCode());
Assertions.assertTrue(creds1.hashCode() == creds3.hashCode());
}
@Test
@ -98,9 +98,9 @@ public class TestCredentials {
final UsernamePasswordCredentials creds3 = new UsernamePasswordCredentials(
"name", "otherpwd".toCharArray());
Assert.assertEquals(creds1, creds1);
Assert.assertNotEquals(creds1, creds2);
Assert.assertEquals(creds1, creds3);
Assertions.assertEquals(creds1, creds1);
Assertions.assertNotEquals(creds1, creds2);
Assertions.assertEquals(creds1, creds3);
}
@Test
@ -124,15 +124,15 @@ public class TestCredentials {
final NTCredentials creds9 = new NTCredentials(
"name","pwd".toCharArray(), "somehost", null);
Assert.assertTrue(creds1.hashCode() == creds1.hashCode());
Assert.assertTrue(creds1.hashCode() != creds2.hashCode());
Assert.assertEquals(creds1.hashCode(), creds3.hashCode());
Assert.assertNotEquals(creds1.hashCode(), creds4.hashCode());
Assert.assertNotEquals(creds1.hashCode(), creds5.hashCode());
Assert.assertNotEquals(creds1.hashCode(), creds6.hashCode());
Assert.assertNotEquals(creds1.hashCode(), creds7.hashCode());
Assert.assertEquals(creds8.hashCode(), creds5.hashCode());
Assert.assertEquals(creds9.hashCode(), creds7.hashCode());
Assertions.assertTrue(creds1.hashCode() == creds1.hashCode());
Assertions.assertTrue(creds1.hashCode() != creds2.hashCode());
Assertions.assertEquals(creds1.hashCode(), creds3.hashCode());
Assertions.assertNotEquals(creds1.hashCode(), creds4.hashCode());
Assertions.assertNotEquals(creds1.hashCode(), creds5.hashCode());
Assertions.assertNotEquals(creds1.hashCode(), creds6.hashCode());
Assertions.assertNotEquals(creds1.hashCode(), creds7.hashCode());
Assertions.assertEquals(creds8.hashCode(), creds5.hashCode());
Assertions.assertEquals(creds9.hashCode(), creds7.hashCode());
}
@Test
@ -156,15 +156,15 @@ public class TestCredentials {
final NTCredentials creds9 = new NTCredentials(
"name","pwd".toCharArray(), "somehost", null);
Assert.assertEquals(creds1, creds1);
Assert.assertNotEquals(creds1, creds2);
Assert.assertEquals(creds1, creds3);
Assert.assertNotEquals(creds1, creds4);
Assert.assertNotEquals(creds1, creds5);
Assert.assertNotEquals(creds1, creds6);
Assert.assertNotEquals(creds1, creds7);
Assert.assertEquals(creds8, creds5);
Assert.assertEquals(creds9, creds7);
Assertions.assertEquals(creds1, creds1);
Assertions.assertNotEquals(creds1, creds2);
Assertions.assertEquals(creds1, creds3);
Assertions.assertNotEquals(creds1, creds4);
Assertions.assertNotEquals(creds1, creds5);
Assertions.assertNotEquals(creds1, creds6);
Assertions.assertNotEquals(creds1, creds7);
Assertions.assertEquals(creds8, creds5);
Assertions.assertEquals(creds9, creds7);
}
@ -179,7 +179,7 @@ public class TestCredentials {
final ByteArrayInputStream inBuffer = new ByteArrayInputStream(raw);
final ObjectInputStream inStream = new ObjectInputStream(inBuffer);
final UsernamePasswordCredentials clone = (UsernamePasswordCredentials) inStream.readObject();
Assert.assertEquals(orig, clone);
Assertions.assertEquals(orig, clone);
}
@Test
@ -193,7 +193,7 @@ public class TestCredentials {
final ByteArrayInputStream inBuffer = new ByteArrayInputStream(raw);
final ObjectInputStream inStream = new ObjectInputStream(inBuffer);
final NTCredentials clone = (NTCredentials) inStream.readObject();
Assert.assertEquals(orig, clone);
Assertions.assertEquals(orig, clone);
}
}

View File

@ -30,8 +30,8 @@ package org.apache.hc.client5.http.classic.methods;
import java.util.Set;
import org.apache.hc.core5.http.message.BasicHttpResponse;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class TestHttpOptions {
@ -44,8 +44,8 @@ public class TestHttpOptions {
final HttpOptions opt = new HttpOptions("*");
final Set<String> methodsName = opt.getAllowedMethods(resp);
Assert.assertTrue(methodsName.contains("POST"));
Assert.assertTrue(methodsName.contains("GET"));
Assertions.assertTrue(methodsName.contains("POST"));
Assertions.assertTrue(methodsName.contains("GET"));
}
}

View File

@ -29,22 +29,22 @@ package org.apache.hc.client5.http.classic.methods;
import java.net.URI;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class TestHttpRequestBase {
@Test
public void testBasicProperties() throws Exception {
final HttpGet httpget = new HttpGet("http://host/path");
Assert.assertEquals("GET", httpget.getMethod());
Assert.assertEquals(new URI("http://host/path"), httpget.getUri());
Assertions.assertEquals("GET", httpget.getMethod());
Assertions.assertEquals(new URI("http://host/path"), httpget.getUri());
}
@Test
public void testEmptyURI() throws Exception {
final HttpGet httpget = new HttpGet("");
Assert.assertEquals(new URI("/"), httpget.getUri());
Assertions.assertEquals(new URI("/"), httpget.getUri());
}
}

View File

@ -27,15 +27,15 @@
package org.apache.hc.client5.http.classic.methods;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class TestHttpTrace {
@Test
public void testHttpTraceSetEntity() {
final HttpTrace httpTrace = new HttpTrace("/path");
Assert.assertThrows(IllegalStateException.class, () ->
Assertions.assertThrows(IllegalStateException.class, () ->
httpTrace.setEntity(null));
}

View File

@ -34,8 +34,8 @@ import org.apache.hc.client5.http.auth.StandardAuthScheme;
import org.apache.hc.client5.http.cookie.StandardCookieSpec;
import org.apache.hc.core5.util.TimeValue;
import org.apache.hc.core5.util.Timeout;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class TestRequestConfig {
@ -48,16 +48,16 @@ public class TestRequestConfig {
@Test
public void testDefaults() {
final RequestConfig config = RequestConfig.DEFAULT;
Assert.assertEquals(Timeout.ofMinutes(3), config.getConnectionRequestTimeout());
Assert.assertFalse(config.isExpectContinueEnabled());
Assert.assertTrue(config.isAuthenticationEnabled());
Assert.assertTrue(config.isRedirectsEnabled());
Assert.assertFalse(config.isCircularRedirectsAllowed());
Assert.assertEquals(50, config.getMaxRedirects());
Assert.assertNull(config.getCookieSpec());
Assert.assertNull(config.getTargetPreferredAuthSchemes());
Assert.assertNull(config.getProxyPreferredAuthSchemes());
Assert.assertTrue(config.isContentCompressionEnabled());
Assertions.assertEquals(Timeout.ofMinutes(3), config.getConnectionRequestTimeout());
Assertions.assertFalse(config.isExpectContinueEnabled());
Assertions.assertTrue(config.isAuthenticationEnabled());
Assertions.assertTrue(config.isRedirectsEnabled());
Assertions.assertFalse(config.isCircularRedirectsAllowed());
Assertions.assertEquals(50, config.getMaxRedirects());
Assertions.assertNull(config.getCookieSpec());
Assertions.assertNull(config.getTargetPreferredAuthSchemes());
Assertions.assertNull(config.getProxyPreferredAuthSchemes());
Assertions.assertTrue(config.isContentCompressionEnabled());
}
@Test
@ -75,16 +75,16 @@ public class TestRequestConfig {
.setContentCompressionEnabled(false)
.build();
final RequestConfig config = RequestConfig.copy(config0).build();
Assert.assertEquals(TimeValue.ofMilliseconds(44), config.getConnectionRequestTimeout());
Assert.assertTrue(config.isExpectContinueEnabled());
Assert.assertFalse(config.isAuthenticationEnabled());
Assert.assertFalse(config.isRedirectsEnabled());
Assert.assertTrue(config.isCircularRedirectsAllowed());
Assert.assertEquals(100, config.getMaxRedirects());
Assert.assertEquals(StandardCookieSpec.STRICT, config.getCookieSpec());
Assert.assertEquals(Collections.singletonList(StandardAuthScheme.NTLM), config.getTargetPreferredAuthSchemes());
Assert.assertEquals(Collections.singletonList(StandardAuthScheme.DIGEST), config.getProxyPreferredAuthSchemes());
Assert.assertFalse(config.isContentCompressionEnabled());
Assertions.assertEquals(TimeValue.ofMilliseconds(44), config.getConnectionRequestTimeout());
Assertions.assertTrue(config.isExpectContinueEnabled());
Assertions.assertFalse(config.isAuthenticationEnabled());
Assertions.assertFalse(config.isRedirectsEnabled());
Assertions.assertTrue(config.isCircularRedirectsAllowed());
Assertions.assertEquals(100, config.getMaxRedirects());
Assertions.assertEquals(StandardCookieSpec.STRICT, config.getCookieSpec());
Assertions.assertEquals(Collections.singletonList(StandardAuthScheme.NTLM), config.getTargetPreferredAuthSchemes());
Assertions.assertEquals(Collections.singletonList(StandardAuthScheme.DIGEST), config.getProxyPreferredAuthSchemes());
Assertions.assertFalse(config.isContentCompressionEnabled());
}
}

View File

@ -27,8 +27,8 @@
package org.apache.hc.client5.http.cookie;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
/**
* Test cases for {@link CookieOrigin}.
@ -38,43 +38,43 @@ public class TestCookieOrigin {
@Test
public void testConstructor() {
final CookieOrigin origin = new CookieOrigin("www.apache.org", 80, "/", false);
Assert.assertEquals("www.apache.org", origin.getHost());
Assert.assertEquals(80, origin.getPort());
Assert.assertEquals("/", origin.getPath());
Assert.assertFalse(origin.isSecure());
Assertions.assertEquals("www.apache.org", origin.getHost());
Assertions.assertEquals(80, origin.getPort());
Assertions.assertEquals("/", origin.getPath());
Assertions.assertFalse(origin.isSecure());
}
@Test
public void testNullHost() {
Assert.assertThrows(NullPointerException.class, () ->
Assertions.assertThrows(NullPointerException.class, () ->
new CookieOrigin(null, 80, "/", false));
}
@Test
public void testEmptyHost() {
Assert.assertThrows(IllegalArgumentException.class, () ->
Assertions.assertThrows(IllegalArgumentException.class, () ->
new CookieOrigin(" ", 80, "/", false));
}
@Test
public void testNegativePort() {
Assert.assertThrows(IllegalArgumentException.class, () ->
Assertions.assertThrows(IllegalArgumentException.class, () ->
new CookieOrigin("www.apache.org", -80, "/", false));
}
@Test
public void testNullPath() {
Assert.assertThrows(NullPointerException.class, () ->
Assertions.assertThrows(NullPointerException.class, () ->
new CookieOrigin("www.apache.org", 80, null, false));
}
@Test
public void testEmptyPath() {
final CookieOrigin origin = new CookieOrigin("www.apache.org", 80, "", false);
Assert.assertEquals("www.apache.org", origin.getHost());
Assert.assertEquals(80, origin.getPort());
Assert.assertEquals("/", origin.getPath());
Assert.assertFalse(origin.isSecure());
Assertions.assertEquals("www.apache.org", origin.getHost());
Assertions.assertEquals(80, origin.getPort());
Assertions.assertEquals("/", origin.getPath());
Assertions.assertFalse(origin.isSecure());
}
}

View File

@ -30,8 +30,8 @@ package org.apache.hc.client5.http.cookie;
import java.util.Comparator;
import org.apache.hc.client5.http.impl.cookie.BasicClientCookie;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
/**
* Test cases for {@link CookiePathComparator}.
@ -45,8 +45,8 @@ public class TestCookiePathComparator {
final BasicClientCookie cookie2 = new BasicClientCookie("name1", "value");
cookie2.setPath("/a/");
final Comparator<Cookie> comparator = new CookiePathComparator();
Assert.assertTrue(comparator.compare(cookie1, cookie2) < 0);
Assert.assertTrue(comparator.compare(cookie2, cookie1) > 0);
Assertions.assertTrue(comparator.compare(cookie1, cookie2) < 0);
Assertions.assertTrue(comparator.compare(cookie2, cookie1) > 0);
}
@Test
@ -56,8 +56,8 @@ public class TestCookiePathComparator {
final BasicClientCookie cookie2 = new BasicClientCookie("name1", "value");
cookie2.setPath("/a");
final Comparator<Cookie> comparator = new CookiePathComparator();
Assert.assertTrue(comparator.compare(cookie1, cookie2) < 0);
Assert.assertTrue(comparator.compare(cookie2, cookie1) > 0);
Assertions.assertTrue(comparator.compare(cookie1, cookie2) < 0);
Assertions.assertTrue(comparator.compare(cookie2, cookie1) > 0);
}
@Test
@ -67,8 +67,8 @@ public class TestCookiePathComparator {
final BasicClientCookie cookie2 = new BasicClientCookie("name1", "value");
cookie2.setPath("/a");
final Comparator<Cookie> comparator = new CookiePathComparator();
Assert.assertEquals(0, comparator.compare(cookie1, cookie2));
Assert.assertEquals(0, comparator.compare(cookie2, cookie1));
Assertions.assertEquals(0, comparator.compare(cookie1, cookie2));
Assertions.assertEquals(0, comparator.compare(cookie2, cookie1));
}
@Test
@ -78,8 +78,8 @@ public class TestCookiePathComparator {
final BasicClientCookie cookie2 = new BasicClientCookie("name1", "value");
cookie2.setPath("/a");
final Comparator<Cookie> comparator = new CookiePathComparator();
Assert.assertEquals(0, comparator.compare(cookie1, cookie2));
Assert.assertEquals(0, comparator.compare(cookie2, cookie1));
Assertions.assertEquals(0, comparator.compare(cookie1, cookie2));
Assertions.assertEquals(0, comparator.compare(cookie2, cookie1));
}
@Test
@ -89,8 +89,8 @@ public class TestCookiePathComparator {
final BasicClientCookie cookie2 = new BasicClientCookie("name1", "value");
cookie2.setPath("/");
final Comparator<Cookie> comparator = new CookiePathComparator();
Assert.assertEquals(0, comparator.compare(cookie1, cookie2));
Assert.assertEquals(0, comparator.compare(cookie2, cookie1));
Assertions.assertEquals(0, comparator.compare(cookie1, cookie2));
Assertions.assertEquals(0, comparator.compare(cookie2, cookie1));
}
@Test
@ -100,8 +100,8 @@ public class TestCookiePathComparator {
final BasicClientCookie cookie2 = new BasicClientCookie("name1", "value");
cookie2.setPath("/that");
final Comparator<Cookie> comparator = new CookiePathComparator();
Assert.assertEquals(0, comparator.compare(cookie1, cookie2));
Assert.assertEquals(0, comparator.compare(cookie2, cookie1));
Assertions.assertEquals(0, comparator.compare(cookie1, cookie2));
Assertions.assertEquals(0, comparator.compare(cookie2, cookie1));
}
}

View File

@ -31,9 +31,9 @@ import java.util.Comparator;
import java.util.Date;
import org.apache.hc.client5.http.impl.cookie.BasicClientCookie;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* Test cases for {@link org.apache.hc.client5.http.cookie.CookiePriorityComparator}.
@ -42,7 +42,7 @@ public class TestCookiePriorityComparator {
private Comparator<Cookie> comparator;
@Before
@BeforeEach
public void setup() {
comparator = CookiePriorityComparator.INSTANCE;
}
@ -53,8 +53,8 @@ public class TestCookiePriorityComparator {
cookie1.setPath("/a/b/");
final BasicClientCookie cookie2 = new BasicClientCookie("name1", "value");
cookie2.setPath("/a/");
Assert.assertTrue(comparator.compare(cookie1, cookie2) < 0);
Assert.assertTrue(comparator.compare(cookie2, cookie1) > 0);
Assertions.assertTrue(comparator.compare(cookie1, cookie2) < 0);
Assertions.assertTrue(comparator.compare(cookie2, cookie1) > 0);
}
@Test
@ -63,8 +63,8 @@ public class TestCookiePriorityComparator {
cookie1.setPath("/a");
final BasicClientCookie cookie2 = new BasicClientCookie("name1", "value");
cookie2.setPath("/a");
Assert.assertEquals(0, comparator.compare(cookie1, cookie2));
Assert.assertEquals(0, comparator.compare(cookie2, cookie1));
Assertions.assertEquals(0, comparator.compare(cookie1, cookie2));
Assertions.assertEquals(0, comparator.compare(cookie2, cookie1));
}
@Test
@ -73,8 +73,8 @@ public class TestCookiePriorityComparator {
cookie1.setPath("/a/");
final BasicClientCookie cookie2 = new BasicClientCookie("name1", "value");
cookie2.setPath("/a");
Assert.assertTrue(comparator.compare(cookie1, cookie2) < 0);
Assert.assertTrue(comparator.compare(cookie2, cookie1) > 0);
Assertions.assertTrue(comparator.compare(cookie1, cookie2) < 0);
Assertions.assertTrue(comparator.compare(cookie2, cookie1) > 0);
}
@Test
@ -83,8 +83,8 @@ public class TestCookiePriorityComparator {
cookie1.setPath(null);
final BasicClientCookie cookie2 = new BasicClientCookie("name1", "value");
cookie2.setPath("/");
Assert.assertEquals(0, comparator.compare(cookie1, cookie2));
Assert.assertEquals(0, comparator.compare(cookie2, cookie1));
Assertions.assertEquals(0, comparator.compare(cookie1, cookie2));
Assertions.assertEquals(0, comparator.compare(cookie2, cookie1));
}
@Test
@ -93,8 +93,8 @@ public class TestCookiePriorityComparator {
cookie1.setPath("/this");
final BasicClientCookie cookie2 = new BasicClientCookie("name1", "value");
cookie2.setPath("/that");
Assert.assertEquals(0, comparator.compare(cookie1, cookie2));
Assert.assertEquals(0, comparator.compare(cookie2, cookie1));
Assertions.assertEquals(0, comparator.compare(cookie1, cookie2));
Assertions.assertEquals(0, comparator.compare(cookie2, cookie1));
}
@Test
@ -105,8 +105,8 @@ public class TestCookiePriorityComparator {
final BasicClientCookie cookie2 = new BasicClientCookie("name1", "value");
cookie2.setPath("/blah");
cookie2.setCreationDate(new Date(System.currentTimeMillis()));
Assert.assertTrue(comparator.compare(cookie1, cookie2) < 0);
Assert.assertTrue(comparator.compare(cookie2, cookie1) > 0);
Assertions.assertTrue(comparator.compare(cookie1, cookie2) < 0);
Assertions.assertTrue(comparator.compare(cookie2, cookie1) > 0);
}
}

View File

@ -40,8 +40,8 @@ import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.InputStreamEntity;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class TestDecompressingEntity {
@ -50,13 +50,13 @@ public class TestDecompressingEntity {
final CRC32 crc32 = new CRC32();
final StringEntity wrapped = new StringEntity("1234567890", StandardCharsets.US_ASCII);
final ChecksumEntity entity = new ChecksumEntity(wrapped, crc32);
Assert.assertFalse(entity.isStreaming());
Assertions.assertFalse(entity.isStreaming());
final String s = EntityUtils.toString(entity);
Assert.assertEquals("1234567890", s);
Assert.assertEquals(639479525L, crc32.getValue());
Assertions.assertEquals("1234567890", s);
Assertions.assertEquals(639479525L, crc32.getValue());
final InputStream in1 = entity.getContent();
final InputStream in2 = entity.getContent();
Assert.assertNotSame(in1, in2);
Assertions.assertNotSame(in1, in2);
}
@Test
@ -65,13 +65,13 @@ public class TestDecompressingEntity {
final ByteArrayInputStream in = new ByteArrayInputStream("1234567890".getBytes(StandardCharsets.US_ASCII));
final InputStreamEntity wrapped = new InputStreamEntity(in, -1, ContentType.DEFAULT_TEXT);
final ChecksumEntity entity = new ChecksumEntity(wrapped, crc32);
Assert.assertTrue(entity.isStreaming());
Assertions.assertTrue(entity.isStreaming());
final String s = EntityUtils.toString(entity);
Assert.assertEquals("1234567890", s);
Assert.assertEquals(639479525L, crc32.getValue());
Assertions.assertEquals("1234567890", s);
Assertions.assertEquals(639479525L, crc32.getValue());
final InputStream in1 = entity.getContent();
final InputStream in2 = entity.getContent();
Assert.assertSame(in1, in2);
Assertions.assertSame(in1, in2);
EntityUtils.consume(entity);
EntityUtils.consume(entity);
}
@ -81,14 +81,14 @@ public class TestDecompressingEntity {
final CRC32 crc32 = new CRC32();
final StringEntity wrapped = new StringEntity("1234567890", StandardCharsets.US_ASCII);
final ChecksumEntity entity = new ChecksumEntity(wrapped, crc32);
Assert.assertFalse(entity.isStreaming());
Assertions.assertFalse(entity.isStreaming());
final ByteArrayOutputStream out = new ByteArrayOutputStream();
entity.writeTo(out);
final String s = new String(out.toByteArray(), StandardCharsets.US_ASCII);
Assert.assertEquals("1234567890", s);
Assert.assertEquals(639479525L, crc32.getValue());
Assertions.assertEquals("1234567890", s);
Assertions.assertEquals(639479525L, crc32.getValue());
}
static class ChecksumEntity extends DecompressingEntity {

View File

@ -34,8 +34,8 @@ import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.io.entity.ByteArrayEntity;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class TestDeflate {
@ -53,7 +53,7 @@ public class TestDeflate {
final int len = compresser.deflate(compressed);
final HttpEntity entity = new DeflateDecompressingEntity(new ByteArrayEntity(compressed, 0, len, ContentType.APPLICATION_OCTET_STREAM));
Assert.assertEquals(s, EntityUtils.toString(entity));
Assertions.assertEquals(s, EntityUtils.toString(entity));
}
}

View File

@ -33,63 +33,63 @@ import java.io.InputStream;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
public class TestEntityBuilder {
@Test
public void testBuildEmptyEntity() throws Exception {
Assert.assertThrows(IllegalStateException.class, () ->
Assertions.assertThrows(IllegalStateException.class, () ->
EntityBuilder.create().build());
}
@Test
public void testBuildTextEntity() throws Exception {
final HttpEntity entity = EntityBuilder.create().setText("stuff").build();
Assert.assertNotNull(entity);
Assert.assertNotNull(entity.getContent());
Assert.assertNotNull(entity.getContentType());
Assert.assertEquals("text/plain; charset=ISO-8859-1", entity.getContentType());
Assertions.assertNotNull(entity);
Assertions.assertNotNull(entity.getContent());
Assertions.assertNotNull(entity.getContentType());
Assertions.assertEquals("text/plain; charset=ISO-8859-1", entity.getContentType());
}
@Test
public void testBuildBinaryEntity() throws Exception {
final HttpEntity entity = EntityBuilder.create().setBinary(new byte[] {0, 1, 2}).build();
Assert.assertNotNull(entity);
Assert.assertNotNull(entity.getContent());
Assert.assertNotNull(entity.getContentType());
Assert.assertEquals("application/octet-stream", entity.getContentType());
Assertions.assertNotNull(entity);
Assertions.assertNotNull(entity.getContent());
Assertions.assertNotNull(entity.getContentType());
Assertions.assertEquals("application/octet-stream", entity.getContentType());
}
@Test
public void testBuildStreamEntity() throws Exception {
final InputStream in = Mockito.mock(InputStream.class);
final HttpEntity entity = EntityBuilder.create().setStream(in).build();
Assert.assertNotNull(entity);
Assert.assertNotNull(entity.getContent());
Assert.assertNotNull(entity.getContentType());
Assert.assertEquals(-1, entity.getContentLength());
Assert.assertEquals("application/octet-stream", entity.getContentType());
Assertions.assertNotNull(entity);
Assertions.assertNotNull(entity.getContent());
Assertions.assertNotNull(entity.getContentType());
Assertions.assertEquals(-1, entity.getContentLength());
Assertions.assertEquals("application/octet-stream", entity.getContentType());
}
@Test
public void testBuildSerializableEntity() throws Exception {
final HttpEntity entity = EntityBuilder.create().setSerializable(Boolean.TRUE).build();
Assert.assertNotNull(entity);
Assert.assertNotNull(entity.getContent());
Assert.assertNotNull(entity.getContentType());
Assert.assertEquals("application/octet-stream", entity.getContentType());
Assertions.assertNotNull(entity);
Assertions.assertNotNull(entity.getContent());
Assertions.assertNotNull(entity.getContentType());
Assertions.assertEquals("application/octet-stream", entity.getContentType());
}
@Test
public void testBuildFileEntity() throws Exception {
final File file = new File("stuff");
final HttpEntity entity = EntityBuilder.create().setFile(file).build();
Assert.assertNotNull(entity);
Assert.assertNotNull(entity.getContentType());
Assert.assertEquals("application/octet-stream", entity.getContentType());
Assertions.assertNotNull(entity);
Assertions.assertNotNull(entity.getContentType());
Assertions.assertEquals("application/octet-stream", entity.getContentType());
}
@Test
@ -99,29 +99,29 @@ public class TestEntityBuilder {
.setContentEncoding("identity")
.setBinary(new byte[] {0, 1, 2})
.setText("{\"stuff\"}").build();
Assert.assertNotNull(entity);
Assert.assertNotNull(entity.getContentType());
Assert.assertEquals("application/json; charset=UTF-8", entity.getContentType());
Assert.assertNotNull(entity.getContentEncoding());
Assert.assertEquals("identity", entity.getContentEncoding());
Assert.assertEquals("{\"stuff\"}", EntityUtils.toString(entity));
Assertions.assertNotNull(entity);
Assertions.assertNotNull(entity.getContentType());
Assertions.assertEquals("application/json; charset=UTF-8", entity.getContentType());
Assertions.assertNotNull(entity.getContentEncoding());
Assertions.assertEquals("identity", entity.getContentEncoding());
Assertions.assertEquals("{\"stuff\"}", EntityUtils.toString(entity));
}
@Test
public void testBuildChunked() throws Exception {
final HttpEntity entity = EntityBuilder.create().setText("stuff").chunked().build();
Assert.assertNotNull(entity);
Assert.assertTrue(entity.isChunked());
Assertions.assertNotNull(entity);
Assertions.assertTrue(entity.isChunked());
}
@Test
public void testBuildGZipped() throws Exception {
final HttpEntity entity = EntityBuilder.create().setText("stuff").gzipCompressed().build();
Assert.assertNotNull(entity);
Assert.assertNotNull(entity.getContentType());
Assert.assertEquals("text/plain; charset=ISO-8859-1", entity.getContentType());
Assert.assertNotNull(entity.getContentEncoding());
Assert.assertEquals("gzip", entity.getContentEncoding());
Assertions.assertNotNull(entity);
Assertions.assertNotNull(entity.getContentType());
Assertions.assertEquals("text/plain; charset=ISO-8859-1", entity.getContentType());
Assertions.assertNotNull(entity.getContentEncoding());
Assertions.assertEquals("gzip", entity.getContentEncoding());
}
}

View File

@ -39,8 +39,8 @@ import org.apache.hc.core5.http.io.entity.ByteArrayEntity;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.InputStreamEntity;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentMatchers;
import org.mockito.Mockito;
@ -51,10 +51,10 @@ public class TestGZip {
final String s = "some kind of text";
final StringEntity e = new StringEntity(s, ContentType.TEXT_PLAIN, false);
final GzipCompressingEntity gzipe = new GzipCompressingEntity(e);
Assert.assertTrue(gzipe.isChunked());
Assert.assertEquals(-1, gzipe.getContentLength());
Assert.assertNotNull(gzipe.getContentEncoding());
Assert.assertEquals("gzip", gzipe.getContentEncoding());
Assertions.assertTrue(gzipe.isChunked());
Assertions.assertEquals(-1, gzipe.getContentLength());
Assertions.assertNotNull(gzipe.getContentEncoding());
Assertions.assertEquals("gzip", gzipe.getContentEncoding());
}
@Test
@ -65,7 +65,7 @@ public class TestGZip {
gzipe.writeTo(buf);
final ByteArrayEntity out = new ByteArrayEntity(buf.toByteArray(), ContentType.APPLICATION_OCTET_STREAM);
final GzipDecompressingEntity gunzipe = new GzipDecompressingEntity(out);
Assert.assertEquals("some kind of text", EntityUtils.toString(gunzipe, StandardCharsets.US_ASCII));
Assertions.assertEquals("some kind of text", EntityUtils.toString(gunzipe, StandardCharsets.US_ASCII));
}
@Test
@ -96,7 +96,7 @@ public class TestGZip {
}
try (final GzipDecompressingEntity entity = new GzipDecompressingEntity(new InputStreamEntity(new ByteArrayInputStream(bytes), ContentType.APPLICATION_OCTET_STREAM))) {
Assert.assertEquals("stream-1\nstream-2\n", EntityUtils.toString(entity, StandardCharsets.US_ASCII));
Assertions.assertEquals("stream-1\nstream-2\n", EntityUtils.toString(entity, StandardCharsets.US_ASCII));
}
}

View File

@ -30,8 +30,8 @@ package org.apache.hc.client5.http.entity.mime;
import java.io.File;
import org.apache.hc.core5.http.ContentType;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class FormBodyPartTest {
@ -40,6 +40,6 @@ public class FormBodyPartTest {
final File tmp= File.createTempFile("test", "test");
tmp.deleteOnExit();
final FileBody obj = new FileBody(tmp, ContentType.APPLICATION_OCTET_STREAM);
Assert.assertEquals(tmp.getName(), obj.getFilename());
Assertions.assertEquals(tmp.getName(), obj.getFilename());
}
}

View File

@ -27,17 +27,17 @@
package org.apache.hc.client5.http.entity.mime;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.apache.commons.codec.DecoderException;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class HttpRFC7578MultipartTest {
@Test
public void testPercentDecodingWithTooShortMessage() throws Exception {
Assert.assertThrows(DecoderException.class, () ->
Assertions.assertThrows(DecoderException.class, () ->
new HttpRFC7578Multipart.PercentCodec().decode("%".getBytes()));
}

View File

@ -32,8 +32,8 @@ import java.util.Arrays;
import java.util.List;
import org.apache.hc.core5.http.ContentType;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class TestFormBodyPartBuilder {
@ -44,11 +44,11 @@ public class TestFormBodyPartBuilder {
.setName("blah")
.setBody(stringBody)
.build();
Assert.assertNotNull(bodyPart);
Assert.assertEquals("blah", bodyPart.getName());
Assert.assertEquals(stringBody, bodyPart.getBody());
Assertions.assertNotNull(bodyPart);
Assertions.assertEquals("blah", bodyPart.getName());
Assertions.assertEquals(stringBody, bodyPart.getBody());
final Header header = bodyPart.getHeader();
Assert.assertNotNull(header);
Assertions.assertNotNull(header);
assertFields(Arrays.asList(
new MimeField("Content-Disposition", "form-data; name=\"blah\""),
new MimeField("Content-Type", "text/plain; charset=ISO-8859-1")),
@ -63,11 +63,11 @@ public class TestFormBodyPartBuilder {
.setName("blah")
.setBody(stringBody)
.build();
Assert.assertNotNull(bodyPart1);
Assert.assertEquals("blah", bodyPart1.getName());
Assert.assertEquals(stringBody, bodyPart1.getBody());
Assertions.assertNotNull(bodyPart1);
Assertions.assertEquals("blah", bodyPart1.getName());
Assertions.assertEquals(stringBody, bodyPart1.getBody());
final Header header1 = bodyPart1.getHeader();
Assert.assertNotNull(header1);
Assertions.assertNotNull(header1);
assertFields(Arrays.asList(
new MimeField("Content-Disposition", "form-data; name=\"blah\""),
new MimeField("Content-Type", "text/plain; charset=ISO-8859-1")),
@ -78,11 +78,11 @@ public class TestFormBodyPartBuilder {
.setBody(fileBody)
.build();
Assert.assertNotNull(bodyPart2);
Assert.assertEquals("yada", bodyPart2.getName());
Assert.assertEquals(fileBody, bodyPart2.getBody());
Assertions.assertNotNull(bodyPart2);
Assertions.assertEquals("yada", bodyPart2.getName());
Assertions.assertEquals(fileBody, bodyPart2.getBody());
final Header header2 = bodyPart2.getHeader();
Assert.assertNotNull(header2);
Assertions.assertNotNull(header2);
assertFields(Arrays.asList(
new MimeField("Content-Disposition", "form-data; name=\"yada\"; filename=\"stuff.bin\""),
new MimeField("Content-Type", "application/octet-stream")),
@ -102,9 +102,9 @@ public class TestFormBodyPartBuilder {
.addField("header3", "blah")
.build();
Assert.assertNotNull(bodyPart1);
Assertions.assertNotNull(bodyPart1);
final Header header1 = bodyPart1.getHeader();
Assert.assertNotNull(header1);
Assertions.assertNotNull(header1);
assertFields(Arrays.asList(
new MimeField("header1", "blah"),
@ -122,9 +122,9 @@ public class TestFormBodyPartBuilder {
.removeFields("header3")
.build();
Assert.assertNotNull(bodyPart2);
Assertions.assertNotNull(bodyPart2);
final Header header2 = bodyPart2.getHeader();
Assert.assertNotNull(header2);
Assertions.assertNotNull(header2);
assertFields(Arrays.asList(
new MimeField("header1", "blah"),
@ -139,9 +139,9 @@ public class TestFormBodyPartBuilder {
.addField("Content-Transfer-Encoding", "encoding stuff")
.build();
Assert.assertNotNull(bodyPart3);
Assertions.assertNotNull(bodyPart3);
final Header header3 = bodyPart3.getHeader();
Assert.assertNotNull(header3);
Assertions.assertNotNull(header3);
assertFields(Arrays.asList(
new MimeField("header1", "blah"),
@ -154,14 +154,14 @@ public class TestFormBodyPartBuilder {
}
private static void assertFields(final List<MimeField> expected, final List<MimeField> result) {
Assert.assertNotNull(result);
Assert.assertEquals(expected.size(), result.size());
Assertions.assertNotNull(result);
Assertions.assertEquals(expected.size(), result.size());
for (int i = 0; i < expected.size(); i++) {
final MimeField expectedField = expected.get(i);
final MimeField resultField = result.get(i);
Assert.assertNotNull(resultField);
Assert.assertEquals(expectedField.getName(), resultField.getName());
Assert.assertEquals(expectedField.getBody(), resultField.getBody());
Assertions.assertNotNull(resultField);
Assertions.assertEquals(expectedField.getName(), resultField.getName());
Assertions.assertEquals(expectedField.getBody(), resultField.getBody());
}
}

Some files were not shown because too many files have changed in this diff Show More