Migrated test cases to JUnit 4.x

git-svn-id: https://svn.apache.org/repos/asf/httpcomponents/httpclient/trunk@938585 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Oleg Kalnichevski 2010-04-27 18:02:08 +00:00
parent 4defb0689f
commit 160af55cb1
67 changed files with 2601 additions and 3356 deletions

View File

@ -32,96 +32,81 @@ import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.junit.Assert;
import org.junit.Test;
public class TestCredentials extends TestCase {
// ------------------------------------------------------------ Constructor
public TestCredentials(final String testName) {
super(testName);
}
// ------------------------------------------------------------------- Main
public static void main(String args[]) {
String[] testCaseName = { TestCredentials.class.getName() };
junit.textui.TestRunner.main(testCaseName);
}
// ------------------------------------------------------- TestCase Methods
public static Test suite() {
return new TestSuite(TestCredentials.class);
}
public class TestCredentials {
@Test
public void testUsernamePasswordCredentialsBasics() {
UsernamePasswordCredentials creds1 = new UsernamePasswordCredentials(
"name", "pwd");
assertEquals("name", creds1.getUserName());
assertEquals(new BasicUserPrincipal("name"),
Assert.assertEquals("name", creds1.getUserName());
Assert.assertEquals(new BasicUserPrincipal("name"),
creds1.getUserPrincipal());
assertEquals("pwd", creds1.getPassword());
assertEquals("[principal: name]", creds1.toString());
Assert.assertEquals("pwd", creds1.getPassword());
Assert.assertEquals("[principal: name]", creds1.toString());
UsernamePasswordCredentials creds2 = new UsernamePasswordCredentials(
"name:pwd");
assertEquals("name", creds2.getUserName());
assertEquals(new BasicUserPrincipal("name"),
Assert.assertEquals("name", creds2.getUserName());
Assert.assertEquals(new BasicUserPrincipal("name"),
creds2.getUserPrincipal());
assertEquals("pwd", creds2.getPassword());
assertEquals("[principal: name]", creds2.toString());
Assert.assertEquals("pwd", creds2.getPassword());
Assert.assertEquals("[principal: name]", creds2.toString());
UsernamePasswordCredentials creds3 = new UsernamePasswordCredentials(
"name");
assertEquals("name", creds3.getUserName());
assertEquals(new BasicUserPrincipal("name"),
Assert.assertEquals("name", creds3.getUserName());
Assert.assertEquals(new BasicUserPrincipal("name"),
creds3.getUserPrincipal());
assertEquals(null, creds3.getPassword());
assertEquals("[principal: name]", creds3.toString());
Assert.assertEquals(null, creds3.getPassword());
Assert.assertEquals("[principal: name]", creds3.toString());
}
@Test
public void testNTCredentialsBasics() {
NTCredentials creds1 = new NTCredentials(
"name", "pwd", "localhost", "domain");
assertEquals("name", creds1.getUserName());
assertEquals(new NTUserPrincipal("DOMAIN", "name"),
Assert.assertEquals("name", creds1.getUserName());
Assert.assertEquals(new NTUserPrincipal("DOMAIN", "name"),
creds1.getUserPrincipal());
assertEquals("pwd", creds1.getPassword());
assertEquals("[principal: DOMAIN/name][workstation: LOCALHOST]",
Assert.assertEquals("pwd", creds1.getPassword());
Assert.assertEquals("[principal: DOMAIN/name][workstation: LOCALHOST]",
creds1.toString());
NTCredentials creds2 = new NTCredentials(
"name", null, null, null);
assertEquals("name", creds2.getUserName());
assertEquals(new NTUserPrincipal(null, "name"),
Assert.assertEquals("name", creds2.getUserName());
Assert.assertEquals(new NTUserPrincipal(null, "name"),
creds2.getUserPrincipal());
assertEquals(null, creds2.getPassword());
assertEquals("[principal: name][workstation: null]",
Assert.assertEquals(null, creds2.getPassword());
Assert.assertEquals("[principal: name][workstation: null]",
creds2.toString());
NTCredentials creds3 = new NTCredentials(
"domain/name:pwd");
assertEquals("name", creds3.getUserName());
assertEquals(new NTUserPrincipal("DOMAIN", "name"),
Assert.assertEquals("name", creds3.getUserName());
Assert.assertEquals(new NTUserPrincipal("DOMAIN", "name"),
creds3.getUserPrincipal());
assertEquals("pwd", creds3.getPassword());
assertEquals("[principal: DOMAIN/name][workstation: null]",
Assert.assertEquals("pwd", creds3.getPassword());
Assert.assertEquals("[principal: DOMAIN/name][workstation: null]",
creds3.toString());
NTCredentials creds4 = new NTCredentials(
"domain/name");
assertEquals("name", creds4.getUserName());
assertEquals(new NTUserPrincipal("DOMAIN", "name"),
Assert.assertEquals("name", creds4.getUserName());
Assert.assertEquals(new NTUserPrincipal("DOMAIN", "name"),
creds4.getUserPrincipal());
assertEquals(null, creds4.getPassword());
assertEquals("[principal: DOMAIN/name][workstation: null]",
Assert.assertEquals(null, creds4.getPassword());
Assert.assertEquals("[principal: DOMAIN/name][workstation: null]",
creds4.toString());
NTCredentials creds5 = new NTCredentials(
"name");
assertEquals("name", creds5.getUserName());
assertEquals(new NTUserPrincipal(null, "name"),
Assert.assertEquals("name", creds5.getUserName());
Assert.assertEquals(new NTUserPrincipal(null, "name"),
creds5.getUserPrincipal());
assertEquals(null, creds5.getPassword());
assertEquals("[principal: name][workstation: null]",
Assert.assertEquals(null, creds5.getPassword());
Assert.assertEquals("[principal: name][workstation: null]",
creds5.toString());
}
@Test
public void testUsernamePasswordCredentialsHashCode() {
UsernamePasswordCredentials creds1 = new UsernamePasswordCredentials(
"name", "pwd");
@ -130,11 +115,12 @@ public class TestCredentials extends TestCase {
UsernamePasswordCredentials creds3 = new UsernamePasswordCredentials(
"name", "otherpwd");
assertTrue(creds1.hashCode() == creds1.hashCode());
assertTrue(creds1.hashCode() != creds2.hashCode());
assertTrue(creds1.hashCode() == creds3.hashCode());
Assert.assertTrue(creds1.hashCode() == creds1.hashCode());
Assert.assertTrue(creds1.hashCode() != creds2.hashCode());
Assert.assertTrue(creds1.hashCode() == creds3.hashCode());
}
@Test
public void testUsernamePasswordCredentialsEquals() {
UsernamePasswordCredentials creds1 = new UsernamePasswordCredentials(
"name", "pwd");
@ -143,11 +129,12 @@ public class TestCredentials extends TestCase {
UsernamePasswordCredentials creds3 = new UsernamePasswordCredentials(
"name", "otherpwd");
assertTrue(creds1.equals(creds1));
assertFalse(creds1.equals(creds2));
assertTrue(creds1.equals(creds3));
Assert.assertTrue(creds1.equals(creds1));
Assert.assertFalse(creds1.equals(creds2));
Assert.assertTrue(creds1.equals(creds3));
}
@Test
public void testNTCredentialsHashCode() {
NTCredentials creds1 = new NTCredentials(
"name", "pwd", "somehost", "domain");
@ -168,17 +155,18 @@ public class TestCredentials extends TestCase {
NTCredentials creds9 = new NTCredentials(
"name", "pwd", "somehost", null);
assertTrue(creds1.hashCode() == creds1.hashCode());
assertTrue(creds1.hashCode() != creds2.hashCode());
assertTrue(creds1.hashCode() == creds3.hashCode());
assertFalse(creds1.hashCode() == creds4.hashCode());
assertFalse(creds1.hashCode() == creds5.hashCode());
assertFalse(creds1.hashCode() == creds6.hashCode());
assertFalse(creds1.hashCode() == creds7.hashCode());
assertTrue(creds8.hashCode() == creds5.hashCode());
assertTrue(creds9.hashCode() == creds7.hashCode());
Assert.assertTrue(creds1.hashCode() == creds1.hashCode());
Assert.assertTrue(creds1.hashCode() != creds2.hashCode());
Assert.assertTrue(creds1.hashCode() == creds3.hashCode());
Assert.assertFalse(creds1.hashCode() == creds4.hashCode());
Assert.assertFalse(creds1.hashCode() == creds5.hashCode());
Assert.assertFalse(creds1.hashCode() == creds6.hashCode());
Assert.assertFalse(creds1.hashCode() == creds7.hashCode());
Assert.assertTrue(creds8.hashCode() == creds5.hashCode());
Assert.assertTrue(creds9.hashCode() == creds7.hashCode());
}
@Test
public void testNTCredentialsEquals() {
NTCredentials creds1 = new NTCredentials(
"name", "pwd", "somehost", "domain");
@ -199,18 +187,19 @@ public class TestCredentials extends TestCase {
NTCredentials creds9 = new NTCredentials(
"name", "pwd", "somehost", null);
assertTrue(creds1.equals(creds1));
assertFalse(creds1.equals(creds2));
assertTrue(creds1.equals(creds3));
assertFalse(creds1.equals(creds4));
assertFalse(creds1.equals(creds5));
assertFalse(creds1.equals(creds6));
assertFalse(creds1.equals(creds7));
assertTrue(creds8.equals(creds5));
assertTrue(creds9.equals(creds7));
Assert.assertTrue(creds1.equals(creds1));
Assert.assertFalse(creds1.equals(creds2));
Assert.assertTrue(creds1.equals(creds3));
Assert.assertFalse(creds1.equals(creds4));
Assert.assertFalse(creds1.equals(creds5));
Assert.assertFalse(creds1.equals(creds6));
Assert.assertFalse(creds1.equals(creds7));
Assert.assertTrue(creds8.equals(creds5));
Assert.assertTrue(creds9.equals(creds7));
}
@Test
public void testUsernamePasswordCredentialsSerialization() throws Exception {
UsernamePasswordCredentials orig = new UsernamePasswordCredentials("name", "pwd");
ByteArrayOutputStream outbuffer = new ByteArrayOutputStream();
@ -221,9 +210,10 @@ public class TestCredentials extends TestCase {
ByteArrayInputStream inbuffer = new ByteArrayInputStream(raw);
ObjectInputStream instream = new ObjectInputStream(inbuffer);
UsernamePasswordCredentials clone = (UsernamePasswordCredentials) instream.readObject();
assertEquals(orig, clone);
Assert.assertEquals(orig, clone);
}
@Test
public void testNTCredentialsSerialization() throws Exception {
NTCredentials orig = new NTCredentials("name", "pwd", "somehost", "domain");
ByteArrayOutputStream outbuffer = new ByteArrayOutputStream();
@ -234,7 +224,7 @@ public class TestCredentials extends TestCase {
ByteArrayInputStream inbuffer = new ByteArrayInputStream(raw);
ObjectInputStream instream = new ObjectInputStream(inbuffer);
NTCredentials clone = (NTCredentials) instream.readObject();
assertEquals(orig, clone);
Assert.assertEquals(orig, clone);
}
}

View File

@ -29,33 +29,15 @@ package org.apache.http.client.methods;
import java.util.Set;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.apache.http.ProtocolVersion;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.message.BasicStatusLine;
import org.junit.Assert;
import org.junit.Test;
public class TestHttpOptions extends TestCase {
// ------------------------------------------------------------ Constructor
public TestHttpOptions(final String testName) {
super(testName);
}
// ------------------------------------------------------------------- Main
public static void main(String args[]) {
String[] testCaseName = { TestHttpOptions.class.getName() };
junit.textui.TestRunner.main(testCaseName);
}
// ------------------------------------------------------- TestCase Methods
public static Test suite() {
return new TestSuite(TestHttpOptions.class);
}
public class TestHttpOptions {
@Test
public void testMultipleAllows() {
ProtocolVersion proto = new ProtocolVersion("HTTP", 1, 1);
BasicStatusLine line = new BasicStatusLine(proto, 200, "test reason");
@ -66,8 +48,8 @@ public class TestHttpOptions extends TestCase {
HttpOptions opt = new HttpOptions();
Set<String> methodsName = opt.getAllowedMethods(resp);
assertTrue(methodsName.contains("POST"));
assertTrue(methodsName.contains("GET"));
Assert.assertTrue(methodsName.contains("POST"));
Assert.assertTrue(methodsName.contains("GET"));
}
}

View File

@ -35,44 +35,28 @@ import org.apache.http.entity.InputStreamEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.LangUtils;
import org.junit.Assert;
import org.junit.Test;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
public class TestHttpRequestBase extends TestCase {
// ------------------------------------------------------------ Constructor
public TestHttpRequestBase(final String testName) {
super(testName);
}
// ------------------------------------------------------------------- Main
public static void main(String args[]) {
String[] testCaseName = { TestHttpRequestBase.class.getName() };
junit.textui.TestRunner.main(testCaseName);
}
// ------------------------------------------------------- TestCase Methods
public static Test suite() {
return new TestSuite(TestHttpRequestBase.class);
}
public class TestHttpRequestBase {
@Test
public void testBasicProperties() throws Exception {
HttpGet httpget = new HttpGet("http://host/path");
httpget.getParams().setParameter(
HttpProtocolParams.PROTOCOL_VERSION, HttpVersion.HTTP_1_0);
assertEquals("GET", httpget.getRequestLine().getMethod());
assertEquals("http://host/path", httpget.getRequestLine().getUri());
assertEquals(HttpVersion.HTTP_1_0, httpget.getRequestLine().getProtocolVersion());
Assert.assertEquals("GET", httpget.getRequestLine().getMethod());
Assert.assertEquals("http://host/path", httpget.getRequestLine().getUri());
Assert.assertEquals(HttpVersion.HTTP_1_0, httpget.getRequestLine().getProtocolVersion());
}
@Test
public void testEmptyURI() throws Exception {
HttpGet httpget = new HttpGet("");
assertEquals("/", httpget.getRequestLine().getUri());
Assert.assertEquals("/", httpget.getRequestLine().getUri());
}
@Test
public void testCloneBasicRequests() throws Exception {
HttpGet httpget = new HttpGet("http://host/path");
httpget.addHeader("h1", "this header");
@ -82,20 +66,21 @@ public class TestHttpRequestBase extends TestCase {
httpget.getParams().setParameter("p2", "whatever");
HttpGet clone = (HttpGet) httpget.clone();
assertEquals(httpget.getMethod(), clone.getMethod());
assertEquals(httpget.getURI(), clone.getURI());
Assert.assertEquals(httpget.getMethod(), clone.getMethod());
Assert.assertEquals(httpget.getURI(), clone.getURI());
Header[] headers1 = httpget.getAllHeaders();
Header[] headers2 = clone.getAllHeaders();
assertTrue(LangUtils.equals(headers1, headers2));
assertTrue(httpget.getParams() != clone.getParams());
Assert.assertTrue(LangUtils.equals(headers1, headers2));
Assert.assertTrue(httpget.getParams() != clone.getParams());
assertEquals(Integer.valueOf(1), clone.getParams().getParameter("p1"));
assertEquals("whatever", clone.getParams().getParameter("p2"));
assertEquals(null, clone.getParams().getParameter("p3"));
Assert.assertEquals(Integer.valueOf(1), clone.getParams().getParameter("p1"));
Assert.assertEquals("whatever", clone.getParams().getParameter("p2"));
Assert.assertEquals(null, clone.getParams().getParameter("p3"));
}
@Test
public void testCloneEntityEnclosingRequests() throws Exception {
HttpPost httppost = new HttpPost("http://host/path");
httppost.addHeader("h1", "this header");
@ -105,35 +90,35 @@ public class TestHttpRequestBase extends TestCase {
httppost.getParams().setParameter("p2", "whatever");
HttpPost clone = (HttpPost) httppost.clone();
assertEquals(httppost.getMethod(), clone.getMethod());
assertEquals(httppost.getURI(), clone.getURI());
Assert.assertEquals(httppost.getMethod(), clone.getMethod());
Assert.assertEquals(httppost.getURI(), clone.getURI());
Header[] headers1 = httppost.getAllHeaders();
Header[] headers2 = clone.getAllHeaders();
assertTrue(LangUtils.equals(headers1, headers2));
assertTrue(httppost.getParams() != clone.getParams());
Assert.assertTrue(LangUtils.equals(headers1, headers2));
Assert.assertTrue(httppost.getParams() != clone.getParams());
assertEquals(Integer.valueOf(1), clone.getParams().getParameter("p1"));
assertEquals("whatever", clone.getParams().getParameter("p2"));
assertEquals(null, clone.getParams().getParameter("p3"));
Assert.assertEquals(Integer.valueOf(1), clone.getParams().getParameter("p1"));
Assert.assertEquals("whatever", clone.getParams().getParameter("p2"));
Assert.assertEquals(null, clone.getParams().getParameter("p3"));
assertNull(clone.getEntity());
Assert.assertNull(clone.getEntity());
StringEntity e1 = new StringEntity("stuff");
httppost.setEntity(e1);
clone = (HttpPost) httppost.clone();
assertTrue(clone.getEntity() instanceof StringEntity);
assertFalse(clone.getEntity().equals(e1));
Assert.assertTrue(clone.getEntity() instanceof StringEntity);
Assert.assertFalse(clone.getEntity().equals(e1));
}
@Test(expected=CloneNotSupportedException.class)
public void testCloneStreamingEntityEnclosingRequests() throws Exception {
ByteArrayInputStream instream = new ByteArrayInputStream(new byte[] {});
InputStreamEntity e2 = new InputStreamEntity(instream, -1);
HttpPost httppost = new HttpPost("http://host/path");
httppost.setEntity(e2);
try {
httppost.clone();
fail("CloneNotSupportedException should have been thrown");
} catch (CloneNotSupportedException expected) {
}
httppost.clone();
}
}

View File

@ -28,9 +28,6 @@ package org.apache.http.client.protocol;
import java.io.IOException;
import java.util.List;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
@ -55,32 +52,17 @@ import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestHandler;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/**
* Cookie2 support tests.
*
*/
public class TestCookie2Support extends BasicServerTestBase {
// ------------------------------------------------------------ Constructor
public TestCookie2Support(final String testName) {
super(testName);
}
// ------------------------------------------------------------------- Main
public static void main(String args[]) {
String[] testCaseName = { TestCookie2Support.class.getName() };
junit.textui.TestRunner.main(testCaseName);
}
// ------------------------------------------------------- TestCase Methods
public static Test suite() {
return new TestSuite(TestCookie2Support.class);
}
@Override
protected void setUp() throws Exception {
@Before
public void setUp() throws Exception {
localServer = new LocalTestServer(null, null);
localServer.registerDefaultHandlers();
localServer.start();
@ -101,6 +83,7 @@ public class TestCookie2Support extends BasicServerTestBase {
}
@Test
public void testCookieVersionSupportHeader1() throws Exception {
this.localServer.register("*", new CookieVer0Service());
@ -120,8 +103,8 @@ public class TestCookie2Support extends BasicServerTestBase {
}
List<Cookie> cookies = cookieStore.getCookies();
assertNotNull(cookies);
assertEquals(1, cookies.size());
Assert.assertNotNull(cookies);
Assert.assertEquals(1, cookies.size());
HttpResponse response2 = client.execute(getServerHttp(), httpget, context);
HttpEntity e2 = response2.getEntity();
@ -132,8 +115,8 @@ public class TestCookie2Support extends BasicServerTestBase {
HttpRequest reqWrapper = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
Header cookiesupport = reqWrapper.getFirstHeader("Cookie2");
assertNotNull(cookiesupport);
assertEquals("$Version=1", cookiesupport.getValue());
Assert.assertNotNull(cookiesupport);
Assert.assertEquals("$Version=1", cookiesupport.getValue());
}
private static class CookieVer1Service implements HttpRequestHandler {
@ -152,6 +135,7 @@ public class TestCookie2Support extends BasicServerTestBase {
}
@Test
public void testCookieVersionSupportHeader2() throws Exception {
this.localServer.register("*", new CookieVer1Service());
@ -171,8 +155,8 @@ public class TestCookie2Support extends BasicServerTestBase {
}
List<Cookie> cookies = cookieStore.getCookies();
assertNotNull(cookies);
assertEquals(2, cookies.size());
Assert.assertNotNull(cookies);
Assert.assertEquals(2, cookies.size());
HttpResponse response2 = client.execute(getServerHttp(), httpget, context);
HttpEntity e2 = response2.getEntity();
@ -183,8 +167,8 @@ public class TestCookie2Support extends BasicServerTestBase {
HttpRequest reqWrapper = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
Header cookiesupport = reqWrapper.getFirstHeader(SM.COOKIE2);
assertNotNull(cookiesupport);
assertEquals("$Version=1", cookiesupport.getValue());
Assert.assertNotNull(cookiesupport);
Assert.assertEquals("$Version=1", cookiesupport.getValue());
}
private static class CookieVer2Service implements HttpRequestHandler {
@ -202,6 +186,7 @@ public class TestCookie2Support extends BasicServerTestBase {
}
@Test
public void testCookieVersionSupportHeader3() throws Exception {
this.localServer.register("*", new CookieVer2Service());
@ -221,8 +206,8 @@ public class TestCookie2Support extends BasicServerTestBase {
}
List<Cookie> cookies = cookieStore.getCookies();
assertNotNull(cookies);
assertEquals(1, cookies.size());
Assert.assertNotNull(cookies);
Assert.assertEquals(1, cookies.size());
HttpResponse response2 = client.execute(getServerHttp(), httpget, context);
HttpEntity e2 = response2.getEntity();
@ -233,8 +218,8 @@ public class TestCookie2Support extends BasicServerTestBase {
HttpRequest reqWrapper = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
Header cookiesupport = reqWrapper.getFirstHeader("Cookie2");
assertNotNull(cookiesupport);
assertEquals("$Version=1", cookiesupport.getValue());
Assert.assertNotNull(cookiesupport);
Assert.assertEquals("$Version=1", cookiesupport.getValue());
}
private static class SetCookieVersionMixService implements HttpRequestHandler {
@ -253,6 +238,7 @@ public class TestCookie2Support extends BasicServerTestBase {
}
@Test
public void testSetCookieVersionMix() throws Exception {
this.localServer.register("*", new SetCookieVersionMixService());
@ -272,10 +258,10 @@ public class TestCookie2Support extends BasicServerTestBase {
}
List<Cookie> cookies = cookieStore.getCookies();
assertNotNull(cookies);
assertEquals(1, cookies.size());
assertEquals("right", cookies.get(0).getValue());
assertTrue(cookies.get(0) instanceof SetCookie2);
Assert.assertNotNull(cookies);
Assert.assertEquals(1, cookies.size());
Assert.assertEquals("right", cookies.get(0).getValue());
Assert.assertTrue(cookies.get(0) instanceof SetCookie2);
}
}

View File

@ -60,35 +60,17 @@ import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestHandler;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/**
* Redirection test cases.
*
*/
public class TestRedirects extends BasicServerTestBase {
// ------------------------------------------------------------ Constructor
public TestRedirects(final String testName) {
super(testName);
}
// ------------------------------------------------------------------- Main
public static void main(String args[]) {
String[] testCaseName = { TestRedirects.class.getName() };
junit.textui.TestRunner.main(testCaseName);
}
// ------------------------------------------------------- TestCase Methods
public static Test suite() {
return new TestSuite(TestRedirects.class);
}
@Override
protected void setUp() throws Exception {
@Before
public void setUp() throws Exception {
localServer = new LocalTestServer(null, null);
localServer.registerDefaultHandlers();
localServer.start();
@ -235,6 +217,7 @@ public class TestRedirects extends BasicServerTestBase {
}
}
@Test
public void testBasicRedirect300() throws Exception {
InetSocketAddress address = this.localServer.getServiceAddress();
int port = address.getPort();
@ -256,10 +239,11 @@ public class TestRedirects extends BasicServerTestBase {
HttpRequest reqWrapper = (HttpRequest) context.getAttribute(
ExecutionContext.HTTP_REQUEST);
assertEquals(HttpStatus.SC_MULTIPLE_CHOICES, response.getStatusLine().getStatusCode());
assertEquals("/oldlocation/", reqWrapper.getRequestLine().getUri());
Assert.assertEquals(HttpStatus.SC_MULTIPLE_CHOICES, response.getStatusLine().getStatusCode());
Assert.assertEquals("/oldlocation/", reqWrapper.getRequestLine().getUri());
}
@Test
public void testBasicRedirect301() throws Exception {
InetSocketAddress address = this.localServer.getServiceAddress();
int port = address.getPort();
@ -283,12 +267,13 @@ public class TestRedirects extends BasicServerTestBase {
HttpHost targetHost = (HttpHost) context.getAttribute(
ExecutionContext.HTTP_TARGET_HOST);
assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
assertEquals("/newlocation/", reqWrapper.getRequestLine().getUri());
assertEquals(host, targetHost.getHostName());
assertEquals(port, targetHost.getPort());
Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertEquals("/newlocation/", reqWrapper.getRequestLine().getUri());
Assert.assertEquals(host, targetHost.getHostName());
Assert.assertEquals(port, targetHost.getPort());
}
@Test
public void testBasicRedirect302() throws Exception {
InetSocketAddress address = this.localServer.getServiceAddress();
int port = address.getPort();
@ -312,12 +297,13 @@ public class TestRedirects extends BasicServerTestBase {
HttpHost targetHost = (HttpHost) context.getAttribute(
ExecutionContext.HTTP_TARGET_HOST);
assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
assertEquals("/newlocation/", reqWrapper.getRequestLine().getUri());
assertEquals(host, targetHost.getHostName());
assertEquals(port, targetHost.getPort());
Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertEquals("/newlocation/", reqWrapper.getRequestLine().getUri());
Assert.assertEquals(host, targetHost.getHostName());
Assert.assertEquals(port, targetHost.getPort());
}
@Test
public void testBasicRedirect303() throws Exception {
InetSocketAddress address = this.localServer.getServiceAddress();
int port = address.getPort();
@ -341,12 +327,13 @@ public class TestRedirects extends BasicServerTestBase {
HttpHost targetHost = (HttpHost) context.getAttribute(
ExecutionContext.HTTP_TARGET_HOST);
assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
assertEquals("/newlocation/", reqWrapper.getRequestLine().getUri());
assertEquals(host, targetHost.getHostName());
assertEquals(port, targetHost.getPort());
Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertEquals("/newlocation/", reqWrapper.getRequestLine().getUri());
Assert.assertEquals(host, targetHost.getHostName());
Assert.assertEquals(port, targetHost.getPort());
}
@Test
public void testBasicRedirect304() throws Exception {
InetSocketAddress address = this.localServer.getServiceAddress();
int port = address.getPort();
@ -368,10 +355,11 @@ public class TestRedirects extends BasicServerTestBase {
HttpRequest reqWrapper = (HttpRequest) context.getAttribute(
ExecutionContext.HTTP_REQUEST);
assertEquals(HttpStatus.SC_NOT_MODIFIED, response.getStatusLine().getStatusCode());
assertEquals("/oldlocation/", reqWrapper.getRequestLine().getUri());
Assert.assertEquals(HttpStatus.SC_NOT_MODIFIED, response.getStatusLine().getStatusCode());
Assert.assertEquals("/oldlocation/", reqWrapper.getRequestLine().getUri());
}
@Test
public void testBasicRedirect305() throws Exception {
InetSocketAddress address = this.localServer.getServiceAddress();
int port = address.getPort();
@ -393,10 +381,11 @@ public class TestRedirects extends BasicServerTestBase {
HttpRequest reqWrapper = (HttpRequest) context.getAttribute(
ExecutionContext.HTTP_REQUEST);
assertEquals(HttpStatus.SC_USE_PROXY, response.getStatusLine().getStatusCode());
assertEquals("/oldlocation/", reqWrapper.getRequestLine().getUri());
Assert.assertEquals(HttpStatus.SC_USE_PROXY, response.getStatusLine().getStatusCode());
Assert.assertEquals("/oldlocation/", reqWrapper.getRequestLine().getUri());
}
@Test
public void testBasicRedirect307() throws Exception {
InetSocketAddress address = this.localServer.getServiceAddress();
int port = address.getPort();
@ -420,12 +409,13 @@ public class TestRedirects extends BasicServerTestBase {
HttpHost targetHost = (HttpHost) context.getAttribute(
ExecutionContext.HTTP_TARGET_HOST);
assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
assertEquals("/newlocation/", reqWrapper.getRequestLine().getUri());
assertEquals(host, targetHost.getHostName());
assertEquals(port, targetHost.getPort());
Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertEquals("/newlocation/", reqWrapper.getRequestLine().getUri());
Assert.assertEquals(host, targetHost.getHostName());
Assert.assertEquals(port, targetHost.getPort());
}
@Test(expected=ClientProtocolException.class)
public void testMaxRedirectCheck() throws Exception {
this.localServer.register("*", new CircularRedirectService());
@ -434,15 +424,15 @@ public class TestRedirects extends BasicServerTestBase {
client.getParams().setIntParameter(ClientPNames.MAX_REDIRECTS, 5);
HttpGet httpget = new HttpGet("/circular-oldlocation/");
try {
client.execute(getServerHttp(), httpget);
fail("ClientProtocolException exception should have been thrown");
} catch (ClientProtocolException e) {
assertTrue(e.getCause() instanceof RedirectException);
Assert.assertTrue(e.getCause() instanceof RedirectException);
throw e;
}
}
@Test(expected=ClientProtocolException.class)
public void testCircularRedirect() throws Exception {
this.localServer.register("*", new CircularRedirectService());
@ -453,12 +443,13 @@ public class TestRedirects extends BasicServerTestBase {
try {
client.execute(getServerHttp(), httpget);
fail("ClientProtocolException exception should have been thrown");
} catch (ClientProtocolException e) {
assertTrue(e.getCause() instanceof CircularRedirectException);
Assert.assertTrue(e.getCause() instanceof CircularRedirectException);
throw e;
}
}
@Test
public void testPostNoRedirect() throws Exception {
InetSocketAddress address = this.localServer.getServiceAddress();
int port = address.getPort();
@ -480,11 +471,12 @@ public class TestRedirects extends BasicServerTestBase {
HttpRequest reqWrapper = (HttpRequest) context.getAttribute(
ExecutionContext.HTTP_REQUEST);
assertEquals(HttpStatus.SC_MOVED_TEMPORARILY, response.getStatusLine().getStatusCode());
assertEquals("/oldlocation/", reqWrapper.getRequestLine().getUri());
assertEquals("POST", reqWrapper.getRequestLine().getMethod());
Assert.assertEquals(HttpStatus.SC_MOVED_TEMPORARILY, response.getStatusLine().getStatusCode());
Assert.assertEquals("/oldlocation/", reqWrapper.getRequestLine().getUri());
Assert.assertEquals("POST", reqWrapper.getRequestLine().getMethod());
}
@Test
public void testPostRedirectSeeOther() throws Exception {
InetSocketAddress address = this.localServer.getServiceAddress();
int port = address.getPort();
@ -507,11 +499,12 @@ public class TestRedirects extends BasicServerTestBase {
HttpRequest reqWrapper = (HttpRequest) context.getAttribute(
ExecutionContext.HTTP_REQUEST);
assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
assertEquals("/newlocation/", reqWrapper.getRequestLine().getUri());
assertEquals("GET", reqWrapper.getRequestLine().getMethod());
Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertEquals("/newlocation/", reqWrapper.getRequestLine().getUri());
Assert.assertEquals("GET", reqWrapper.getRequestLine().getMethod());
}
@Test
public void testRelativeRedirect() throws Exception {
InetSocketAddress address = this.localServer.getServiceAddress();
int port = address.getPort();
@ -536,12 +529,13 @@ public class TestRedirects extends BasicServerTestBase {
HttpHost targetHost = (HttpHost) context.getAttribute(
ExecutionContext.HTTP_TARGET_HOST);
assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
assertEquals("/relativelocation/", reqWrapper.getRequestLine().getUri());
assertEquals(host, targetHost.getHostName());
assertEquals(port, targetHost.getPort());
Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertEquals("/relativelocation/", reqWrapper.getRequestLine().getUri());
Assert.assertEquals(host, targetHost.getHostName());
Assert.assertEquals(port, targetHost.getPort());
}
@Test
public void testRelativeRedirect2() throws Exception {
InetSocketAddress address = this.localServer.getServiceAddress();
int port = address.getPort();
@ -566,12 +560,13 @@ public class TestRedirects extends BasicServerTestBase {
HttpHost targetHost = (HttpHost) context.getAttribute(
ExecutionContext.HTTP_TARGET_HOST);
assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
assertEquals("/test/relativelocation", reqWrapper.getRequestLine().getUri());
assertEquals(host, targetHost.getHostName());
assertEquals(port, targetHost.getPort());
Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertEquals("/test/relativelocation", reqWrapper.getRequestLine().getUri());
Assert.assertEquals(host, targetHost.getHostName());
Assert.assertEquals(port, targetHost.getPort());
}
@Test(expected=ClientProtocolException.class)
public void testRejectRelativeRedirect() throws Exception {
this.localServer.register("*", new RelativeRedirectService());
@ -583,13 +578,13 @@ public class TestRedirects extends BasicServerTestBase {
try {
client.execute(getServerHttp(), httpget);
fail("ClientProtocolException exception should have been thrown");
} catch (ClientProtocolException e) {
assertTrue(e.getCause() instanceof ProtocolException);
// expected
Assert.assertTrue(e.getCause() instanceof ProtocolException);
throw e;
}
}
@Test(expected=IllegalStateException.class)
public void testRejectBogusRedirectLocation() throws Exception {
this.localServer.register("*", new BogusRedirectService("xxx://bogus"));
@ -597,14 +592,10 @@ public class TestRedirects extends BasicServerTestBase {
HttpGet httpget = new HttpGet("/oldlocation/");
try {
client.execute(getServerHttp(), httpget);
fail("IllegalStateException should have been thrown");
} catch (IllegalStateException e) {
// expected
}
client.execute(getServerHttp(), httpget);
}
@Test(expected=ClientProtocolException.class)
public void testRejectInvalidRedirectLocation() throws Exception {
InetSocketAddress address = this.localServer.getServiceAddress();
int port = address.getPort();
@ -618,13 +609,13 @@ public class TestRedirects extends BasicServerTestBase {
try {
client.execute(getServerHttp(), httpget);
fail("ClientProtocolException should have been thrown");
} catch (ClientProtocolException e) {
assertTrue(e.getCause() instanceof ProtocolException);
// expected
Assert.assertTrue(e.getCause() instanceof ProtocolException);
throw e;
}
}
@Test
public void testRedirectWithCookie() throws Exception {
InetSocketAddress address = this.localServer.getServiceAddress();
int port = address.getPort();
@ -657,13 +648,14 @@ public class TestRedirects extends BasicServerTestBase {
HttpRequest reqWrapper = (HttpRequest) context.getAttribute(
ExecutionContext.HTTP_REQUEST);
assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
assertEquals("/newlocation/", reqWrapper.getRequestLine().getUri());
Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertEquals("/newlocation/", reqWrapper.getRequestLine().getUri());
Header[] headers = reqWrapper.getHeaders(SM.COOKIE);
assertEquals("There can only be one (cookie)", 1, headers.length);
Assert.assertEquals("There can only be one (cookie)", 1, headers.length);
}
@Test
public void testDefaultHeadersRedirect() throws Exception {
InetSocketAddress address = this.localServer.getServiceAddress();
int port = address.getPort();
@ -692,11 +684,11 @@ public class TestRedirects extends BasicServerTestBase {
HttpRequest reqWrapper = (HttpRequest) context.getAttribute(
ExecutionContext.HTTP_REQUEST);
assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
assertEquals("/newlocation/", reqWrapper.getRequestLine().getUri());
Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertEquals("/newlocation/", reqWrapper.getRequestLine().getUri());
Header header = reqWrapper.getFirstHeader(HTTP.USER_AGENT);
assertEquals("my-test-client", header.getValue());
Assert.assertEquals("my-test-client", header.getValue());
}
}

View File

@ -29,9 +29,6 @@ package org.apache.http.client.protocol;
import java.io.IOException;
import java.net.InetSocketAddress;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
@ -45,24 +42,14 @@ import org.apache.http.localserver.BasicServerTestBase;
import org.apache.http.localserver.LocalTestServer;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestHandler;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class TestUriEscapes extends BasicServerTestBase {
public TestUriEscapes(final String testName) {
super(testName);
}
public static void main(String args[]) {
String[] testCaseName = { TestUriEscapes.class.getName() };
junit.textui.TestRunner.main(testCaseName);
}
public static Test suite() {
return new TestSuite(TestUriEscapes.class);
}
@Override
protected void setUp() throws Exception {
@Before
public void setUp() throws Exception {
localServer = new LocalTestServer(null, null);
localServer.registerDefaultHandlers();
localServer.start();
@ -110,55 +97,68 @@ public class TestUriEscapes extends BasicServerTestBase {
response.getEntity().consumeContent();
}
assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
assertEquals(uri, listener.getRequestedUri());
Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertEquals(uri, listener.getRequestedUri());
}
@Test
public void testEscapedAmpersandInQueryAbsolute() throws Exception {
doTest("/path/a=b&c=%26d", false);
}
@Test
public void testEscapedAmpersandInQueryRelative() throws Exception {
doTest("/path/a=b&c=%26d", true);
}
@Test
public void testPlusInPathAbsolute() throws Exception {
doTest("/path+go", false);
}
@Test
public void testPlusInPathRelative() throws Exception {
doTest("/path+go", true);
}
@Test
public void testEscapedSpaceInPathAbsolute() throws Exception {
doTest("/path%20go?a=b&c=d", false);
}
@Test
public void testEscapedSpaceInPathRelative() throws Exception {
doTest("/path%20go?a=b&c=d", true);
}
@Test
public void testEscapedAmpersandInPathAbsolute() throws Exception {
doTest("/this%26that?a=b&c=d", false);
}
@Test
public void testEscapedAmpersandInPathRelative() throws Exception {
doTest("/this%26that?a=b&c=d", true);
}
@Test
public void testEscapedSpaceInQueryAbsolute() throws Exception {
doTest("/path?a=b&c=d%20e", false);
}
@Test
public void testEscapedSpaceInQueryRelative() throws Exception {
doTest("/path?a=b&c=d%20e", true);
}
@Test
public void testPlusInQueryAbsolute() throws Exception {
doTest("/path?a=b&c=d+e", false);
}
@Test
public void testPlusInQueryRelative() throws Exception {
doTest("/path?a=b&c=d+e", true);
}
}

View File

@ -27,65 +27,54 @@
package org.apache.http.client.utils;
import org.apache.http.client.utils.Rfc3492Idn;
import org.junit.Assert;
import org.junit.Test;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
public class TestRfc3492Idn extends TestCase {
public TestRfc3492Idn(String testName) {
super(testName);
}
public static void main(String args[]) {
String[] testCaseName = { TestRfc3492Idn.class.getName() };
junit.textui.TestRunner.main(testCaseName);
}
public static Test suite() {
return new TestSuite(TestRfc3492Idn.class);
}
public class TestRfc3492Idn {
/**
* Some of the sample strings from RFC 3492
*/
@Test
public void testDecode() throws Exception {
Rfc3492Idn idn = new Rfc3492Idn();
// (A) Arabic
assertEquals("\u0644\u064A\u0647\u0645\u0627\u0628\u062A\u0643\u0644" +
Assert.assertEquals("\u0644\u064A\u0647\u0645\u0627\u0628\u062A\u0643\u0644" +
"\u0645\u0648\u0634\u0639\u0631\u0628\u064A\u061F",
idn.decode("egbpdaj6bu4bxfgehfvwxn"));
// (B) Chinese (simplified)
assertEquals("\u4ED6\u4EEC\u4E3A\u4EC0\u4E48\u4E0D\u8BF4\u4E2D\u6587",
Assert.assertEquals("\u4ED6\u4EEC\u4E3A\u4EC0\u4E48\u4E0D\u8BF4\u4E2D\u6587",
idn.decode("ihqwcrb4cv8a8dqg056pqjye"));
// (I) Russian (Cyrillic)
assertEquals("\u043F\u043E\u0447\u0435\u043C\u0443\u0436\u0435\u043E"+
Assert.assertEquals("\u043F\u043E\u0447\u0435\u043C\u0443\u0436\u0435\u043E"+
"\u043D\u0438\u043D\u0435\u0433\u043E\u0432\u043E\u0440"+
"\u044F\u0442\u043F\u043E\u0440\u0443\u0441\u0441\u043A"+
"\u0438",
idn.decode("b1abfaaepdrnnbgefbaDotcwatmq2g4l"));
// (P) Maji<de>Koi<suru>5<byou><mae>
assertEquals("\u004D\u0061\u006A\u0069\u3067\u004B\u006F\u0069\u3059" +
Assert.assertEquals("\u004D\u0061\u006A\u0069\u3067\u004B\u006F\u0069\u3059" +
"\u308B\u0035\u79D2\u524D",
idn.decode("MajiKoi5-783gue6qz075azm5e"));
}
@Test
public void testToUnicode() throws Exception {
Rfc3492Idn idn = new Rfc3492Idn();
// (A) Arabic
assertEquals("\u0644\u064A\u0647\u0645\u0627\u0628\u062A\u0643\u0644" +
Assert.assertEquals("\u0644\u064A\u0647\u0645\u0627\u0628\u062A\u0643\u0644" +
"\u0645\u0648\u0634\u0639\u0631\u0628\u064A\u061F",
idn.toUnicode("xn--egbpdaj6bu4bxfgehfvwxn"));
// some real-world domains
assertEquals("www.z\u00fcrich.ch",
Assert.assertEquals("www.z\u00fcrich.ch",
idn.toUnicode("www.xn--zrich-kva.ch"));
assertEquals("www.g\u00e4ggelig\u00e4\u00e4l.ch",
Assert.assertEquals("www.g\u00e4ggelig\u00e4\u00e4l.ch",
idn.toUnicode("www.xn--gggeligl-0zaga.ch"));
}
}

View File

@ -28,256 +28,290 @@ package org.apache.http.client.utils;
import java.net.URI;
import org.apache.http.HttpHost;
import junit.framework.Assert;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.junit.Assert;
import org.junit.Test;
/**
* This TestCase contains test methods for URI resolving according to RFC 3986.
* The examples are listed in section "5.4 Reference Resolution Examples"
*/
public class TestURIUtils extends TestCase {
public class TestURIUtils {
private URI baseURI = URI.create("http://a/b/c/d;p?q");
public TestURIUtils(final String testName) {
super(testName);
}
public static void main(String args[]) {
String[] testCaseName = { TestURIUtils.class.getName() };
junit.textui.TestRunner.main(testCaseName);
}
public static Test suite() {
return new TestSuite(TestURIUtils.class);
}
@Test
public void testRewite00() throws Exception {
URI uri = URI.create("http://thishost/stuff");
HttpHost target = new HttpHost("thathost", -1);
Assert.assertEquals("http://thathost/stuff", URIUtils.rewriteURI(uri, target).toString());
}
@Test
public void testRewite01() throws Exception {
URI uri = URI.create("http://thishost/stuff");
Assert.assertEquals("/stuff", URIUtils.rewriteURI(uri, null).toString());
}
@Test
public void testRewite02() throws Exception {
URI uri = URI.create("http://thishost//");
Assert.assertEquals("/", URIUtils.rewriteURI(uri, null).toString());
}
@Test
public void testRewite03() throws Exception {
URI uri = URI.create("http://thishost//stuff///morestuff");
Assert.assertEquals("/stuff/morestuff", URIUtils.rewriteURI(uri, null).toString());
}
@Test
public void testRewite04() throws Exception {
URI uri = URI.create("http://thishost/stuff#crap");
HttpHost target = new HttpHost("thathost", -1);
Assert.assertEquals("http://thathost/stuff", URIUtils.rewriteURI(uri, target, true).toString());
}
@Test
public void testRewite05() throws Exception {
URI uri = URI.create("http://thishost/stuff#crap");
HttpHost target = new HttpHost("thathost", -1);
Assert.assertEquals("http://thathost/stuff#crap", URIUtils.rewriteURI(uri, target, false).toString());
}
@Test
public void testResolve00() {
Assert.assertEquals("g:h", URIUtils.resolve(this.baseURI, "g:h").toString());
}
@Test
public void testResolve01() {
Assert.assertEquals("http://a/b/c/g", URIUtils.resolve(this.baseURI, "g").toString());
}
@Test
public void testResolve02() {
Assert.assertEquals("http://a/b/c/g", URIUtils.resolve(this.baseURI, "./g").toString());
}
@Test
public void testResolve03() {
Assert.assertEquals("http://a/b/c/g/", URIUtils.resolve(this.baseURI, "g/").toString());
}
@Test
public void testResolve04() {
Assert.assertEquals("http://a/g", URIUtils.resolve(this.baseURI, "/g").toString());
}
@Test
public void testResolve05() {
Assert.assertEquals("http://g", URIUtils.resolve(this.baseURI, "//g").toString());
}
@Test
public void testResolve06() {
Assert.assertEquals("http://a/b/c/d;p?y", URIUtils.resolve(this.baseURI, "?y").toString());
}
@Test
public void testResolve06_() {
Assert.assertEquals("http://a/b/c/d;p?y#f", URIUtils.resolve(this.baseURI, "?y#f")
.toString());
}
@Test
public void testResolve07() {
Assert.assertEquals("http://a/b/c/g?y", URIUtils.resolve(this.baseURI, "g?y").toString());
}
@Test
public void testResolve08() {
Assert
.assertEquals("http://a/b/c/d;p?q#s", URIUtils.resolve(this.baseURI, "#s")
.toString());
Assert.assertEquals("http://a/b/c/d;p?q#s", URIUtils.resolve(this.baseURI, "#s")
.toString());
}
@Test
public void testResolve09() {
Assert.assertEquals("http://a/b/c/g#s", URIUtils.resolve(this.baseURI, "g#s").toString());
}
@Test
public void testResolve10() {
Assert.assertEquals("http://a/b/c/g?y#s", URIUtils.resolve(this.baseURI, "g?y#s")
.toString());
}
@Test
public void testResolve11() {
Assert.assertEquals("http://a/b/c/;x", URIUtils.resolve(this.baseURI, ";x").toString());
}
@Test
public void testResolve12() {
Assert.assertEquals("http://a/b/c/g;x", URIUtils.resolve(this.baseURI, "g;x").toString());
}
@Test
public void testResolve13() {
Assert.assertEquals("http://a/b/c/g;x?y#s", URIUtils.resolve(this.baseURI, "g;x?y#s")
.toString());
}
@Test
public void testResolve14() {
Assert.assertEquals("http://a/b/c/d;p?q", URIUtils.resolve(this.baseURI, "").toString());
}
@Test
public void testResolve15() {
Assert.assertEquals("http://a/b/c/", URIUtils.resolve(this.baseURI, ".").toString());
}
@Test
public void testResolve16() {
Assert.assertEquals("http://a/b/c/", URIUtils.resolve(this.baseURI, "./").toString());
}
@Test
public void testResolve17() {
Assert.assertEquals("http://a/b/", URIUtils.resolve(this.baseURI, "..").toString());
}
@Test
public void testResolve18() {
Assert.assertEquals("http://a/b/", URIUtils.resolve(this.baseURI, "../").toString());
}
@Test
public void testResolve19() {
Assert.assertEquals("http://a/b/g", URIUtils.resolve(this.baseURI, "../g").toString());
}
@Test
public void testResolve20() {
Assert.assertEquals("http://a/", URIUtils.resolve(this.baseURI, "../..").toString());
}
@Test
public void testResolve21() {
Assert.assertEquals("http://a/", URIUtils.resolve(this.baseURI, "../../").toString());
}
@Test
public void testResolve22() {
Assert.assertEquals("http://a/g", URIUtils.resolve(this.baseURI, "../../g").toString());
}
@Test
public void testResolveAbnormal23() {
Assert.assertEquals("http://a/g", URIUtils.resolve(this.baseURI, "../../../g").toString());
}
@Test
public void testResolveAbnormal24() {
Assert.assertEquals("http://a/g", URIUtils.resolve(this.baseURI, "../../../../g")
.toString());
}
@Test
public void testResolve25() {
Assert.assertEquals("http://a/g", URIUtils.resolve(this.baseURI, "/./g").toString());
}
@Test
public void testResolve26() {
Assert.assertEquals("http://a/g", URIUtils.resolve(this.baseURI, "/../g").toString());
}
@Test
public void testResolve27() {
Assert.assertEquals("http://a/b/c/g.", URIUtils.resolve(this.baseURI, "g.").toString());
}
@Test
public void testResolve28() {
Assert.assertEquals("http://a/b/c/.g", URIUtils.resolve(this.baseURI, ".g").toString());
}
@Test
public void testResolve29() {
Assert.assertEquals("http://a/b/c/g..", URIUtils.resolve(this.baseURI, "g..").toString());
}
@Test
public void testResolve30() {
Assert.assertEquals("http://a/b/c/..g", URIUtils.resolve(this.baseURI, "..g").toString());
}
@Test
public void testResolve31() {
Assert.assertEquals("http://a/b/g", URIUtils.resolve(this.baseURI, "./../g").toString());
}
@Test
public void testResolve32() {
Assert.assertEquals("http://a/b/c/g/", URIUtils.resolve(this.baseURI, "./g/.").toString());
}
@Test
public void testResolve33() {
Assert.assertEquals("http://a/b/c/g/h", URIUtils.resolve(this.baseURI, "g/./h").toString());
}
@Test
public void testResolve34() {
Assert.assertEquals("http://a/b/c/h", URIUtils.resolve(this.baseURI, "g/../h").toString());
}
@Test
public void testResolve35() {
Assert.assertEquals("http://a/b/c/g;x=1/y", URIUtils.resolve(this.baseURI, "g;x=1/./y")
.toString());
}
@Test
public void testResolve36() {
Assert.assertEquals("http://a/b/c/y", URIUtils.resolve(this.baseURI, "g;x=1/../y")
.toString());
}
@Test
public void testResolve37() {
Assert.assertEquals("http://a/b/c/g?y/./x", URIUtils.resolve(this.baseURI, "g?y/./x")
.toString());
}
@Test
public void testResolve38() {
Assert.assertEquals("http://a/b/c/g?y/../x", URIUtils.resolve(this.baseURI, "g?y/../x")
.toString());
}
@Test
public void testResolve39() {
Assert.assertEquals("http://a/b/c/g#s/./x", URIUtils.resolve(this.baseURI, "g#s/./x")
.toString());
}
@Test
public void testResolve40() {
Assert.assertEquals("http://a/b/c/g#s/../x", URIUtils.resolve(this.baseURI, "g#s/../x")
.toString());
}
@Test
public void testResolve41() {
Assert.assertEquals("http:g", URIUtils.resolve(this.baseURI, "http:g").toString());
}
// examples from section 5.2.4
@Test
public void testResolve42() {
Assert.assertEquals("http://s/a/g", URIUtils.resolve(this.baseURI,
"http://s/a/b/c/./../../g").toString());
}
@Test
public void testResolve43() {
Assert.assertEquals("http://s/mid/6", URIUtils.resolve(this.baseURI,
"http://s/mid/content=5/../6").toString());

View File

@ -31,86 +31,73 @@ import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.apache.http.NameValuePair;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.junit.Assert;
import org.junit.Test;
public class TestURLEncodedUtils extends TestCase {
public TestURLEncodedUtils(final String testName) {
super(testName);
}
public static void main(String args[]) {
String[] testCaseName = { TestURLEncodedUtils.class.getName() };
junit.textui.TestRunner.main(testCaseName);
}
public static Test suite() {
return new TestSuite(TestURLEncodedUtils.class);
}
public class TestURLEncodedUtils {
@Test
public void testParseURI () throws Exception {
List <NameValuePair> result;
result = parse("", null);
assertTrue(result.isEmpty());
Assert.assertTrue(result.isEmpty());
result = parse("Name1=Value1", null);
assertEquals(1, result.size());
Assert.assertEquals(1, result.size());
assertNameValuePair(result.get(0), "Name1", "Value1");
result = parse("Name2=", null);
assertEquals(1, result.size());
Assert.assertEquals(1, result.size());
assertNameValuePair(result.get(0), "Name2", null);
result = parse("Name3", null);
assertEquals(1, result.size());
Assert.assertEquals(1, result.size());
assertNameValuePair(result.get(0), "Name3", null);
result = parse("Name4=Value+4%21", null);
assertEquals(1, result.size());
Assert.assertEquals(1, result.size());
assertNameValuePair(result.get(0), "Name4", "Value 4!");
result = parse("Name4=Value%2B4%21", null);
assertEquals(1, result.size());
Assert.assertEquals(1, result.size());
assertNameValuePair(result.get(0), "Name4", "Value+4!");
result = parse("Name4=Value+4%21+%214", null);
assertEquals(1, result.size());
Assert.assertEquals(1, result.size());
assertNameValuePair(result.get(0), "Name4", "Value 4! !4");
result = parse("Name5=aaa&Name6=bbb", null);
assertEquals(2, result.size());
Assert.assertEquals(2, result.size());
assertNameValuePair(result.get(0), "Name5", "aaa");
assertNameValuePair(result.get(1), "Name6", "bbb");
result = parse("Name7=aaa&Name7=b%2Cb&Name7=ccc", null);
assertEquals(3, result.size());
Assert.assertEquals(3, result.size());
assertNameValuePair(result.get(0), "Name7", "aaa");
assertNameValuePair(result.get(1), "Name7", "b,b");
assertNameValuePair(result.get(2), "Name7", "ccc");
result = parse("Name8=xx%2C++yy++%2Czz", null);
assertEquals(1, result.size());
Assert.assertEquals(1, result.size());
assertNameValuePair(result.get(0), "Name8", "xx, yy ,zz");
}
@Test
public void testParseEntity () throws Exception {
final StringEntity entity = new StringEntity("Name1=Value1", null);
entity.setContentType(URLEncodedUtils.CONTENT_TYPE);
final List <NameValuePair> result = URLEncodedUtils.parse(entity);
assertEquals(1, result.size());
Assert.assertEquals(1, result.size());
assertNameValuePair(result.get(0), "Name1", "Value1");
entity.setContentType("text/test");
assertTrue(URLEncodedUtils.parse(entity).isEmpty());
Assert.assertTrue(URLEncodedUtils.parse(entity).isEmpty());
}
static final int SWISS_GERMAN_HELLO [] = {
@ -132,6 +119,7 @@ public class TestURLEncodedUtils extends TestCase {
return buffer.toString();
}
@Test
public void testParseUTF8Entity () throws Exception {
String ru_hello = constructString(RUSSIAN_HELLO);
String ch_hello = constructString(SWISS_GERMAN_HELLO);
@ -141,68 +129,70 @@ public class TestURLEncodedUtils extends TestCase {
String s = URLEncodedUtils.format(parameters, HTTP.UTF_8);
assertEquals("russian=%D0%92%D1%81%D0%B5%D0%BC_%D0%BF%D1%80%D0%B8%D0%B2%D0%B5%D1%82" +
Assert.assertEquals("russian=%D0%92%D1%81%D0%B5%D0%BC_%D0%BF%D1%80%D0%B8%D0%B2%D0%B5%D1%82" +
"&swiss=Gr%C3%BCezi_z%C3%A4m%C3%A4", s);
StringEntity entity = new StringEntity(s, HTTP.UTF_8);
entity.setContentType(URLEncodedUtils.CONTENT_TYPE + HTTP.CHARSET_PARAM + HTTP.UTF_8);
List <NameValuePair> result = URLEncodedUtils.parse(entity);
assertEquals(2, result.size());
Assert.assertEquals(2, result.size());
assertNameValuePair(result.get(0), "russian", ru_hello);
assertNameValuePair(result.get(1), "swiss", ch_hello);
}
@Test
public void testIsEncoded () throws Exception {
final StringEntity entity = new StringEntity("...", null);
entity.setContentType(URLEncodedUtils.CONTENT_TYPE);
assertTrue(URLEncodedUtils.isEncoded(entity));
Assert.assertTrue(URLEncodedUtils.isEncoded(entity));
entity.setContentType(URLEncodedUtils.CONTENT_TYPE + "; charset=US-ASCII");
assertTrue(URLEncodedUtils.isEncoded(entity));
Assert.assertTrue(URLEncodedUtils.isEncoded(entity));
entity.setContentType("text/test");
assertFalse(URLEncodedUtils.isEncoded(entity));
Assert.assertFalse(URLEncodedUtils.isEncoded(entity));
}
@Test
public void testFormat () throws Exception {
final List <NameValuePair> params = new ArrayList <NameValuePair>();
assertEquals(0, URLEncodedUtils.format(params, null).length());
Assert.assertEquals(0, URLEncodedUtils.format(params, null).length());
params.clear();
params.add(new BasicNameValuePair("Name1", "Value1"));
assertEquals("Name1=Value1", URLEncodedUtils.format(params, null));
Assert.assertEquals("Name1=Value1", URLEncodedUtils.format(params, null));
params.clear();
params.add(new BasicNameValuePair("Name2", null));
assertEquals("Name2=", URLEncodedUtils.format(params, null));
Assert.assertEquals("Name2=", URLEncodedUtils.format(params, null));
params.clear();
params.add(new BasicNameValuePair("Name4", "Value 4!"));
assertEquals("Name4=Value+4%21", URLEncodedUtils.format(params, null));
Assert.assertEquals("Name4=Value+4%21", URLEncodedUtils.format(params, null));
params.clear();
params.add(new BasicNameValuePair("Name4", "Value+4!"));
assertEquals("Name4=Value%2B4%21", URLEncodedUtils.format(params, null));
Assert.assertEquals("Name4=Value%2B4%21", URLEncodedUtils.format(params, null));
params.clear();
params.add(new BasicNameValuePair("Name4", "Value 4! !4"));
assertEquals("Name4=Value+4%21+%214", URLEncodedUtils.format(params, null));
Assert.assertEquals("Name4=Value+4%21+%214", URLEncodedUtils.format(params, null));
params.clear();
params.add(new BasicNameValuePair("Name5", "aaa"));
params.add(new BasicNameValuePair("Name6", "bbb"));
assertEquals("Name5=aaa&Name6=bbb", URLEncodedUtils.format(params, null));
Assert.assertEquals("Name5=aaa&Name6=bbb", URLEncodedUtils.format(params, null));
params.clear();
params.add(new BasicNameValuePair("Name7", "aaa"));
params.add(new BasicNameValuePair("Name7", "b,b"));
params.add(new BasicNameValuePair("Name7", "ccc"));
assertEquals("Name7=aaa&Name7=b%2Cb&Name7=ccc", URLEncodedUtils.format(params, null));
Assert.assertEquals("Name7=aaa&Name7=b%2Cb&Name7=ccc", URLEncodedUtils.format(params, null));
params.clear();
params.add(new BasicNameValuePair("Name8", "xx, yy ,zz"));
assertEquals("Name8=xx%2C++yy++%2Czz", URLEncodedUtils.format(params, null));
Assert.assertEquals("Name8=xx%2C++yy++%2Czz", URLEncodedUtils.format(params, null));
}
private List <NameValuePair> parse (final String params, final String encoding) {
@ -213,7 +203,8 @@ public class TestURLEncodedUtils extends TestCase {
final NameValuePair parameter,
final String expectedName,
final String expectedValue) {
assertEquals(parameter.getName(), expectedName);
assertEquals(parameter.getValue(), expectedValue);
Assert.assertEquals(parameter.getName(), expectedName);
Assert.assertEquals(parameter.getValue(), expectedValue);
}
}

View File

@ -32,9 +32,6 @@ import java.io.IOException;
import java.io.OutputStream;
import java.util.concurrent.TimeUnit;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
@ -53,35 +50,25 @@ import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestHandler;
import org.apache.http.util.EntityUtils;
import org.junit.Assert;
import org.junit.Test;
public class TestConnectionAutoRelease extends ServerTestBase {
public TestConnectionAutoRelease(String testName) {
super(testName);
}
public static void main(String args[]) {
String[] testCaseName = { TestConnectionAutoRelease.class.getName() };
junit.textui.TestRunner.main(testCaseName);
}
public static Test suite() {
return new TestSuite(TestConnectionAutoRelease.class);
}
public ThreadSafeClientConnManager createTSCCM(SchemeRegistry schreg) {
private ThreadSafeClientConnManager createTSCCM(SchemeRegistry schreg) {
if (schreg == null)
schreg = supportedSchemes;
return new ThreadSafeClientConnManager(schreg);
}
@Test
public void testReleaseOnEntityConsumeContent() throws Exception {
ThreadSafeClientConnManager mgr = createTSCCM(null);
mgr.setDefaultMaxPerRoute(1);
mgr.setMaxTotalConnections(1);
// Zero connections in the pool
assertEquals(0, mgr.getConnectionsInPool());
Assert.assertEquals(0, mgr.getConnectionsInPool());
DefaultHttpClient client = new DefaultHttpClient(mgr);
@ -94,16 +81,16 @@ public class TestConnectionAutoRelease extends ServerTestBase {
ClientConnectionRequest connreq = mgr.requestConnection(new HttpRoute(target), null);
try {
connreq.getConnection(250, TimeUnit.MILLISECONDS);
fail("ConnectionPoolTimeoutException should have been thrown");
Assert.fail("ConnectionPoolTimeoutException should have been thrown");
} catch (ConnectionPoolTimeoutException expected) {
}
HttpEntity e = response.getEntity();
assertNotNull(e);
Assert.assertNotNull(e);
e.consumeContent();
// Expect one connection in the pool
assertEquals(1, mgr.getConnectionsInPool());
Assert.assertEquals(1, mgr.getConnectionsInPool());
// Make sure one connection is available
connreq = mgr.requestConnection(new HttpRoute(target), null);
@ -114,13 +101,14 @@ public class TestConnectionAutoRelease extends ServerTestBase {
mgr.shutdown();
}
@Test
public void testReleaseOnEntityWriteTo() throws Exception {
ThreadSafeClientConnManager mgr = createTSCCM(null);
mgr.setDefaultMaxPerRoute(1);
mgr.setMaxTotalConnections(1);
// Zero connections in the pool
assertEquals(0, mgr.getConnectionsInPool());
Assert.assertEquals(0, mgr.getConnectionsInPool());
DefaultHttpClient client = new DefaultHttpClient(mgr);
@ -133,17 +121,17 @@ public class TestConnectionAutoRelease extends ServerTestBase {
ClientConnectionRequest connreq = mgr.requestConnection(new HttpRoute(target), null);
try {
connreq.getConnection(250, TimeUnit.MILLISECONDS);
fail("ConnectionPoolTimeoutException should have been thrown");
Assert.fail("ConnectionPoolTimeoutException should have been thrown");
} catch (ConnectionPoolTimeoutException expected) {
}
HttpEntity e = response.getEntity();
assertNotNull(e);
Assert.assertNotNull(e);
ByteArrayOutputStream outsteam = new ByteArrayOutputStream();
e.writeTo(outsteam);
// Expect one connection in the pool
assertEquals(1, mgr.getConnectionsInPool());
Assert.assertEquals(1, mgr.getConnectionsInPool());
// Make sure one connection is available
connreq = mgr.requestConnection(new HttpRoute(target), null);
@ -154,13 +142,14 @@ public class TestConnectionAutoRelease extends ServerTestBase {
mgr.shutdown();
}
@Test
public void testReleaseOnAbort() throws Exception {
ThreadSafeClientConnManager mgr = createTSCCM(null);
mgr.setDefaultMaxPerRoute(1);
mgr.setMaxTotalConnections(1);
// Zero connections in the pool
assertEquals(0, mgr.getConnectionsInPool());
Assert.assertEquals(0, mgr.getConnectionsInPool());
DefaultHttpClient client = new DefaultHttpClient(mgr);
@ -173,16 +162,16 @@ public class TestConnectionAutoRelease extends ServerTestBase {
ClientConnectionRequest connreq = mgr.requestConnection(new HttpRoute(target), null);
try {
connreq.getConnection(250, TimeUnit.MILLISECONDS);
fail("ConnectionPoolTimeoutException should have been thrown");
Assert.fail("ConnectionPoolTimeoutException should have been thrown");
} catch (ConnectionPoolTimeoutException expected) {
}
HttpEntity e = response.getEntity();
assertNotNull(e);
Assert.assertNotNull(e);
httpget.abort();
// Expect zero connections in the pool
assertEquals(0, mgr.getConnectionsInPool());
Assert.assertEquals(0, mgr.getConnectionsInPool());
// Make sure one connection is available
connreq = mgr.requestConnection(new HttpRoute(target), null);
@ -193,6 +182,7 @@ public class TestConnectionAutoRelease extends ServerTestBase {
mgr.shutdown();
}
@Test
public void testReleaseOnIOException() throws Exception {
localServer.register("/dropdead", new HttpRequestHandler() {
@ -232,7 +222,7 @@ public class TestConnectionAutoRelease extends ServerTestBase {
mgr.setMaxTotalConnections(1);
// Zero connections in the pool
assertEquals(0, mgr.getConnectionsInPool());
Assert.assertEquals(0, mgr.getConnectionsInPool());
DefaultHttpClient client = new DefaultHttpClient(mgr);
@ -245,22 +235,22 @@ public class TestConnectionAutoRelease extends ServerTestBase {
ClientConnectionRequest connreq = mgr.requestConnection(new HttpRoute(target), null);
try {
connreq.getConnection(250, TimeUnit.MILLISECONDS);
fail("ConnectionPoolTimeoutException should have been thrown");
Assert.fail("ConnectionPoolTimeoutException should have been thrown");
} catch (ConnectionPoolTimeoutException expected) {
}
HttpEntity e = response.getEntity();
assertNotNull(e);
Assert.assertNotNull(e);
// Read the content
try {
EntityUtils.toByteArray(e);
fail("MalformedChunkCodingException should have been thrown");
Assert.fail("MalformedChunkCodingException should have been thrown");
} catch (MalformedChunkCodingException expected) {
}
// Expect zero connections in the pool
assertEquals(0, mgr.getConnectionsInPool());
Assert.assertEquals(0, mgr.getConnectionsInPool());
// Make sure one connection is available
connreq = mgr.requestConnection(new HttpRoute(target), null);

View File

@ -31,10 +31,6 @@ import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URI;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
@ -63,32 +59,22 @@ import org.apache.http.protocol.ResponseConnControl;
import org.apache.http.protocol.ResponseContent;
import org.apache.http.protocol.ResponseDate;
import org.apache.http.protocol.ResponseServer;
import org.junit.After;
import org.junit.Assert;
import org.junit.Test;
public class TestConnectionReuse extends TestCase {
public TestConnectionReuse(String testName) {
super(testName);
}
public static void main(String args[]) {
String[] testCaseName = { TestConnectionReuse.class.getName() };
junit.textui.TestRunner.main(testCaseName);
}
public static Test suite() {
return new TestSuite(TestConnectionReuse.class);
}
public class TestConnectionReuse {
protected LocalTestServer localServer;
@Override
protected void tearDown() throws Exception {
@After
public void tearDown() throws Exception {
if (this.localServer != null) {
this.localServer.stop();
}
}
@Test
public void testReuseOfPersistentConnections() throws Exception {
BasicHttpProcessor httpproc = new BasicHttpProcessor();
httpproc.addInterceptor(new ResponseDate());
@ -144,7 +130,7 @@ public class TestConnectionReuse extends TestCase {
}
// Expect some connection in the pool
assertTrue(mgr.getConnectionsInPool() > 0);
Assert.assertTrue(mgr.getConnectionsInPool() > 0);
mgr.shutdown();
}
@ -159,6 +145,7 @@ public class TestConnectionReuse extends TestCase {
}
@Test
public void testReuseOfClosedConnections() throws Exception {
BasicHttpProcessor httpproc = new BasicHttpProcessor();
httpproc.addInterceptor(new ResponseDate());
@ -214,11 +201,12 @@ public class TestConnectionReuse extends TestCase {
}
// Expect zero connections in the pool
assertEquals(0, mgr.getConnectionsInPool());
Assert.assertEquals(0, mgr.getConnectionsInPool());
mgr.shutdown();
}
@Test
public void testReuseOfAbortedConnections() throws Exception {
BasicHttpProcessor httpproc = new BasicHttpProcessor();
httpproc.addInterceptor(new ResponseDate());
@ -274,11 +262,12 @@ public class TestConnectionReuse extends TestCase {
}
// Expect zero connections in the pool
assertEquals(0, mgr.getConnectionsInPool());
Assert.assertEquals(0, mgr.getConnectionsInPool());
mgr.shutdown();
}
@Test
public void testKeepAliveHeaderRespected() throws Exception {
BasicHttpProcessor httpproc = new BasicHttpProcessor();
httpproc.addInterceptor(new ResponseDate());
@ -315,15 +304,15 @@ public class TestConnectionReuse extends TestCase {
if(response.getEntity() != null)
response.getEntity().consumeContent();
assertEquals(1, mgr.getConnectionsInPool());
assertEquals(1, localServer.getAcceptedConnectionCount());
Assert.assertEquals(1, mgr.getConnectionsInPool());
Assert.assertEquals(1, localServer.getAcceptedConnectionCount());
response = client.execute(target, new HttpGet("/random/2000"));
if(response.getEntity() != null)
response.getEntity().consumeContent();
assertEquals(1, mgr.getConnectionsInPool());
assertEquals(1, localServer.getAcceptedConnectionCount());
Assert.assertEquals(1, mgr.getConnectionsInPool());
Assert.assertEquals(1, localServer.getAcceptedConnectionCount());
// Now sleep for 1.1 seconds and let the timeout do its work
Thread.sleep(1100);
@ -331,8 +320,8 @@ public class TestConnectionReuse extends TestCase {
if(response.getEntity() != null)
response.getEntity().consumeContent();
assertEquals(1, mgr.getConnectionsInPool());
assertEquals(2, localServer.getAcceptedConnectionCount());
Assert.assertEquals(1, mgr.getConnectionsInPool());
Assert.assertEquals(2, localServer.getAcceptedConnectionCount());
// Do another request just under the 1 second limit & make
// sure we reuse that connection.
@ -341,8 +330,8 @@ public class TestConnectionReuse extends TestCase {
if(response.getEntity() != null)
response.getEntity().consumeContent();
assertEquals(1, mgr.getConnectionsInPool());
assertEquals(2, localServer.getAcceptedConnectionCount());
Assert.assertEquals(1, mgr.getConnectionsInPool());
Assert.assertEquals(2, localServer.getAcceptedConnectionCount());
mgr.shutdown();

View File

@ -27,49 +27,37 @@
package org.apache.http.conn;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.junit.Assert;
import org.junit.Test;
/**
* Unit tests for exceptions.
* Trivial, but it looks better in the Clover reports.
*/
public class TestExceptions extends TestCase {
public TestExceptions(String testName) {
super(testName);
}
public static void main(String args[]) {
String[] testCaseName = { TestExceptions.class.getName() };
junit.textui.TestRunner.main(testCaseName);
}
public static Test suite() {
return new TestSuite(TestExceptions.class);
}
public class TestExceptions {
@Test
public void testCTX() {
String msg = "sample exception message";
ConnectTimeoutException ctx =
new ConnectTimeoutException(msg);
assertFalse(ctx.toString().indexOf(msg) < 0);
assertSame(msg, ctx.getMessage());
Assert.assertFalse(ctx.toString().indexOf(msg) < 0);
Assert.assertSame(msg, ctx.getMessage());
ctx = new ConnectTimeoutException();
assertNull(ctx.getMessage());
Assert.assertNull(ctx.getMessage());
}
@Test
public void testCPTX() {
String msg = "sample exception message";
ConnectionPoolTimeoutException cptx =
new ConnectionPoolTimeoutException(msg);
assertFalse(cptx.toString().indexOf(msg) < 0);
assertSame(msg, cptx.getMessage());
Assert.assertFalse(cptx.toString().indexOf(msg) < 0);
Assert.assertSame(msg, cptx.getMessage());
cptx = new ConnectionPoolTimeoutException();
assertNull(cptx.getMessage());
Assert.assertNull(cptx.getMessage());
}
}

View File

@ -29,79 +29,63 @@ package org.apache.http.conn;
import java.util.List;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.apache.http.HttpHost;
//import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.mockup.SecureSocketFactoryMockup;
import org.junit.Assert;
import org.junit.Test;
/**
* Unit tests for {@link Scheme} and {@link SchemeRegistry}.
*
*/
public class TestScheme extends TestCase {
public TestScheme(String testName) {
super(testName);
}
public static void main(String args[]) {
String[] testCaseName = { TestScheme.class.getName() };
junit.textui.TestRunner.main(testCaseName);
}
public static Test suite() {
return new TestSuite(TestScheme.class);
}
public class TestScheme {
@Test
public void testConstructor() {
Scheme http = new Scheme("http", 80, PlainSocketFactory.getSocketFactory());
assertEquals("http", http.getName());
assertEquals(80, http.getDefaultPort());
assertSame(PlainSocketFactory.getSocketFactory(), http.getSchemeSocketFactory());
assertFalse(http.isLayered());
Assert.assertEquals("http", http.getName());
Assert.assertEquals(80, http.getDefaultPort());
Assert.assertSame(PlainSocketFactory.getSocketFactory(), http.getSchemeSocketFactory());
Assert.assertFalse(http.isLayered());
Scheme https = new Scheme("https", 443, SecureSocketFactoryMockup.INSTANCE);
assertEquals("https", https.getName());
assertEquals(443, https.getDefaultPort());
assertSame(SecureSocketFactoryMockup.INSTANCE, https.getSchemeSocketFactory());
assertTrue(https.isLayered());
Assert.assertEquals("https", https.getName());
Assert.assertEquals(443, https.getDefaultPort());
Assert.assertSame(SecureSocketFactoryMockup.INSTANCE, https.getSchemeSocketFactory());
Assert.assertTrue(https.isLayered());
Scheme hTtP = new Scheme("hTtP", 80, PlainSocketFactory.getSocketFactory());
assertEquals("http", hTtP.getName());
Assert.assertEquals("http", hTtP.getName());
// the rest is no different from above
try {
new Scheme(null, 80, PlainSocketFactory.getSocketFactory());
fail("IllegalArgumentException should have been thrown");
Assert.fail("IllegalArgumentException should have been thrown");
} catch (IllegalArgumentException ex) {
// expected
}
try {
new Scheme("http", 80, null);
fail("IllegalArgumentException should have been thrown");
Assert.fail("IllegalArgumentException should have been thrown");
} catch (IllegalArgumentException ex) {
// expected
}
try {
new Scheme("http", -1, PlainSocketFactory.getSocketFactory());
fail("IllegalArgumentException should have been thrown");
Assert.fail("IllegalArgumentException should have been thrown");
} catch (IllegalArgumentException ex) {
// expected
}
try {
new Scheme("http", 70000, PlainSocketFactory.getSocketFactory());
fail("IllegalArgumentException should have been thrown");
Assert.fail("IllegalArgumentException should have been thrown");
} catch (IllegalArgumentException ex) {
// expected
}
}
@Test
public void testRegisterUnregister() {
SchemeRegistry schmreg = new SchemeRegistry();
@ -112,33 +96,33 @@ public class TestScheme extends TestCase {
HttpHost host = new HttpHost("www.test.invalid", -1, "http");
HttpHost hosts = new HttpHost("www.test.invalid", -1, "https");
assertNull(schmreg.register(myhttp));
assertNull(schmreg.register(https));
assertSame(myhttp, schmreg.register(http));
assertSame(http, schmreg.getScheme("http"));
assertSame(http, schmreg.getScheme(host));
assertSame(https, schmreg.getScheme("https"));
assertSame(https, schmreg.getScheme(hosts));
Assert.assertNull(schmreg.register(myhttp));
Assert.assertNull(schmreg.register(https));
Assert.assertSame(myhttp, schmreg.register(http));
Assert.assertSame(http, schmreg.getScheme("http"));
Assert.assertSame(http, schmreg.getScheme(host));
Assert.assertSame(https, schmreg.getScheme("https"));
Assert.assertSame(https, schmreg.getScheme(hosts));
schmreg.unregister("http");
schmreg.unregister("https");
assertNull(schmreg.get("http")); // get() does not throw exception
Assert.assertNull(schmreg.get("http")); // get() does not throw exception
try {
schmreg.getScheme("http"); // getScheme() does throw exception
fail("IllegalStateException should have been thrown");
Assert.fail("IllegalStateException should have been thrown");
} catch (IllegalStateException ex) {
// expected
}
}
@Test
public void testIterator() {
SchemeRegistry schmreg = new SchemeRegistry();
List<String> names = schmreg.getSchemeNames();
assertNotNull(names);
assertTrue(names.isEmpty());
Assert.assertNotNull(names);
Assert.assertTrue(names.isEmpty());
Scheme http = new Scheme("http", 80, PlainSocketFactory.getSocketFactory());
Scheme https = new Scheme("https", 443, SecureSocketFactoryMockup.INSTANCE);
@ -147,8 +131,8 @@ public class TestScheme extends TestCase {
schmreg.register(https);
names = schmreg.getSchemeNames();
assertNotNull(names);
assertFalse(names.isEmpty());
Assert.assertNotNull(names);
Assert.assertFalse(names.isEmpty());
boolean flaghttp = false;
boolean flaghttps = false;
@ -159,93 +143,98 @@ public class TestScheme extends TestCase {
else if ("https".equals(name))
flaghttps = true;
else
fail("unexpected name in iterator: " + name);
Assert.fail("unexpected name in iterator: " + name);
assertNotNull(schmreg.get(name));
Assert.assertNotNull(schmreg.get(name));
schmreg.unregister(name);
assertNull(schmreg.get(name));
Assert.assertNull(schmreg.get(name));
name = names.get(1);
if ("http".equals(name)) {
if (flaghttp) fail("name 'http' found twice");
if (flaghttp) Assert.fail("name 'http' found twice");
} else if ("https".equals(name)) {
if (flaghttps) fail("name 'https' found twice");
if (flaghttps) Assert.fail("name 'https' found twice");
} else {
fail("unexpected name in iterator: " + name);
Assert.fail("unexpected name in iterator: " + name);
}
assertNotNull(schmreg.get(name));
Assert.assertNotNull(schmreg.get(name));
}
@Test
public void testIllegalRegisterUnregister() {
SchemeRegistry schmreg = new SchemeRegistry();
try {
schmreg.register(null);
fail("IllegalArgumentException should have been thrown");
Assert.fail("IllegalArgumentException should have been thrown");
} catch (IllegalArgumentException ex) {
// expected
}
try {
schmreg.unregister(null);
fail("IllegalArgumentException should have been thrown");
Assert.fail("IllegalArgumentException should have been thrown");
} catch (IllegalArgumentException ex) {
// expected
}
try {
schmreg.get(null);
fail("IllegalArgumentException should have been thrown");
Assert.fail("IllegalArgumentException should have been thrown");
} catch (IllegalArgumentException ex) {
// expected
}
try {
schmreg.getScheme((String)null);
fail("IllegalArgumentException should have been thrown");
Assert.fail("IllegalArgumentException should have been thrown");
} catch (IllegalArgumentException ex) {
// expected
}
try {
schmreg.getScheme((HttpHost)null);
fail("IllegalArgumentException should have been thrown");
Assert.fail("IllegalArgumentException should have been thrown");
} catch (IllegalArgumentException ex) {
// expected
}
}
@Test
public void testResolvePort() {
Scheme http = new Scheme("http", 80, PlainSocketFactory.getSocketFactory());
assertEquals(8080, http.resolvePort(8080));
assertEquals(80, http.resolvePort(-1));
Assert.assertEquals(8080, http.resolvePort(8080));
Assert.assertEquals(80, http.resolvePort(-1));
}
@Test
public void testHashCode() {
Scheme http = new Scheme("http", 80, PlainSocketFactory.getSocketFactory());
Scheme myhttp = new Scheme("http", 80, PlainSocketFactory.getSocketFactory());
Scheme https = new Scheme("https", 443, SecureSocketFactoryMockup.INSTANCE);
assertTrue(http.hashCode() != https.hashCode()); // not guaranteed
assertTrue(http.hashCode() == myhttp.hashCode());
Assert.assertTrue(http.hashCode() != https.hashCode()); // not guaranteed
Assert.assertTrue(http.hashCode() == myhttp.hashCode());
}
@Test
public void testEquals() {
Scheme http = new Scheme("http", 80, PlainSocketFactory.getSocketFactory());
Scheme myhttp = new Scheme("http", 80, PlainSocketFactory.getSocketFactory());
Scheme https = new Scheme("https", 443, SecureSocketFactoryMockup.INSTANCE);
assertFalse(http.equals(https));
assertFalse(http.equals(null));
assertFalse(http.equals("http"));
assertTrue(http.equals(http));
assertTrue(http.equals(myhttp));
assertFalse(http.equals(https));
Assert.assertFalse(http.equals(https));
Assert.assertFalse(http.equals(null));
Assert.assertFalse(http.equals("http"));
Assert.assertTrue(http.equals(http));
Assert.assertTrue(http.equals(myhttp));
Assert.assertFalse(http.equals(https));
}
@Test
public void testToString() {
Scheme http = new Scheme("http", 80, PlainSocketFactory.getSocketFactory());
// test it twice, the result is cached
assertEquals("http:80", http.toString());
assertEquals("http:80", http.toString());
Assert.assertEquals("http:80", http.toString());
Assert.assertEquals("http:80", http.toString());
}
}

View File

@ -29,10 +29,6 @@ package org.apache.http.conn.params;
import java.net.InetAddress;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.apache.http.HttpHost;
import org.apache.http.params.HttpParams;
import org.apache.http.params.BasicHttpParams;
@ -41,12 +37,14 @@ import org.apache.http.conn.routing.HttpRoute;
// for hierarchy testing
import org.apache.http.impl.client.ClientParamsStack;
import org.junit.Assert;
import org.junit.Test;
/**
* Unit tests for parameters.
* Trivial, but it looks better in the Clover reports.
*/
public class TestRouteParams extends TestCase {
public class TestRouteParams {
public final static
HttpHost TARGET1 = new HttpHost("target1.test.invalid");
@ -63,44 +61,29 @@ public class TestRouteParams extends TestCase {
}
}
public TestRouteParams(String testName) {
super(testName);
}
public static void main(String args[]) {
String[] testCaseName = { TestRouteParams.class.getName() };
junit.textui.TestRunner.main(testCaseName);
}
public static Test suite() {
return new TestSuite(TestRouteParams.class);
}
@Test
public void testSetGet() {
HttpParams params = new BasicHttpParams();
assertNull("phantom proxy",
Assert.assertNull("phantom proxy",
ConnRouteParams.getDefaultProxy(params));
assertNull("phantom route",
Assert.assertNull("phantom route",
ConnRouteParams.getForcedRoute(params));
assertNull("phantom address",
Assert.assertNull("phantom address",
ConnRouteParams.getLocalAddress(params));
ConnRouteParams.setDefaultProxy(params, TARGET1);
assertSame("wrong proxy", TARGET1,
Assert.assertSame("wrong proxy", TARGET1,
ConnRouteParams.getDefaultProxy(params));
ConnRouteParams.setForcedRoute(params, ROUTE1);
assertSame("wrong route", ROUTE1,
Assert.assertSame("wrong route", ROUTE1,
ConnRouteParams.getForcedRoute(params));
ConnRouteParams.setLocalAddress(params, LOCAL1);
assertSame("wrong address", LOCAL1,
Assert.assertSame("wrong address", LOCAL1,
ConnRouteParams.getLocalAddress(params));
}
@Test
public void testSetNull() {
HttpParams params = new BasicHttpParams();
@ -108,23 +91,23 @@ public class TestRouteParams extends TestCase {
ConnRouteParams.setForcedRoute(params, null);
ConnRouteParams.setLocalAddress(params, null);
assertNull("phantom proxy",
Assert.assertNull("phantom proxy",
ConnRouteParams.getDefaultProxy(params));
assertNull("phantom route",
Assert.assertNull("phantom route",
ConnRouteParams.getForcedRoute(params));
assertNull("phantom address",
Assert.assertNull("phantom address",
ConnRouteParams.getLocalAddress(params));
ConnRouteParams.setDefaultProxy(params, ConnRouteParams.NO_HOST);
assertNull("null proxy not detected",
Assert.assertNull("null proxy not detected",
ConnRouteParams.getDefaultProxy(params));
ConnRouteParams.setForcedRoute(params, ConnRouteParams.NO_ROUTE);
assertNull("null route not detected",
Assert.assertNull("null route not detected",
ConnRouteParams.getForcedRoute(params));
}
@Test
public void testUnsetHierarchy() {
// hierarchical unsetting is only tested for the default proxy
HttpParams daddy = new BasicHttpParams();
@ -136,32 +119,32 @@ public class TestRouteParams extends TestCase {
HttpParams hierarchy =
new ClientParamsStack(null, daddy, child, null);
assertNull("1", ConnRouteParams.getDefaultProxy(hierarchy));
Assert.assertNull("1", ConnRouteParams.getDefaultProxy(hierarchy));
hierarchy = new ClientParamsStack
(null,
daddy,
new ClientParamsStack(null, child, dummy, null),
null);
assertNull("2", ConnRouteParams.getDefaultProxy(hierarchy));
Assert.assertNull("2", ConnRouteParams.getDefaultProxy(hierarchy));
hierarchy = new ClientParamsStack
(null, daddy, new DefaultedHttpParams(child, dummy), null);
assertNull("3", ConnRouteParams.getDefaultProxy(hierarchy));
Assert.assertNull("3", ConnRouteParams.getDefaultProxy(hierarchy));
hierarchy = new DefaultedHttpParams(child, daddy);
assertNull("4", ConnRouteParams.getDefaultProxy(hierarchy));
Assert.assertNull("4", ConnRouteParams.getDefaultProxy(hierarchy));
hierarchy = new DefaultedHttpParams
(new DefaultedHttpParams(child, dummy), daddy);
assertNull("5", ConnRouteParams.getDefaultProxy(hierarchy));
Assert.assertNull("5", ConnRouteParams.getDefaultProxy(hierarchy));
hierarchy = new DefaultedHttpParams
(child, new DefaultedHttpParams(dummy, daddy));
assertNull("6", ConnRouteParams.getDefaultProxy(hierarchy));
Assert.assertNull("6", ConnRouteParams.getDefaultProxy(hierarchy));
}
@Test
public void testBadArgs() {
try {
@ -201,5 +184,4 @@ public class TestRouteParams extends TestCase {
}
}
}

View File

@ -27,25 +27,21 @@
package org.apache.http.conn.routing;
import java.net.InetAddress;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.apache.http.HttpHost;
import org.apache.http.conn.routing.RouteInfo.TunnelType;
import org.apache.http.conn.routing.RouteInfo.LayerType;
import org.junit.Assert;
import org.junit.Test;
/**
* Tests for <code>HttpRoute</code>.
* Tests for {@link HttpRoute}.
*/
public class TestHttpRoute extends TestCase {
public class TestHttpRoute {
// a selection of constants for generating routes
public final static
@ -86,63 +82,50 @@ public class TestHttpRoute extends TestCase {
}
}
public TestHttpRoute(String testName) {
super(testName);
}
public static void main(String args[]) {
String[] testCaseName = { TestHttpRoute.class.getName() };
junit.textui.TestRunner.main(testCaseName);
}
public static Test suite() {
return new TestSuite(TestHttpRoute.class);
}
@Test
public void testCstrFullRoute() {
// create a route with all arguments and check the details
HttpHost[] chain3 = { PROXY1, PROXY2, PROXY3 };
HttpRoute route = new HttpRoute(TARGET1, LOCAL41, chain3, false,
TunnelType.PLAIN, LayerType.PLAIN);
assertEquals("wrong target",
Assert.assertEquals("wrong target",
TARGET1, route.getTargetHost());
assertEquals("wrong local address",
Assert.assertEquals("wrong local address",
LOCAL41, route.getLocalAddress());
assertEquals("wrong proxy host",
Assert.assertEquals("wrong proxy host",
PROXY1, route.getProxyHost());
assertEquals("wrong hop count",
Assert.assertEquals("wrong hop count",
4, route.getHopCount());
assertEquals("wrong hop 0",
Assert.assertEquals("wrong hop 0",
PROXY1, route.getHopTarget(0));
assertEquals("wrong hop 1",
Assert.assertEquals("wrong hop 1",
PROXY2, route.getHopTarget(1));
assertEquals("wrong hop 2",
Assert.assertEquals("wrong hop 2",
PROXY3, route.getHopTarget(2));
assertEquals("wrong hop 3",
Assert.assertEquals("wrong hop 3",
TARGET1, route.getHopTarget(3));
assertEquals("wrong flag: secured",
Assert.assertEquals("wrong flag: secured",
false, route.isSecure());
assertEquals("wrong flag: tunnelled",
Assert.assertEquals("wrong flag: tunnelled",
false, route.isTunnelled());
assertEquals("wrong flag: layered",
Assert.assertEquals("wrong flag: layered",
false, route.isLayered());
String routestr = route.toString();
assertTrue("missing target in toString",
Assert.assertTrue("missing target in toString",
routestr.indexOf(TARGET1.getHostName()) >= 0);
assertTrue("missing local address in toString",
Assert.assertTrue("missing local address in toString",
routestr.indexOf(LOCAL41.toString()) >= 0);
assertTrue("missing proxy 1 in toString",
Assert.assertTrue("missing proxy 1 in toString",
routestr.indexOf(PROXY1.getHostName()) >= 0);
assertTrue("missing proxy 2 in toString",
Assert.assertTrue("missing proxy 2 in toString",
routestr.indexOf(PROXY2.getHostName()) >= 0);
assertTrue("missing proxy 3 in toString",
Assert.assertTrue("missing proxy 3 in toString",
routestr.indexOf(PROXY3.getHostName()) >= 0);
}
@Test
public void testCstrFullFlags() {
// tests the flag parameters in the full-blown constructor
@ -173,37 +156,37 @@ public class TestHttpRoute extends TestCase {
(TARGET1, LOCAL41, chain3, true,
TunnelType.TUNNELLED, LayerType.LAYERED);
assertFalse("routefff.secure", routefff.isSecure());
assertFalse("routefff.tunnel", routefff.isTunnelled());
assertFalse("routefff.layer" , routefff.isLayered());
Assert.assertFalse("routefff.secure", routefff.isSecure());
Assert.assertFalse("routefff.tunnel", routefff.isTunnelled());
Assert.assertFalse("routefff.layer" , routefff.isLayered());
assertFalse("routefft.secure", routefft.isSecure());
assertFalse("routefft.tunnel", routefft.isTunnelled());
assertTrue ("routefft.layer" , routefft.isLayered());
Assert.assertFalse("routefft.secure", routefft.isSecure());
Assert.assertFalse("routefft.tunnel", routefft.isTunnelled());
Assert.assertTrue ("routefft.layer" , routefft.isLayered());
assertFalse("routeftf.secure", routeftf.isSecure());
assertTrue ("routeftf.tunnel", routeftf.isTunnelled());
assertFalse("routeftf.layer" , routeftf.isLayered());
Assert.assertFalse("routeftf.secure", routeftf.isSecure());
Assert.assertTrue ("routeftf.tunnel", routeftf.isTunnelled());
Assert.assertFalse("routeftf.layer" , routeftf.isLayered());
assertFalse("routeftt.secure", routeftt.isSecure());
assertTrue ("routeftt.tunnel", routeftt.isTunnelled());
assertTrue ("routeftt.layer" , routeftt.isLayered());
Assert.assertFalse("routeftt.secure", routeftt.isSecure());
Assert.assertTrue ("routeftt.tunnel", routeftt.isTunnelled());
Assert.assertTrue ("routeftt.layer" , routeftt.isLayered());
assertTrue ("routetff.secure", routetff.isSecure());
assertFalse("routetff.tunnel", routetff.isTunnelled());
assertFalse("routetff.layer" , routetff.isLayered());
Assert.assertTrue ("routetff.secure", routetff.isSecure());
Assert.assertFalse("routetff.tunnel", routetff.isTunnelled());
Assert.assertFalse("routetff.layer" , routetff.isLayered());
assertTrue ("routetft.secure", routetft.isSecure());
assertFalse("routetft.tunnel", routetft.isTunnelled());
assertTrue ("routetft.layer" , routetft.isLayered());
Assert.assertTrue ("routetft.secure", routetft.isSecure());
Assert.assertFalse("routetft.tunnel", routetft.isTunnelled());
Assert.assertTrue ("routetft.layer" , routetft.isLayered());
assertTrue ("routettf.secure", routettf.isSecure());
assertTrue ("routettf.tunnel", routettf.isTunnelled());
assertFalse("routettf.layer" , routettf.isLayered());
Assert.assertTrue ("routettf.secure", routettf.isSecure());
Assert.assertTrue ("routettf.tunnel", routettf.isTunnelled());
Assert.assertFalse("routettf.layer" , routettf.isLayered());
assertTrue ("routettt.secure", routettt.isSecure());
assertTrue ("routettt.tunnel", routettt.isTunnelled());
assertTrue ("routettt.layer" , routettt.isLayered());
Assert.assertTrue ("routettt.secure", routettt.isSecure());
Assert.assertTrue ("routettt.tunnel", routettt.isTunnelled());
Assert.assertTrue ("routettt.layer" , routettt.isLayered());
Set<HttpRoute> routes = new HashSet<HttpRoute>();
@ -215,7 +198,7 @@ public class TestHttpRoute extends TestCase {
routes.add(routetft);
routes.add(routettf);
routes.add(routettt);
assertEquals("some flagged routes are equal", 8, routes.size());
Assert.assertEquals("some flagged routes are equal", 8, routes.size());
// we can't test hashCode in general due to its dependency
// on InetAddress and HttpHost, but we can check for the flags
@ -228,7 +211,7 @@ public class TestHttpRoute extends TestCase {
routecodes.add(Integer.valueOf(routetft.hashCode()));
routecodes.add(Integer.valueOf(routettf.hashCode()));
routecodes.add(Integer.valueOf(routettt.hashCode()));
assertEquals("some flagged routes have same hashCode",
Assert.assertEquals("some flagged routes have same hashCode",
8, routecodes.size());
Set<String> routestrings = new HashSet<String>();
@ -240,11 +223,11 @@ public class TestHttpRoute extends TestCase {
routestrings.add(routetft.toString());
routestrings.add(routettf.toString());
routestrings.add(routettt.toString());
assertEquals("some flagged route.toString() are equal",
Assert.assertEquals("some flagged route.toString() are equal",
8, routestrings.size());
}
@Test
public void testInvalidArguments() {
HttpHost[] chain0 = { null };
HttpHost[] chain1 = { PROXY1 };
@ -253,12 +236,12 @@ public class TestHttpRoute extends TestCase {
// for reference: this one should succeed
HttpRoute route = new HttpRoute(TARGET1, null, chain1, false,
TunnelType.TUNNELLED, LayerType.PLAIN);
assertNotNull(route);
Assert.assertNotNull(route);
try {
route = new HttpRoute(null, null, chain1, false,
TunnelType.TUNNELLED, LayerType.PLAIN);
fail("missing target not detected");
Assert.fail("missing target not detected");
} catch (IllegalArgumentException iax) {
// expected
}
@ -266,7 +249,7 @@ public class TestHttpRoute extends TestCase {
try {
route = new HttpRoute(TARGET1, null, (HttpHost[]) null, false,
TunnelType.TUNNELLED, LayerType.PLAIN);
fail("missing proxy for tunnel not detected");
Assert.fail("missing proxy for tunnel not detected");
} catch (IllegalArgumentException iax) {
// expected
}
@ -275,7 +258,7 @@ public class TestHttpRoute extends TestCase {
try {
route = new HttpRoute(TARGET1, null, chain0, false,
TunnelType.PLAIN, LayerType.PLAIN);
fail("invalid proxy chain (0) not detected");
Assert.fail("invalid proxy chain (0) not detected");
} catch (IllegalArgumentException iax) {
// expected
}
@ -283,13 +266,13 @@ public class TestHttpRoute extends TestCase {
try {
new HttpRoute(TARGET1, null, chain4, false,
TunnelType.PLAIN, LayerType.PLAIN);
fail("invalid proxy chain (4) not detected");
Assert.fail("invalid proxy chain (4) not detected");
} catch (IllegalArgumentException iax) {
// expected
}
}
@Test
public void testNullEnums() {
// tests the default values for the enum parameters
@ -298,14 +281,14 @@ public class TestHttpRoute extends TestCase {
HttpRoute route = new HttpRoute(TARGET1, null, PROXY1, false,
null, null); // here are defaults
assertFalse("default tunnelling", route.isTunnelled());
assertEquals("untunnelled", TunnelType.PLAIN, route.getTunnelType());
Assert.assertFalse("default tunnelling", route.isTunnelled());
Assert.assertEquals("untunnelled", TunnelType.PLAIN, route.getTunnelType());
assertFalse("default layering", route.isLayered());
assertEquals("unlayered", LayerType.PLAIN, route.getLayerType());
Assert.assertFalse("default layering", route.isLayered());
Assert.assertEquals("unlayered", LayerType.PLAIN, route.getLayerType());
}
@Test
public void testEqualsHashcodeClone() throws CloneNotSupportedException {
HttpHost[] chain0 = { };
HttpHost[] chain1 = { PROXY1 };
@ -319,17 +302,17 @@ public class TestHttpRoute extends TestCase {
TunnelType.PLAIN, LayerType.PLAIN);
HttpRoute route1c = (HttpRoute) route1a.clone();
assertEquals("1a 1a", route1a, route1a);
assertEquals("1a 1b", route1a, route1b);
assertEquals("1a 1c", route1a, route1c);
Assert.assertEquals("1a 1a", route1a, route1a);
Assert.assertEquals("1a 1b", route1a, route1b);
Assert.assertEquals("1a 1c", route1a, route1c);
assertEquals("hashcode 1a", route1a.hashCode(), route1a.hashCode());
assertEquals("hashcode 1b", route1a.hashCode(), route1b.hashCode());
assertEquals("hashcode 1c", route1a.hashCode(), route1c.hashCode());
Assert.assertEquals("hashcode 1a", route1a.hashCode(), route1a.hashCode());
Assert.assertEquals("hashcode 1b", route1a.hashCode(), route1b.hashCode());
Assert.assertEquals("hashcode 1c", route1a.hashCode(), route1c.hashCode());
assertEquals("toString 1a", route1a.toString(), route1a.toString());
assertEquals("toString 1b", route1a.toString(), route1b.toString());
assertEquals("toString 1c", route1a.toString(), route1c.toString());
Assert.assertEquals("toString 1a", route1a.toString(), route1a.toString());
Assert.assertEquals("toString 1b", route1a.toString(), route1b.toString());
Assert.assertEquals("toString 1c", route1a.toString(), route1c.toString());
// now create some differing routes
HttpRoute route2a = new HttpRoute(TARGET2, LOCAL41, chain3, false,
@ -357,60 +340,60 @@ public class TestHttpRoute extends TestCase {
TunnelType.PLAIN, LayerType.LAYERED);
// check a special case first: 2f should be the same as 2e
assertEquals("2e 2f", route2e, route2f);
assertEquals("hashcode 2e 2f", route2e.hashCode(), route2f.hashCode());
assertEquals("toString 2e 2f", route2e.toString(), route2f.toString());
Assert.assertEquals("2e 2f", route2e, route2f);
Assert.assertEquals("hashcode 2e 2f", route2e.hashCode(), route2f.hashCode());
Assert.assertEquals("toString 2e 2f", route2e.toString(), route2f.toString());
assertFalse("1a 2a", route1a.equals(route2a));
assertFalse("1a 2b", route1a.equals(route2b));
assertFalse("1a 2c", route1a.equals(route2c));
assertFalse("1a 2d", route1a.equals(route2d));
assertFalse("1a 2e", route1a.equals(route2e));
assertFalse("1a 2f", route1a.equals(route2f));
assertFalse("1a 2g", route1a.equals(route2g));
assertFalse("1a 2h", route1a.equals(route2h));
assertFalse("1a 2i", route1a.equals(route2i));
assertFalse("1a 2j", route1a.equals(route2j));
assertFalse("1a 2k", route1a.equals(route2k));
Assert.assertFalse("1a 2a", route1a.equals(route2a));
Assert.assertFalse("1a 2b", route1a.equals(route2b));
Assert.assertFalse("1a 2c", route1a.equals(route2c));
Assert.assertFalse("1a 2d", route1a.equals(route2d));
Assert.assertFalse("1a 2e", route1a.equals(route2e));
Assert.assertFalse("1a 2f", route1a.equals(route2f));
Assert.assertFalse("1a 2g", route1a.equals(route2g));
Assert.assertFalse("1a 2h", route1a.equals(route2h));
Assert.assertFalse("1a 2i", route1a.equals(route2i));
Assert.assertFalse("1a 2j", route1a.equals(route2j));
Assert.assertFalse("1a 2k", route1a.equals(route2k));
// repeat the checks in the other direction
// there could be problems with detecting null attributes
assertFalse("2a 1a", route2a.equals(route1a));
assertFalse("2b 1a", route2b.equals(route1a));
assertFalse("2c 1a", route2c.equals(route1a));
assertFalse("2d 1a", route2d.equals(route1a));
assertFalse("2e 1a", route2e.equals(route1a));
assertFalse("2f 1a", route2f.equals(route1a));
assertFalse("2g 1a", route2g.equals(route1a));
assertFalse("2h 1a", route2h.equals(route1a));
assertFalse("2i 1a", route2i.equals(route1a));
assertFalse("2j 1a", route2j.equals(route1a));
assertFalse("2k 1a", route2k.equals(route1a));
Assert.assertFalse("2a 1a", route2a.equals(route1a));
Assert.assertFalse("2b 1a", route2b.equals(route1a));
Assert.assertFalse("2c 1a", route2c.equals(route1a));
Assert.assertFalse("2d 1a", route2d.equals(route1a));
Assert.assertFalse("2e 1a", route2e.equals(route1a));
Assert.assertFalse("2f 1a", route2f.equals(route1a));
Assert.assertFalse("2g 1a", route2g.equals(route1a));
Assert.assertFalse("2h 1a", route2h.equals(route1a));
Assert.assertFalse("2i 1a", route2i.equals(route1a));
Assert.assertFalse("2j 1a", route2j.equals(route1a));
Assert.assertFalse("2k 1a", route2k.equals(route1a));
// don't check hashCode, it's not guaranteed to be different
assertFalse("toString 1a 2a",
Assert.assertFalse("toString 1a 2a",
route1a.toString().equals(route2a.toString()));
assertFalse("toString 1a 2b",
Assert.assertFalse("toString 1a 2b",
route1a.toString().equals(route2b.toString()));
assertFalse("toString 1a 2c",
Assert.assertFalse("toString 1a 2c",
route1a.toString().equals(route2c.toString()));
assertFalse("toString 1a 2d",
Assert.assertFalse("toString 1a 2d",
route1a.toString().equals(route2d.toString()));
assertFalse("toString 1a 2e",
Assert.assertFalse("toString 1a 2e",
route1a.toString().equals(route2e.toString()));
assertFalse("toString 1a 2f",
Assert.assertFalse("toString 1a 2f",
route1a.toString().equals(route2f.toString()));
assertFalse("toString 1a 2g",
Assert.assertFalse("toString 1a 2g",
route1a.toString().equals(route2g.toString()));
assertFalse("toString 1a 2h",
Assert.assertFalse("toString 1a 2h",
route1a.toString().equals(route2h.toString()));
assertFalse("toString 1a 2i",
Assert.assertFalse("toString 1a 2i",
route1a.toString().equals(route2i.toString()));
assertFalse("toString 1a 2j",
Assert.assertFalse("toString 1a 2j",
route1a.toString().equals(route2j.toString()));
assertFalse("toString 1a 2k",
Assert.assertFalse("toString 1a 2k",
route1a.toString().equals(route2k.toString()));
// now check that all of the routes are different from eachother
@ -428,15 +411,15 @@ public class TestHttpRoute extends TestCase {
routes.add(route2i);
routes.add(route2j);
routes.add(route2k);
assertEquals("some routes are equal", 11, routes.size());
Assert.assertEquals("some routes are equal", 11, routes.size());
// and a run of cloning over the set
Iterator<HttpRoute> iter = routes.iterator();
while (iter.hasNext()) {
HttpRoute origin = iter.next();
HttpRoute cloned = (HttpRoute) origin.clone();
assertEquals("clone of " + origin, origin, cloned);
assertTrue("clone of " + origin, routes.contains(cloned));
Assert.assertEquals("clone of " + origin, origin, cloned);
Assert.assertTrue("clone of " + origin, routes.contains(cloned));
}
// and don't forget toString
@ -453,31 +436,31 @@ public class TestHttpRoute extends TestCase {
routestrings.add(route2i.toString());
routestrings.add(route2j.toString());
routestrings.add(route2k.toString());
assertEquals("some route.toString() are equal",
Assert.assertEquals("some route.toString() are equal",
11, routestrings.size());
// finally, compare with nonsense
assertFalse("route equals null", route1a.equals(null));
assertFalse("route equals string", route1a.equals("route1a"));
Assert.assertFalse("route equals null", route1a.equals(null));
Assert.assertFalse("route equals string", route1a.equals("route1a"));
}
@Test
public void testHopping() {
// test getHopCount() and getHopTarget() with different proxy chains
HttpHost[] proxies = null;
HttpRoute route = new HttpRoute(TARGET1, null, proxies, true,
TunnelType.PLAIN, LayerType.PLAIN);
assertEquals("A: hop count", 1, route.getHopCount());
assertEquals("A: hop 0", TARGET1, route.getHopTarget(0));
Assert.assertEquals("A: hop count", 1, route.getHopCount());
Assert.assertEquals("A: hop 0", TARGET1, route.getHopTarget(0));
try {
HttpHost beyond = route.getHopTarget(1);
fail("A: hop 1 is " + beyond);
Assert.fail("A: hop 1 is " + beyond);
} catch (IllegalArgumentException iax) {
// expected
}
try {
HttpHost before = route.getHopTarget(-1);
fail("A: hop -1 is " + before);
Assert.fail("A: hop -1 is " + before);
} catch (IllegalArgumentException iax) {
// expected
}
@ -486,18 +469,18 @@ public class TestHttpRoute extends TestCase {
proxies = new HttpHost[]{ PROXY3 };
route = new HttpRoute(TARGET1, LOCAL62, proxies, false,
TunnelType.TUNNELLED, LayerType.PLAIN);
assertEquals("B: hop count", 2, route.getHopCount());
assertEquals("B: hop 0", PROXY3, route.getHopTarget(0));
assertEquals("B: hop 1", TARGET1, route.getHopTarget(1));
Assert.assertEquals("B: hop count", 2, route.getHopCount());
Assert.assertEquals("B: hop 0", PROXY3, route.getHopTarget(0));
Assert.assertEquals("B: hop 1", TARGET1, route.getHopTarget(1));
try {
HttpHost beyond = route.getHopTarget(2);
fail("B: hop 2 is " + beyond);
Assert.fail("B: hop 2 is " + beyond);
} catch (IllegalArgumentException iax) {
// expected
}
try {
HttpHost before = route.getHopTarget(-2);
fail("B: hop -2 is " + before);
Assert.fail("B: hop -2 is " + before);
} catch (IllegalArgumentException iax) {
// expected
}
@ -506,74 +489,74 @@ public class TestHttpRoute extends TestCase {
proxies = new HttpHost[]{ PROXY3, PROXY1, PROXY2 };
route = new HttpRoute(TARGET1, LOCAL42, proxies, false,
TunnelType.PLAIN, LayerType.LAYERED);
assertEquals("C: hop count", 4, route.getHopCount());
assertEquals("C: hop 0", PROXY3 , route.getHopTarget(0));
assertEquals("C: hop 1", PROXY1 , route.getHopTarget(1));
assertEquals("C: hop 2", PROXY2 , route.getHopTarget(2));
assertEquals("C: hop 3", TARGET1, route.getHopTarget(3));
Assert.assertEquals("C: hop count", 4, route.getHopCount());
Assert.assertEquals("C: hop 0", PROXY3 , route.getHopTarget(0));
Assert.assertEquals("C: hop 1", PROXY1 , route.getHopTarget(1));
Assert.assertEquals("C: hop 2", PROXY2 , route.getHopTarget(2));
Assert.assertEquals("C: hop 3", TARGET1, route.getHopTarget(3));
try {
HttpHost beyond = route.getHopTarget(4);
fail("C: hop 4 is " + beyond);
Assert.fail("C: hop 4 is " + beyond);
} catch (IllegalArgumentException iax) {
// expected
}
try {
HttpHost before = route.getHopTarget(Integer.MIN_VALUE);
fail("C: hop -<min> is " + before);
Assert.fail("C: hop -<min> is " + before);
} catch (IllegalArgumentException iax) {
// expected
}
}
@Test
public void testCstr1() {
HttpRoute route = new HttpRoute(TARGET2);
HttpRoute should = new HttpRoute
(TARGET2, null, (HttpHost[]) null, false,
TunnelType.PLAIN, LayerType.PLAIN);
assertEquals("bad convenience route", route, should);
Assert.assertEquals("bad convenience route", route, should);
}
@Test
public void testCstr3() {
// test convenience constructor with 3 arguments
HttpRoute route = new HttpRoute(TARGET2, LOCAL61, false);
HttpRoute should = new HttpRoute
(TARGET2, LOCAL61, (HttpHost[]) null, false,
TunnelType.PLAIN, LayerType.PLAIN);
assertEquals("bad convenience route 3/insecure", route, should);
Assert.assertEquals("bad convenience route 3/insecure", route, should);
route = new HttpRoute(TARGET2, null, true);
should = new HttpRoute(TARGET2, null, (HttpHost[]) null, true,
TunnelType.PLAIN, LayerType.PLAIN);
assertEquals("bad convenience route 3/secure", route, should);
Assert.assertEquals("bad convenience route 3/secure", route, should);
}
@Test
public void testCstr4() {
// test convenience constructor with 4 arguments
HttpRoute route = new HttpRoute(TARGET2, null, PROXY2, false);
HttpRoute should = new HttpRoute
(TARGET2, null, new HttpHost[]{ PROXY2 }, false,
TunnelType.PLAIN, LayerType.PLAIN);
assertEquals("bad convenience route 4/insecure", route, should);
Assert.assertEquals("bad convenience route 4/insecure", route, should);
route = new HttpRoute(TARGET2, LOCAL42, PROXY1, true);
should = new HttpRoute
(TARGET2, LOCAL42, new HttpHost[]{ PROXY1 }, true,
TunnelType.TUNNELLED, LayerType.LAYERED);
assertEquals("bad convenience route 4/secure", route, should);
Assert.assertEquals("bad convenience route 4/secure", route, should);
// this constructor REQUIRES a proxy to be specified
try {
new HttpRoute(TARGET1, LOCAL61, null, false);
fail("missing proxy not detected");
Assert.fail("missing proxy not detected");
} catch (IllegalArgumentException iax) {
// expected
}
}
@Test
public void testCstr6() {
// test convenience constructor with 6 arguments
HttpRoute route = new HttpRoute
@ -582,7 +565,7 @@ public class TestHttpRoute extends TestCase {
HttpRoute should = new HttpRoute
(TARGET2, null, new HttpHost[]{ PROXY2 }, true,
TunnelType.TUNNELLED, LayerType.PLAIN);
assertEquals("bad convenience route 6/proxied", route, should);
Assert.assertEquals("bad convenience route 6/proxied", route, should);
route = new HttpRoute
(TARGET2, null, (HttpHost) null, true,
@ -590,12 +573,12 @@ public class TestHttpRoute extends TestCase {
should = new HttpRoute
(TARGET2, null, (HttpHost[]) null, true,
TunnelType.PLAIN, LayerType.LAYERED);
assertEquals("bad convenience route 6/direct", route, should);
Assert.assertEquals("bad convenience route 6/direct", route, should);
// handling of null vs. empty chain is checked in the equals tests
}
@Test
public void testImmutable() throws CloneNotSupportedException {
HttpHost[] proxies = new HttpHost[]{ PROXY1, PROXY2, PROXY3 };
@ -610,9 +593,8 @@ public class TestHttpRoute extends TestCase {
proxies[1] = PROXY3;
proxies[2] = PROXY2;
assertEquals("route differs from clone", route2, route1);
assertEquals("route was modified", route3, route1);
Assert.assertEquals("route differs from clone", route2, route1);
Assert.assertEquals("route was modified", route3, route1);
}
} // class TestHttpRoute
}

View File

@ -27,22 +27,18 @@
package org.apache.http.conn.routing;
import java.net.InetAddress;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.apache.http.HttpHost;
import org.apache.http.conn.routing.RouteInfo.TunnelType;
import org.apache.http.conn.routing.RouteInfo.LayerType;
import org.junit.Assert;
import org.junit.Test;
/**
* Tests for <code>BasicRouteDirector</code>.
* Tests for {@link BasicRouteDirector}.
*/
public class TestRouteDirector extends TestCase {
public class TestRouteDirector {
// a selection of constants for generating routes
public final static
@ -83,35 +79,14 @@ public class TestRouteDirector extends TestCase {
}
}
public TestRouteDirector(String testName) {
super(testName);
}
public static void main(String args[]) {
String[] testCaseName = { TestRouteDirector.class.getName() };
junit.textui.TestRunner.main(testCaseName);
}
public static Test suite() {
return new TestSuite(TestRouteDirector.class);
}
@Test(expected=IllegalArgumentException.class)
public void testIllegal() {
HttpRouteDirector rowdy = new BasicRouteDirector();
HttpRoute route = new HttpRoute(TARGET1);
try {
rowdy.nextStep(null, route);
fail("null argument not detected");
} catch (IllegalArgumentException iax) {
// expected
}
rowdy.nextStep(null, route);
}
@Test
public void testDirect() {
HttpRouteDirector rowdy = new BasicRouteDirector();
@ -120,31 +95,31 @@ public class TestRouteDirector extends TestCase {
HttpRoute route1p1 = new HttpRoute(TARGET1, null, PROXY1, false);
int step = rowdy.nextStep(route1, null);
assertEquals("wrong step to route1",
Assert.assertEquals("wrong step to route1",
HttpRouteDirector.CONNECT_TARGET, step);
step = rowdy.nextStep(route2, null);
assertEquals("wrong step to route2",
Assert.assertEquals("wrong step to route2",
HttpRouteDirector.CONNECT_TARGET, step);
step = rowdy.nextStep(route1, route1);
assertEquals("complete route1 not detected",
Assert.assertEquals("complete route1 not detected",
HttpRouteDirector.COMPLETE, step);
step = rowdy.nextStep(route2, route2);
assertEquals("complete route2 not detected",
Assert.assertEquals("complete route2 not detected",
HttpRouteDirector.COMPLETE, step);
step = rowdy.nextStep(route1, route2);
assertEquals("unreachable target not detected",
Assert.assertEquals("unreachable target not detected",
HttpRouteDirector.UNREACHABLE, step);
step = rowdy.nextStep(route1, route1p1);
assertEquals("invalid proxy not detected",
Assert.assertEquals("invalid proxy not detected",
HttpRouteDirector.UNREACHABLE, step);
}
@Test
public void testProxy() {
HttpRouteDirector rowdy = new BasicRouteDirector();
@ -155,43 +130,43 @@ public class TestRouteDirector extends TestCase {
HttpRoute route1 = new HttpRoute(TARGET1);
int step = rowdy.nextStep(route1p1, null);
assertEquals("wrong step to route1p1",
Assert.assertEquals("wrong step to route1p1",
HttpRouteDirector.CONNECT_PROXY, step);
step = rowdy.nextStep(route1p2, null);
assertEquals("wrong step to route1p2",
Assert.assertEquals("wrong step to route1p2",
HttpRouteDirector.CONNECT_PROXY, step);
step = rowdy.nextStep(route1p1, route1p1);
assertEquals("complete route1p1 not detected",
Assert.assertEquals("complete route1p1 not detected",
HttpRouteDirector.COMPLETE, step);
step = rowdy.nextStep(route1p2, route1p2);
assertEquals("complete route1p2 not detected",
Assert.assertEquals("complete route1p2 not detected",
HttpRouteDirector.COMPLETE, step);
step = rowdy.nextStep(route2p1, route2p1);
assertEquals("complete route2p1 not detected",
Assert.assertEquals("complete route2p1 not detected",
HttpRouteDirector.COMPLETE, step);
step = rowdy.nextStep(route1p1, route1p2);
assertEquals("unreachable route1p1 via route1p2 not detected",
Assert.assertEquals("unreachable route1p1 via route1p2 not detected",
HttpRouteDirector.UNREACHABLE, step);
step = rowdy.nextStep(route1p1, route2p1);
assertEquals("unreachable route1p1 via route2p1 not detected",
Assert.assertEquals("unreachable route1p1 via route2p1 not detected",
HttpRouteDirector.UNREACHABLE, step);
step = rowdy.nextStep(route1p1, route0);
assertEquals("unreachable route1p1 via route0 not detected",
Assert.assertEquals("unreachable route1p1 via route0 not detected",
HttpRouteDirector.UNREACHABLE, step);
step = rowdy.nextStep(route1p1, route1);
assertEquals("unreachable route1p1 via route1 not detected",
Assert.assertEquals("unreachable route1p1 via route1 not detected",
HttpRouteDirector.UNREACHABLE, step);
}
@Test
public void testProxyChain() {
HttpHost[] chainA = { PROXY1 };
HttpHost[] chainB = { PROXY1, PROXY2 };
@ -208,45 +183,45 @@ public class TestRouteDirector extends TestCase {
TunnelType.PLAIN, LayerType.PLAIN);
int step = rowdy.nextStep(route1cA, null);
assertEquals("wrong step to route1cA",
Assert.assertEquals("wrong step to route1cA",
HttpRouteDirector.CONNECT_PROXY, step);
step = rowdy.nextStep(route1cB, null);
assertEquals("wrong step to route1cB",
Assert.assertEquals("wrong step to route1cB",
HttpRouteDirector.CONNECT_PROXY, step);
step = rowdy.nextStep(route1cC, null);
assertEquals("wrong step to route1cC",
Assert.assertEquals("wrong step to route1cC",
HttpRouteDirector.CONNECT_PROXY, step);
step = rowdy.nextStep(route1cD, null);
assertEquals("wrong step to route1cD",
Assert.assertEquals("wrong step to route1cD",
HttpRouteDirector.CONNECT_PROXY, step);
step = rowdy.nextStep(route1cB, route1cA);
assertEquals("wrong step to route 1cB from 1cA",
Assert.assertEquals("wrong step to route 1cB from 1cA",
HttpRouteDirector.TUNNEL_PROXY, step);
step = rowdy.nextStep(route1cB, route1cB);
assertEquals("complete route 1cB not detected",
Assert.assertEquals("complete route 1cB not detected",
HttpRouteDirector.COMPLETE, step);
step = rowdy.nextStep(route1cB, route1cC);
assertEquals("unreachable route 1cB from 1cC not detected",
Assert.assertEquals("unreachable route 1cB from 1cC not detected",
HttpRouteDirector.UNREACHABLE, step);
step = rowdy.nextStep(route1cB, route1cD);
assertEquals("unreachable route 1cB from 1cD not detected",
Assert.assertEquals("unreachable route 1cB from 1cD not detected",
HttpRouteDirector.UNREACHABLE, step);
step = rowdy.nextStep(route1cA, route1cB);
assertEquals("unreachable route 1cA from 1cB not detected",
Assert.assertEquals("unreachable route 1cA from 1cB not detected",
HttpRouteDirector.UNREACHABLE, step);
}
@Test
public void testLocalDirect() {
HttpRouteDirector rowdy = new BasicRouteDirector();
@ -256,65 +231,65 @@ public class TestRouteDirector extends TestCase {
HttpRoute route1l00 = new HttpRoute(TARGET1, null, false);
int step = rowdy.nextStep(route1l41, null);
assertEquals("wrong step to route1l41",
Assert.assertEquals("wrong step to route1l41",
HttpRouteDirector.CONNECT_TARGET, step);
step = rowdy.nextStep(route1l42, null);
assertEquals("wrong step to route1l42",
Assert.assertEquals("wrong step to route1l42",
HttpRouteDirector.CONNECT_TARGET, step);
step = rowdy.nextStep(route1l61, null);
assertEquals("wrong step to route1l61",
Assert.assertEquals("wrong step to route1l61",
HttpRouteDirector.CONNECT_TARGET, step);
step = rowdy.nextStep(route1l00, null);
assertEquals("wrong step to route1l00",
Assert.assertEquals("wrong step to route1l00",
HttpRouteDirector.CONNECT_TARGET, step);
step = rowdy.nextStep(route1l41, route1l41);
assertEquals("complete route1l41 not detected",
Assert.assertEquals("complete route1l41 not detected",
HttpRouteDirector.COMPLETE, step);
step = rowdy.nextStep(route1l42, route1l42);
assertEquals("complete route1l42 not detected",
Assert.assertEquals("complete route1l42 not detected",
HttpRouteDirector.COMPLETE, step);
step = rowdy.nextStep(route1l61, route1l61);
assertEquals("complete route1l61 not detected",
Assert.assertEquals("complete route1l61 not detected",
HttpRouteDirector.COMPLETE, step);
step = rowdy.nextStep(route1l00, route1l00);
assertEquals("complete route1l00 not detected",
Assert.assertEquals("complete route1l00 not detected",
HttpRouteDirector.COMPLETE, step);
step = rowdy.nextStep(route1l41, route1l42);
assertEquals("unreachable route1l41 via route1l42 not detected",
Assert.assertEquals("unreachable route1l41 via route1l42 not detected",
HttpRouteDirector.UNREACHABLE, step);
step = rowdy.nextStep(route1l41, route1l61);
assertEquals("unreachable route1l41 via route1l61 not detected",
Assert.assertEquals("unreachable route1l41 via route1l61 not detected",
HttpRouteDirector.UNREACHABLE, step);
step = rowdy.nextStep(route1l41, route1l00);
assertEquals("unreachable route1l41 via route1l00 not detected",
Assert.assertEquals("unreachable route1l41 via route1l00 not detected",
HttpRouteDirector.UNREACHABLE, step);
step = rowdy.nextStep(route1l00, route1l41);
assertEquals("complete route1l00 as route1l41 not detected",
Assert.assertEquals("complete route1l00 as route1l41 not detected",
HttpRouteDirector.COMPLETE, step);
step = rowdy.nextStep(route1l00, route1l42);
assertEquals("complete route1l00 as route1l42 not detected",
Assert.assertEquals("complete route1l00 as route1l42 not detected",
HttpRouteDirector.COMPLETE, step);
step = rowdy.nextStep(route1l00, route1l61);
assertEquals("complete route1l00 as route1l61 not detected",
Assert.assertEquals("complete route1l00 as route1l61 not detected",
HttpRouteDirector.COMPLETE, step);
}
@Test
public void testDirectSecure() {
HttpRouteDirector rowdy = new BasicRouteDirector();
@ -324,35 +299,35 @@ public class TestRouteDirector extends TestCase {
HttpRoute route1p1s = new HttpRoute(TARGET1, null, PROXY1, true);
int step = rowdy.nextStep(route1u, null);
assertEquals("wrong step to route1u",
Assert.assertEquals("wrong step to route1u",
HttpRouteDirector.CONNECT_TARGET, step);
step = rowdy.nextStep(route1s, null);
assertEquals("wrong step to route1s",
Assert.assertEquals("wrong step to route1s",
HttpRouteDirector.CONNECT_TARGET, step);
// unrequested security is currently not tolerated
step = rowdy.nextStep(route1u, route1s);
assertEquals("unreachable route 1u from 1s not detected",
Assert.assertEquals("unreachable route 1u from 1s not detected",
HttpRouteDirector.UNREACHABLE, step);
// secure layering of direct connections is currently not supported
step = rowdy.nextStep(route1s, route1u);
assertEquals("unreachable route 1s from 1u not detected",
Assert.assertEquals("unreachable route 1s from 1u not detected",
HttpRouteDirector.UNREACHABLE, step);
step = rowdy.nextStep(route1s, route1p1u);
assertEquals("unreachable route 1s from 1p1u not detected",
Assert.assertEquals("unreachable route 1s from 1p1u not detected",
HttpRouteDirector.UNREACHABLE, step);
step = rowdy.nextStep(route1s, route1p1s);
assertEquals("unreachable route 1s from 1p1s not detected",
Assert.assertEquals("unreachable route 1s from 1p1s not detected",
HttpRouteDirector.UNREACHABLE, step);
}
@Test
public void testProxyTLS() {
HttpRouteDirector rowdy = new BasicRouteDirector();
@ -378,118 +353,118 @@ public class TestRouteDirector extends TestCase {
// we don't consider a route that is layered but not tunnelled
int step = rowdy.nextStep(route1, null);
assertEquals("wrong step to route1",
Assert.assertEquals("wrong step to route1",
HttpRouteDirector.CONNECT_PROXY, step);
step = rowdy.nextStep(route1t, null);
assertEquals("wrong step to route1t",
Assert.assertEquals("wrong step to route1t",
HttpRouteDirector.CONNECT_PROXY, step);
step = rowdy.nextStep(route1tl, null);
assertEquals("wrong step to route1tl",
Assert.assertEquals("wrong step to route1tl",
HttpRouteDirector.CONNECT_PROXY, step);
step = rowdy.nextStep(route1s, null);
assertEquals("wrong step to route1s",
Assert.assertEquals("wrong step to route1s",
HttpRouteDirector.CONNECT_PROXY, step);
step = rowdy.nextStep(route1ts, null);
assertEquals("wrong step to route1ts",
Assert.assertEquals("wrong step to route1ts",
HttpRouteDirector.CONNECT_PROXY, step);
step = rowdy.nextStep(route1tls, null);
assertEquals("wrong step to route1tls",
Assert.assertEquals("wrong step to route1tls",
HttpRouteDirector.CONNECT_PROXY, step);
step = rowdy.nextStep(route1, route1);
assertEquals("complete route1 not detected",
Assert.assertEquals("complete route1 not detected",
HttpRouteDirector.COMPLETE, step);
step = rowdy.nextStep(route1t, route1t);
assertEquals("complete route1t not detected",
Assert.assertEquals("complete route1t not detected",
HttpRouteDirector.COMPLETE, step);
step = rowdy.nextStep(route1tl, route1tl);
assertEquals("complete route1tl not detected",
Assert.assertEquals("complete route1tl not detected",
HttpRouteDirector.COMPLETE, step);
step = rowdy.nextStep(route1s, route1s);
assertEquals("complete route1s not detected",
Assert.assertEquals("complete route1s not detected",
HttpRouteDirector.COMPLETE, step);
step = rowdy.nextStep(route1ts, route1ts);
assertEquals("complete route1ts not detected",
Assert.assertEquals("complete route1ts not detected",
HttpRouteDirector.COMPLETE, step);
step = rowdy.nextStep(route1tls, route1tls);
assertEquals("complete route1tls not detected",
Assert.assertEquals("complete route1tls not detected",
HttpRouteDirector.COMPLETE, step);
step = rowdy.nextStep(route1, route1t);
assertEquals("unreachable route1 from 1t not detected",
Assert.assertEquals("unreachable route1 from 1t not detected",
HttpRouteDirector.UNREACHABLE, step);
step = rowdy.nextStep(route1, route1tl);
assertEquals("unreachable route1 from 1tl not detected",
Assert.assertEquals("unreachable route1 from 1tl not detected",
HttpRouteDirector.UNREACHABLE, step);
// unrequested security is currently not tolerated
step = rowdy.nextStep(route1, route1s);
assertEquals("unreachable route1 from 1s not detected",
Assert.assertEquals("unreachable route1 from 1s not detected",
HttpRouteDirector.UNREACHABLE, step);
step = rowdy.nextStep(route1, route1ts);
assertEquals("unreachable route1 from 1ts not detected",
Assert.assertEquals("unreachable route1 from 1ts not detected",
HttpRouteDirector.UNREACHABLE, step);
step = rowdy.nextStep(route1, route1tls);
assertEquals("unreachable route1 from 1tls not detected",
Assert.assertEquals("unreachable route1 from 1tls not detected",
HttpRouteDirector.UNREACHABLE, step);
// securing requires layering
step = rowdy.nextStep(route1s, route1);
assertEquals("unreachable route1s from 1 not detected",
Assert.assertEquals("unreachable route1s from 1 not detected",
HttpRouteDirector.UNREACHABLE, step);
// securing requires layering, and multiple layers are not supported
step = rowdy.nextStep(route1tls, route1tl);
assertEquals("unreachable route1tls from 1tl not detected",
Assert.assertEquals("unreachable route1tls from 1tl not detected",
HttpRouteDirector.UNREACHABLE, step);
// cases where tunnelling to the target is required
step = rowdy.nextStep(route1t, route1);
assertEquals("wrong step to route1t from 1",
Assert.assertEquals("wrong step to route1t from 1",
HttpRouteDirector.TUNNEL_TARGET, step);
step = rowdy.nextStep(route1tl, route1);
assertEquals("wrong step to route1tl from 1",
Assert.assertEquals("wrong step to route1tl from 1",
HttpRouteDirector.TUNNEL_TARGET, step);
step = rowdy.nextStep(route1tls, route1);
assertEquals("wrong step to route1tls from 1",
Assert.assertEquals("wrong step to route1tls from 1",
HttpRouteDirector.TUNNEL_TARGET, step);
// cases where layering on the tunnel is required
step = rowdy.nextStep(route1tl, route1t);
assertEquals("wrong step to route1tl from 1t",
Assert.assertEquals("wrong step to route1tl from 1t",
HttpRouteDirector.LAYER_PROTOCOL, step);
step = rowdy.nextStep(route1tl, route1ts);
assertEquals("wrong step to route1tl from 1ts",
Assert.assertEquals("wrong step to route1tl from 1ts",
HttpRouteDirector.LAYER_PROTOCOL, step);
step = rowdy.nextStep(route1tls, route1t);
assertEquals("wrong step to route1tls from 1t",
Assert.assertEquals("wrong step to route1tls from 1t",
HttpRouteDirector.LAYER_PROTOCOL, step);
step = rowdy.nextStep(route1tls, route1ts);
assertEquals("wrong step to route1tls from 1ts",
Assert.assertEquals("wrong step to route1tls from 1ts",
HttpRouteDirector.LAYER_PROTOCOL, step);
// There are some odd cases left over, like having a secure tunnel
@ -497,5 +472,4 @@ public class TestRouteDirector extends TestCase {
// proxy that becomes unsecure by tunnelling to another proxy.
}
} // class TestRouteDirector
}

View File

@ -27,24 +27,20 @@
package org.apache.http.conn.routing;
import java.net.InetAddress;
import java.util.HashSet;
import java.util.Set;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.apache.http.HttpHost;
import org.apache.http.conn.routing.RouteInfo.TunnelType;
import org.apache.http.conn.routing.RouteInfo.LayerType;
import org.junit.Assert;
import org.junit.Test;
/**
* Tests for <code>RouteTracker</code>.
* Tests for {@link RouteTracker}.
*/
public class TestRouteTracker extends TestCase {
public class TestRouteTracker {
// a selection of constants for generating routes
public final static
@ -85,47 +81,33 @@ public class TestRouteTracker extends TestCase {
}
}
public TestRouteTracker(String testName) {
super(testName);
}
public static void main(String args[]) {
String[] testCaseName = { TestRouteTracker.class.getName() };
junit.textui.TestRunner.main(testCaseName);
}
public static Test suite() {
return new TestSuite(TestRouteTracker.class);
}
@Test
public void testCstrTargetLocal() {
RouteTracker rt = new RouteTracker(TARGET1, null);
assertEquals("wrong target (target,null)",
Assert.assertEquals("wrong target (target,null)",
TARGET1, rt.getTargetHost());
assertEquals("wrong local address (target,null)",
Assert.assertEquals("wrong local address (target,null)",
null, rt.getLocalAddress());
assertEquals("wrong hop count (target,null)",
Assert.assertEquals("wrong hop count (target,null)",
0, rt.getHopCount());
assertEquals("wrong proxy (target,null)",
Assert.assertEquals("wrong proxy (target,null)",
null, rt.getProxyHost());
assertEquals("wrong route (target,null)",
Assert.assertEquals("wrong route (target,null)",
null, rt.toRoute());
checkCTLS(rt, false, false, false, false);
rt = new RouteTracker(TARGET2, LOCAL61);
assertEquals("wrong target (target,local)",
Assert.assertEquals("wrong target (target,local)",
TARGET2, rt.getTargetHost());
assertEquals("wrong local address (target,local)",
Assert.assertEquals("wrong local address (target,local)",
LOCAL61, rt.getLocalAddress());
assertEquals("wrong hop count (target,local)",
Assert.assertEquals("wrong hop count (target,local)",
0, rt.getHopCount());
assertEquals("wrong proxy (target,local)",
Assert.assertEquals("wrong proxy (target,local)",
null, rt.getProxyHost());
assertEquals("wrong route (target,local)",
Assert.assertEquals("wrong route (target,local)",
null, rt.toRoute());
checkCTLS(rt, false, false, false, false);
@ -133,55 +115,55 @@ public class TestRouteTracker extends TestCase {
rt = null;
try {
new RouteTracker(null, LOCAL41);
fail("null target not detected");
Assert.fail("null target not detected");
} catch (IllegalArgumentException iax) {
// expected
}
}
@Test
public void testCstrRoute() {
HttpRoute r = new HttpRoute(TARGET1);
RouteTracker rt = new RouteTracker(r);
assertEquals("wrong target (r1)",
Assert.assertEquals("wrong target (r1)",
TARGET1, rt.getTargetHost());
assertEquals("wrong local address (r1)",
Assert.assertEquals("wrong local address (r1)",
null, rt.getLocalAddress());
assertEquals("wrong hop count (r1)",
Assert.assertEquals("wrong hop count (r1)",
0, rt.getHopCount());
assertEquals("wrong proxy (r1)",
Assert.assertEquals("wrong proxy (r1)",
null, rt.getProxyHost());
assertEquals("wrong route (r1)",
Assert.assertEquals("wrong route (r1)",
null, rt.toRoute());
checkCTLS(rt, false, false, false, false);
r = new HttpRoute(TARGET2, LOCAL61, true);
rt = new RouteTracker(r);
assertEquals("wrong target (r2)",
Assert.assertEquals("wrong target (r2)",
TARGET2, rt.getTargetHost());
assertEquals("wrong local address (r2)",
Assert.assertEquals("wrong local address (r2)",
LOCAL61, rt.getLocalAddress());
assertEquals("wrong hop count (r2)",
Assert.assertEquals("wrong hop count (r2)",
0, rt.getHopCount());
assertEquals("wrong proxy (r2)",
Assert.assertEquals("wrong proxy (r2)",
null, rt.getProxyHost());
assertEquals("wrong route (r2)",
Assert.assertEquals("wrong route (r2)",
null, rt.toRoute());
checkCTLS(rt, false, false, false, false);
r = new HttpRoute(TARGET1, LOCAL42, PROXY3, true);
rt = new RouteTracker(r);
assertEquals("wrong target (r3)",
Assert.assertEquals("wrong target (r3)",
TARGET1, rt.getTargetHost());
assertEquals("wrong local address (r3)",
Assert.assertEquals("wrong local address (r3)",
LOCAL42, rt.getLocalAddress());
assertEquals("wrong hop count (r3)",
Assert.assertEquals("wrong hop count (r3)",
0, rt.getHopCount());
assertEquals("wrong proxy (r3)",
Assert.assertEquals("wrong proxy (r3)",
null, rt.getProxyHost());
assertEquals("wrong route (r3)",
Assert.assertEquals("wrong route (r3)",
null, rt.toRoute());
checkCTLS(rt, false, false, false, false);
@ -189,27 +171,27 @@ public class TestRouteTracker extends TestCase {
rt = null;
try {
new RouteTracker(null);
fail("null route not detected");
Assert.fail("null route not detected");
} catch (NullPointerException npx) {
// expected
}
}
@Test
public void testIllegalArgs() {
RouteTracker rt = new RouteTracker(TARGET2, null);
try {
rt.connectProxy(null, true);
fail("missing proxy argument not detected (connect/false)");
Assert.fail("missing proxy argument not detected (connect/false)");
} catch (IllegalArgumentException iax) {
// expected
}
try {
rt.connectProxy(null, false);
fail("missing proxy argument not detected (connect/true)");
Assert.fail("missing proxy argument not detected (connect/true)");
} catch (IllegalArgumentException iax) {
// expected
}
@ -218,55 +200,55 @@ public class TestRouteTracker extends TestCase {
try {
rt.tunnelProxy(null, false);
fail("missing proxy argument not detected (tunnel/false)");
Assert.fail("missing proxy argument not detected (tunnel/false)");
} catch (IllegalArgumentException iax) {
// expected
}
try {
rt.tunnelProxy(null, true);
fail("missing proxy argument not detected (tunnel/true)");
Assert.fail("missing proxy argument not detected (tunnel/true)");
} catch (IllegalArgumentException iax) {
// expected
}
try {
rt.getHopTarget(-1);
fail("negative hop index not detected");
Assert.fail("negative hop index not detected");
} catch (IllegalArgumentException iax) {
// expected
}
try {
rt.getHopTarget(2);
fail("excessive hop index not detected");
Assert.fail("excessive hop index not detected");
} catch (IllegalArgumentException iax) {
// expected
}
}
@Test
public void testIllegalStates() {
RouteTracker rt = new RouteTracker(TARGET1, null);
try {
rt.tunnelTarget(false);
fail("unconnectedness not detected (tunnelTarget)");
Assert.fail("unconnectedness not detected (tunnelTarget)");
} catch (IllegalStateException isx) {
// expected
}
try {
rt.tunnelProxy(PROXY1, false);
fail("unconnectedness not detected (tunnelProxy)");
Assert.fail("unconnectedness not detected (tunnelProxy)");
} catch (IllegalStateException isx) {
// expected
}
try {
rt.layerProtocol(true);
fail("unconnectedness not detected (layerProtocol)");
Assert.fail("unconnectedness not detected (layerProtocol)");
} catch (IllegalStateException isx) {
// expected
}
@ -277,79 +259,79 @@ public class TestRouteTracker extends TestCase {
try {
rt.connectTarget(false);
fail("connectedness not detected (connectTarget)");
Assert.fail("connectedness not detected (connectTarget)");
} catch (IllegalStateException isx) {
// expected
}
try {
rt.connectProxy(PROXY2, false);
fail("connectedness not detected (connectProxy)");
Assert.fail("connectedness not detected (connectProxy)");
} catch (IllegalStateException isx) {
// expected
}
try {
rt.tunnelTarget(false);
fail("unproxiedness not detected (tunnelTarget)");
Assert.fail("unproxiedness not detected (tunnelTarget)");
} catch (IllegalStateException isx) {
// expected
}
try {
rt.tunnelProxy(PROXY1, false);
fail("unproxiedness not detected (tunnelProxy)");
Assert.fail("unproxiedness not detected (tunnelProxy)");
} catch (IllegalStateException isx) {
// expected
}
}
@Test
public void testDirectRoutes() {
final HttpRouteDirector rd = new BasicRouteDirector();
HttpRoute r = new HttpRoute(TARGET1, LOCAL41, false);
RouteTracker rt = new RouteTracker(r);
boolean complete = checkVia(rt, r, rd, 2);
assertTrue("incomplete route 1", complete);
Assert.assertTrue("incomplete route 1", complete);
r = new HttpRoute(TARGET2, LOCAL62, true);
rt = new RouteTracker(r);
complete = checkVia(rt, r, rd, 2);
assertTrue("incomplete route 2", complete);
Assert.assertTrue("incomplete route 2", complete);
}
@Test
public void testProxyRoutes() {
final HttpRouteDirector rd = new BasicRouteDirector();
HttpRoute r = new HttpRoute(TARGET2, null, PROXY1, false);
RouteTracker rt = new RouteTracker(r);
boolean complete = checkVia(rt, r, rd, 2);
assertTrue("incomplete route 1", complete);
Assert.assertTrue("incomplete route 1", complete);
// tunnelled, but neither secure nor layered
r = new HttpRoute(TARGET1, LOCAL61, PROXY3, false,
TunnelType.TUNNELLED, LayerType.PLAIN);
rt = new RouteTracker(r);
complete = checkVia(rt, r, rd, 3);
assertTrue("incomplete route 2", complete);
Assert.assertTrue("incomplete route 2", complete);
// tunnelled, layered, but not secure
r = new HttpRoute(TARGET1, LOCAL61, PROXY3, false,
TunnelType.TUNNELLED, LayerType.LAYERED);
rt = new RouteTracker(r);
complete = checkVia(rt, r, rd, 4);
assertTrue("incomplete route 3", complete);
Assert.assertTrue("incomplete route 3", complete);
// tunnelled, layered, secure
r = new HttpRoute(TARGET1, LOCAL61, PROXY3, true);
rt = new RouteTracker(r);
complete = checkVia(rt, r, rd, 4);
assertTrue("incomplete route 4", complete);
Assert.assertTrue("incomplete route 4", complete);
}
@Test
public void testProxyChainRoutes() {
final HttpRouteDirector rd = new BasicRouteDirector();
@ -358,7 +340,7 @@ public class TestRouteTracker extends TestCase {
TunnelType.PLAIN, LayerType.PLAIN);
RouteTracker rt = new RouteTracker(r);
boolean complete = checkVia(rt, r, rd, 3);
assertTrue("incomplete route 1", complete);
Assert.assertTrue("incomplete route 1", complete);
// tunnelled, but neither secure nor layered
proxies = new HttpHost[]{ PROXY3, PROXY2 };
@ -366,7 +348,7 @@ public class TestRouteTracker extends TestCase {
TunnelType.TUNNELLED, LayerType.PLAIN);
rt = new RouteTracker(r);
complete = checkVia(rt, r, rd, 4);
assertTrue("incomplete route 2", complete);
Assert.assertTrue("incomplete route 2", complete);
// tunnelled, layered, but not secure
proxies = new HttpHost[]{ PROXY3, PROXY2, PROXY1 };
@ -374,7 +356,7 @@ public class TestRouteTracker extends TestCase {
TunnelType.TUNNELLED, LayerType.LAYERED);
rt = new RouteTracker(r);
complete = checkVia(rt, r, rd, 6);
assertTrue("incomplete route 3", complete);
Assert.assertTrue("incomplete route 3", complete);
// tunnelled, layered, secure
proxies = new HttpHost[]{ PROXY1, PROXY3 };
@ -382,10 +364,10 @@ public class TestRouteTracker extends TestCase {
TunnelType.TUNNELLED, LayerType.LAYERED);
rt = new RouteTracker(r);
complete = checkVia(rt, r, rd, 5);
assertTrue("incomplete route 4", complete);
Assert.assertTrue("incomplete route 4", complete);
}
@Test
public void testEqualsHashcodeCloneToString()
throws CloneNotSupportedException {
@ -393,25 +375,25 @@ public class TestRouteTracker extends TestCase {
RouteTracker rt4 = new RouteTracker(TARGET1, LOCAL41);
RouteTracker rt6 = new RouteTracker(TARGET1, LOCAL62);
assertFalse("rt0", rt0.equals(null));
assertTrue("rt0", rt0.equals(rt0));
assertFalse("rt0", rt0.equals(rt0.toString()));
Assert.assertFalse("rt0", rt0.equals(null));
Assert.assertTrue("rt0", rt0.equals(rt0));
Assert.assertFalse("rt0", rt0.equals(rt0.toString()));
assertFalse("rt0 == rt4", rt0.equals(rt4));
assertFalse("rt4 == rt0", rt4.equals(rt0));
assertFalse("rt0 == rt6", rt0.equals(rt6));
assertFalse("rt6 == rt0", rt6.equals(rt0));
assertFalse("rt4 == rt6", rt4.equals(rt6));
assertFalse("rt6 == rt4", rt6.equals(rt4));
Assert.assertFalse("rt0 == rt4", rt0.equals(rt4));
Assert.assertFalse("rt4 == rt0", rt4.equals(rt0));
Assert.assertFalse("rt0 == rt6", rt0.equals(rt6));
Assert.assertFalse("rt6 == rt0", rt6.equals(rt0));
Assert.assertFalse("rt4 == rt6", rt4.equals(rt6));
Assert.assertFalse("rt6 == rt4", rt6.equals(rt4));
// it is likely but not guaranteed that the hashcodes are different
assertFalse("rt0 == rt4 (hashcode)", rt0.hashCode() == rt4.hashCode());
assertFalse("rt0 == rt6 (hashcode)", rt0.hashCode() == rt6.hashCode());
assertFalse("rt6 == rt4 (hashcode)", rt6.hashCode() == rt4.hashCode());
Assert.assertFalse("rt0 == rt4 (hashcode)", rt0.hashCode() == rt4.hashCode());
Assert.assertFalse("rt0 == rt6 (hashcode)", rt0.hashCode() == rt6.hashCode());
Assert.assertFalse("rt6 == rt4 (hashcode)", rt6.hashCode() == rt4.hashCode());
assertEquals("rt0 (clone)", rt0, rt0.clone());
assertEquals("rt4 (clone)", rt4, rt4.clone());
assertEquals("rt6 (clone)", rt6, rt6.clone());
Assert.assertEquals("rt0 (clone)", rt0, rt0.clone());
Assert.assertEquals("rt4 (clone)", rt4, rt4.clone());
Assert.assertEquals("rt6 (clone)", rt6, rt6.clone());
// we collect (clones of) the different tracked routes along the way
@ -429,127 +411,127 @@ public class TestRouteTracker extends TestCase {
RouteTracker rt = null;
assertTrue(hs.add(rt0));
assertTrue(hs.add(rt4));
assertTrue(hs.add(rt6));
Assert.assertTrue(hs.add(rt0));
Assert.assertTrue(hs.add(rt4));
Assert.assertTrue(hs.add(rt6));
assertTrue(hc0.add(Integer.valueOf(rt0.hashCode())));
assertTrue(hc4.add(Integer.valueOf(rt4.hashCode())));
assertTrue(hc6.add(Integer.valueOf(rt6.hashCode())));
Assert.assertTrue(hc0.add(Integer.valueOf(rt0.hashCode())));
Assert.assertTrue(hc4.add(Integer.valueOf(rt4.hashCode())));
Assert.assertTrue(hc6.add(Integer.valueOf(rt6.hashCode())));
rt = (RouteTracker) rt0.clone();
rt.connectTarget(false);
assertTrue(hs.add(rt));
assertTrue(hc0.add(Integer.valueOf(rt.hashCode())));
Assert.assertTrue(hs.add(rt));
Assert.assertTrue(hc0.add(Integer.valueOf(rt.hashCode())));
rt = (RouteTracker) rt0.clone();
rt.connectTarget(true);
assertTrue(hs.add(rt));
assertTrue(hc0.add(Integer.valueOf(rt.hashCode())));
Assert.assertTrue(hs.add(rt));
Assert.assertTrue(hc0.add(Integer.valueOf(rt.hashCode())));
// proxy (insecure) -> tunnel (insecure) -> layer (secure)
rt = (RouteTracker) rt4.clone();
rt.connectProxy(PROXY1, false);
assertTrue(hs.add((RouteTracker) rt.clone()));
Assert.assertTrue(hs.add((RouteTracker) rt.clone()));
// this is not guaranteed to be unique...
assertTrue(hc4.add(Integer.valueOf(rt.hashCode())));
Assert.assertTrue(hc4.add(Integer.valueOf(rt.hashCode())));
rt.tunnelTarget(false);
assertTrue(hs.add((RouteTracker) rt.clone()));
assertTrue(hc4.add(Integer.valueOf(rt.hashCode())));
Assert.assertTrue(hs.add((RouteTracker) rt.clone()));
Assert.assertTrue(hc4.add(Integer.valueOf(rt.hashCode())));
rt.layerProtocol(true);
assertTrue(hs.add((RouteTracker) rt.clone()));
assertTrue(hc4.add(Integer.valueOf(rt.hashCode())));
Assert.assertTrue(hs.add((RouteTracker) rt.clone()));
Assert.assertTrue(hc4.add(Integer.valueOf(rt.hashCode())));
// proxy (secure) -> tunnel (secure) -> layer (insecure)
rt = (RouteTracker) rt4.clone();
rt.connectProxy(PROXY1, true);
assertTrue(hs.add((RouteTracker) rt.clone()));
Assert.assertTrue(hs.add((RouteTracker) rt.clone()));
// this is not guaranteed to be unique...
assertTrue(hc4.add(Integer.valueOf(rt.hashCode())));
Assert.assertTrue(hc4.add(Integer.valueOf(rt.hashCode())));
rt.tunnelTarget(true);
assertTrue(hs.add((RouteTracker) rt.clone()));
assertTrue(hc4.add(Integer.valueOf(rt.hashCode())));
Assert.assertTrue(hs.add((RouteTracker) rt.clone()));
Assert.assertTrue(hc4.add(Integer.valueOf(rt.hashCode())));
rt.layerProtocol(false);
assertTrue(hs.add((RouteTracker) rt.clone()));
assertTrue(hc4.add(Integer.valueOf(rt.hashCode())));
Assert.assertTrue(hs.add((RouteTracker) rt.clone()));
Assert.assertTrue(hc4.add(Integer.valueOf(rt.hashCode())));
// PROXY1/i -> PROXY2/i -> tunnel/i -> layer/s
rt = (RouteTracker) rt6.clone();
rt.connectProxy(PROXY1, false);
assertTrue(hs.add((RouteTracker) rt.clone()));
Assert.assertTrue(hs.add((RouteTracker) rt.clone()));
// this is not guaranteed to be unique...
assertTrue(hc6.add(Integer.valueOf(rt.hashCode())));
Assert.assertTrue(hc6.add(Integer.valueOf(rt.hashCode())));
rt.tunnelProxy(PROXY2, false);
assertTrue(hs.add((RouteTracker) rt.clone()));
Assert.assertTrue(hs.add((RouteTracker) rt.clone()));
// this is not guaranteed to be unique...
assertTrue(hc6.add(Integer.valueOf(rt.hashCode())));
Assert.assertTrue(hc6.add(Integer.valueOf(rt.hashCode())));
rt.tunnelTarget(false);
assertTrue(hs.add((RouteTracker) rt.clone()));
assertTrue(hc6.add(Integer.valueOf(rt.hashCode())));
Assert.assertTrue(hs.add((RouteTracker) rt.clone()));
Assert.assertTrue(hc6.add(Integer.valueOf(rt.hashCode())));
rt.layerProtocol(true);
assertTrue(hs.add((RouteTracker) rt.clone()));
assertTrue(hc6.add(Integer.valueOf(rt.hashCode())));
Assert.assertTrue(hs.add((RouteTracker) rt.clone()));
Assert.assertTrue(hc6.add(Integer.valueOf(rt.hashCode())));
// PROXY1/s -> PROXY2/s -> tunnel/s -> layer/i
rt = (RouteTracker) rt6.clone();
rt.connectProxy(PROXY1, true);
assertTrue(hs.add((RouteTracker) rt.clone()));
Assert.assertTrue(hs.add((RouteTracker) rt.clone()));
// this is not guaranteed to be unique...
assertTrue(hc6.add(Integer.valueOf(rt.hashCode())));
Assert.assertTrue(hc6.add(Integer.valueOf(rt.hashCode())));
rt.tunnelProxy(PROXY2, true);
assertTrue(hs.add((RouteTracker) rt.clone()));
Assert.assertTrue(hs.add((RouteTracker) rt.clone()));
// this is not guaranteed to be unique...
assertTrue(hc6.add(Integer.valueOf(rt.hashCode())));
Assert.assertTrue(hc6.add(Integer.valueOf(rt.hashCode())));
rt.tunnelTarget(true);
assertTrue(hs.add((RouteTracker) rt.clone()));
assertTrue(hc6.add(Integer.valueOf(rt.hashCode())));
Assert.assertTrue(hs.add((RouteTracker) rt.clone()));
Assert.assertTrue(hc6.add(Integer.valueOf(rt.hashCode())));
rt.layerProtocol(false);
assertTrue(hs.add((RouteTracker) rt.clone()));
assertTrue(hc6.add(Integer.valueOf(rt.hashCode())));
Assert.assertTrue(hs.add((RouteTracker) rt.clone()));
Assert.assertTrue(hc6.add(Integer.valueOf(rt.hashCode())));
// PROXY2/i -> PROXY1/i -> tunnel/i -> layer/s
rt = (RouteTracker) rt6.clone();
rt.connectProxy(PROXY2, false);
assertTrue(hs.add((RouteTracker) rt.clone()));
Assert.assertTrue(hs.add((RouteTracker) rt.clone()));
// this is not guaranteed to be unique...
assertTrue(hc6.add(Integer.valueOf(rt.hashCode())));
Assert.assertTrue(hc6.add(Integer.valueOf(rt.hashCode())));
rt.tunnelProxy(PROXY1, false);
assertTrue(hs.add((RouteTracker) rt.clone()));
Assert.assertTrue(hs.add((RouteTracker) rt.clone()));
// proxy chain sequence does not affect hashcode, so duplicate:
// assertTrue(hc6.add(Integer.valueOf(rt.hashCode())));
// Assert.assertTrue(hc6.add(Integer.valueOf(rt.hashCode())));
rt.tunnelTarget(false);
assertTrue(hs.add((RouteTracker) rt.clone()));
Assert.assertTrue(hs.add((RouteTracker) rt.clone()));
// proxy chain sequence does not affect hashcode, so duplicate:
// assertTrue(hc6.add(Integer.valueOf(rt.hashCode())));
// Assert.assertTrue(hc6.add(Integer.valueOf(rt.hashCode())));
rt.layerProtocol(true);
assertTrue(hs.add((RouteTracker) rt.clone()));
Assert.assertTrue(hs.add((RouteTracker) rt.clone()));
// proxy chain sequence does not affect hashcode, so duplicate:
// assertTrue(hc6.add(Integer.valueOf(rt.hashCode())));
// Assert.assertTrue(hc6.add(Integer.valueOf(rt.hashCode())));
// check that all toString are OK and different
Set<String> rtstrings = new HashSet<String>();
for (RouteTracker current: hs) {
final String rts = checkToString(current);
assertTrue("duplicate toString: " + rts, rtstrings.add(rts));
Assert.assertTrue("duplicate toString: " + rts, rtstrings.add(rts));
}
}
@ -559,16 +541,16 @@ public class TestRouteTracker extends TestCase {
boolean c, boolean t,
boolean l, boolean s) {
String rts = rt.toString();
assertEquals("wrong flag connected: " + rts, c, rt.isConnected());
assertEquals("wrong flag tunnelled: " + rts, t, rt.isTunnelled());
assertEquals("wrong enum tunnelled: " + rts,
Assert.assertEquals("wrong flag connected: " + rts, c, rt.isConnected());
Assert.assertEquals("wrong flag tunnelled: " + rts, t, rt.isTunnelled());
Assert.assertEquals("wrong enum tunnelled: " + rts,
t ? TunnelType.TUNNELLED : TunnelType.PLAIN,
rt.getTunnelType());
assertEquals("wrong flag layered: " + rts, l, rt.isLayered());
assertEquals("wrong enum layered: " + rts,
Assert.assertEquals("wrong flag layered: " + rts, l, rt.isLayered());
Assert.assertEquals("wrong enum layered: " + rts,
l ? LayerType.LAYERED : LayerType.PLAIN,
rt.getLayerType());
assertEquals("wrong flag secure: " + rts, s, rt.isSecure());
Assert.assertEquals("wrong flag secure: " + rts, s, rt.isSecure());
}
@ -597,16 +579,16 @@ public class TestRouteTracker extends TestCase {
case HttpRouteDirector.COMPLETE:
complete = true;
assertEquals(r, rt.toRoute());
Assert.assertEquals(r, rt.toRoute());
break;
case HttpRouteDirector.CONNECT_TARGET: {
final boolean sec = r.isSecure();
rt.connectTarget(sec);
checkCTLS(rt, true, false, false, sec);
assertEquals("wrong hop count "+msg,
Assert.assertEquals("wrong hop count "+msg,
1, rt.getHopCount());
assertEquals("wrong hop0 "+msg,
Assert.assertEquals("wrong hop0 "+msg,
r.getTargetHost(), rt.getHopTarget(0));
} break;
@ -615,11 +597,11 @@ public class TestRouteTracker extends TestCase {
final boolean sec = false;
rt.connectProxy(r.getProxyHost(), sec);
checkCTLS(rt, true, false, false, sec);
assertEquals("wrong hop count "+msg,
Assert.assertEquals("wrong hop count "+msg,
2, rt.getHopCount());
assertEquals("wrong hop0 "+msg,
Assert.assertEquals("wrong hop0 "+msg,
r.getProxyHost(), rt.getHopTarget(0));
assertEquals("wrong hop1 "+msg,
Assert.assertEquals("wrong hop1 "+msg,
r.getTargetHost(), rt.getHopTarget(1));
} break;
@ -629,11 +611,11 @@ public class TestRouteTracker extends TestCase {
final boolean sec = false;
rt.tunnelTarget(sec);
checkCTLS(rt, true, true, false, sec);
assertEquals("wrong hop count "+msg,
Assert.assertEquals("wrong hop count "+msg,
hops, rt.getHopCount());
assertEquals("wrong hop0 "+msg,
Assert.assertEquals("wrong hop0 "+msg,
r.getProxyHost(), rt.getHopTarget(0));
assertEquals("wrong hopN "+msg,
Assert.assertEquals("wrong hopN "+msg,
r.getTargetHost(), rt.getHopTarget(hops-1));
} break;
@ -646,13 +628,13 @@ public class TestRouteTracker extends TestCase {
// Since we're tunnelling to a proxy and not the target,
// the 'tunelling' flag is false: no end-to-end tunnel.
checkCTLS(rt, true, false, false, sec);
assertEquals("wrong hop count "+msg,
Assert.assertEquals("wrong hop count "+msg,
hops+1, rt.getHopCount());
assertEquals("wrong hop0 "+msg,
Assert.assertEquals("wrong hop0 "+msg,
r.getProxyHost(), rt.getHopTarget(0));
assertEquals("wrong hop"+hops+" "+msg,
Assert.assertEquals("wrong hop"+hops+" "+msg,
pxy, rt.getHopTarget(hops-1));
assertEquals("wrong hopN "+msg,
Assert.assertEquals("wrong hopN "+msg,
r.getTargetHost(), rt.getHopTarget(hops));
} break;
@ -662,18 +644,18 @@ public class TestRouteTracker extends TestCase {
final boolean sec = r.isSecure();
rt.layerProtocol(sec);
checkCTLS(rt, true, tun, true, sec);
assertEquals("wrong hop count "+msg,
Assert.assertEquals("wrong hop count "+msg,
hops, rt.getHopCount());
assertEquals("wrong proxy "+msg,
Assert.assertEquals("wrong proxy "+msg,
r.getProxyHost(), rt.getProxyHost());
assertEquals("wrong target "+msg,
Assert.assertEquals("wrong target "+msg,
r.getTargetHost(), rt.getTargetHost());
} break;
// UNREACHABLE
default:
fail("unexpected action " + action + " from director, "+msg);
Assert.fail("unexpected action " + action + " from director, "+msg);
break;
} // switch
@ -699,18 +681,17 @@ public class TestRouteTracker extends TestCase {
if (rt.getLocalAddress() != null) {
final String las = rt.getLocalAddress().toString();
assertFalse("no local address in toString(): " + rts,
Assert.assertFalse("no local address in toString(): " + rts,
rts.indexOf(las) < 0);
}
for (int i=0; i<rt.getHopCount(); i++) {
final String hts = rt.getHopTarget(i).toString();
assertFalse("hop "+i+" ("+hts+") missing in toString(): " + rts,
Assert.assertFalse("hop "+i+" ("+hts+") missing in toString(): " + rts,
rts.indexOf(hts) < 0);
}
return rts;
}
} // class TestRouteTracker
}

View File

@ -27,34 +27,21 @@
package org.apache.http.conn.scheme;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.junit.Assert;
import org.junit.Test;
/**
* Unit tests for {@link Scheme}.
*/
public class TestScheme extends TestCase {
public TestScheme(String testName) {
super(testName);
}
public static void main(String args[]) {
String[] testCaseName = { TestScheme.class.getName() };
junit.textui.TestRunner.main(testCaseName);
}
public static Test suite() {
return new TestSuite(TestScheme.class);
}
public class TestScheme {
@Test
public void testPortResolution() {
Scheme http = new Scheme("http", 80, PlainSocketFactory.getSocketFactory());
assertEquals(80, http.resolvePort(0));
assertEquals(80, http.resolvePort(-1));
assertEquals(8080, http.resolvePort(8080));
assertEquals(80808080, http.resolvePort(80808080));
Assert.assertEquals(80, http.resolvePort(0));
Assert.assertEquals(80, http.resolvePort(-1));
Assert.assertEquals(8080, http.resolvePort(8080));
Assert.assertEquals(80808080, http.resolvePort(80808080));
}
}

View File

@ -34,28 +34,15 @@ import java.security.cert.X509Certificate;
import javax.net.ssl.SSLException;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.junit.Assert;
import org.junit.Test;
/**
* Unit tests for {@link X509HostnameVerifier}.
*/
public class TestHostnameVerifier extends TestCase {
public TestHostnameVerifier(String testName) {
super(testName);
}
public static void main(String args[]) throws Exception {
String[] testCaseName = { TestHostnameVerifier.class.getName() };
junit.textui.TestRunner.main(testCaseName);
}
public static Test suite() {
return new TestSuite(TestHostnameVerifier.class);
}
public class TestHostnameVerifier {
@Test
public void testVerify() throws Exception {
X509HostnameVerifier DEFAULT = new BrowserCompatHostnameVerifier();
X509HostnameVerifier STRICT = new StrictHostnameVerifier();
@ -200,6 +187,7 @@ public class TestHostnameVerifier extends TestCase {
//exceptionPlease(STRICT,"a.b.\u82b1\u5b50.co.jp", x509 );
}
@Test
public void testSubjectAlt() throws Exception {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream in = new ByteArrayInputStream(CertificatesToPlayWith.X509_MULTIPLE_SUBJECT_ALT);
@ -207,7 +195,7 @@ public class TestHostnameVerifier extends TestCase {
X509HostnameVerifier verifier = SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER;
assertEquals("CN=localhost, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=CH",
Assert.assertEquals("CN=localhost, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=CH",
x509.getSubjectDN().getName());
verifier.verify("localhost", x509);
@ -216,24 +204,24 @@ public class TestHostnameVerifier extends TestCase {
try {
verifier.verify("local.host", x509);
fail("SSLException should have been thrown");
Assert.fail("SSLException should have been thrown");
} catch (SSLException ex) {
// expected
}
try {
verifier.verify("127.0.0.2", x509);
fail("SSLException should have been thrown");
Assert.fail("SSLException should have been thrown");
} catch (SSLException ex) {
// expected
}
}
private void exceptionPlease(X509HostnameVerifier hv, String host,
public void exceptionPlease(X509HostnameVerifier hv, String host,
X509Certificate x509) {
try {
hv.verify(host, x509);
fail("HostnameVerifier shouldn't allow [" + host + "]");
Assert.fail("HostnameVerifier shouldn't allow [" + host + "]");
}
catch(SSLException e) {
// whew! we're okay!

View File

@ -45,9 +45,6 @@ import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
@ -55,25 +52,16 @@ import org.apache.http.conn.scheme.Scheme;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.localserver.BasicServerTestBase;
import org.apache.http.localserver.LocalTestServer;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
/**
* Unit tests for {@link SSLSocketFactory}.
*/
public class TestSSLSocketFactory extends BasicServerTestBase {
public TestSSLSocketFactory(String testName) {
super(testName);
}
public static void main(String args[]) throws Exception {
String[] testCaseName = { TestSSLSocketFactory.class.getName() };
junit.textui.TestRunner.main(testCaseName);
}
public static Test suite() {
return new TestSuite(TestSSLSocketFactory.class);
}
private KeyManagerFactory createKeyManagerFactory() throws NoSuchAlgorithmException {
String algo = KeyManagerFactory.getDefaultAlgorithm();
try {
@ -95,8 +83,8 @@ public class TestSSLSocketFactory extends BasicServerTestBase {
private SSLContext serverSSLContext;
private SSLContext clientSSLContext;
@Override
protected void setUp() throws Exception {
@Before
public void setUp() throws Exception {
ClassLoader cl = getClass().getClassLoader();
URL url = cl.getResource("test.keystore");
KeyStore keystore = KeyStore.getInstance("jks");
@ -156,6 +144,7 @@ public class TestSSLSocketFactory extends BasicServerTestBase {
}
@Test
public void testBasicSSL() throws Exception {
TestX509HostnameVerifier hostVerifier = new TestX509HostnameVerifier();
@ -168,10 +157,11 @@ public class TestSSLSocketFactory extends BasicServerTestBase {
HttpHost target = getServerHttp();
HttpGet httpget = new HttpGet("/random/100");
HttpResponse response = httpclient.execute(target, httpget);
assertEquals(200, response.getStatusLine().getStatusCode());
assertTrue(hostVerifier.isFired());
Assert.assertEquals(200, response.getStatusLine().getStatusCode());
Assert.assertTrue(hostVerifier.isFired());
}
@Test(expected=SSLPeerUnverifiedException.class)
public void testSSLTrustVerification() throws Exception {
// Use default SSL context
SSLContext defaultsslcontext = SSLContext.getInstance("TLS");
@ -186,13 +176,11 @@ public class TestSSLSocketFactory extends BasicServerTestBase {
HttpHost target = getServerHttp();
HttpGet httpget = new HttpGet("/random/100");
try {
httpclient.execute(target, httpget);
fail("SSLException should have been thrown");
} catch (SSLPeerUnverifiedException expected) {
}
httpclient.execute(target, httpget);
}
@Test
@Ignore
public void testSSLTrustVerificationOverride() throws Exception {
// Use default SSL context
SSLContext defaultsslcontext = SSLContext.getInstance("TLS");
@ -214,7 +202,7 @@ public class TestSSLSocketFactory extends BasicServerTestBase {
HttpHost target = getServerHttp();
HttpGet httpget = new HttpGet("/random/100");
HttpResponse response = httpclient.execute(target, httpget);
assertEquals(200, response.getStatusLine().getStatusCode());
Assert.assertEquals(200, response.getStatusLine().getStatusCode());
}
}

View File

@ -27,52 +27,42 @@
package org.apache.http.conn.util;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.junit.Assert;
import org.junit.Test;
/**
* Unit tests for InetAddressUtils.
*/
public class TestInetAddressUtils extends TestCase {
public TestInetAddressUtils(String testName) {
super(testName);
}
public static void main(String args[]) {
String[] testCaseName = { TestInetAddressUtils.class.getName() };
junit.textui.TestRunner.main(testCaseName);
}
public static Test suite() {
return new TestSuite(TestInetAddressUtils.class);
}
public class TestInetAddressUtils {
@Test
public void testValidIPv4Address() {
assertTrue(InetAddressUtils.isIPv4Address("127.0.0.1"));
assertTrue(InetAddressUtils.isIPv4Address("192.168.0.0"));
assertTrue(InetAddressUtils.isIPv4Address("255.255.255.255"));
Assert.assertTrue(InetAddressUtils.isIPv4Address("127.0.0.1"));
Assert.assertTrue(InetAddressUtils.isIPv4Address("192.168.0.0"));
Assert.assertTrue(InetAddressUtils.isIPv4Address("255.255.255.255"));
}
@Test
public void testInvalidIPv4Address() {
assertFalse(InetAddressUtils.isIPv4Address(" 127.0.0.1 ")); // Blanks not allowed
assertFalse(InetAddressUtils.isIPv4Address("g.ar.ba.ge"));
assertFalse(InetAddressUtils.isIPv4Address("192.168.0"));
assertFalse(InetAddressUtils.isIPv4Address("256.255.255.255"));
Assert.assertFalse(InetAddressUtils.isIPv4Address(" 127.0.0.1 ")); // Blanks not allowed
Assert.assertFalse(InetAddressUtils.isIPv4Address("g.ar.ba.ge"));
Assert.assertFalse(InetAddressUtils.isIPv4Address("192.168.0"));
Assert.assertFalse(InetAddressUtils.isIPv4Address("256.255.255.255"));
}
@Test
public void testValidIPv6Address() {
assertTrue(InetAddressUtils.isIPv6StdAddress("2001:0db8:0000:0000:0000:0000:1428:57ab"));
assertTrue(InetAddressUtils.isIPv6StdAddress("2001:db8:0:0:0:0:1428:57ab"));
assertTrue(InetAddressUtils.isIPv6HexCompressedAddress("2001:0db8:0:0::1428:57ab"));
assertTrue(InetAddressUtils.isIPv6HexCompressedAddress("2001:0db8::1428:57ab"));
assertTrue(InetAddressUtils.isIPv6HexCompressedAddress("2001:db8::1428:57ab"));
Assert.assertTrue(InetAddressUtils.isIPv6StdAddress("2001:0db8:0000:0000:0000:0000:1428:57ab"));
Assert.assertTrue(InetAddressUtils.isIPv6StdAddress("2001:db8:0:0:0:0:1428:57ab"));
Assert.assertTrue(InetAddressUtils.isIPv6HexCompressedAddress("2001:0db8:0:0::1428:57ab"));
Assert.assertTrue(InetAddressUtils.isIPv6HexCompressedAddress("2001:0db8::1428:57ab"));
Assert.assertTrue(InetAddressUtils.isIPv6HexCompressedAddress("2001:db8::1428:57ab"));
}
@Test
public void testInvalidIPv6Address() {
assertFalse(InetAddressUtils.isIPv6Address("2001:0db8:0000:garb:age0:0000:1428:57ab"));
assertFalse(InetAddressUtils.isIPv6Address("2001:0gb8:0000:0000:0000:0000:1428:57ab"));
Assert.assertFalse(InetAddressUtils.isIPv6Address("2001:0db8:0000:garb:age0:0000:1428:57ab"));
Assert.assertFalse(InetAddressUtils.isIPv6Address("2001:0gb8:0000:0000:0000:0000:1428:57ab"));
}
}

View File

@ -27,74 +27,50 @@
package org.apache.http.cookie;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.junit.Assert;
import org.junit.Test;
/**
* Test cases for {@link CookieOrigin}.
*/
public class TestCookieOrigin extends TestCase {
// ------------------------------------------------------------ Constructor
public TestCookieOrigin(String name) {
super(name);
}
// ------------------------------------------------------- TestCase Methods
public static Test suite() {
return new TestSuite(TestCookieOrigin.class);
}
public class TestCookieOrigin {
@Test
public void testConstructor() {
CookieOrigin origin = new CookieOrigin("www.apache.org", 80, "/", false);
assertEquals("www.apache.org", origin.getHost());
assertEquals(80, origin.getPort());
assertEquals("/", origin.getPath());
assertFalse(origin.isSecure());
Assert.assertEquals("www.apache.org", origin.getHost());
Assert.assertEquals(80, origin.getPort());
Assert.assertEquals("/", origin.getPath());
Assert.assertFalse(origin.isSecure());
}
@Test(expected=IllegalArgumentException.class)
public void testNullHost() {
try {
new CookieOrigin(null, 80, "/", false);
} catch (IllegalArgumentException ex) {
// expected
}
new CookieOrigin(null, 80, "/", false);
}
@Test(expected=IllegalArgumentException.class)
public void testEmptyHost() {
try {
new CookieOrigin(" ", 80, "/", false);
} catch (IllegalArgumentException ex) {
// expected
}
new CookieOrigin(" ", 80, "/", false);
}
@Test(expected=IllegalArgumentException.class)
public void testNegativePort() {
try {
new CookieOrigin("www.apache.org", -80, "/", false);
} catch (IllegalArgumentException ex) {
// expected
}
new CookieOrigin("www.apache.org", -80, "/", false);
}
@Test(expected=IllegalArgumentException.class)
public void testNullPath() {
try {
new CookieOrigin("www.apache.org", 80, null, false);
} catch (IllegalArgumentException ex) {
// expected
}
new CookieOrigin("www.apache.org", 80, null, false);
}
@Test
public void testEmptyPath() {
CookieOrigin origin = new CookieOrigin("www.apache.org", 80, "", false);
assertEquals("www.apache.org", origin.getHost());
assertEquals(80, origin.getPort());
assertEquals("/", origin.getPath());
assertFalse(origin.isSecure());
Assert.assertEquals("www.apache.org", origin.getHost());
Assert.assertEquals(80, origin.getPort());
Assert.assertEquals("/", origin.getPath());
Assert.assertFalse(origin.isSecure());
}
}

View File

@ -30,87 +30,78 @@ package org.apache.http.cookie;
import java.util.Comparator;
import org.apache.http.impl.cookie.BasicClientCookie;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.junit.Assert;
import org.junit.Test;
/**
* Test cases for {@link CookiePathComparator}.
*/
public class TestCookiePathComparator extends TestCase {
// ------------------------------------------------------------ Constructor
public TestCookiePathComparator(String name) {
super(name);
}
// ------------------------------------------------------- TestCase Methods
public static Test suite() {
return new TestSuite(TestCookiePathComparator.class);
}
public class TestCookiePathComparator {
@Test
public void testUnequality1() {
BasicClientCookie cookie1 = new BasicClientCookie("name1", "value");
cookie1.setPath("/a/b/");
BasicClientCookie cookie2 = new BasicClientCookie("name1", "value");
cookie2.setPath("/a/");
Comparator<Cookie> comparator = new CookiePathComparator();
assertTrue(comparator.compare(cookie1, cookie2) < 0);
assertTrue(comparator.compare(cookie2, cookie1) > 0);
Assert.assertTrue(comparator.compare(cookie1, cookie2) < 0);
Assert.assertTrue(comparator.compare(cookie2, cookie1) > 0);
}
@Test
public void testUnequality2() {
BasicClientCookie cookie1 = new BasicClientCookie("name1", "value");
cookie1.setPath("/a/b");
BasicClientCookie cookie2 = new BasicClientCookie("name1", "value");
cookie2.setPath("/a");
Comparator<Cookie> comparator = new CookiePathComparator();
assertTrue(comparator.compare(cookie1, cookie2) < 0);
assertTrue(comparator.compare(cookie2, cookie1) > 0);
Assert.assertTrue(comparator.compare(cookie1, cookie2) < 0);
Assert.assertTrue(comparator.compare(cookie2, cookie1) > 0);
}
@Test
public void testEquality1() {
BasicClientCookie cookie1 = new BasicClientCookie("name1", "value");
cookie1.setPath("/a");
BasicClientCookie cookie2 = new BasicClientCookie("name1", "value");
cookie2.setPath("/a");
Comparator<Cookie> comparator = new CookiePathComparator();
assertTrue(comparator.compare(cookie1, cookie2) == 0);
assertTrue(comparator.compare(cookie2, cookie1) == 0);
Assert.assertTrue(comparator.compare(cookie1, cookie2) == 0);
Assert.assertTrue(comparator.compare(cookie2, cookie1) == 0);
}
@Test
public void testEquality2() {
BasicClientCookie cookie1 = new BasicClientCookie("name1", "value");
cookie1.setPath("/a/");
BasicClientCookie cookie2 = new BasicClientCookie("name1", "value");
cookie2.setPath("/a");
Comparator<Cookie> comparator = new CookiePathComparator();
assertTrue(comparator.compare(cookie1, cookie2) == 0);
assertTrue(comparator.compare(cookie2, cookie1) == 0);
Assert.assertTrue(comparator.compare(cookie1, cookie2) == 0);
Assert.assertTrue(comparator.compare(cookie2, cookie1) == 0);
}
@Test
public void testEquality3() {
BasicClientCookie cookie1 = new BasicClientCookie("name1", "value");
cookie1.setPath(null);
BasicClientCookie cookie2 = new BasicClientCookie("name1", "value");
cookie2.setPath("/");
Comparator<Cookie> comparator = new CookiePathComparator();
assertTrue(comparator.compare(cookie1, cookie2) == 0);
assertTrue(comparator.compare(cookie2, cookie1) == 0);
Assert.assertTrue(comparator.compare(cookie1, cookie2) == 0);
Assert.assertTrue(comparator.compare(cookie2, cookie1) == 0);
}
@Test
public void testEquality4() {
BasicClientCookie cookie1 = new BasicClientCookie("name1", "value");
cookie1.setPath("/this");
BasicClientCookie cookie2 = new BasicClientCookie("name1", "value");
cookie2.setPath("/that");
Comparator<Cookie> comparator = new CookiePathComparator();
assertTrue(comparator.compare(cookie1, cookie2) == 0);
assertTrue(comparator.compare(cookie2, cookie1) == 0);
Assert.assertTrue(comparator.compare(cookie1, cookie2) == 0);
Assert.assertTrue(comparator.compare(cookie2, cookie1) == 0);
}
}

View File

@ -31,44 +31,29 @@ import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.apache.http.impl.cookie.BrowserCompatSpecFactory;
import org.apache.http.impl.cookie.NetscapeDraftSpecFactory;
import org.apache.http.impl.cookie.RFC2109SpecFactory;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.junit.Assert;
import org.junit.Test;
/**
* Test cases for {@link CookieSpecRegistry}.
*/
public class TestCookiePolicy extends TestCase {
// ------------------------------------------------------------ Constructor
public TestCookiePolicy(String name) {
super(name);
}
// ------------------------------------------------------- TestCase Methods
public static Test suite() {
return new TestSuite(TestCookiePolicy.class);
}
public class TestCookiePolicy {
private static final String BROWSER_COMPATIBILITY = "BROWSER_COMPATIBILITY";
private static final String NETSCAPE = "NETSCAPE";
private static final String RFC_2109 = "RFC_2109";
@Test
public void testRegisterUnregisterCookieSpecFactory() {
CookieSpecRegistry registry = new CookieSpecRegistry();
List<String> names = registry.getSpecNames();
assertNotNull(names);
assertEquals(0, names.size());
Assert.assertNotNull(names);
Assert.assertEquals(0, names.size());
registry.register(BROWSER_COMPATIBILITY,
new BrowserCompatSpecFactory());
@ -82,12 +67,12 @@ public class TestCookiePolicy extends TestCase {
new NetscapeDraftSpecFactory());
names = registry.getSpecNames();
assertNotNull(names);
assertEquals(3, names.size());
Assert.assertNotNull(names);
Assert.assertEquals(3, names.size());
HashSet<String> m = new HashSet<String>(names);
assertTrue(m.contains(BROWSER_COMPATIBILITY.toLowerCase(Locale.ENGLISH)));
assertTrue(m.contains(NETSCAPE.toLowerCase(Locale.ENGLISH)));
assertTrue(m.contains(RFC_2109.toLowerCase(Locale.ENGLISH)));
Assert.assertTrue(m.contains(BROWSER_COMPATIBILITY.toLowerCase(Locale.ENGLISH)));
Assert.assertTrue(m.contains(NETSCAPE.toLowerCase(Locale.ENGLISH)));
Assert.assertTrue(m.contains(RFC_2109.toLowerCase(Locale.ENGLISH)));
registry.unregister(NETSCAPE);
registry.unregister(NETSCAPE);
@ -96,10 +81,11 @@ public class TestCookiePolicy extends TestCase {
registry.unregister("whatever");
names = registry.getSpecNames();
assertNotNull(names);
assertEquals(0, names.size());
Assert.assertNotNull(names);
Assert.assertEquals(0, names.size());
}
@Test
public void testGetNewCookieSpec() {
CookieSpecRegistry registry = new CookieSpecRegistry();
registry.register(BROWSER_COMPATIBILITY,
@ -109,50 +95,51 @@ public class TestCookiePolicy extends TestCase {
registry.register(RFC_2109,
new RFC2109SpecFactory());
assertNotNull(registry.getCookieSpec(NETSCAPE));
assertNotNull(registry.getCookieSpec(RFC_2109));
assertNotNull(registry.getCookieSpec(BROWSER_COMPATIBILITY));
Assert.assertNotNull(registry.getCookieSpec(NETSCAPE));
Assert.assertNotNull(registry.getCookieSpec(RFC_2109));
Assert.assertNotNull(registry.getCookieSpec(BROWSER_COMPATIBILITY));
try {
registry.getCookieSpec("whatever");
fail("IllegalStateException should have been thrown");
Assert.fail("IllegalStateException should have been thrown");
} catch (IllegalStateException ex) {
// expected
}
HttpParams params = new BasicHttpParams();
assertNotNull(registry.getCookieSpec(NETSCAPE, params));
assertNotNull(registry.getCookieSpec(RFC_2109, params));
assertNotNull(registry.getCookieSpec(BROWSER_COMPATIBILITY, params));
Assert.assertNotNull(registry.getCookieSpec(NETSCAPE, params));
Assert.assertNotNull(registry.getCookieSpec(RFC_2109, params));
Assert.assertNotNull(registry.getCookieSpec(BROWSER_COMPATIBILITY, params));
try {
registry.getCookieSpec("whatever", params);
fail("IllegalStateException should have been thrown");
Assert.fail("IllegalStateException should have been thrown");
} catch (IllegalStateException ex) {
// expected
}
}
@Test
public void testInvalidInput() {
CookieSpecRegistry registry = new CookieSpecRegistry();
try {
registry.register(null, null);
fail("IllegalArgumentException should have been thrown");
Assert.fail("IllegalArgumentException should have been thrown");
} catch (IllegalArgumentException ex) {
// expected
}
try {
registry.register("whatever", null);
fail("IllegalArgumentException should have been thrown");
Assert.fail("IllegalArgumentException should have been thrown");
} catch (IllegalArgumentException ex) {
// expected
}
try {
registry.unregister(null);
fail("IllegalArgumentException should have been thrown");
Assert.fail("IllegalArgumentException should have been thrown");
} catch (IllegalArgumentException ex) {
// expected
}
try {
registry.getCookieSpec((String)null);
fail("IllegalArgumentException should have been thrown");
Assert.fail("IllegalArgumentException should have been thrown");
} catch (IllegalArgumentException ex) {
// expected
}

View File

@ -26,10 +26,6 @@
package org.apache.http.impl.auth;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.Header;
import org.apache.http.HttpRequest;
@ -40,44 +36,23 @@ import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicHttpRequest;
import org.apache.http.util.EncodingUtils;
import org.junit.Assert;
import org.junit.Test;
/**
* Basic authentication test cases.
*
* @version $Id$
*/
public class TestBasicScheme extends TestCase {
public class TestBasicScheme {
// ------------------------------------------------------------ Constructor
public TestBasicScheme(final String testName) {
super(testName);
}
// ------------------------------------------------------------------- Main
public static void main(String args[]) {
String[] testCaseName = { TestBasicScheme.class.getName() };
junit.textui.TestRunner.main(testCaseName);
}
// ------------------------------------------------------- TestCase Methods
public static Test suite() {
TestSuite suite = new TestSuite(TestBasicScheme.class);
return suite;
}
public void testBasicAuthenticationWithNoRealm() {
@Test(expected=MalformedChallengeException.class)
public void testBasicAuthenticationWithNoRealm() throws Exception {
String challenge = "Basic";
Header header = new BasicHeader(AUTH.WWW_AUTH, challenge);
try {
AuthScheme authscheme = new BasicScheme();
authscheme.processChallenge(header);
fail("Should have thrown MalformedChallengeException");
} catch(MalformedChallengeException e) {
// expected
}
AuthScheme authscheme = new BasicScheme();
authscheme.processChallenge(header);
}
@Test
public void testBasicAuthenticationWith88591Chars() throws Exception {
int[] germanChars = { 0xE4, 0x2D, 0xF6, 0x2D, 0xFc };
StringBuilder buffer = new StringBuilder();
@ -87,9 +62,10 @@ public class TestBasicScheme extends TestCase {
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("dh", buffer.toString());
Header header = BasicScheme.authenticate(credentials, "ISO-8859-1", false);
assertEquals("Basic ZGg65C32Lfw=", header.getValue());
Assert.assertEquals("Basic ZGg65C32Lfw=", header.getValue());
}
@Test
public void testBasicAuthentication() throws Exception {
UsernamePasswordCredentials creds =
new UsernamePasswordCredentials("testuser", "testpass");
@ -104,13 +80,14 @@ public class TestBasicScheme extends TestCase {
String expected = "Basic " + EncodingUtils.getAsciiString(
Base64.encodeBase64(EncodingUtils.getAsciiBytes("testuser:testpass")));
assertEquals(AUTH.WWW_AUTH_RESP, authResponse.getName());
assertEquals(expected, authResponse.getValue());
assertEquals("test", authscheme.getRealm());
assertTrue(authscheme.isComplete());
assertFalse(authscheme.isConnectionBased());
Assert.assertEquals(AUTH.WWW_AUTH_RESP, authResponse.getName());
Assert.assertEquals(expected, authResponse.getValue());
Assert.assertEquals("test", authscheme.getRealm());
Assert.assertTrue(authscheme.isComplete());
Assert.assertFalse(authscheme.isConnectionBased());
}
@Test
public void testBasicProxyAuthentication() throws Exception {
UsernamePasswordCredentials creds =
new UsernamePasswordCredentials("testuser", "testpass");
@ -125,11 +102,11 @@ public class TestBasicScheme extends TestCase {
String expected = "Basic " + EncodingUtils.getAsciiString(
Base64.encodeBase64(EncodingUtils.getAsciiBytes("testuser:testpass")));
assertEquals(AUTH.PROXY_AUTH_RESP, authResponse.getName());
assertEquals(expected, authResponse.getValue());
assertEquals("test", authscheme.getRealm());
assertTrue(authscheme.isComplete());
assertFalse(authscheme.isConnectionBased());
Assert.assertEquals(AUTH.PROXY_AUTH_RESP, authResponse.getName());
Assert.assertEquals(expected, authResponse.getValue());
Assert.assertEquals("test", authscheme.getRealm());
Assert.assertTrue(authscheme.isComplete());
Assert.assertFalse(authscheme.isConnectionBased());
}
}

View File

@ -29,10 +29,6 @@ package org.apache.http.impl.auth;
import java.util.HashMap;
import java.util.Map;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpRequest;
@ -44,52 +40,29 @@ import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicHeaderValueParser;
import org.apache.http.message.BasicHttpRequest;
import org.junit.Assert;
import org.junit.Test;
/**
* Test Methods for DigestScheme Authentication.
*
*/
public class TestDigestScheme extends TestCase {
// ------------------------------------------------------------ Constructor
public TestDigestScheme(String testName) {
super(testName);
}
// ------------------------------------------------------------------- Main
public static void main(String args[]) {
String[] testCaseName = { TestDigestScheme.class.getName() };
junit.textui.TestRunner.main(testCaseName);
}
// ------------------------------------------------------- TestCase Methods
public static Test suite() {
return new TestSuite(TestDigestScheme.class);
}
public class TestDigestScheme {
@Test(expected=MalformedChallengeException.class)
public void testDigestAuthenticationWithNoRealm() throws Exception {
Header authChallenge = new BasicHeader(AUTH.WWW_AUTH, "Digest");
try {
AuthScheme authscheme = new DigestScheme();
authscheme.processChallenge(authChallenge);
fail("Should have thrown MalformedChallengeException");
} catch(MalformedChallengeException e) {
// expected
}
AuthScheme authscheme = new DigestScheme();
authscheme.processChallenge(authChallenge);
}
@Test(expected=MalformedChallengeException.class)
public void testDigestAuthenticationWithNoRealm2() throws Exception {
Header authChallenge = new BasicHeader(AUTH.WWW_AUTH, "Digest ");
try {
AuthScheme authscheme = new DigestScheme();
authscheme.processChallenge(authChallenge);
fail("Should have thrown MalformedChallengeException");
} catch(MalformedChallengeException e) {
// expected
}
AuthScheme authscheme = new DigestScheme();
authscheme.processChallenge(authChallenge);
}
@Test
public void testDigestAuthenticationWithDefaultCreds() throws Exception {
String challenge = "Digest realm=\"realm1\", nonce=\"f2a3f18799759d4f1a1c068b92b573cb\"";
Header authChallenge = new BasicHeader(AUTH.WWW_AUTH, challenge);
@ -100,13 +73,14 @@ public class TestDigestScheme extends TestCase {
Header authResponse = authscheme.authenticate(cred, request);
Map<String, String> table = parseAuthResponse(authResponse);
assertEquals("username", table.get("username"));
assertEquals("realm1", table.get("realm"));
assertEquals("/", table.get("uri"));
assertEquals("f2a3f18799759d4f1a1c068b92b573cb", table.get("nonce"));
assertEquals("e95a7ddf37c2eab009568b1ed134f89a", table.get("response"));
Assert.assertEquals("username", table.get("username"));
Assert.assertEquals("realm1", table.get("realm"));
Assert.assertEquals("/", table.get("uri"));
Assert.assertEquals("f2a3f18799759d4f1a1c068b92b573cb", table.get("nonce"));
Assert.assertEquals("e95a7ddf37c2eab009568b1ed134f89a", table.get("response"));
}
@Test
public void testDigestAuthentication() throws Exception {
String challenge = "Digest realm=\"realm1\", nonce=\"f2a3f18799759d4f1a1c068b92b573cb\"";
Header authChallenge = new BasicHeader(AUTH.WWW_AUTH, challenge);
@ -117,13 +91,14 @@ public class TestDigestScheme extends TestCase {
Header authResponse = authscheme.authenticate(cred, request);
Map<String, String> table = parseAuthResponse(authResponse);
assertEquals("username", table.get("username"));
assertEquals("realm1", table.get("realm"));
assertEquals("/", table.get("uri"));
assertEquals("f2a3f18799759d4f1a1c068b92b573cb", table.get("nonce"));
assertEquals("e95a7ddf37c2eab009568b1ed134f89a", table.get("response"));
Assert.assertEquals("username", table.get("username"));
Assert.assertEquals("realm1", table.get("realm"));
Assert.assertEquals("/", table.get("uri"));
Assert.assertEquals("f2a3f18799759d4f1a1c068b92b573cb", table.get("nonce"));
Assert.assertEquals("e95a7ddf37c2eab009568b1ed134f89a", table.get("response"));
}
@Test
public void testDigestAuthenticationWithSHA() throws Exception {
String challenge = "Digest realm=\"realm1\", " +
"nonce=\"f2a3f18799759d4f1a1c068b92b573cb\", " +
@ -136,13 +111,14 @@ public class TestDigestScheme extends TestCase {
Header authResponse = authscheme.authenticate(cred, request);
Map<String, String> table = parseAuthResponse(authResponse);
assertEquals("username", table.get("username"));
assertEquals("realm1", table.get("realm"));
assertEquals("/", table.get("uri"));
assertEquals("f2a3f18799759d4f1a1c068b92b573cb", table.get("nonce"));
assertEquals("8769e82e4e28ecc040b969562b9050580c6d186d", table.get("response"));
Assert.assertEquals("username", table.get("username"));
Assert.assertEquals("realm1", table.get("realm"));
Assert.assertEquals("/", table.get("uri"));
Assert.assertEquals("f2a3f18799759d4f1a1c068b92b573cb", table.get("nonce"));
Assert.assertEquals("8769e82e4e28ecc040b969562b9050580c6d186d", table.get("response"));
}
@Test
public void testDigestAuthenticationWithQueryStringInDigestURI() throws Exception {
String challenge = "Digest realm=\"realm1\", nonce=\"f2a3f18799759d4f1a1c068b92b573cb\"";
Header authChallenge = new BasicHeader(AUTH.WWW_AUTH, challenge);
@ -153,13 +129,14 @@ public class TestDigestScheme extends TestCase {
Header authResponse = authscheme.authenticate(cred, request);
Map<String, String> table = parseAuthResponse(authResponse);
assertEquals("username", table.get("username"));
assertEquals("realm1", table.get("realm"));
assertEquals("/?param=value", table.get("uri"));
assertEquals("f2a3f18799759d4f1a1c068b92b573cb", table.get("nonce"));
assertEquals("a847f58f5fef0bc087bcb9c3eb30e042", table.get("response"));
Assert.assertEquals("username", table.get("username"));
Assert.assertEquals("realm1", table.get("realm"));
Assert.assertEquals("/?param=value", table.get("uri"));
Assert.assertEquals("f2a3f18799759d4f1a1c068b92b573cb", table.get("nonce"));
Assert.assertEquals("a847f58f5fef0bc087bcb9c3eb30e042", table.get("response"));
}
@Test
public void testDigestAuthenticationWithMultipleRealms() throws Exception {
String challenge1 = "Digest realm=\"realm1\", nonce=\"abcde\"";
String challenge2 = "Digest realm=\"realm2\", nonce=\"123546\"";
@ -173,11 +150,11 @@ public class TestDigestScheme extends TestCase {
Header authResponse = authscheme.authenticate(cred, request);
Map<String, String> table = parseAuthResponse(authResponse);
assertEquals("username", table.get("username"));
assertEquals("realm1", table.get("realm"));
assertEquals("/", table.get("uri"));
assertEquals("abcde", table.get("nonce"));
assertEquals("786f500303eac1478f3c2865e676ed68", table.get("response"));
Assert.assertEquals("username", table.get("username"));
Assert.assertEquals("realm1", table.get("realm"));
Assert.assertEquals("/", table.get("uri"));
Assert.assertEquals("abcde", table.get("nonce"));
Assert.assertEquals("786f500303eac1478f3c2865e676ed68", table.get("response"));
authChallenge = new BasicHeader(AUTH.WWW_AUTH, challenge2);
DigestScheme authscheme2 = new DigestScheme();
@ -185,16 +162,17 @@ public class TestDigestScheme extends TestCase {
authResponse = authscheme2.authenticate(cred2, request);
table = parseAuthResponse(authResponse);
assertEquals("uname2", table.get("username"));
assertEquals("realm2", table.get("realm"));
assertEquals("/", table.get("uri"));
assertEquals("123546", table.get("nonce"));
assertEquals("0283edd9ef06a38b378b3b74661391e9", table.get("response"));
Assert.assertEquals("uname2", table.get("username"));
Assert.assertEquals("realm2", table.get("realm"));
Assert.assertEquals("/", table.get("uri"));
Assert.assertEquals("123546", table.get("nonce"));
Assert.assertEquals("0283edd9ef06a38b378b3b74661391e9", table.get("response"));
}
/**
* Test digest authentication using the MD5-sess algorithm.
*/
@Test
public void testDigestAuthenticationMD5Sess() throws Exception {
// Example using Digest auth with MD5-sess
@ -220,26 +198,27 @@ public class TestDigestScheme extends TestCase {
Header authResponse = authscheme.authenticate(cred, request);
String response = authResponse.getValue();
assertTrue(response.indexOf("nc=00000001") > 0); // test for quotes
assertTrue(response.indexOf("qop=auth") > 0); // test for quotes
Assert.assertTrue(response.indexOf("nc=00000001") > 0); // test for quotes
Assert.assertTrue(response.indexOf("qop=auth") > 0); // test for quotes
Map<String, String> table = parseAuthResponse(authResponse);
assertEquals(username, table.get("username"));
assertEquals(realm, table.get("realm"));
assertEquals("MD5-sess", table.get("algorithm"));
assertEquals("/", table.get("uri"));
assertEquals(nonce, table.get("nonce"));
assertEquals(1, Integer.parseInt(table.get("nc"),16));
assertTrue(null != table.get("cnonce"));
assertEquals("SomeString", table.get("opaque"));
assertEquals("auth", table.get("qop"));
Assert.assertEquals(username, table.get("username"));
Assert.assertEquals(realm, table.get("realm"));
Assert.assertEquals("MD5-sess", table.get("algorithm"));
Assert.assertEquals("/", table.get("uri"));
Assert.assertEquals(nonce, table.get("nonce"));
Assert.assertEquals(1, Integer.parseInt(table.get("nc"),16));
Assert.assertTrue(null != table.get("cnonce"));
Assert.assertEquals("SomeString", table.get("opaque"));
Assert.assertEquals("auth", table.get("qop"));
//@TODO: add better check
assertTrue(null != table.get("response"));
Assert.assertTrue(null != table.get("response"));
}
/**
* Test digest authentication using the MD5-sess algorithm.
*/
@Test
public void testDigestAuthenticationMD5SessNoQop() throws Exception {
// Example using Digest auth with MD5-sess
@ -265,21 +244,22 @@ public class TestDigestScheme extends TestCase {
Header authResponse = authscheme.authenticate(cred, request);
Map<String, String> table = parseAuthResponse(authResponse);
assertEquals(username, table.get("username"));
assertEquals(realm, table.get("realm"));
assertEquals("MD5-sess", table.get("algorithm"));
assertEquals("/", table.get("uri"));
assertEquals(nonce, table.get("nonce"));
assertTrue(null == table.get("nc"));
assertEquals("SomeString", table.get("opaque"));
assertTrue(null == table.get("qop"));
Assert.assertEquals(username, table.get("username"));
Assert.assertEquals(realm, table.get("realm"));
Assert.assertEquals("MD5-sess", table.get("algorithm"));
Assert.assertEquals("/", table.get("uri"));
Assert.assertEquals(nonce, table.get("nonce"));
Assert.assertTrue(null == table.get("nc"));
Assert.assertEquals("SomeString", table.get("opaque"));
Assert.assertTrue(null == table.get("qop"));
//@TODO: add better check
assertTrue(null != table.get("response"));
Assert.assertTrue(null != table.get("response"));
}
/**
* Test digest authentication with invalud qop value
*/
@Test(expected=MalformedChallengeException.class)
public void testDigestAuthenticationMD5SessInvalidQop() throws Exception {
// Example using Digest auth with MD5-sess
@ -295,14 +275,11 @@ public class TestDigestScheme extends TestCase {
Header authChallenge = new BasicHeader(AUTH.WWW_AUTH, challenge);
try {
AuthScheme authscheme = new DigestScheme();
authscheme.processChallenge(authChallenge);
fail("MalformedChallengeException exception expected due to invalid qop value");
} catch(MalformedChallengeException e) {
}
AuthScheme authscheme = new DigestScheme();
authscheme.processChallenge(authChallenge);
}
@Test
public void testDigestAuthenticationWithStaleNonce() throws Exception {
String challenge = "Digest realm=\"realm1\", " +
"nonce=\"f2a3f18799759d4f1a1c068b92b573cb\", stale=\"true\"";
@ -310,7 +287,7 @@ public class TestDigestScheme extends TestCase {
AuthScheme authscheme = new DigestScheme();
authscheme.processChallenge(authChallenge);
assertFalse(authscheme.isComplete());
Assert.assertFalse(authscheme.isComplete());
}
private static Map<String, String> parseAuthResponse(final Header authResponse) {

View File

@ -36,25 +36,10 @@ import org.apache.http.auth.MalformedChallengeException;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BufferedHeader;
import org.apache.http.util.CharArrayBuffer;
import org.junit.Assert;
import org.junit.Test;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
public class TestRFC2617Scheme extends TestCase {
// ------------------------------------------------------------ Constructor
public TestRFC2617Scheme(String name) {
super(name);
}
// ------------------------------------------------------- TestCase Methods
public static Test suite() {
return new TestSuite(TestRFC2617Scheme.class);
}
public class TestRFC2617Scheme {
static class TestAuthScheme extends RFC2617Scheme {
@ -78,6 +63,7 @@ public class TestRFC2617Scheme extends TestCase {
}
@Test
public void testProcessChallenge() throws Exception {
TestAuthScheme authscheme = new TestAuthScheme();
Header header = new BasicHeader(
@ -86,14 +72,15 @@ public class TestRFC2617Scheme extends TestCase {
authscheme.processChallenge(header);
assertEquals("test", authscheme.getSchemeName());
assertEquals("realm1", authscheme.getParameter("realm"));
assertEquals(null, authscheme.getParameter("test"));
assertEquals("stuff", authscheme.getParameter("test1"));
assertEquals("stuff, stuff", authscheme.getParameter("test2"));
assertEquals("\"crap", authscheme.getParameter("test3"));
Assert.assertEquals("test", authscheme.getSchemeName());
Assert.assertEquals("realm1", authscheme.getParameter("realm"));
Assert.assertEquals(null, authscheme.getParameter("test"));
Assert.assertEquals("stuff", authscheme.getParameter("test1"));
Assert.assertEquals("stuff, stuff", authscheme.getParameter("test2"));
Assert.assertEquals("\"crap", authscheme.getParameter("test3"));
}
@Test
public void testProcessChallengeWithLotsOfBlanks() throws Exception {
TestAuthScheme authscheme = new TestAuthScheme();
CharArrayBuffer buffer = new CharArrayBuffer(32);
@ -102,41 +89,29 @@ public class TestRFC2617Scheme extends TestCase {
authscheme.processChallenge(header);
assertEquals("test", authscheme.getSchemeName());
assertEquals("realm1", authscheme.getParameter("realm"));
Assert.assertEquals("test", authscheme.getSchemeName());
Assert.assertEquals("realm1", authscheme.getParameter("realm"));
}
@Test(expected=MalformedChallengeException.class)
public void testInvalidHeader() throws Exception {
TestAuthScheme authscheme = new TestAuthScheme();
Header header = new BasicHeader("whatever", "Test realm=\"realm1\"");
try {
authscheme.processChallenge(header);
fail("MalformedChallengeException should have been thrown");
} catch (MalformedChallengeException ex) {
//expected
}
authscheme.processChallenge(header);
}
@Test(expected=MalformedChallengeException.class)
public void testEmptyHeader() throws Exception {
TestAuthScheme authscheme = new TestAuthScheme();
Header header = new BasicHeader(AUTH.WWW_AUTH, "Test ");
try {
authscheme.processChallenge(header);
fail("MalformedChallengeException should have been thrown");
} catch (MalformedChallengeException ex) {
//expected
}
authscheme.processChallenge(header);
}
@Test(expected=MalformedChallengeException.class)
public void testInvalidHeaderValue() throws Exception {
TestAuthScheme authscheme = new TestAuthScheme();
Header header = new BasicHeader("whatever", "whatever");
try {
authscheme.processChallenge(header);
fail("MalformedChallengeException should have been thrown");
} catch (MalformedChallengeException ex) {
//expected
}
authscheme.processChallenge(header);
}
}

View File

@ -36,44 +36,31 @@ import java.util.List;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.cookie.BasicClientCookie;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.junit.Assert;
import org.junit.Test;
/**
* Unit tests for {@link BasicCookieStore}.
*/
public class TestBasicCookieStore extends TestCase {
public TestBasicCookieStore(String testName) {
super(testName);
}
public static void main(String args[]) {
String[] testCaseName = { TestBasicCookieStore.class.getName() };
junit.textui.TestRunner.main(testCaseName);
}
public static Test suite() {
return new TestSuite(TestBasicCookieStore.class);
}
public class TestBasicCookieStore {
@Test
public void testBasics() throws Exception {
BasicCookieStore store = new BasicCookieStore();
store.addCookie(new BasicClientCookie("name1", "value1"));
store.addCookies(new BasicClientCookie[] {new BasicClientCookie("name2", "value2")});
List<Cookie> l = store.getCookies();
assertNotNull(l);
assertEquals(2, l.size());
assertEquals("name1", l.get(0).getName());
assertEquals("name2", l.get(1).getName());
Assert.assertNotNull(l);
Assert.assertEquals(2, l.size());
Assert.assertEquals("name1", l.get(0).getName());
Assert.assertEquals("name2", l.get(1).getName());
store.clear();
l = store.getCookies();
assertNotNull(l);
assertEquals(0, l.size());
Assert.assertNotNull(l);
Assert.assertEquals(0, l.size());
}
@Test
public void testExpiredCookie() throws Exception {
BasicCookieStore store = new BasicCookieStore();
BasicClientCookie cookie = new BasicClientCookie("name1", "value1");
@ -83,10 +70,11 @@ public class TestBasicCookieStore extends TestCase {
cookie.setExpiryDate(c.getTime());
store.addCookie(cookie);
List<Cookie> l = store.getCookies();
assertNotNull(l);
assertEquals(0, l.size());
Assert.assertNotNull(l);
Assert.assertEquals(0, l.size());
}
@Test
public void testSerialization() throws Exception {
BasicCookieStore orig = new BasicCookieStore();
orig.addCookie(new BasicClientCookie("name1", "value1"));
@ -101,12 +89,12 @@ public class TestBasicCookieStore extends TestCase {
BasicCookieStore clone = (BasicCookieStore) instream.readObject();
List<Cookie> expected = orig.getCookies();
List<Cookie> clones = clone.getCookies();
assertNotNull(expected);
assertNotNull(clones);
assertEquals(expected.size(), clones.size());
Assert.assertNotNull(expected);
Assert.assertNotNull(clones);
Assert.assertEquals(expected.size(), clones.size());
for (int i = 0; i < expected.size(); i++) {
assertEquals(expected.get(i).getName(), clones.get(i).getName());
assertEquals(expected.get(i).getValue(), clones.get(i).getValue());
Assert.assertEquals(expected.get(i).getName(), clones.get(i).getName());
Assert.assertEquals(expected.get(i).getValue(), clones.get(i).getValue());
}
}

View File

@ -28,18 +28,13 @@ package org.apache.http.impl.client;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import junit.framework.*;
import org.junit.Assert;
import org.junit.Test;
/**
*
* Simple tests for {@link BasicCredentialsProvider}.
*
*
* @version $Id$
*
*/
public class TestBasicCredentialsProvider extends TestCase {
public class TestBasicCredentialsProvider {
public final static Credentials CREDS1 =
new UsernamePasswordCredentials("user1", "pass1");
@ -55,74 +50,58 @@ public class TestBasicCredentialsProvider extends TestCase {
public final static AuthScope DEFSCOPE =
new AuthScope("host", AuthScope.ANY_PORT, "realm");
// ------------------------------------------------------------ Constructor
public TestBasicCredentialsProvider(String testName) {
super(testName);
}
// ------------------------------------------------------------------- Main
public static void main(String args[]) {
String[] testCaseName = { TestBasicCredentialsProvider.class.getName() };
junit.textui.TestRunner.main(testCaseName);
}
// ------------------------------------------------------- TestCase Methods
public static Test suite() {
return new TestSuite(TestBasicCredentialsProvider.class);
}
// ----------------------------------------------------------- Test Methods
@Test
public void testBasicCredentialsProviderCredentials() {
BasicCredentialsProvider state = new BasicCredentialsProvider();
state.setCredentials(SCOPE1, CREDS1);
state.setCredentials(SCOPE2, CREDS2);
assertEquals(CREDS1, state.getCredentials(SCOPE1));
assertEquals(CREDS2, state.getCredentials(SCOPE2));
Assert.assertEquals(CREDS1, state.getCredentials(SCOPE1));
Assert.assertEquals(CREDS2, state.getCredentials(SCOPE2));
}
@Test
public void testBasicCredentialsProviderNoCredentials() {
BasicCredentialsProvider state = new BasicCredentialsProvider();
assertEquals(null, state.getCredentials(BOGUS));
Assert.assertEquals(null, state.getCredentials(BOGUS));
}
@Test
public void testBasicCredentialsProviderDefaultCredentials() {
BasicCredentialsProvider state = new BasicCredentialsProvider();
state.setCredentials(AuthScope.ANY, CREDS1);
state.setCredentials(SCOPE2, CREDS2);
assertEquals(CREDS1, state.getCredentials(BOGUS));
Assert.assertEquals(CREDS1, state.getCredentials(BOGUS));
}
// --------------------------------- Test Methods for Selecting Credentials
@Test
public void testDefaultCredentials() throws Exception {
BasicCredentialsProvider state = new BasicCredentialsProvider();
Credentials expected = new UsernamePasswordCredentials("name", "pass");
state.setCredentials(AuthScope.ANY, expected);
Credentials got = state.getCredentials(DEFSCOPE);
assertEquals(got, expected);
Assert.assertEquals(got, expected);
}
@Test
public void testRealmCredentials() throws Exception {
BasicCredentialsProvider state = new BasicCredentialsProvider();
Credentials expected = new UsernamePasswordCredentials("name", "pass");
state.setCredentials(DEFSCOPE, expected);
Credentials got = state.getCredentials(DEFSCOPE);
assertEquals(expected, got);
Assert.assertEquals(expected, got);
}
@Test
public void testHostCredentials() throws Exception {
BasicCredentialsProvider state = new BasicCredentialsProvider();
Credentials expected = new UsernamePasswordCredentials("name", "pass");
state.setCredentials(
new AuthScope("host", AuthScope.ANY_PORT, AuthScope.ANY_REALM), expected);
Credentials got = state.getCredentials(DEFSCOPE);
assertEquals(expected, got);
Assert.assertEquals(expected, got);
}
@Test
public void testWrongHostCredentials() throws Exception {
BasicCredentialsProvider state = new BasicCredentialsProvider();
Credentials expected = new UsernamePasswordCredentials("name", "pass");
@ -130,9 +109,10 @@ public class TestBasicCredentialsProvider extends TestCase {
new AuthScope("host1", AuthScope.ANY_PORT, "realm"), expected);
Credentials got = state.getCredentials(
new AuthScope("host2", AuthScope.ANY_PORT, "realm"));
assertNotSame(expected, got);
Assert.assertNotSame(expected, got);
}
@Test
public void testWrongRealmCredentials() throws Exception {
BasicCredentialsProvider state = new BasicCredentialsProvider();
Credentials cred = new UsernamePasswordCredentials("name", "pass");
@ -140,46 +120,46 @@ public class TestBasicCredentialsProvider extends TestCase {
new AuthScope("host", AuthScope.ANY_PORT, "realm1"), cred);
Credentials got = state.getCredentials(
new AuthScope("host", AuthScope.ANY_PORT, "realm2"));
assertNotSame(cred, got);
Assert.assertNotSame(cred, got);
}
// ------------------------------- Test Methods for matching Credentials
@Test
public void testScopeMatching() {
AuthScope authscope1 = new AuthScope("somehost", 80, "somerealm", "somescheme");
AuthScope authscope2 = new AuthScope("someotherhost", 80, "somerealm", "somescheme");
assertTrue(authscope1.match(authscope2) < 0);
Assert.assertTrue(authscope1.match(authscope2) < 0);
int m1 = authscope1.match(
new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, "somescheme"));
int m2 = authscope1.match(
new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, "somerealm", AuthScope.ANY_SCHEME));
assertTrue(m2 > m1);
Assert.assertTrue(m2 > m1);
m1 = authscope1.match(
new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, "somescheme"));
m2 = authscope1.match(
new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, "somerealm", AuthScope.ANY_SCHEME));
assertTrue(m2 > m1);
Assert.assertTrue(m2 > m1);
m1 = authscope1.match(
new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, "somerealm", "somescheme"));
m2 = authscope1.match(
new AuthScope(AuthScope.ANY_HOST, 80, AuthScope.ANY_REALM, AuthScope.ANY_SCHEME));
assertTrue(m2 > m1);
Assert.assertTrue(m2 > m1);
m1 = authscope1.match(
new AuthScope(AuthScope.ANY_HOST, 80, "somerealm", "somescheme"));
m2 = authscope1.match(
new AuthScope("somehost", AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthScope.ANY_SCHEME));
assertTrue(m2 > m1);
Assert.assertTrue(m2 > m1);
m1 = authscope1.match(AuthScope.ANY);
m2 = authscope1.match(
new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, "somescheme"));
assertTrue(m2 > m1);
Assert.assertTrue(m2 > m1);
}
@Test
public void testCredentialsMatching() {
Credentials creds1 = new UsernamePasswordCredentials("name1", "pass1");
Credentials creds2 = new UsernamePasswordCredentials("name2", "pass2");
@ -197,16 +177,17 @@ public class TestBasicCredentialsProvider extends TestCase {
Credentials got = state.getCredentials(
new AuthScope("someotherhost", 80, "someotherrealm", "basic"));
Credentials expected = creds1;
assertEquals(expected, got);
Assert.assertEquals(expected, got);
got = state.getCredentials(
new AuthScope("someotherhost", 80, "somerealm", "basic"));
expected = creds2;
assertEquals(expected, got);
Assert.assertEquals(expected, got);
got = state.getCredentials(
new AuthScope("somehost", 80, "someotherrealm", "basic"));
expected = creds3;
assertEquals(expected, got);
Assert.assertEquals(expected, got);
}
}

View File

@ -28,9 +28,6 @@ package org.apache.http.impl.client;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
@ -59,27 +56,17 @@ import org.apache.http.protocol.ResponseConnControl;
import org.apache.http.protocol.ResponseContent;
import org.apache.http.protocol.ResponseDate;
import org.apache.http.protocol.ResponseServer;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/**
* Unit tests for automatic client authentication.
*/
public class TestClientAuthentication extends BasicServerTestBase {
public TestClientAuthentication(final String testName) {
super(testName);
}
public static void main(String args[]) {
String[] testCaseName = { TestClientAuthentication.class.getName() };
junit.textui.TestRunner.main(testCaseName);
}
public static Test suite() {
return new TestSuite(TestClientAuthentication.class);
}
@Override
protected void setUp() throws Exception {
@Before
public void setUp() throws Exception {
BasicHttpProcessor httpproc = new BasicHttpProcessor();
httpproc.addInterceptor(new ResponseDate());
httpproc.addInterceptor(new ResponseServer());
@ -136,6 +123,7 @@ public class TestClientAuthentication extends BasicServerTestBase {
}
@Test
public void testBasicAuthenticationNoCreds() throws Exception {
localServer.register("*", new AuthHandler());
localServer.start();
@ -149,14 +137,15 @@ public class TestClientAuthentication extends BasicServerTestBase {
HttpResponse response = httpclient.execute(getServerHttp(), httpget);
HttpEntity entity = response.getEntity();
assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode());
assertNotNull(entity);
Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode());
Assert.assertNotNull(entity);
entity.consumeContent();
AuthScope authscope = credsProvider.getAuthScope();
assertNotNull(authscope);
assertEquals("test realm", authscope.getRealm());
Assert.assertNotNull(authscope);
Assert.assertEquals("test realm", authscope.getRealm());
}
@Test
public void testBasicAuthenticationFailure() throws Exception {
localServer.register("*", new AuthHandler());
localServer.start();
@ -171,14 +160,15 @@ public class TestClientAuthentication extends BasicServerTestBase {
HttpResponse response = httpclient.execute(getServerHttp(), httpget);
HttpEntity entity = response.getEntity();
assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode());
assertNotNull(entity);
Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode());
Assert.assertNotNull(entity);
entity.consumeContent();
AuthScope authscope = credsProvider.getAuthScope();
assertNotNull(authscope);
assertEquals("test realm", authscope.getRealm());
Assert.assertNotNull(authscope);
Assert.assertEquals("test realm", authscope.getRealm());
}
@Test
public void testBasicAuthenticationSuccess() throws Exception {
localServer.register("*", new AuthHandler());
localServer.start();
@ -193,14 +183,15 @@ public class TestClientAuthentication extends BasicServerTestBase {
HttpResponse response = httpclient.execute(getServerHttp(), httpget);
HttpEntity entity = response.getEntity();
assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
assertNotNull(entity);
Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertNotNull(entity);
entity.consumeContent();
AuthScope authscope = credsProvider.getAuthScope();
assertNotNull(authscope);
assertEquals("test realm", authscope.getRealm());
Assert.assertNotNull(authscope);
Assert.assertEquals("test realm", authscope.getRealm());
}
@Test
public void testBasicAuthenticationSuccessOnRepeatablePost() throws Exception {
localServer.register("*", new AuthHandler());
localServer.start();
@ -216,14 +207,15 @@ public class TestClientAuthentication extends BasicServerTestBase {
HttpResponse response = httpclient.execute(getServerHttp(), httppost);
HttpEntity entity = response.getEntity();
assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
assertNotNull(entity);
Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertNotNull(entity);
entity.consumeContent();
AuthScope authscope = credsProvider.getAuthScope();
assertNotNull(authscope);
assertEquals("test realm", authscope.getRealm());
Assert.assertNotNull(authscope);
Assert.assertEquals("test realm", authscope.getRealm());
}
@Test(expected=ClientProtocolException.class)
public void testBasicAuthenticationFailureOnNonRepeatablePost() throws Exception {
localServer.register("*", new AuthHandler());
localServer.start();
@ -241,11 +233,12 @@ public class TestClientAuthentication extends BasicServerTestBase {
try {
httpclient.execute(getServerHttp(), httppost);
fail("ClientProtocolException should have been thrown");
Assert.fail("ClientProtocolException should have been thrown");
} catch (ClientProtocolException ex) {
Throwable cause = ex.getCause();
assertNotNull(cause);
assertTrue(cause instanceof NonRepeatableRequestException);
Assert.assertNotNull(cause);
Assert.assertTrue(cause instanceof NonRepeatableRequestException);
throw ex;
}
}
@ -279,6 +272,7 @@ public class TestClientAuthentication extends BasicServerTestBase {
}
@Test
public void testBasicAuthenticationCredentialsCaching() throws Exception {
localServer.register("*", new AuthHandler());
localServer.start();
@ -299,17 +293,17 @@ public class TestClientAuthentication extends BasicServerTestBase {
HttpResponse response1 = httpclient.execute(getServerHttp(), httpget, context);
HttpEntity entity1 = response1.getEntity();
assertEquals(HttpStatus.SC_OK, response1.getStatusLine().getStatusCode());
assertNotNull(entity1);
Assert.assertEquals(HttpStatus.SC_OK, response1.getStatusLine().getStatusCode());
Assert.assertNotNull(entity1);
entity1.consumeContent();
HttpResponse response2 = httpclient.execute(getServerHttp(), httpget, context);
HttpEntity entity2 = response1.getEntity();
assertEquals(HttpStatus.SC_OK, response2.getStatusLine().getStatusCode());
assertNotNull(entity2);
Assert.assertEquals(HttpStatus.SC_OK, response2.getStatusLine().getStatusCode());
Assert.assertNotNull(entity2);
entity1.consumeContent();
assertEquals(1, authHandler.getCount());
Assert.assertEquals(1, authHandler.getCount());
}
}

View File

@ -44,9 +44,7 @@ import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.DeflateDecompressingEntity;
@ -62,6 +60,8 @@ import org.apache.http.localserver.ServerTestBase;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestHandler;
import org.apache.http.util.EntityUtils;
import org.junit.Assert;
import org.junit.Test;
/**
* Test case for how Content Codings are processed. By default, we want to do the right thing and
@ -70,10 +70,6 @@ import org.apache.http.util.EntityUtils;
*/
public class TestContentCodings extends ServerTestBase {
public TestContentCodings(String testName) {
super(testName);
}
/**
* Test for when we don't get an entity back; e.g. for a 204 or 304 response; nothing blows
* up with the new behaviour.
@ -81,6 +77,7 @@ public class TestContentCodings extends ServerTestBase {
* @throws Exception
* if there was a problem
*/
@Test
public void testResponseWithNoContent() throws Exception {
this.localServer.register("*", new HttpRequestHandler() {
@ -99,8 +96,8 @@ public class TestContentCodings extends ServerTestBase {
HttpGet request = new HttpGet("/some-resource");
HttpResponse response = client.execute(getServerHttp(), request);
assertEquals(HttpStatus.SC_NO_CONTENT, response.getStatusLine().getStatusCode());
assertNull(response.getEntity());
Assert.assertEquals(HttpStatus.SC_NO_CONTENT, response.getStatusLine().getStatusCode());
Assert.assertNull(response.getEntity());
client.getConnectionManager().shutdown();
}
@ -112,6 +109,7 @@ public class TestContentCodings extends ServerTestBase {
* @throws Exception
* @see DeflateDecompressingEntity
*/
@Test
public void testDeflateSupportForServerReturningRfc1950Stream() throws Exception {
final String entityText = "Hello, this is some plain text coming back.";
@ -121,7 +119,7 @@ public class TestContentCodings extends ServerTestBase {
HttpGet request = new HttpGet("/some-resource");
HttpResponse response = client.execute(getServerHttp(), request);
assertEquals("The entity text is correctly transported", entityText,
Assert.assertEquals("The entity text is correctly transported", entityText,
EntityUtils.toString(response.getEntity()));
client.getConnectionManager().shutdown();
@ -134,6 +132,7 @@ public class TestContentCodings extends ServerTestBase {
* @throws Exception
* @see DeflateDecompressingEntity
*/
@Test
public void testDeflateSupportForServerReturningRfc1951Stream() throws Exception {
final String entityText = "Hello, this is some plain text coming back.";
@ -142,7 +141,7 @@ public class TestContentCodings extends ServerTestBase {
DefaultHttpClient client = createHttpClient();
HttpGet request = new HttpGet("/some-resource");
HttpResponse response = client.execute(getServerHttp(), request);
assertEquals("The entity text is correctly transported", entityText,
Assert.assertEquals("The entity text is correctly transported", entityText,
EntityUtils.toString(response.getEntity()));
client.getConnectionManager().shutdown();
@ -153,6 +152,7 @@ public class TestContentCodings extends ServerTestBase {
*
* @throws Exception
*/
@Test
public void testGzipSupport() throws Exception {
final String entityText = "Hello, this is some plain text coming back.";
@ -161,7 +161,7 @@ public class TestContentCodings extends ServerTestBase {
DefaultHttpClient client = createHttpClient();
HttpGet request = new HttpGet("/some-resource");
HttpResponse response = client.execute(getServerHttp(), request);
assertEquals("The entity text is correctly transported", entityText,
Assert.assertEquals("The entity text is correctly transported", entityText,
EntityUtils.toString(response.getEntity()));
client.getConnectionManager().shutdown();
@ -173,6 +173,7 @@ public class TestContentCodings extends ServerTestBase {
* @throws Exception
* if there was a problem
*/
@Test
public void testThreadSafetyOfContentCodings() throws Exception {
final String entityText = "Hello, this is some plain text coming back.";
@ -216,78 +217,19 @@ public class TestContentCodings extends ServerTestBase {
for (WorkerTask workerTask : workers) {
if (workerTask.isFailed()) {
fail("A worker failed");
Assert.fail("A worker failed");
}
assertEquals(entityText, workerTask.getText());
Assert.assertEquals(entityText, workerTask.getText());
}
}
/**
* This test is no longer relevant, since the functionality has been added via a new subclass of
* {@link DefaultHttpClient} rather than changing the existing class.
*
* @throws Exception
*/
public void removedTestExistingProtocolInterceptorsAreNotAffected() throws Exception {
final String entityText = "Hello, this is some plain text coming back.";
this.localServer.register("*", createGzipEncodingRequestHandler(entityText));
DefaultHttpClient client = createHttpClient();
HttpGet request = new HttpGet("/some-resource");
client.addRequestInterceptor(new HttpRequestInterceptor() {
/**
* {@inheritDoc}
*/
public void process(
HttpRequest request, HttpContext context) throws HttpException, IOException {
request.addHeader("Accept-Encoding", "gzip");
}
});
/* Get around Java The Language's lack of mutable closures */
final boolean clientSawGzip[] = new boolean[1];
client.addResponseInterceptor(new HttpResponseInterceptor() {
/**
* {@inheritDoc}
*/
public void process(
HttpResponse response, HttpContext context) throws HttpException, IOException {
HttpEntity entity = response.getEntity();
if (entity != null) {
Header ce = entity.getContentEncoding();
if (ce != null) {
HeaderElement[] codecs = ce.getElements();
for (int i = 0, n = codecs.length; i < n; ++i) {
if ("gzip".equalsIgnoreCase(codecs[i].getName())) {
clientSawGzip[0] = true;
return;
}
}
}
}
}
});
client.execute(getServerHttp(), request);
assertTrue("Client which added the new custom protocol interceptor to handle gzip responses " +
"was unaffected.",
clientSawGzip[0]);
client.getConnectionManager().shutdown();
}
/**
* Checks that we can turn off the new Content-Coding support. The default is that it's on, but that is a change
* to existing behaviour and might not be desirable in some situations.
*
* @throws Exception
*/
@Test
public void testCanBeDisabledAtRequestTime() throws Exception {
final String entityText = "Hello, this is some plain text coming back.";
@ -316,8 +258,8 @@ public class TestContentCodings extends ServerTestBase {
HttpResponse response = client.execute(getServerHttp(), request);
assertFalse("The Accept-Encoding header was not there", sawAcceptEncodingHeader[0]);
assertEquals("The entity isn't treated as gzip or zip content", entityText,
Assert.assertFalse("The Accept-Encoding header was not there", sawAcceptEncodingHeader[0]);
Assert.assertEquals("The entity isn't treated as gzip or zip content", entityText,
EntityUtils.toString(response.getEntity()));
client.getConnectionManager().shutdown();
@ -329,6 +271,7 @@ public class TestContentCodings extends ServerTestBase {
*
* @throws Exception
*/
@Test
public void testHttpEntityWriteToForGzip() throws Exception {
final String entityText = "Hello, this is some plain text coming back.";
@ -341,7 +284,7 @@ public class TestContentCodings extends ServerTestBase {
response.getEntity().writeTo(out);
assertEquals(entityText, out.toString("utf-8"));
Assert.assertEquals(entityText, out.toString("utf-8"));
client.getConnectionManager().shutdown();
}
@ -352,6 +295,7 @@ public class TestContentCodings extends ServerTestBase {
*
* @throws Exception
*/
@Test
public void testHttpEntityWriteToForDeflate() throws Exception {
final String entityText = "Hello, this is some plain text coming back.";
@ -364,7 +308,7 @@ public class TestContentCodings extends ServerTestBase {
response.getEntity().writeTo(out);
assertEquals(entityText, out.toString("utf-8"));
Assert.assertEquals(entityText, out.toString("utf-8"));
client.getConnectionManager().shutdown();
}

View File

@ -27,92 +27,75 @@ package org.apache.http.impl.client;
import org.apache.http.cookie.CookieIdentityComparator;
import org.apache.http.impl.cookie.BasicClientCookie;
import junit.framework.*;
import org.junit.Assert;
import org.junit.Test;
/**
* Simple tests for {@link CookieIdentityComparator}.
*
* @version $Id:$
*/
public class TestCookieIdentityComparator extends TestCase {
// ------------------------------------------------------------ Constructor
public TestCookieIdentityComparator(String testName) {
super(testName);
}
// ------------------------------------------------------------------- Main
public static void main(String args[]) {
String[] testCaseName = { TestCookieIdentityComparator.class.getName() };
junit.textui.TestRunner.main(testCaseName);
}
// ------------------------------------------------------- TestCase Methods
public static Test suite() {
return new TestSuite(TestCookieIdentityComparator.class);
}
// ----------------------------------------------------------- Test Methods
public class TestCookieIdentityComparator {
@Test
public void testCookieIdentityComparasionByName() {
CookieIdentityComparator comparator = new CookieIdentityComparator();
BasicClientCookie c1 = new BasicClientCookie("name", "value1");
BasicClientCookie c2 = new BasicClientCookie("name", "value2");
assertTrue(comparator.compare(c1, c2) == 0);
Assert.assertTrue(comparator.compare(c1, c2) == 0);
BasicClientCookie c3 = new BasicClientCookie("name1", "value");
BasicClientCookie c4 = new BasicClientCookie("name2", "value");
assertFalse(comparator.compare(c3, c4) == 0);
Assert.assertFalse(comparator.compare(c3, c4) == 0);
}
@Test
public void testCookieIdentityComparasionByNameAndDomain() {
CookieIdentityComparator comparator = new CookieIdentityComparator();
BasicClientCookie c1 = new BasicClientCookie("name", "value1");
c1.setDomain("www.domain.com");
BasicClientCookie c2 = new BasicClientCookie("name", "value2");
c2.setDomain("www.domain.com");
assertTrue(comparator.compare(c1, c2) == 0);
Assert.assertTrue(comparator.compare(c1, c2) == 0);
BasicClientCookie c3 = new BasicClientCookie("name", "value1");
c3.setDomain("www.domain.com");
BasicClientCookie c4 = new BasicClientCookie("name", "value2");
c4.setDomain("domain.com");
assertFalse(comparator.compare(c3, c4) == 0);
Assert.assertFalse(comparator.compare(c3, c4) == 0);
}
@Test
public void testCookieIdentityComparasionByNameAndNullDomain() {
CookieIdentityComparator comparator = new CookieIdentityComparator();
BasicClientCookie c1 = new BasicClientCookie("name", "value1");
c1.setDomain(null);
BasicClientCookie c2 = new BasicClientCookie("name", "value2");
c2.setDomain(null);
assertTrue(comparator.compare(c1, c2) == 0);
Assert.assertTrue(comparator.compare(c1, c2) == 0);
BasicClientCookie c3 = new BasicClientCookie("name", "value1");
c3.setDomain("www.domain.com");
BasicClientCookie c4 = new BasicClientCookie("name", "value2");
c4.setDomain(null);
assertFalse(comparator.compare(c3, c4) == 0);
Assert.assertFalse(comparator.compare(c3, c4) == 0);
}
@Test
public void testCookieIdentityComparasionByNameAndLocalHost() {
CookieIdentityComparator comparator = new CookieIdentityComparator();
BasicClientCookie c1 = new BasicClientCookie("name", "value1");
c1.setDomain("localhost");
BasicClientCookie c2 = new BasicClientCookie("name", "value2");
c2.setDomain("localhost");
assertTrue(comparator.compare(c1, c2) == 0);
Assert.assertTrue(comparator.compare(c1, c2) == 0);
BasicClientCookie c3 = new BasicClientCookie("name", "value1");
c3.setDomain("localhost.local");
BasicClientCookie c4 = new BasicClientCookie("name", "value2");
c4.setDomain("localhost");
assertTrue(comparator.compare(c3, c4) == 0);
Assert.assertTrue(comparator.compare(c3, c4) == 0);
}
@Test
public void testCookieIdentityComparasionByNameDomainAndPath() {
CookieIdentityComparator comparator = new CookieIdentityComparator();
BasicClientCookie c1 = new BasicClientCookie("name", "value1");
@ -121,7 +104,7 @@ public class TestCookieIdentityComparator extends TestCase {
BasicClientCookie c2 = new BasicClientCookie("name", "value2");
c2.setDomain("www.domain.com");
c2.setPath("/whatever");
assertTrue(comparator.compare(c1, c2) == 0);
Assert.assertTrue(comparator.compare(c1, c2) == 0);
BasicClientCookie c3 = new BasicClientCookie("name", "value1");
c3.setDomain("www.domain.com");
@ -129,9 +112,10 @@ public class TestCookieIdentityComparator extends TestCase {
BasicClientCookie c4 = new BasicClientCookie("name", "value2");
c4.setDomain("domain.com");
c4.setPath("/whatever-not");
assertFalse(comparator.compare(c3, c4) == 0);
Assert.assertFalse(comparator.compare(c3, c4) == 0);
}
@Test
public void testCookieIdentityComparasionByNameDomainAndNullPath() {
CookieIdentityComparator comparator = new CookieIdentityComparator();
BasicClientCookie c1 = new BasicClientCookie("name", "value1");
@ -140,7 +124,7 @@ public class TestCookieIdentityComparator extends TestCase {
BasicClientCookie c2 = new BasicClientCookie("name", "value2");
c2.setDomain("www.domain.com");
c2.setPath(null);
assertTrue(comparator.compare(c1, c2) == 0);
Assert.assertTrue(comparator.compare(c1, c2) == 0);
BasicClientCookie c3 = new BasicClientCookie("name", "value1");
c3.setDomain("www.domain.com");
@ -148,7 +132,7 @@ public class TestCookieIdentityComparator extends TestCase {
BasicClientCookie c4 = new BasicClientCookie("name", "value2");
c4.setDomain("domain.com");
c4.setPath(null);
assertFalse(comparator.compare(c3, c4) == 0);
Assert.assertFalse(comparator.compare(c3, c4) == 0);
}
}

View File

@ -32,9 +32,6 @@ import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.apache.http.Header;
import org.apache.http.HttpClientConnection;
import org.apache.http.HttpEntity;
@ -77,27 +74,17 @@ import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestExecutor;
import org.apache.http.protocol.HttpRequestHandler;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/**
* Unit tests for {@link DefaultRequestDirector}
*/
public class TestDefaultClientRequestDirector extends BasicServerTestBase {
public TestDefaultClientRequestDirector(final String testName) {
super(testName);
}
public static void main(String args[]) {
String[] testCaseName = { TestDefaultClientRequestDirector.class.getName() };
junit.textui.TestRunner.main(testCaseName);
}
public static Test suite() {
return new TestSuite(TestDefaultClientRequestDirector.class);
}
@Override
protected void setUp() throws Exception {
@Before
public void setUp() throws Exception {
localServer = new LocalTestServer(null, null);
localServer.registerDefaultHandlers();
localServer.start();
@ -108,6 +95,7 @@ public class TestDefaultClientRequestDirector extends BasicServerTestBase {
* {@link DefaultRequestDirector} is allocating a connection, that the
* connection is properly aborted.
*/
@Test
public void testAbortInAllocate() throws Exception {
CountDownLatch connLatch = new CountDownLatch(1);
CountDownLatch awaitLatch = new CountDownLatch(1);
@ -130,14 +118,14 @@ public class TestDefaultClientRequestDirector extends BasicServerTestBase {
}
}).start();
assertTrue("should have tried to get a connection", connLatch.await(1, TimeUnit.SECONDS));
Assert.assertTrue("should have tried to get a connection", connLatch.await(1, TimeUnit.SECONDS));
httpget.abort();
assertTrue("should have finished get request", getLatch.await(1, TimeUnit.SECONDS));
assertTrue("should be instanceof IOException, was: " + throwableRef.get(),
Assert.assertTrue("should have finished get request", getLatch.await(1, TimeUnit.SECONDS));
Assert.assertTrue("should be instanceof IOException, was: " + throwableRef.get(),
throwableRef.get() instanceof IOException);
assertTrue("cause should be InterruptedException, was: " + throwableRef.get().getCause(),
Assert.assertTrue("cause should be InterruptedException, was: " + throwableRef.get().getCause(),
throwableRef.get().getCause() instanceof InterruptedException);
}
@ -145,6 +133,7 @@ public class TestDefaultClientRequestDirector extends BasicServerTestBase {
* Tests that an abort called after the connection has been retrieved
* but before a release trigger is set does still abort the request.
*/
@Test
public void testAbortAfterAllocateBeforeRequest() throws Exception {
this.localServer.register("*", new BasicService());
@ -177,8 +166,8 @@ public class TestDefaultClientRequestDirector extends BasicServerTestBase {
releaseLatch.countDown();
assertTrue("should have finished get request", getLatch.await(1, TimeUnit.SECONDS));
assertTrue("should be instanceof IOException, was: " + throwableRef.get(),
Assert.assertTrue("should have finished get request", getLatch.await(1, TimeUnit.SECONDS));
Assert.assertTrue("should be instanceof IOException, was: " + throwableRef.get(),
throwableRef.get() instanceof IOException);
}
@ -186,6 +175,7 @@ public class TestDefaultClientRequestDirector extends BasicServerTestBase {
* Tests that an abort called completely before execute
* still aborts the request.
*/
@Test
public void testAbortBeforeExecute() throws Exception {
this.localServer.register("*", new BasicService());
@ -221,8 +211,8 @@ public class TestDefaultClientRequestDirector extends BasicServerTestBase {
httpget.abort();
startLatch.countDown();
assertTrue("should have finished get request", getLatch.await(1, TimeUnit.SECONDS));
assertTrue("should be instanceof IOException, was: " + throwableRef.get(),
Assert.assertTrue("should have finished get request", getLatch.await(1, TimeUnit.SECONDS));
Assert.assertTrue("should be instanceof IOException, was: " + throwableRef.get(),
throwableRef.get() instanceof IOException);
}
@ -231,6 +221,7 @@ public class TestDefaultClientRequestDirector extends BasicServerTestBase {
* still aborts in the correct place (while trying to get the new
* host's route, not while doing the subsequent request).
*/
@Test
public void testAbortAfterRedirectedRoute() throws Exception {
final int port = this.localServer.getServiceAddress().getPort();
this.localServer.register("*", new BasicRedirectService(port));
@ -260,14 +251,14 @@ public class TestDefaultClientRequestDirector extends BasicServerTestBase {
}
}).start();
assertTrue("should have tried to get a connection", connLatch.await(1, TimeUnit.SECONDS));
Assert.assertTrue("should have tried to get a connection", connLatch.await(1, TimeUnit.SECONDS));
httpget.abort();
assertTrue("should have finished get request", getLatch.await(1, TimeUnit.SECONDS));
assertTrue("should be instanceof IOException, was: " + throwableRef.get(),
Assert.assertTrue("should have finished get request", getLatch.await(1, TimeUnit.SECONDS));
Assert.assertTrue("should be instanceof IOException, was: " + throwableRef.get(),
throwableRef.get() instanceof IOException);
assertTrue("cause should be InterruptedException, was: " + throwableRef.get().getCause(),
Assert.assertTrue("cause should be InterruptedException, was: " + throwableRef.get().getCause(),
throwableRef.get().getCause() instanceof InterruptedException);
}
@ -276,6 +267,7 @@ public class TestDefaultClientRequestDirector extends BasicServerTestBase {
* Tests that if a socket fails to connect, the allocated connection is
* properly released back to the connection manager.
*/
@Test
public void testSocketConnectFailureReleasesConnection() throws Exception {
final ConnMan2 conMan = new ConnMan2();
final DefaultHttpClient client = new DefaultHttpClient(conMan, new BasicHttpParams());
@ -284,13 +276,14 @@ public class TestDefaultClientRequestDirector extends BasicServerTestBase {
try {
client.execute(httpget, context);
fail("expected IOException");
Assert.fail("expected IOException");
} catch(IOException expected) {}
assertNotNull(conMan.allocatedConnection);
assertSame(conMan.allocatedConnection, conMan.releasedConnection);
Assert.assertNotNull(conMan.allocatedConnection);
Assert.assertSame(conMan.allocatedConnection, conMan.releasedConnection);
}
@Test
public void testRequestFailureReleasesConnection() throws Exception {
this.localServer.register("*", new ThrowingService());
@ -303,11 +296,11 @@ public class TestDefaultClientRequestDirector extends BasicServerTestBase {
try {
client.execute(getServerHttp(), httpget);
fail("expected IOException");
Assert.fail("expected IOException");
} catch (IOException expected) {}
assertNotNull(conMan.allocatedConnection);
assertSame(conMan.allocatedConnection, conMan.releasedConnection);
Assert.assertNotNull(conMan.allocatedConnection);
Assert.assertSame(conMan.allocatedConnection, conMan.releasedConnection);
}
private static class ThrowingService implements HttpRequestHandler {
@ -600,6 +593,7 @@ public class TestDefaultClientRequestDirector extends BasicServerTestBase {
}
}
@Test
public void testDefaultHostAtClientLevel() throws Exception {
int port = this.localServer.getServiceAddress().getPort();
this.localServer.register("*", new SimpleService());
@ -617,9 +611,10 @@ public class TestDefaultClientRequestDirector extends BasicServerTestBase {
if (e != null) {
e.consumeContent();
}
assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
}
@Test
public void testDefaultHostAtRequestLevel() throws Exception {
int port = this.localServer.getServiceAddress().getPort();
this.localServer.register("*", new SimpleService());
@ -639,7 +634,7 @@ public class TestDefaultClientRequestDirector extends BasicServerTestBase {
if (e != null) {
e.consumeContent();
}
assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
}
private static class FaultyHttpRequestExecutor extends HttpRequestExecutor {
@ -687,7 +682,7 @@ public class TestDefaultClientRequestDirector extends BasicServerTestBase {
}
@Test
public void testAutoGeneratedHeaders() throws Exception {
int port = this.localServer.getServiceAddress().getPort();
this.localServer.register("*", new SimpleService());
@ -729,14 +724,15 @@ public class TestDefaultClientRequestDirector extends BasicServerTestBase {
HttpRequest reqWrapper = (HttpRequest) context.getAttribute(
ExecutionContext.HTTP_REQUEST);
assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
assertTrue(reqWrapper instanceof RequestWrapper);
Assert.assertTrue(reqWrapper instanceof RequestWrapper);
Header[] myheaders = reqWrapper.getHeaders("my-header");
assertNotNull(myheaders);
assertEquals(1, myheaders.length);
Assert.assertNotNull(myheaders);
Assert.assertEquals(1, myheaders.length);
}
@Test(expected=ClientProtocolException.class)
public void testNonRepeatableEntity() throws Exception {
int port = this.localServer.getServiceAddress().getPort();
this.localServer.register("*", new SimpleService());
@ -755,12 +751,12 @@ public class TestDefaultClientRequestDirector extends BasicServerTestBase {
try {
client.execute(getServerHttp(), httppost, context);
fail("ClientProtocolException should have been thrown");
} catch (ClientProtocolException ex) {
assertTrue(ex.getCause() instanceof NonRepeatableRequestException);
Assert.assertTrue(ex.getCause() instanceof NonRepeatableRequestException);
NonRepeatableRequestException nonRepeat = (NonRepeatableRequestException)ex.getCause();
assertTrue(nonRepeat.getCause() instanceof IOException);
assertEquals(failureMsg, nonRepeat.getCause().getMessage());
Assert.assertTrue(nonRepeat.getCause() instanceof IOException);
Assert.assertEquals(failureMsg, nonRepeat.getCause().getMessage());
throw ex;
}
}

View File

@ -26,10 +26,6 @@
package org.apache.http.impl.client;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
@ -38,50 +34,32 @@ import org.apache.http.message.BasicHttpResponse;
import org.apache.http.message.BasicStatusLine;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.junit.Assert;
import org.junit.Test;
/**
* Simple tests for {@link DefaultConnectionKeepAliveStrategy}.
*
*/
public class TestDefaultConnKeepAliveStrategy extends TestCase {
// ------------------------------------------------------------ Constructor
public TestDefaultConnKeepAliveStrategy(final String testName) {
super(testName);
}
// ------------------------------------------------------------------- Main
public static void main(String args[]) {
String[] testCaseName = { TestDefaultConnKeepAliveStrategy.class.getName() };
junit.textui.TestRunner.main(testCaseName);
}
// ------------------------------------------------------- TestCase Methods
public static Test suite() {
return new TestSuite(TestDefaultConnKeepAliveStrategy.class);
}
public class TestDefaultConnKeepAliveStrategy {
@Test(expected=IllegalArgumentException.class)
public void testIllegalResponseArg() throws Exception {
HttpContext context = new BasicHttpContext(null);
ConnectionKeepAliveStrategy keepAliveStrat = new DefaultConnectionKeepAliveStrategy();
try {
keepAliveStrat.getKeepAliveDuration(null, context);
fail("IllegalArgumentException should have been thrown");
} catch (IllegalArgumentException ex) {
// expected
}
keepAliveStrat.getKeepAliveDuration(null, context);
}
@Test
public void testNoKeepAliveHeader() throws Exception {
HttpContext context = new BasicHttpContext(null);
HttpResponse response = new BasicHttpResponse(
new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"));
ConnectionKeepAliveStrategy keepAliveStrat = new DefaultConnectionKeepAliveStrategy();
long d = keepAliveStrat.getKeepAliveDuration(response, context);
assertEquals(-1, d);
Assert.assertEquals(-1, d);
}
@Test
public void testEmptyKeepAliveHeader() throws Exception {
HttpContext context = new BasicHttpContext(null);
HttpResponse response = new BasicHttpResponse(
@ -89,9 +67,10 @@ public class TestDefaultConnKeepAliveStrategy extends TestCase {
response.addHeader("Keep-Alive", "timeout, max=20");
ConnectionKeepAliveStrategy keepAliveStrat = new DefaultConnectionKeepAliveStrategy();
long d = keepAliveStrat.getKeepAliveDuration(response, context);
assertEquals(-1, d);
Assert.assertEquals(-1, d);
}
@Test
public void testInvalidKeepAliveHeader() throws Exception {
HttpContext context = new BasicHttpContext(null);
HttpResponse response = new BasicHttpResponse(
@ -99,9 +78,10 @@ public class TestDefaultConnKeepAliveStrategy extends TestCase {
response.addHeader("Keep-Alive", "timeout=whatever, max=20");
ConnectionKeepAliveStrategy keepAliveStrat = new DefaultConnectionKeepAliveStrategy();
long d = keepAliveStrat.getKeepAliveDuration(response, context);
assertEquals(-1, d);
Assert.assertEquals(-1, d);
}
@Test
public void testKeepAliveHeader() throws Exception {
HttpContext context = new BasicHttpContext(null);
HttpResponse response = new BasicHttpResponse(
@ -109,7 +89,7 @@ public class TestDefaultConnKeepAliveStrategy extends TestCase {
response.addHeader("Keep-Alive", "timeout=300, max=20");
ConnectionKeepAliveStrategy keepAliveStrat = new DefaultConnectionKeepAliveStrategy();
long d = keepAliveStrat.getKeepAliveDuration(response, context);
assertEquals(300000, d);
Assert.assertEquals(300000, d);
}
}

View File

@ -29,33 +29,15 @@ package org.apache.http.impl.client;
import java.net.URI;
import java.util.List;
import junit.framework.Assert;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.junit.Assert;
import org.junit.Test;
/**
* Simple tests for {@link RedirectLocations}.
*/
public class TestRedirectLocation extends TestCase {
// ------------------------------------------------------------ Constructor
public TestRedirectLocation(final String testName) {
super(testName);
}
// ------------------------------------------------------------------- Main
public static void main(String args[]) {
String[] testCaseName = { TestRedirectLocation.class.getName() };
junit.textui.TestRunner.main(testCaseName);
}
// ------------------------------------------------------- TestCase Methods
public static Test suite() {
return new TestSuite(TestRedirectLocation.class);
}
public class TestRedirectLocation {
@Test
public void testBasics() throws Exception {
RedirectLocations locations = new RedirectLocations();

View File

@ -28,8 +28,6 @@ package org.apache.http.impl.client;
import java.io.IOException;
import java.net.UnknownHostException;
import junit.framework.TestCase;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpRequestBase;
@ -41,9 +39,12 @@ import org.apache.http.impl.conn.SingleClientConnManager;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HttpContext;
import org.junit.Assert;
import org.junit.Test;
public class TestRequestRetryHandler extends TestCase {
public class TestRequestRetryHandler {
@Test(expected=UnknownHostException.class)
public void testUseRetryHandlerInConnectionTimeOutWithThreadSafeClientConnManager()
throws Exception {
@ -54,6 +55,7 @@ public class TestRequestRetryHandler extends TestCase {
assertOnRetry(connManager);
}
@Test(expected=UnknownHostException.class)
public void testUseRetryHandlerInConnectionTimeOutWithSingleClientConnManager()
throws Exception {
@ -77,7 +79,8 @@ public class TestRequestRetryHandler extends TestCase {
try {
client.execute(request);
} catch (UnknownHostException ex) {
assertEquals(2, testRetryHandler.retryNumber);
Assert.assertEquals(2, testRetryHandler.retryNumber);
throw ex;
}
}

View File

@ -28,9 +28,6 @@ package org.apache.http.impl.client;
import java.io.IOException;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
@ -44,32 +41,17 @@ import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestHandler;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/**
* Simple tests for {@link RequestWrapper}.
*
*/
public class TestRequestWrapper extends BasicServerTestBase {
// ------------------------------------------------------------ Constructor
public TestRequestWrapper(final String testName) {
super(testName);
}
// ------------------------------------------------------------------- Main
public static void main(String args[]) {
String[] testCaseName = { TestRequestWrapper.class.getName() };
junit.textui.TestRunner.main(testCaseName);
}
// ------------------------------------------------------- TestCase Methods
public static Test suite() {
return new TestSuite(TestRequestWrapper.class);
}
@Override
protected void setUp() throws Exception {
@Before
public void setUp() throws Exception {
localServer = new LocalTestServer(null, null);
localServer.registerDefaultHandlers();
localServer.start();
@ -91,6 +73,7 @@ public class TestRequestWrapper extends BasicServerTestBase {
}
}
@Test
public void testRequestURIRewriting() throws Exception {
int port = this.localServer.getServiceAddress().getPort();
this.localServer.register("*", new SimpleService());
@ -110,12 +93,13 @@ public class TestRequestWrapper extends BasicServerTestBase {
HttpRequest reqWrapper = (HttpRequest) context.getAttribute(
ExecutionContext.HTTP_REQUEST);
assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
assertTrue(reqWrapper instanceof RequestWrapper);
assertEquals("/path", reqWrapper.getRequestLine().getUri());
Assert.assertTrue(reqWrapper instanceof RequestWrapper);
Assert.assertEquals("/path", reqWrapper.getRequestLine().getUri());
}
@Test
public void testRequestURIRewritingEmptyPath() throws Exception {
int port = this.localServer.getServiceAddress().getPort();
this.localServer.register("*", new SimpleService());
@ -135,10 +119,10 @@ public class TestRequestWrapper extends BasicServerTestBase {
HttpRequest reqWrapper = (HttpRequest) context.getAttribute(
ExecutionContext.HTTP_REQUEST);
assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
assertTrue(reqWrapper instanceof RequestWrapper);
assertEquals("/", reqWrapper.getRequestLine().getUri());
Assert.assertTrue(reqWrapper instanceof RequestWrapper);
Assert.assertEquals("/", reqWrapper.getRequestLine().getUri());
}
}

View File

@ -27,9 +27,6 @@ package org.apache.http.impl.client;
import java.io.IOException;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
@ -50,25 +47,14 @@ import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestHandler;
import org.junit.Assert;
import org.junit.Test;
/**
* Unit tests for {@link DefaultRequestDirector}
*/
public class TestStatefulConnManagement extends ServerTestBase {
public TestStatefulConnManagement(final String testName) {
super(testName);
}
public static void main(String args[]) {
String[] testCaseName = { TestStatefulConnManagement.class.getName() };
junit.textui.TestRunner.main(testCaseName);
}
public static Test suite() {
return new TestSuite(TestStatefulConnManagement.class);
}
private static class SimpleService implements HttpRequestHandler {
public SimpleService() {
@ -85,6 +71,7 @@ public class TestStatefulConnManagement extends ServerTestBase {
}
}
@Test
public void testStatefulConnections() throws Exception {
int workerCount = 5;
@ -135,7 +122,7 @@ public class TestStatefulConnManagement extends ServerTestBase {
if (ex != null) {
throw ex;
}
assertEquals(requestCount, workers[i].getCount());
Assert.assertEquals(requestCount, workers[i].getCount());
}
for (int i = 0; i < contexts.length; i++) {
@ -144,8 +131,8 @@ public class TestStatefulConnManagement extends ServerTestBase {
for (int r = 0; r < requestCount; r++) {
Integer state = (Integer) context.getAttribute("r" + r);
assertNotNull(state);
assertEquals(id, state);
Assert.assertNotNull(state);
Assert.assertEquals(id, state);
}
}

View File

@ -40,29 +40,15 @@ import org.apache.http.message.BasicLineParser;
import org.apache.http.mockup.SessionInputBufferMockup;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.junit.Assert;
import org.junit.Test;
/**
* Tests for <code>DefaultResponseParser</code>.
*/
public class TestDefaultResponseParser extends TestCase {
public TestDefaultResponseParser(String testName) {
super(testName);
}
public static void main(String args[]) {
String[] testCaseName = { TestDefaultResponseParser.class.getName() };
junit.textui.TestRunner.main(testCaseName);
}
public static Test suite() {
return new TestSuite(TestDefaultResponseParser.class);
}
public class TestDefaultResponseParser {
@Test
public void testResponseParsingWithSomeGarbage() throws Exception {
String s =
"garbage\r\n" +
@ -82,17 +68,18 @@ public class TestDefaultResponseParser extends TestCase {
params);
HttpResponse response = (HttpResponse) parser.parse();
assertNotNull(response);
assertEquals(HttpVersion.HTTP_1_1, response.getProtocolVersion());
assertEquals(200, response.getStatusLine().getStatusCode());
Assert.assertNotNull(response);
Assert.assertEquals(HttpVersion.HTTP_1_1, response.getProtocolVersion());
Assert.assertEquals(200, response.getStatusLine().getStatusCode());
Header[] headers = response.getAllHeaders();
assertNotNull(headers);
assertEquals(2, headers.length);
assertEquals("header1", headers[0].getName());
assertEquals("header2", headers[1].getName());
Assert.assertNotNull(headers);
Assert.assertEquals(2, headers.length);
Assert.assertEquals("header1", headers[0].getName());
Assert.assertEquals("header2", headers[1].getName());
}
@Test(expected=ProtocolException.class)
public void testResponseParsingWithTooMuchGarbage() throws Exception {
String s =
"garbage\r\n" +
@ -111,14 +98,10 @@ public class TestDefaultResponseParser extends TestCase {
BasicLineParser.DEFAULT,
new DefaultHttpResponseFactory(),
params);
try {
parser.parse();
fail("ProtocolException should have been thrown");
} catch (ProtocolException ex) {
}
parser.parse();
}
@Test(expected=NoHttpResponseException.class)
public void testResponseParsingNoResponse() throws Exception {
HttpParams params = new BasicHttpParams();
SessionInputBuffer inbuffer = new SessionInputBufferMockup("", "US-ASCII", params);
@ -127,14 +110,10 @@ public class TestDefaultResponseParser extends TestCase {
BasicLineParser.DEFAULT,
new DefaultHttpResponseFactory(),
params);
try {
parser.parse();
fail("NoHttpResponseException should have been thrown");
} catch (NoHttpResponseException ex) {
}
parser.parse();
}
@Test(expected=ProtocolException.class)
public void testResponseParsingOnlyGarbage() throws Exception {
String s =
"garbage\r\n" +
@ -148,12 +127,7 @@ public class TestDefaultResponseParser extends TestCase {
BasicLineParser.DEFAULT,
new DefaultHttpResponseFactory(),
params);
try {
parser.parse();
fail("ProtocolException should have been thrown");
} catch (ProtocolException ex) {
}
parser.parse();
}
}

View File

@ -27,9 +27,6 @@
package org.apache.http.impl.conn;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.apache.http.HttpClientConnection;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
@ -42,7 +39,8 @@ import org.apache.http.localserver.ServerTestBase;
import org.apache.http.params.DefaultedHttpParams;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.util.EntityUtils;
import org.junit.Assert;
import org.junit.Test;
/**
* This is more a test for the {@link LocalTestServer LocalTestServer}
@ -50,21 +48,7 @@ import org.apache.http.util.EntityUtils;
*/
public class TestLocalServer extends ServerTestBase {
public TestLocalServer(String testName) {
super(testName);
}
public static Test suite() {
return new TestSuite(TestLocalServer.class);
}
public static void main(String args[]) {
String[] testCaseName = { TestLocalServer.class.getName() };
junit.textui.TestRunner.main(testCaseName);
}
@Test
public void testEcho() throws Exception {
final String message = "Hello, world!";
@ -95,16 +79,16 @@ public class TestLocalServer extends ServerTestBase {
httpExecutor.postProcess
(response, httpProcessor, httpContext);
assertEquals("wrong status in response", HttpStatus.SC_OK,
Assert.assertEquals("wrong status in response", HttpStatus.SC_OK,
response.getStatusLine().getStatusCode());
String received = EntityUtils.toString(response.getEntity());
conn.close();
assertEquals("wrong echo", message, received);
Assert.assertEquals("wrong echo", message, received);
}
@Test
public void testRandom() throws Exception {
final HttpHost target = getServerHttp();
@ -140,13 +124,13 @@ public class TestLocalServer extends ServerTestBase {
httpExecutor.postProcess
(response, httpProcessor, httpContext);
assertEquals("(" + sizes[i] + ") wrong status in response",
Assert.assertEquals("(" + sizes[i] + ") wrong status in response",
HttpStatus.SC_OK,
response.getStatusLine().getStatusCode());
byte[] data = EntityUtils.toByteArray(response.getEntity());
if (sizes[i] >= 0)
assertEquals("(" + sizes[i] + ") wrong length of response",
Assert.assertEquals("(" + sizes[i] + ") wrong length of response",
sizes[i], data.length);
conn.close();
}

View File

@ -33,10 +33,6 @@ import java.net.InetSocketAddress;
import java.util.List;
import java.util.ArrayList;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpVersion;
@ -49,25 +45,13 @@ import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.mockup.ProxySelectorMockup;
import org.junit.Assert;
import org.junit.Test;
/**
* Tests for <code>ProxySelectorRoutePlanner</code>.
*/
public class TestProxySelRoutePlanner extends TestCase {
public TestProxySelRoutePlanner(String testName) {
super(testName);
}
public static void main(String args[]) {
String[] testCaseName = { TestProxySelRoutePlanner.class.getName() };
junit.textui.TestRunner.main(testCaseName);
}
public static Test suite() {
return new TestSuite(TestProxySelRoutePlanner.class);
}
public class TestProxySelRoutePlanner {
/**
* Instantiates a default scheme registry.
@ -82,7 +66,7 @@ public class TestProxySelRoutePlanner extends TestCase {
return schreg;
}
@Test
public void testDirect() throws Exception {
HttpRoutePlanner hrp =
@ -96,11 +80,11 @@ public class TestProxySelRoutePlanner extends TestCase {
HttpRoute route = hrp.determineRoute(target, request, null);
assertEquals("wrong target", target, route.getTargetHost());
assertEquals("not direct", 1, route.getHopCount());
Assert.assertEquals("wrong target", target, route.getTargetHost());
Assert.assertEquals("not direct", 1, route.getHopCount());
}
@Test
public void testProxy() throws Exception {
InetAddress ia = InetAddress.getByAddress(new byte[] {
@ -124,10 +108,10 @@ public class TestProxySelRoutePlanner extends TestCase {
HttpRoute route = hrp.determineRoute(target, request, null);
assertEquals("wrong target", target, route.getTargetHost());
assertEquals("not via proxy", 2, route.getHopCount());
assertEquals("wrong proxy", isa1.getPort(),
Assert.assertEquals("wrong target", target, route.getTargetHost());
Assert.assertEquals("not via proxy", 2, route.getHopCount());
Assert.assertEquals("wrong proxy", isa1.getPort(),
route.getProxyHost().getPort());
}
} // class TestProxySelRoutePlanner
}

View File

@ -29,9 +29,6 @@ package org.apache.http.impl.conn;
import java.util.concurrent.TimeUnit;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
@ -44,22 +41,11 @@ import org.apache.http.localserver.ServerTestBase;
import org.apache.http.message.BasicHttpRequest;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.util.EntityUtils;
import org.junit.Assert;
import org.junit.Test;
public class TestSCMWithServer extends ServerTestBase {
public TestSCMWithServer(String testName) {
super(testName);
}
public static void main(String args[]) {
String[] testCaseName = { TestSCMWithServer.class.getName() };
junit.textui.TestRunner.main(testCaseName);
}
public static Test suite() {
return new TestSuite(TestSCMWithServer.class);
}
/**
* Helper to instantiate a <code>SingleClientConnManager</code>.
*
@ -78,6 +64,7 @@ public class TestSCMWithServer extends ServerTestBase {
* Tests that SCM can still connect to the same host after
* a connection was aborted.
*/
@Test
public void testOpenAfterAbort() throws Exception {
SingleClientConnManager mgr = createSCCM(null);
@ -85,11 +72,11 @@ public class TestSCMWithServer extends ServerTestBase {
final HttpRoute route = new HttpRoute(target, null, false);
ManagedClientConnection conn = mgr.getConnection(route, null);
assertTrue(conn instanceof AbstractClientConnAdapter);
Assert.assertTrue(conn instanceof AbstractClientConnAdapter);
((AbstractClientConnAdapter) conn).abortConnection();
conn = mgr.getConnection(route, null);
assertFalse("connection should have been closed", conn.isOpen());
Assert.assertFalse("connection should have been closed", conn.isOpen());
conn.open(route, httpContext, defaultParams);
mgr.releaseConnection(conn, -1, null);
@ -99,6 +86,7 @@ public class TestSCMWithServer extends ServerTestBase {
/**
* Tests releasing with time limits.
*/
@Test
public void testReleaseConnectionWithTimeLimits() throws Exception {
SingleClientConnManager mgr = createSCCM(null);
@ -119,11 +107,11 @@ public class TestSCMWithServer extends ServerTestBase {
request, conn, target,
httpExecutor, httpProcessor, defaultParams, httpContext);
assertEquals("wrong status in first response",
Assert.assertEquals("wrong status in first response",
HttpStatus.SC_OK,
response.getStatusLine().getStatusCode());
byte[] data = EntityUtils.toByteArray(response.getEntity());
assertEquals("wrong length of first response entity",
Assert.assertEquals("wrong length of first response entity",
rsplen, data.length);
// ignore data, but it must be read
@ -131,7 +119,7 @@ public class TestSCMWithServer extends ServerTestBase {
// expect the next connection obtained to be closed
mgr.releaseConnection(conn, 100, TimeUnit.MILLISECONDS);
conn = mgr.getConnection(route, null);
assertFalse("connection should have been closed", conn.isOpen());
Assert.assertFalse("connection should have been closed", conn.isOpen());
// repeat the communication, no need to prepare the request again
conn.open(route, httpContext, defaultParams);
@ -139,11 +127,11 @@ public class TestSCMWithServer extends ServerTestBase {
response = httpExecutor.execute(request, conn, httpContext);
httpExecutor.postProcess(response, httpProcessor, httpContext);
assertEquals("wrong status in second response",
Assert.assertEquals("wrong status in second response",
HttpStatus.SC_OK,
response.getStatusLine().getStatusCode());
data = EntityUtils.toByteArray(response.getEntity());
assertEquals("wrong length of second response entity",
Assert.assertEquals("wrong length of second response entity",
rsplen, data.length);
// ignore data, but it must be read
@ -152,18 +140,18 @@ public class TestSCMWithServer extends ServerTestBase {
conn.markReusable();
mgr.releaseConnection(conn, 100, TimeUnit.MILLISECONDS);
conn = mgr.getConnection(route, null);
assertTrue("connection should have been open", conn.isOpen());
Assert.assertTrue("connection should have been open", conn.isOpen());
// repeat the communication, no need to prepare the request again
httpContext.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
response = httpExecutor.execute(request, conn, httpContext);
httpExecutor.postProcess(response, httpProcessor, httpContext);
assertEquals("wrong status in third response",
Assert.assertEquals("wrong status in third response",
HttpStatus.SC_OK,
response.getStatusLine().getStatusCode());
data = EntityUtils.toByteArray(response.getEntity());
assertEquals("wrong length of third response entity",
Assert.assertEquals("wrong length of third response entity",
rsplen, data.length);
// ignore data, but it must be read
@ -171,7 +159,7 @@ public class TestSCMWithServer extends ServerTestBase {
mgr.releaseConnection(conn, 100, TimeUnit.MILLISECONDS);
Thread.sleep(150);
conn = mgr.getConnection(route, null);
assertTrue("connection should have been closed", !conn.isOpen());
Assert.assertTrue("connection should have been closed", !conn.isOpen());
// repeat the communication, no need to prepare the request again
conn.open(route, httpContext, defaultParams);
@ -179,18 +167,18 @@ public class TestSCMWithServer extends ServerTestBase {
response = httpExecutor.execute(request, conn, httpContext);
httpExecutor.postProcess(response, httpProcessor, httpContext);
assertEquals("wrong status in third response",
Assert.assertEquals("wrong status in third response",
HttpStatus.SC_OK,
response.getStatusLine().getStatusCode());
data = EntityUtils.toByteArray(response.getEntity());
assertEquals("wrong length of fourth response entity",
Assert.assertEquals("wrong length of fourth response entity",
rsplen, data.length);
// ignore data, but it must be read
mgr.shutdown();
}
@Test
public void testCloseExpiredConnections() throws Exception {
SingleClientConnManager mgr = createSCCM(null);
@ -205,17 +193,18 @@ public class TestSCMWithServer extends ServerTestBase {
mgr.closeExpiredConnections();
conn = mgr.getConnection(route, null);
assertTrue(conn.isOpen());
Assert.assertTrue(conn.isOpen());
mgr.releaseConnection(conn, 100, TimeUnit.MILLISECONDS);
Thread.sleep(150);
mgr.closeExpiredConnections();
conn = mgr.getConnection(route, null);
assertFalse(conn.isOpen());
Assert.assertFalse(conn.isOpen());
mgr.shutdown();
}
@Test(expected=IllegalStateException.class)
public void testAlreadyLeased() throws Exception {
SingleClientConnManager mgr = createSCCM(null);
@ -227,12 +216,7 @@ public class TestSCMWithServer extends ServerTestBase {
mgr.releaseConnection(conn, 100, TimeUnit.MILLISECONDS);
mgr.getConnection(route, null);
try {
mgr.getConnection(route, null);
fail("IllegalStateException should have been thrown");
} catch (IllegalStateException ex) {
mgr.shutdown();
}
mgr.getConnection(route, null);
}
}

View File

@ -29,10 +29,6 @@ package org.apache.http.impl.conn;
import java.util.concurrent.TimeUnit;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.apache.http.HttpHost;
import org.apache.http.HttpVersion;
import org.apache.http.conn.ClientConnectionManager;
@ -47,26 +43,14 @@ import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.junit.Assert;
import org.junit.Test;
/**
* Tests for <code>ThreadSafeClientConnManager</code> that do not require
* a server to communicate with.
*/
public class TestTSCCMNoServer extends TestCase {
public TestTSCCMNoServer(String testName) {
super(testName);
}
public static void main(String args[]) {
String[] testCaseName = { TestTSCCMNoServer.class.getName() };
junit.textui.TestRunner.main(testCaseName);
}
public static Test suite() {
return new TestSuite(TestTSCCMNoServer.class);
}
public class TestTSCCMNoServer {
private static ManagedClientConnection getConnection(
final ClientConnectionManager mgr,
@ -126,27 +110,21 @@ public class TestTSCCMNoServer extends TestCase {
return schreg;
}
@Test
public void testConstructor() {
SchemeRegistry schreg = createSchemeRegistry();
ThreadSafeClientConnManager mgr = new ThreadSafeClientConnManager(schreg);
assertNotNull(mgr);
Assert.assertNotNull(mgr);
mgr.shutdown();
mgr = null;
try {
mgr = new ThreadSafeClientConnManager(null);
fail("null parameter not detected");
} catch (IllegalArgumentException iax) {
// expected
} finally {
if (mgr != null)
mgr.shutdown();
}
} // testConstructor
}
@Test(expected=IllegalArgumentException.class)
public void testIllegalConstructor() {
new ThreadSafeClientConnManager(null);
}
@Test(expected=IllegalArgumentException.class)
public void testGetConnection()
throws InterruptedException, ConnectionPoolTimeoutException {
ThreadSafeClientConnManager mgr = createTSCCM(null);
@ -155,26 +133,22 @@ public class TestTSCCMNoServer extends TestCase {
HttpRoute route = new HttpRoute(target, null, false);
ManagedClientConnection conn = getConnection(mgr, route);
assertNotNull(conn);
assertNull(conn.getRoute());
assertFalse(conn.isOpen());
Assert.assertNotNull(conn);
Assert.assertNull(conn.getRoute());
Assert.assertFalse(conn.isOpen());
mgr.releaseConnection(conn, -1, null);
try {
getConnection(mgr, null);
fail("null route not detected");
} catch (IllegalArgumentException iax) {
// expected
} finally {
mgr.shutdown();
}
mgr.shutdown();
}
// testTimeout in 3.x TestHttpConnectionManager is redundant
// several other tests here rely on timeout behavior
@Test
public void testMaxConnTotal()
throws InterruptedException, ConnectionPoolTimeoutException {
@ -188,14 +162,14 @@ public class TestTSCCMNoServer extends TestCase {
HttpRoute route2 = new HttpRoute(target2, null, false);
ManagedClientConnection conn1 = getConnection(mgr, route1);
assertNotNull(conn1);
Assert.assertNotNull(conn1);
ManagedClientConnection conn2 = getConnection(mgr, route2);
assertNotNull(conn2);
Assert.assertNotNull(conn2);
try {
// this should fail quickly, connection has not been released
getConnection(mgr, route2, 100L, TimeUnit.MILLISECONDS);
fail("ConnectionPoolTimeoutException should have been thrown");
Assert.fail("ConnectionPoolTimeoutException should have been thrown");
} catch (ConnectionPoolTimeoutException e) {
// expected
}
@ -208,14 +182,13 @@ public class TestTSCCMNoServer extends TestCase {
try {
getConnection(mgr, route2, 100L, TimeUnit.MILLISECONDS);
} catch (ConnectionPoolTimeoutException cptx) {
cptx.printStackTrace();
fail("connection should have been available: " + cptx);
Assert.fail("connection should have been available: " + cptx);
}
mgr.shutdown();
}
@Test
public void testMaxConnPerHost() throws Exception {
HttpHost target1 = new HttpHost("www.test1.invalid", 80, "http");
@ -234,17 +207,17 @@ public class TestTSCCMNoServer extends TestCase {
// route 3, limit 3
ManagedClientConnection conn1 =
getConnection(mgr, route3, 10L, TimeUnit.MILLISECONDS);
assertNotNull(conn1);
Assert.assertNotNull(conn1);
ManagedClientConnection conn2 =
getConnection(mgr, route3, 10L, TimeUnit.MILLISECONDS);
assertNotNull(conn2);
Assert.assertNotNull(conn2);
ManagedClientConnection conn3 =
getConnection(mgr, route3, 10L, TimeUnit.MILLISECONDS);
assertNotNull(conn3);
Assert.assertNotNull(conn3);
try {
// should fail quickly, connection has not been released
getConnection(mgr, route3, 10L, TimeUnit.MILLISECONDS);
fail("ConnectionPoolTimeoutException should have been thrown");
Assert.fail("ConnectionPoolTimeoutException should have been thrown");
} catch (ConnectionPoolTimeoutException e) {
// expected
}
@ -255,7 +228,7 @@ public class TestTSCCMNoServer extends TestCase {
try {
// should fail quickly, connection has not been released
getConnection(mgr, route2, 10L, TimeUnit.MILLISECONDS);
fail("ConnectionPoolTimeoutException should have been thrown");
Assert.fail("ConnectionPoolTimeoutException should have been thrown");
} catch (ConnectionPoolTimeoutException e) {
// expected
}
@ -265,7 +238,7 @@ public class TestTSCCMNoServer extends TestCase {
try {
// should fail quickly, connection has not been released
getConnection(mgr, route1, 10L, TimeUnit.MILLISECONDS);
fail("ConnectionPoolTimeoutException should have been thrown");
Assert.fail("ConnectionPoolTimeoutException should have been thrown");
} catch (ConnectionPoolTimeoutException e) {
// expected
}
@ -274,13 +247,13 @@ public class TestTSCCMNoServer extends TestCase {
// check releaseConnection with invalid arguments
try {
mgr.releaseConnection(null, -1, null);
fail("null connection adapter not detected");
Assert.fail("null connection adapter not detected");
} catch (IllegalArgumentException iax) {
// expected
}
try {
mgr.releaseConnection(new ClientConnAdapterMockup(null), -1, null);
fail("foreign connection adapter not detected");
Assert.fail("foreign connection adapter not detected");
} catch (IllegalArgumentException iax) {
// expected
}
@ -288,7 +261,7 @@ public class TestTSCCMNoServer extends TestCase {
mgr.shutdown();
}
@Test
public void testReleaseConnection() throws Exception {
ThreadSafeClientConnManager mgr = createTSCCM(null);
@ -309,27 +282,27 @@ public class TestTSCCMNoServer extends TestCase {
getConnection(mgr, route2, 10L, TimeUnit.MILLISECONDS);
ManagedClientConnection conn3 =
getConnection(mgr, route3, 10L, TimeUnit.MILLISECONDS);
assertNotNull(conn1);
assertNotNull(conn2);
assertNotNull(conn3);
Assert.assertNotNull(conn1);
Assert.assertNotNull(conn2);
Assert.assertNotNull(conn3);
// obtaining another connection for either of the three should fail
// this is somehow redundant with testMaxConnPerHost
try {
getConnection(mgr, route1, 10L, TimeUnit.MILLISECONDS);
fail("ConnectionPoolTimeoutException should have been thrown");
Assert.fail("ConnectionPoolTimeoutException should have been thrown");
} catch (ConnectionPoolTimeoutException e) {
// expected
}
try {
getConnection(mgr, route2, 10L, TimeUnit.MILLISECONDS);
fail("ConnectionPoolTimeoutException should have been thrown");
Assert.fail("ConnectionPoolTimeoutException should have been thrown");
} catch (ConnectionPoolTimeoutException e) {
// expected
}
try {
getConnection(mgr, route3, 10L, TimeUnit.MILLISECONDS);
fail("ConnectionPoolTimeoutException should have been thrown");
Assert.fail("ConnectionPoolTimeoutException should have been thrown");
} catch (ConnectionPoolTimeoutException e) {
// expected
}
@ -339,16 +312,16 @@ public class TestTSCCMNoServer extends TestCase {
conn2 = null;
try {
getConnection(mgr, route1, 10L, TimeUnit.MILLISECONDS);
fail("ConnectionPoolTimeoutException should have been thrown");
Assert.fail("ConnectionPoolTimeoutException should have been thrown");
} catch (ConnectionPoolTimeoutException e) {
// expected
}
// this one succeeds
conn2 = getConnection(mgr, route2, 10L, TimeUnit.MILLISECONDS);
assertNotNull(conn2);
Assert.assertNotNull(conn2);
try {
getConnection(mgr, route3, 10L, TimeUnit.MILLISECONDS);
fail("ConnectionPoolTimeoutException should have been thrown");
Assert.fail("ConnectionPoolTimeoutException should have been thrown");
} catch (ConnectionPoolTimeoutException e) {
// expected
}
@ -356,7 +329,7 @@ public class TestTSCCMNoServer extends TestCase {
mgr.shutdown();
}
@Test
public void testDeleteClosedConnections()
throws InterruptedException, ConnectionPoolTimeoutException {
@ -367,28 +340,29 @@ public class TestTSCCMNoServer extends TestCase {
ManagedClientConnection conn = getConnection(mgr, route);
assertEquals("connectionsInPool",
Assert.assertEquals("connectionsInPool",
mgr.getConnectionsInPool(), 1);
assertEquals("connectionsInPool(host)",
Assert.assertEquals("connectionsInPool(host)",
mgr.getConnectionsInPool(route), 1);
mgr.releaseConnection(conn, -1, null);
assertEquals("connectionsInPool",
Assert.assertEquals("connectionsInPool",
mgr.getConnectionsInPool(), 1);
assertEquals("connectionsInPool(host)",
Assert.assertEquals("connectionsInPool(host)",
mgr.getConnectionsInPool(route), 1);
// this implicitly deletes them
mgr.closeIdleConnections(0L, TimeUnit.MILLISECONDS);
assertEquals("connectionsInPool",
Assert.assertEquals("connectionsInPool",
mgr.getConnectionsInPool(), 0);
assertEquals("connectionsInPool(host)",
Assert.assertEquals("connectionsInPool(host)",
mgr.getConnectionsInPool(route), 0);
mgr.shutdown();
}
@Test
public void testShutdown() throws Exception {
// 3.x: TestHttpConnectionManager.testShutdown
@ -418,23 +392,23 @@ public class TestTSCCMNoServer extends TestCase {
gct.join(10000);
assertNull("thread should not have obtained connection",
Assert.assertNull("thread should not have obtained connection",
gct.getConnection());
assertNotNull("thread should have gotten an exception",
Assert.assertNotNull("thread should have gotten an exception",
gct.getException());
assertSame("thread got wrong exception",
Assert.assertSame("thread got wrong exception",
IllegalStateException.class, gct.getException().getClass());
// the manager is down, we should not be able to get a connection
try {
getConnection(mgr, route, 1L, TimeUnit.MILLISECONDS);
fail("shut-down manager does not raise exception");
Assert.fail("shut-down manager does not raise exception");
} catch (IllegalStateException isx) {
// expected
}
}
@Test
public void testInterruptThread() throws Exception {
// 3.x: TestHttpConnectionManager.testWaitingThreadInterrupted
@ -457,16 +431,16 @@ public class TestTSCCMNoServer extends TestCase {
gct.join(10000);
assertNotNull("thread should have gotten an exception",
Assert.assertNotNull("thread should have gotten an exception",
gct.getException());
assertSame("thread got wrong exception",
Assert.assertSame("thread got wrong exception",
InterruptedException.class,
gct.getException().getClass());
// make sure the manager is still working
try {
getConnection(mgr, route, 10L, TimeUnit.MILLISECONDS);
fail("should have gotten a timeout");
Assert.fail("should have gotten a timeout");
} catch (ConnectionPoolTimeoutException e) {
// expected
}
@ -474,13 +448,12 @@ public class TestTSCCMNoServer extends TestCase {
mgr.releaseConnection(conn, -1, null);
// this time: no exception
conn = getConnection(mgr, route, 10L, TimeUnit.MILLISECONDS);
assertNotNull("should have gotten a connection", conn);
Assert.assertNotNull("should have gotten a connection", conn);
mgr.shutdown();
}
@Test
public void testReusePreference() throws Exception {
// 3.x: TestHttpConnectionManager.testHostReusePreference
@ -513,14 +486,15 @@ public class TestTSCCMNoServer extends TestCase {
gct1.join(10000);
gct2.join(10000);
assertNotNull("thread 1 should have gotten a connection",
Assert.assertNotNull("thread 1 should have gotten a connection",
gct1.getConnection());
assertNull ("thread 2 should NOT have gotten a connection",
Assert.assertNull ("thread 2 should NOT have gotten a connection",
gct2.getConnection());
mgr.shutdown();
}
@Test
public void testAbortAfterRequestStarts() throws Exception {
ThreadSafeClientConnManager mgr = createTSCCM(null);
mgr.setMaxTotalConnections(1);
@ -538,16 +512,16 @@ public class TestTSCCMNoServer extends TestCase {
request.abortRequest();
gct.join(10000);
assertNotNull("thread should have gotten an exception",
Assert.assertNotNull("thread should have gotten an exception",
gct.getException());
assertSame("thread got wrong exception",
Assert.assertSame("thread got wrong exception",
InterruptedException.class,
gct.getException().getClass());
// make sure the manager is still working
try {
getConnection(mgr, route, 10L, TimeUnit.MILLISECONDS);
fail("should have gotten a timeout");
Assert.fail("should have gotten a timeout");
} catch (ConnectionPoolTimeoutException e) {
// expected
}
@ -555,11 +529,12 @@ public class TestTSCCMNoServer extends TestCase {
mgr.releaseConnection(conn, -1, null);
// this time: no exception
conn = getConnection(mgr, route, 10L, TimeUnit.MILLISECONDS);
assertNotNull("should have gotten a connection", conn);
Assert.assertNotNull("should have gotten a connection", conn);
mgr.shutdown();
}
@Test
public void testAbortBeforeRequestStarts() throws Exception {
ThreadSafeClientConnManager mgr = createTSCCM(null);
mgr.setMaxTotalConnections(1);
@ -577,16 +552,16 @@ public class TestTSCCMNoServer extends TestCase {
Thread.sleep(100); // give extra thread time to block
gct.join(10000);
assertNotNull("thread should have gotten an exception",
Assert.assertNotNull("thread should have gotten an exception",
gct.getException());
assertSame("thread got wrong exception",
Assert.assertSame("thread got wrong exception",
InterruptedException.class,
gct.getException().getClass());
// make sure the manager is still working
try {
getConnection(mgr, route, 10L, TimeUnit.MILLISECONDS);
fail("should have gotten a timeout");
Assert.fail("should have gotten a timeout");
} catch (ConnectionPoolTimeoutException e) {
// expected
}
@ -594,9 +569,9 @@ public class TestTSCCMNoServer extends TestCase {
mgr.releaseConnection(conn, -1, null);
// this time: no exception
conn = getConnection(mgr, route, 10L, TimeUnit.MILLISECONDS);
assertNotNull("should have gotten a connection", conn);
Assert.assertNotNull("should have gotten a connection", conn);
mgr.shutdown();
}
} // class TestTSCCMNoServer
}

View File

@ -38,9 +38,6 @@ import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
@ -66,6 +63,8 @@ import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.junit.Assert;
import org.junit.Test;
/**
* Tests for <code>ThreadSafeClientConnManager</code> that do require
@ -73,20 +72,6 @@ import org.apache.http.util.EntityUtils;
*/
public class TestTSCCMWithServer extends ServerTestBase {
public TestTSCCMWithServer(String testName) {
super(testName);
}
public static void main(String args[]) {
String[] testCaseName = { TestTSCCMWithServer.class.getName() };
junit.textui.TestRunner.main(testCaseName);
}
public static Test suite() {
return new TestSuite(TestTSCCMWithServer.class);
}
/**
* Helper to instantiate a <code>ThreadSafeClientConnManager</code>.
*
@ -101,11 +86,10 @@ public class TestTSCCMWithServer extends ServerTestBase {
return new ThreadSafeClientConnManager(schreg);
}
/**
* Tests executing several requests in parallel.
*/
@Test
public void testParallelRequests() throws Exception {
// 3.x: TestHttpConnectionManager.testGetFromMultipleThreads
@ -146,16 +130,16 @@ public class TestTSCCMWithServer extends ServerTestBase {
for (int i=0; i<threads.length; i++) {
threads[i].join(10000);
assertNull("exception in thread " + i,
Assert.assertNull("exception in thread " + i,
threads[i].getException());
assertNotNull("no response in thread " + i,
Assert.assertNotNull("no response in thread " + i,
threads[i].getResponse());
assertEquals("wrong status code in thread " + i, 200,
Assert.assertEquals("wrong status code in thread " + i, 200,
threads[i].getResponse()
.getStatusLine().getStatusCode());
assertNotNull("no response data in thread " + i,
Assert.assertNotNull("no response data in thread " + i,
threads[i].getResponseData());
assertEquals("wrong length of data in thread" + i, rsplen,
Assert.assertEquals("wrong length of data in thread" + i, rsplen,
threads[i].getResponseData().length);
}
@ -181,6 +165,7 @@ public class TestTSCCMWithServer extends ServerTestBase {
/**
* Tests releasing and re-using a connection after a response is read.
*/
@Test
public void testReleaseConnection() throws Exception {
ThreadSafeClientConnManager mgr = createTSCCM(null);
@ -202,11 +187,11 @@ public class TestTSCCMWithServer extends ServerTestBase {
request, conn, target,
httpExecutor, httpProcessor, defaultParams, httpContext);
assertEquals("wrong status in first response",
Assert.assertEquals("wrong status in first response",
HttpStatus.SC_OK,
response.getStatusLine().getStatusCode());
byte[] data = EntityUtils.toByteArray(response.getEntity());
assertEquals("wrong length of first response entity",
Assert.assertEquals("wrong length of first response entity",
rsplen, data.length);
// ignore data, but it must be read
@ -214,7 +199,7 @@ public class TestTSCCMWithServer extends ServerTestBase {
try {
// this should fail quickly, connection has not been released
getConnection(mgr, route, 10L, TimeUnit.MILLISECONDS);
fail("ConnectionPoolTimeoutException should have been thrown");
Assert.fail("ConnectionPoolTimeoutException should have been thrown");
} catch (ConnectionPoolTimeoutException e) {
// expected
}
@ -223,7 +208,7 @@ public class TestTSCCMWithServer extends ServerTestBase {
// expect the next connection obtained to be closed
mgr.releaseConnection(conn, -1, null);
conn = getConnection(mgr, route);
assertFalse("connection should have been closed", conn.isOpen());
Assert.assertFalse("connection should have been closed", conn.isOpen());
// repeat the communication, no need to prepare the request again
conn.open(route, httpContext, defaultParams);
@ -231,11 +216,11 @@ public class TestTSCCMWithServer extends ServerTestBase {
response = httpExecutor.execute(request, conn, httpContext);
httpExecutor.postProcess(response, httpProcessor, httpContext);
assertEquals("wrong status in second response",
Assert.assertEquals("wrong status in second response",
HttpStatus.SC_OK,
response.getStatusLine().getStatusCode());
data = EntityUtils.toByteArray(response.getEntity());
assertEquals("wrong length of second response entity",
Assert.assertEquals("wrong length of second response entity",
rsplen, data.length);
// ignore data, but it must be read
@ -244,18 +229,18 @@ public class TestTSCCMWithServer extends ServerTestBase {
conn.markReusable();
mgr.releaseConnection(conn, -1, null);
conn = getConnection(mgr, route);
assertTrue("connection should have been open", conn.isOpen());
Assert.assertTrue("connection should have been open", conn.isOpen());
// repeat the communication, no need to prepare the request again
httpContext.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
response = httpExecutor.execute(request, conn, httpContext);
httpExecutor.postProcess(response, httpProcessor, httpContext);
assertEquals("wrong status in third response",
Assert.assertEquals("wrong status in third response",
HttpStatus.SC_OK,
response.getStatusLine().getStatusCode());
data = EntityUtils.toByteArray(response.getEntity());
assertEquals("wrong length of third response entity",
Assert.assertEquals("wrong length of third response entity",
rsplen, data.length);
// ignore data, but it must be read
@ -266,6 +251,7 @@ public class TestTSCCMWithServer extends ServerTestBase {
/**
* Tests releasing with time limits.
*/
@Test
public void testReleaseConnectionWithTimeLimits() throws Exception {
ThreadSafeClientConnManager mgr = createTSCCM(null);
@ -287,11 +273,11 @@ public class TestTSCCMWithServer extends ServerTestBase {
request, conn, target,
httpExecutor, httpProcessor, defaultParams, httpContext);
assertEquals("wrong status in first response",
Assert.assertEquals("wrong status in first response",
HttpStatus.SC_OK,
response.getStatusLine().getStatusCode());
byte[] data = EntityUtils.toByteArray(response.getEntity());
assertEquals("wrong length of first response entity",
Assert.assertEquals("wrong length of first response entity",
rsplen, data.length);
// ignore data, but it must be read
@ -299,7 +285,7 @@ public class TestTSCCMWithServer extends ServerTestBase {
try {
// this should fail quickly, connection has not been released
getConnection(mgr, route, 10L, TimeUnit.MILLISECONDS);
fail("ConnectionPoolTimeoutException should have been thrown");
Assert.fail("ConnectionPoolTimeoutException should have been thrown");
} catch (ConnectionPoolTimeoutException e) {
// expected
}
@ -308,7 +294,7 @@ public class TestTSCCMWithServer extends ServerTestBase {
// expect the next connection obtained to be closed
mgr.releaseConnection(conn, 100, TimeUnit.MILLISECONDS);
conn = getConnection(mgr, route);
assertFalse("connection should have been closed", conn.isOpen());
Assert.assertFalse("connection should have been closed", conn.isOpen());
// repeat the communication, no need to prepare the request again
conn.open(route, httpContext, defaultParams);
@ -316,11 +302,11 @@ public class TestTSCCMWithServer extends ServerTestBase {
response = httpExecutor.execute(request, conn, httpContext);
httpExecutor.postProcess(response, httpProcessor, httpContext);
assertEquals("wrong status in second response",
Assert.assertEquals("wrong status in second response",
HttpStatus.SC_OK,
response.getStatusLine().getStatusCode());
data = EntityUtils.toByteArray(response.getEntity());
assertEquals("wrong length of second response entity",
Assert.assertEquals("wrong length of second response entity",
rsplen, data.length);
// ignore data, but it must be read
@ -329,18 +315,18 @@ public class TestTSCCMWithServer extends ServerTestBase {
conn.markReusable();
mgr.releaseConnection(conn, 100, TimeUnit.MILLISECONDS);
conn = getConnection(mgr, route);
assertTrue("connection should have been open", conn.isOpen());
Assert.assertTrue("connection should have been open", conn.isOpen());
// repeat the communication, no need to prepare the request again
httpContext.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
response = httpExecutor.execute(request, conn, httpContext);
httpExecutor.postProcess(response, httpProcessor, httpContext);
assertEquals("wrong status in third response",
Assert.assertEquals("wrong status in third response",
HttpStatus.SC_OK,
response.getStatusLine().getStatusCode());
data = EntityUtils.toByteArray(response.getEntity());
assertEquals("wrong length of third response entity",
Assert.assertEquals("wrong length of third response entity",
rsplen, data.length);
// ignore data, but it must be read
@ -348,7 +334,7 @@ public class TestTSCCMWithServer extends ServerTestBase {
mgr.releaseConnection(conn, 100, TimeUnit.MILLISECONDS);
Thread.sleep(150);
conn = getConnection(mgr, route);
assertTrue("connection should have been closed", !conn.isOpen());
Assert.assertTrue("connection should have been closed", !conn.isOpen());
// repeat the communication, no need to prepare the request again
conn.open(route, httpContext, defaultParams);
@ -356,18 +342,18 @@ public class TestTSCCMWithServer extends ServerTestBase {
response = httpExecutor.execute(request, conn, httpContext);
httpExecutor.postProcess(response, httpProcessor, httpContext);
assertEquals("wrong status in third response",
Assert.assertEquals("wrong status in third response",
HttpStatus.SC_OK,
response.getStatusLine().getStatusCode());
data = EntityUtils.toByteArray(response.getEntity());
assertEquals("wrong length of fourth response entity",
Assert.assertEquals("wrong length of fourth response entity",
rsplen, data.length);
// ignore data, but it must be read
mgr.shutdown();
}
@Test
public void testCloseExpiredConnections() throws Exception {
ThreadSafeClientConnManager mgr = createTSCCM(null);
@ -379,36 +365,36 @@ public class TestTSCCMWithServer extends ServerTestBase {
ManagedClientConnection conn = getConnection(mgr, route);
conn.open(route, httpContext, defaultParams);
assertEquals("connectionsInPool", 1, mgr.getConnectionsInPool());
assertEquals("connectionsInPool(host)", 1, mgr.getConnectionsInPool(route));
Assert.assertEquals("connectionsInPool", 1, mgr.getConnectionsInPool());
Assert.assertEquals("connectionsInPool(host)", 1, mgr.getConnectionsInPool(route));
mgr.releaseConnection(conn, 100, TimeUnit.MILLISECONDS);
// Released, still active.
assertEquals("connectionsInPool", 1, mgr.getConnectionsInPool());
assertEquals("connectionsInPool(host)", 1, mgr.getConnectionsInPool(route));
Assert.assertEquals("connectionsInPool", 1, mgr.getConnectionsInPool());
Assert.assertEquals("connectionsInPool(host)", 1, mgr.getConnectionsInPool(route));
mgr.closeExpiredConnections();
// Time has not expired yet.
assertEquals("connectionsInPool", 1, mgr.getConnectionsInPool());
assertEquals("connectionsInPool(host)", 1, mgr.getConnectionsInPool(route));
Assert.assertEquals("connectionsInPool", 1, mgr.getConnectionsInPool());
Assert.assertEquals("connectionsInPool(host)", 1, mgr.getConnectionsInPool(route));
Thread.sleep(150);
mgr.closeExpiredConnections();
// Time expired now, connections are destroyed.
assertEquals("connectionsInPool", 0, mgr.getConnectionsInPool());
assertEquals("connectionsInPool(host)", 0, mgr.getConnectionsInPool(route));
Assert.assertEquals("connectionsInPool", 0, mgr.getConnectionsInPool());
Assert.assertEquals("connectionsInPool(host)", 0, mgr.getConnectionsInPool(route));
mgr.shutdown();
}
/**
* Tests releasing connection from #abort method called from the
* main execution thread while there is no blocking I/O operation.
*/
@Test
public void testReleaseConnectionOnAbort() throws Exception {
ThreadSafeClientConnManager mgr = createTSCCM(null);
@ -430,7 +416,7 @@ public class TestTSCCMWithServer extends ServerTestBase {
request, conn, target,
httpExecutor, httpProcessor, defaultParams, httpContext);
assertEquals("wrong status in first response",
Assert.assertEquals("wrong status in first response",
HttpStatus.SC_OK,
response.getStatusLine().getStatusCode());
@ -438,18 +424,18 @@ public class TestTSCCMWithServer extends ServerTestBase {
try {
// this should fail quickly, connection has not been released
getConnection(mgr, route, 100L, TimeUnit.MILLISECONDS);
fail("ConnectionPoolTimeoutException should have been thrown");
Assert.fail("ConnectionPoolTimeoutException should have been thrown");
} catch (ConnectionPoolTimeoutException e) {
// expected
}
// abort the connection
assertTrue(conn instanceof AbstractClientConnAdapter);
Assert.assertTrue(conn instanceof AbstractClientConnAdapter);
((AbstractClientConnAdapter) conn).abortConnection();
// the connection is expected to be released back to the manager
conn = getConnection(mgr, route, 5L, TimeUnit.SECONDS);
assertFalse("connection should have been closed", conn.isOpen());
Assert.assertFalse("connection should have been closed", conn.isOpen());
mgr.releaseConnection(conn, -1, null);
mgr.shutdown();
@ -458,6 +444,7 @@ public class TestTSCCMWithServer extends ServerTestBase {
/**
* Tests GC of an unreferenced connection manager.
*/
@Test
public void testConnectionManagerGC() throws Exception {
// 3.x: TestHttpConnectionManager.testDroppedThread
@ -501,9 +488,10 @@ public class TestTSCCMWithServer extends ServerTestBase {
System.gc();
Thread.sleep(1000);
assertNull("TSCCM not garbage collected", wref.get());
Assert.assertNull("TSCCM not garbage collected", wref.get());
}
@Test
public void testAbortDuringConnecting() throws Exception {
final CountDownLatch connectLatch = new CountDownLatch(1);
final StallingSocketFactory stallingSocketFactory = new StallingSocketFactory(
@ -519,7 +507,7 @@ public class TestTSCCMWithServer extends ServerTestBase {
final HttpRoute route = new HttpRoute(target, null, false);
final ManagedClientConnection conn = getConnection(mgr, route);
assertTrue(conn instanceof AbstractClientConnAdapter);
Assert.assertTrue(conn instanceof AbstractClientConnAdapter);
final AtomicReference<Throwable> throwRef = new AtomicReference<Throwable>();
Thread abortingThread = new Thread(new Runnable() {
@ -537,24 +525,25 @@ public class TestTSCCMWithServer extends ServerTestBase {
try {
conn.open(route, httpContext, defaultParams);
fail("expected SocketException");
Assert.fail("expected SocketException");
} catch(SocketException expected) {}
abortingThread.join(5000);
if(throwRef.get() != null)
throw new RuntimeException(throwRef.get());
assertFalse(conn.isOpen());
assertEquals(0, localServer.getAcceptedConnectionCount());
Assert.assertFalse(conn.isOpen());
Assert.assertEquals(0, localServer.getAcceptedConnectionCount());
// the connection is expected to be released back to the manager
ManagedClientConnection conn2 = getConnection(mgr, route, 5L, TimeUnit.SECONDS);
assertFalse("connection should have been closed", conn2.isOpen());
Assert.assertFalse("connection should have been closed", conn2.isOpen());
mgr.releaseConnection(conn2, -1, null);
mgr.shutdown();
}
@Test
public void testAbortBeforeSocketCreate() throws Exception {
final CountDownLatch connectLatch = new CountDownLatch(1);
final StallingSocketFactory stallingSocketFactory = new StallingSocketFactory(
@ -570,7 +559,7 @@ public class TestTSCCMWithServer extends ServerTestBase {
final HttpRoute route = new HttpRoute(target, null, false);
final ManagedClientConnection conn = getConnection(mgr, route);
assertTrue(conn instanceof AbstractClientConnAdapter);
Assert.assertTrue(conn instanceof AbstractClientConnAdapter);
final AtomicReference<Throwable> throwRef = new AtomicReference<Throwable>();
Thread abortingThread = new Thread(new Runnable() {
@ -588,26 +577,27 @@ public class TestTSCCMWithServer extends ServerTestBase {
try {
conn.open(route, httpContext, defaultParams);
fail("expected exception");
Assert.fail("expected exception");
} catch(IOException expected) {
assertEquals("Connection already shutdown", expected.getMessage());
Assert.assertEquals("Connection already shutdown", expected.getMessage());
}
abortingThread.join(5000);
if(throwRef.get() != null)
throw new RuntimeException(throwRef.get());
assertFalse(conn.isOpen());
assertEquals(0, localServer.getAcceptedConnectionCount());
Assert.assertFalse(conn.isOpen());
Assert.assertEquals(0, localServer.getAcceptedConnectionCount());
// the connection is expected to be released back to the manager
ManagedClientConnection conn2 = getConnection(mgr, route, 5L, TimeUnit.SECONDS);
assertFalse("connection should have been closed", conn2.isOpen());
Assert.assertFalse("connection should have been closed", conn2.isOpen());
mgr.releaseConnection(conn2, -1, null);
mgr.shutdown();
}
@Test
public void testAbortAfterSocketConnect() throws Exception {
final CountDownLatch connectLatch = new CountDownLatch(1);
final StallingSocketFactory stallingSocketFactory = new StallingSocketFactory(
@ -623,7 +613,7 @@ public class TestTSCCMWithServer extends ServerTestBase {
final HttpRoute route = new HttpRoute(target, null, false);
final ManagedClientConnection conn = getConnection(mgr, route);
assertTrue(conn instanceof AbstractClientConnAdapter);
Assert.assertTrue(conn instanceof AbstractClientConnAdapter);
final AtomicReference<Throwable> throwRef = new AtomicReference<Throwable>();
Thread abortingThread = new Thread(new Runnable() {
@ -641,14 +631,14 @@ public class TestTSCCMWithServer extends ServerTestBase {
try {
conn.open(route, httpContext, defaultParams);
fail("expected SocketException");
Assert.fail("expected SocketException");
} catch(SocketException expected) {}
abortingThread.join(5000);
if(throwRef.get() != null)
throw new RuntimeException(throwRef.get());
assertFalse(conn.isOpen());
Assert.assertFalse(conn.isOpen());
// Give the server a bit of time to accept the connection, but
// ensure that it can accept it.
for(int i = 0; i < 10; i++) {
@ -656,16 +646,17 @@ public class TestTSCCMWithServer extends ServerTestBase {
break;
Thread.sleep(100);
}
assertEquals(1, localServer.getAcceptedConnectionCount());
Assert.assertEquals(1, localServer.getAcceptedConnectionCount());
// the connection is expected to be released back to the manager
ManagedClientConnection conn2 = getConnection(mgr, route, 5L, TimeUnit.SECONDS);
assertFalse("connection should have been closed", conn2.isOpen());
Assert.assertFalse("connection should have been closed", conn2.isOpen());
mgr.releaseConnection(conn2, -1, null);
mgr.shutdown();
}
@Test
public void testAbortAfterOperatorOpen() throws Exception {
final CountDownLatch connectLatch = new CountDownLatch(1);
final AtomicReference<StallingOperator> operatorRef = new AtomicReference<StallingOperator>();
@ -679,13 +670,13 @@ public class TestTSCCMWithServer extends ServerTestBase {
}
};
mgr.setMaxTotalConnections(1);
assertNotNull(operatorRef.get());
Assert.assertNotNull(operatorRef.get());
final HttpHost target = getServerHttp();
final HttpRoute route = new HttpRoute(target, null, false);
final ManagedClientConnection conn = getConnection(mgr, route);
assertTrue(conn instanceof AbstractClientConnAdapter);
Assert.assertTrue(conn instanceof AbstractClientConnAdapter);
final AtomicReference<Throwable> throwRef = new AtomicReference<Throwable>();
Thread abortingThread = new Thread(new Runnable() {
@ -703,16 +694,16 @@ public class TestTSCCMWithServer extends ServerTestBase {
try {
conn.open(route, httpContext, defaultParams);
fail("expected exception");
Assert.fail("expected exception");
} catch(IOException iox) {
assertEquals("Request aborted", iox.getMessage());
Assert.assertEquals("Request aborted", iox.getMessage());
}
abortingThread.join(5000);
if(throwRef.get() != null)
throw new RuntimeException(throwRef.get());
assertFalse(conn.isOpen());
Assert.assertFalse(conn.isOpen());
// Give the server a bit of time to accept the connection, but
// ensure that it can accept it.
for(int i = 0; i < 10; i++) {
@ -720,11 +711,11 @@ public class TestTSCCMWithServer extends ServerTestBase {
break;
Thread.sleep(100);
}
assertEquals(1, localServer.getAcceptedConnectionCount());
Assert.assertEquals(1, localServer.getAcceptedConnectionCount());
// the connection is expected to be released back to the manager
ManagedClientConnection conn2 = getConnection(mgr, route, 5L, TimeUnit.SECONDS);
assertFalse("connection should have been closed", conn2.isOpen());
Assert.assertFalse("connection should have been closed", conn2.isOpen());
mgr.releaseConnection(conn2, -1, null);
mgr.shutdown();
@ -826,5 +817,4 @@ public class TestTSCCMWithServer extends ServerTestBase {
private enum WaitPolicy { BEFORE_CREATE, BEFORE_CONNECT, AFTER_CONNECT, AFTER_OPEN }
} // class TestTSCCMWithServer
}

View File

@ -29,9 +29,6 @@ package org.apache.http.impl.conn.tsccm;
import java.util.concurrent.TimeUnit;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.apache.http.HttpHost;
import org.apache.http.conn.ClientConnectionOperator;
import org.apache.http.conn.ConnectionPoolTimeoutException;
@ -39,22 +36,12 @@ import org.apache.http.conn.params.ConnPerRouteBean;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.impl.conn.DefaultClientConnectionOperator;
import org.apache.http.localserver.ServerTestBase;
import org.junit.Assert;
import org.junit.Test;
public class TestConnPoolByRoute extends ServerTestBase {
public TestConnPoolByRoute(String testName) {
super(testName);
}
public static void main(String args[]) {
String[] testCaseName = { TestConnPoolByRoute.class.getName() };
junit.textui.TestRunner.main(testCaseName);
}
public static Test suite() {
return new TestSuite(TestConnPoolByRoute.class);
}
@Test
public void testStatelessConnections() throws Exception {
final HttpHost target = getServerHttp();
final HttpRoute route = new HttpRoute(target, null, false);
@ -68,21 +55,21 @@ public class TestConnPoolByRoute extends ServerTestBase {
// Allocate max possible entries
PoolEntryRequest r1 = connPool.requestPoolEntry(route, null);
BasicPoolEntry e1 = r1.getPoolEntry(10, TimeUnit.SECONDS);
assertNotNull(e1);
Assert.assertNotNull(e1);
PoolEntryRequest r2 = connPool.requestPoolEntry(route, null);
BasicPoolEntry e2 = r2.getPoolEntry(10, TimeUnit.SECONDS);
assertNotNull(e2);
Assert.assertNotNull(e2);
PoolEntryRequest r3 = connPool.requestPoolEntry(route, null);
BasicPoolEntry e3 = r3.getPoolEntry(10, TimeUnit.SECONDS);
assertNotNull(e3);
Assert.assertNotNull(e3);
// Attempt to allocate one more. Expected to fail
PoolEntryRequest r4 = connPool.requestPoolEntry(route, null);
try {
r4.getPoolEntry(250, TimeUnit.MICROSECONDS);
fail("ConnectionPoolTimeoutException should have been thrown");
Assert.fail("ConnectionPoolTimeoutException should have been thrown");
} catch (ConnectionPoolTimeoutException expected) {
}
@ -92,13 +79,14 @@ public class TestConnPoolByRoute extends ServerTestBase {
// This time the request should succeed
PoolEntryRequest r5 = connPool.requestPoolEntry(route, null);
BasicPoolEntry e5 = r5.getPoolEntry(10, TimeUnit.SECONDS);
assertNotNull(e5);
Assert.assertNotNull(e5);
} finally {
connPool.shutdown();
}
}
@Test
public void testStatefullConnections() throws Exception {
final HttpHost target = getServerHttp();
final HttpRoute route = new HttpRoute(target, null, false);
@ -139,14 +127,14 @@ public class TestConnPoolByRoute extends ServerTestBase {
PoolEntryRequest r6 = connPool.requestPoolEntry(route, Integer.valueOf(1));
BasicPoolEntry e6 = r6.getPoolEntry(10, TimeUnit.SECONDS);
assertNotNull(e4.getState());
assertNotNull(e5.getState());
assertNotNull(e6.getState());
Assert.assertNotNull(e4.getState());
Assert.assertNotNull(e5.getState());
Assert.assertNotNull(e6.getState());
// Check whether we got the same objects
assertTrue(e4 == e2);
assertTrue(e5 == e3);
assertTrue(e6 == e1);
Assert.assertTrue(e4 == e2);
Assert.assertTrue(e5 == e3);
Assert.assertTrue(e6 == e1);
// Release entries again
connPool.freeEntry(e4, true, -1, null);
@ -158,8 +146,8 @@ public class TestConnPoolByRoute extends ServerTestBase {
BasicPoolEntry e7 = r7.getPoolEntry(10, TimeUnit.SECONDS);
// Make sure we got a closed connection and a stateless entry back
assertFalse(e7.getConnection().isOpen());
assertNull(e7.getState());
Assert.assertFalse(e7.getConnection().isOpen());
Assert.assertNull(e7.getState());
} finally {
connPool.shutdown();

View File

@ -30,10 +30,6 @@ package org.apache.http.impl.conn.tsccm;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.Condition;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.apache.http.HttpHost;
import org.apache.http.conn.ClientConnectionOperator;
import org.apache.http.conn.ClientConnectionRequest;
@ -46,6 +42,8 @@ import org.apache.http.conn.scheme.SchemeSocketFactory;
import org.apache.http.conn.params.ConnPerRoute;
import org.apache.http.impl.conn.GetConnThread;
import org.junit.Assert;
import org.junit.Test;
/**
* Tests for spurious wakeups in <code>WaitingThread</code>.
@ -54,28 +52,13 @@ import org.apache.http.impl.conn.GetConnThread;
* satisfying the condition.
*
*/
public class TestSpuriousWakeup extends TestCase {
public class TestSpuriousWakeup {
public final static
HttpHost TARGET = new HttpHost("target.test.invalid");
public final static
HttpRoute ROUTE = new HttpRoute(TARGET);
public TestSpuriousWakeup(String testName) {
super(testName);
}
public static void main(String args[]) {
String[] testCaseName = { TestSpuriousWakeup.class.getName() };
junit.textui.TestRunner.main(testCaseName);
}
public static Test suite() {
return new TestSuite(TestSpuriousWakeup.class);
}
/**
* An extended connection pool that gives access to some internals.
*/
@ -126,8 +109,7 @@ public class TestSpuriousWakeup extends TestCase {
} // class XTSCCM
@Test
public void testSpuriousWakeup() throws Exception {
SchemeRegistry schreg = new SchemeRegistry();
SchemeSocketFactory sf = PlainSocketFactory.getSocketFactory();
@ -141,14 +123,14 @@ public class TestSpuriousWakeup extends TestCase {
// take out the only connection
ClientConnectionRequest connRequest = mgr.requestConnection(ROUTE, null);
ManagedClientConnection conn = connRequest.getConnection(0, null);
assertNotNull(conn);
Assert.assertNotNull(conn);
// send a thread waiting
GetConnThread gct = new GetConnThread(mgr, ROUTE, 0L);
gct.start();
Thread.sleep(100); // give extra thread time to block
assertEquals("thread not waiting",
Assert.assertEquals("thread not waiting",
Thread.State.WAITING, gct.getState());
// get access to the objects we need
@ -173,14 +155,13 @@ public class TestSpuriousWakeup extends TestCase {
// now give the waiting thread some time to register a wakeup
Thread.sleep(100);
assertEquals("thread no longer waiting, iteration " + i,
Assert.assertEquals("thread no longer waiting, iteration " + i,
Thread.State.WAITING, gct.getState());
}
} finally {
// don't worry about releasing the connection, just shut down
mgr.shutdown();
}
} // testSpuriousWakeup
}
} // class TestSpuriousWakeup
}

View File

@ -31,44 +31,26 @@ import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.apache.http.HttpHost;
import org.apache.http.conn.params.ConnPerRoute;
import org.apache.http.conn.params.ConnPerRouteBean;
import org.apache.http.conn.routing.HttpRoute;
import org.junit.Assert;
import org.junit.Test;
/**
* Tests for <code>WaitingThread</code>.
*/
public class TestWaitingThread extends TestCase {
public class TestWaitingThread {
public final static
HttpHost TARGET = new HttpHost("target.test.invalid");
public TestWaitingThread(String testName) {
super(testName);
}
public static void main(String args[]) {
String[] testCaseName = { TestWaitingThread.class.getName() };
junit.textui.TestRunner.main(testCaseName);
}
public static Test suite() {
return new TestSuite(TestWaitingThread.class);
}
@Test
public void testConstructor() {
try {
new WaitingThread(null, null);
fail("null condition not detected");
Assert.fail("null condition not detected");
} catch (IllegalArgumentException iax) {
// expected
}
@ -77,20 +59,20 @@ public class TestWaitingThread extends TestCase {
Condition cnd = lck.newCondition();
WaitingThread wt = new WaitingThread(cnd, null);
assertEquals("wrong condition", cnd, wt.getCondition());
assertNull ("pool from nowhere", wt.getPool());
assertNull ("thread from nowhere", wt.getThread());
Assert.assertEquals("wrong condition", cnd, wt.getCondition());
Assert.assertNull ("pool from nowhere", wt.getPool());
Assert.assertNull ("thread from nowhere", wt.getThread());
HttpRoute route = new HttpRoute(TARGET);
ConnPerRoute connPerRoute = new ConnPerRouteBean(10);
RouteSpecificPool rospl = new RouteSpecificPool(route, connPerRoute);
wt = new WaitingThread(cnd, rospl);
assertEquals("wrong condition", cnd, wt.getCondition());
assertEquals("wrong pool", rospl, wt.getPool());
assertNull ("thread from nowhere", wt.getThread());
Assert.assertEquals("wrong condition", cnd, wt.getCondition());
Assert.assertEquals("wrong pool", rospl, wt.getPool());
Assert.assertNull ("thread from nowhere", wt.getThread());
}
@Test
public void testAwaitWakeup() throws InterruptedException {
Lock lck = new ReentrantLock();
@ -101,13 +83,13 @@ public class TestWaitingThread extends TestCase {
ath.start();
Thread.sleep(100); // give extra thread time to block
assertNull("thread caught exception", ath.getException());
assertTrue("thread not waiting", ath.isWaiting());
assertEquals("wrong thread", ath, wt.getThread());
Assert.assertNull("thread caught exception", ath.getException());
Assert.assertTrue("thread not waiting", ath.isWaiting());
Assert.assertEquals("wrong thread", ath, wt.getThread());
Thread.sleep(500); // just for fun, let it wait for some time
// this may fail due to a spurious wakeup
assertTrue("thread not waiting, spurious wakeup?", ath.isWaiting());
Assert.assertTrue("thread not waiting, spurious wakeup?", ath.isWaiting());
try {
lck.lock();
@ -117,12 +99,12 @@ public class TestWaitingThread extends TestCase {
}
ath.join(10000);
assertFalse("thread still waiting", ath.isWaiting());
assertNull("thread caught exception", ath.getException());
assertNull("thread still there", wt.getThread());
Assert.assertFalse("thread still waiting", ath.isWaiting());
Assert.assertNull("thread caught exception", ath.getException());
Assert.assertNull("thread still there", wt.getThread());
}
@Test
public void testInterrupt() throws InterruptedException {
Lock lck = new ReentrantLock();
@ -133,21 +115,21 @@ public class TestWaitingThread extends TestCase {
ath.start();
Thread.sleep(100); // give extra thread time to block
assertNull("thread caught exception", ath.getException());
assertTrue("thread not waiting", ath.isWaiting());
assertEquals("wrong thread", ath, wt.getThread());
Assert.assertNull("thread caught exception", ath.getException());
Assert.assertTrue("thread not waiting", ath.isWaiting());
Assert.assertEquals("wrong thread", ath, wt.getThread());
ath.interrupt();
Thread.sleep(100); // give extra thread time to wake up
assertFalse("thread still waiting", ath.isWaiting());
assertNotNull("thread didn't catch exception", ath.getException());
assertTrue("thread caught wrong exception",
Assert.assertFalse("thread still waiting", ath.isWaiting());
Assert.assertNotNull("thread didn't catch exception", ath.getException());
Assert.assertTrue("thread caught wrong exception",
ath.getException() instanceof InterruptedException);
assertNull("thread still there", wt.getThread());
Assert.assertNull("thread still there", wt.getThread());
}
@Test
public void testIllegal() throws InterruptedException {
Lock lck = new ReentrantLock();
@ -157,7 +139,7 @@ public class TestWaitingThread extends TestCase {
try {
lck.lock();
wt.wakeup();
fail("missing waiter not detected");
Assert.fail("missing waiter not detected");
} catch (IllegalStateException isx) {
// expected
} finally {
@ -168,17 +150,17 @@ public class TestWaitingThread extends TestCase {
ath1.start();
Thread.sleep(100); // give extra thread time to block
assertNull("thread caught exception", ath1.getException());
assertTrue("thread not waiting", ath1.isWaiting());
assertEquals("wrong thread", ath1, wt.getThread());
Assert.assertNull("thread caught exception", ath1.getException());
Assert.assertTrue("thread not waiting", ath1.isWaiting());
Assert.assertEquals("wrong thread", ath1, wt.getThread());
AwaitThread ath2 = new AwaitThread(wt, lck, null);
ath2.start();
Thread.sleep(100); // give extra thread time to try to block
assertFalse("thread waiting", ath2.isWaiting());
assertNotNull("thread didn't catch exception", ath2.getException());
assertTrue("thread caught wrong exception",
Assert.assertFalse("thread waiting", ath2.isWaiting());
Assert.assertNotNull("thread didn't catch exception", ath2.getException());
Assert.assertTrue("thread caught wrong exception",
ath2.getException() instanceof IllegalStateException);
// clean up by letting the threads terminate
@ -186,5 +168,4 @@ public class TestWaitingThread extends TestCase {
ath2.interrupt();
}
} // class TestWaitingThread
}

View File

@ -30,32 +30,16 @@ package org.apache.http.impl.cookie;
import java.util.Iterator;
import java.util.List;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.apache.http.Header;
import org.apache.http.cookie.Cookie;
import org.apache.http.cookie.CookieAttributeHandler;
import org.apache.http.cookie.CookieOrigin;
import org.apache.http.cookie.MalformedCookieException;
import org.apache.http.cookie.SetCookie;
import org.junit.Assert;
import org.junit.Test;
public class TestAbstractCookieSpec extends TestCase {
public TestAbstractCookieSpec(String testName) {
super(testName);
}
public static Test suite() {
return new TestSuite(TestAbstractCookieSpec.class);
}
// ------------------------------------------------------------------- Main
public static void main(String args[]) {
String[] testCaseName = { TestAbstractCookieSpec.class.getName() };
junit.textui.TestRunner.main(testCaseName);
}
public class TestAbstractCookieSpec {
private static class DummyCookieSpec extends AbstractCookieSpec {
@ -98,6 +82,7 @@ public class TestAbstractCookieSpec extends TestCase {
}
@Test
public void testSimpleRegisterAndGet() {
CookieAttributeHandler h1 = new DummyCookieAttribHandler();
CookieAttributeHandler h2 = new DummyCookieAttribHandler();
@ -108,19 +93,20 @@ public class TestAbstractCookieSpec extends TestCase {
cookiespec.registerAttribHandler("thistoo", h1);
cookiespec.registerAttribHandler("thattoo", h2);
assertTrue(h1 == cookiespec.getAttribHandler("this"));
assertTrue(h2 == cookiespec.getAttribHandler("that"));
assertTrue(h1 == cookiespec.getAttribHandler("thistoo"));
assertTrue(h2 == cookiespec.getAttribHandler("thattoo"));
Assert.assertTrue(h1 == cookiespec.getAttribHandler("this"));
Assert.assertTrue(h2 == cookiespec.getAttribHandler("that"));
Assert.assertTrue(h1 == cookiespec.getAttribHandler("thistoo"));
Assert.assertTrue(h2 == cookiespec.getAttribHandler("thattoo"));
Iterator<CookieAttributeHandler> it = cookiespec.getAttribHandlers().iterator();
assertNotNull(it.next());
assertNotNull(it.next());
assertNotNull(it.next());
assertNotNull(it.next());
assertFalse(it.hasNext());
Assert.assertNotNull(it.next());
Assert.assertNotNull(it.next());
Assert.assertNotNull(it.next());
Assert.assertNotNull(it.next());
Assert.assertFalse(it.hasNext());
}
@Test(expected=IllegalStateException.class)
public void testInvalidHandler() {
CookieAttributeHandler h1 = new DummyCookieAttribHandler();
CookieAttributeHandler h2 = new DummyCookieAttribHandler();
@ -129,29 +115,20 @@ public class TestAbstractCookieSpec extends TestCase {
cookiespec.registerAttribHandler("this", h1);
cookiespec.registerAttribHandler("that", h2);
assertNull(cookiespec.findAttribHandler("whatever"));
try {
cookiespec.getAttribHandler("whatever");
fail("IllegalStateException should have been thrown");
} catch (IllegalStateException ex) {
// expected
}
Assert.assertNull(cookiespec.findAttribHandler("whatever"));
cookiespec.getAttribHandler("whatever");
}
public void testBasicPathInvalidInput() throws Exception {
@Test(expected=IllegalArgumentException.class)
public void testBasicPathInvalidInput1() throws Exception {
AbstractCookieSpec cookiespec = new DummyCookieSpec();
try {
cookiespec.registerAttribHandler(null, null);
fail("IllegalArgumentException must have been thrown");
} catch (IllegalArgumentException ex) {
// expected
}
try {
cookiespec.registerAttribHandler("whatever", null);
fail("IllegalArgumentException must have been thrown");
} catch (IllegalArgumentException ex) {
// expected
}
cookiespec.registerAttribHandler(null, null);
}
@Test(expected=IllegalArgumentException.class)
public void testBasicPathInvalidInput2() throws Exception {
AbstractCookieSpec cookiespec = new DummyCookieSpec();
cookiespec.registerAttribHandler("whatever", null);
}
}

View File

@ -32,53 +32,42 @@ import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.junit.Assert;
import org.junit.Test;
/**
* Unit tests for {@link BasicClientCookie}.
*/
public class TestBasicClientCookie extends TestCase {
public TestBasicClientCookie(String testName) {
super(testName);
}
public static void main(String args[]) {
String[] testCaseName = { TestBasicClientCookie.class.getName() };
junit.textui.TestRunner.main(testCaseName);
}
public static Test suite() {
return new TestSuite(TestBasicClientCookie.class);
}
public class TestBasicClientCookie {
@Test
public void testConstructor() {
BasicClientCookie cookie = new BasicClientCookie("name", "value");
assertEquals("name", cookie.getName());
assertEquals("value", cookie.getValue());
Assert.assertEquals("name", cookie.getName());
Assert.assertEquals("value", cookie.getValue());
try {
new BasicClientCookie(null, null);
fail("IllegalArgumentException should have been thrown");
Assert.fail("IllegalArgumentException should have been thrown");
} catch (IllegalArgumentException ex) {
//expected
}
}
@Test
public void testCloning() throws Exception {
BasicClientCookie orig = new BasicClientCookie("name", "value");
orig.setDomain("domain");
orig.setPath("/");
orig.setAttribute("attrib", "stuff");
BasicClientCookie clone = (BasicClientCookie) orig.clone();
assertEquals(orig.getName(), clone.getName());
assertEquals(orig.getValue(), clone.getValue());
assertEquals(orig.getDomain(), clone.getDomain());
assertEquals(orig.getPath(), clone.getPath());
assertEquals(orig.getAttribute("attrib"), clone.getAttribute("attrib"));
Assert.assertEquals(orig.getName(), clone.getName());
Assert.assertEquals(orig.getValue(), clone.getValue());
Assert.assertEquals(orig.getDomain(), clone.getDomain());
Assert.assertEquals(orig.getPath(), clone.getPath());
Assert.assertEquals(orig.getAttribute("attrib"), clone.getAttribute("attrib"));
}
@Test
public void testSerialization() throws Exception {
BasicClientCookie orig = new BasicClientCookie("name", "value");
orig.setDomain("domain");
@ -92,11 +81,11 @@ public class TestBasicClientCookie extends TestCase {
ByteArrayInputStream inbuffer = new ByteArrayInputStream(raw);
ObjectInputStream instream = new ObjectInputStream(inbuffer);
BasicClientCookie clone = (BasicClientCookie) instream.readObject();
assertEquals(orig.getName(), clone.getName());
assertEquals(orig.getValue(), clone.getValue());
assertEquals(orig.getDomain(), clone.getDomain());
assertEquals(orig.getPath(), clone.getPath());
assertEquals(orig.getAttribute("attrib"), clone.getAttribute("attrib"));
Assert.assertEquals(orig.getName(), clone.getName());
Assert.assertEquals(orig.getValue(), clone.getValue());
Assert.assertEquals(orig.getDomain(), clone.getDomain());
Assert.assertEquals(orig.getPath(), clone.getPath());
Assert.assertEquals(orig.getAttribute("attrib"), clone.getAttribute("attrib"));
}
}

View File

@ -32,40 +32,28 @@ import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.junit.Assert;
import org.junit.Test;
/**
* Unit tests for {@link BasicClientCookie2}.
*/
public class TestBasicClientCookie2 extends TestCase {
public TestBasicClientCookie2(String testName) {
super(testName);
}
public static void main(String args[]) {
String[] testCaseName = { TestBasicClientCookie2.class.getName() };
junit.textui.TestRunner.main(testCaseName);
}
public static Test suite() {
return new TestSuite(TestBasicClientCookie2.class);
}
public class TestBasicClientCookie2 {
@Test
public void testConstructor() {
BasicClientCookie2 cookie = new BasicClientCookie2("name", "value");
assertEquals("name", cookie.getName());
assertEquals("value", cookie.getValue());
Assert.assertEquals("name", cookie.getName());
Assert.assertEquals("value", cookie.getValue());
try {
new BasicClientCookie2(null, null);
fail("IllegalArgumentException should have been thrown");
Assert.fail("IllegalArgumentException should have been thrown");
} catch (IllegalArgumentException ex) {
//expected
}
}
@Test
public void testCloning() throws Exception {
BasicClientCookie2 orig = new BasicClientCookie2("name", "value");
orig.setDomain("domain");
@ -73,16 +61,17 @@ public class TestBasicClientCookie2 extends TestCase {
orig.setAttribute("attrib", "stuff");
orig.setPorts(new int[] {80, 8080});
BasicClientCookie2 clone = (BasicClientCookie2) orig.clone();
assertEquals(orig.getName(), clone.getName());
assertEquals(orig.getValue(), clone.getValue());
assertEquals(orig.getDomain(), clone.getDomain());
assertEquals(orig.getPath(), clone.getPath());
assertEquals(orig.getAttribute("attrib"), clone.getAttribute("attrib"));
assertEquals(orig.getPorts().length, clone.getPorts().length);
assertEquals(orig.getPorts()[0], clone.getPorts()[0]);
assertEquals(orig.getPorts()[1], clone.getPorts()[1]);
Assert.assertEquals(orig.getName(), clone.getName());
Assert.assertEquals(orig.getValue(), clone.getValue());
Assert.assertEquals(orig.getDomain(), clone.getDomain());
Assert.assertEquals(orig.getPath(), clone.getPath());
Assert.assertEquals(orig.getAttribute("attrib"), clone.getAttribute("attrib"));
Assert.assertEquals(orig.getPorts().length, clone.getPorts().length);
Assert.assertEquals(orig.getPorts()[0], clone.getPorts()[0]);
Assert.assertEquals(orig.getPorts()[1], clone.getPorts()[1]);
}
@Test
public void testSerialization() throws Exception {
BasicClientCookie2 orig = new BasicClientCookie2("name", "value");
orig.setDomain("domain");
@ -97,18 +86,18 @@ public class TestBasicClientCookie2 extends TestCase {
ByteArrayInputStream inbuffer = new ByteArrayInputStream(raw);
ObjectInputStream instream = new ObjectInputStream(inbuffer);
BasicClientCookie2 clone = (BasicClientCookie2) instream.readObject();
assertEquals(orig.getName(), clone.getName());
assertEquals(orig.getValue(), clone.getValue());
assertEquals(orig.getDomain(), clone.getDomain());
assertEquals(orig.getPath(), clone.getPath());
assertEquals(orig.getAttribute("attrib"), clone.getAttribute("attrib"));
Assert.assertEquals(orig.getName(), clone.getName());
Assert.assertEquals(orig.getValue(), clone.getValue());
Assert.assertEquals(orig.getDomain(), clone.getDomain());
Assert.assertEquals(orig.getPath(), clone.getPath());
Assert.assertEquals(orig.getAttribute("attrib"), clone.getAttribute("attrib"));
int[] expected = orig.getPorts();
int[] clones = clone.getPorts();
assertNotNull(expected);
assertNotNull(clones);
assertEquals(expected.length, clones.length);
Assert.assertNotNull(expected);
Assert.assertNotNull(clones);
Assert.assertEquals(expected.length, clones.length);
for (int i = 0; i < expected.length; i++) {
assertEquals(expected[i], clones[i]);
Assert.assertEquals(expected[i], clones[i]);
}
}

View File

@ -33,10 +33,6 @@ import java.util.Arrays;
import java.util.Date;
import java.util.Locale;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.apache.http.cookie.CookieAttributeHandler;
import org.apache.http.cookie.CookieOrigin;
import org.apache.http.cookie.MalformedCookieException;
@ -50,47 +46,34 @@ import org.apache.http.impl.cookie.BasicSecureHandler;
import org.apache.http.impl.cookie.DateUtils;
import org.apache.http.impl.cookie.PublicSuffixFilter;
import org.apache.http.impl.cookie.RFC2109DomainHandler;
import org.junit.Assert;
import org.junit.Test;
public class TestBasicCookieAttribHandlers extends TestCase {
public TestBasicCookieAttribHandlers(String testName) {
super(testName);
}
public static Test suite() {
return new TestSuite(TestBasicCookieAttribHandlers.class);
}
// ------------------------------------------------------------------- Main
public static void main(String args[]) {
String[] testCaseName = { TestBasicCookieAttribHandlers.class.getName() };
junit.textui.TestRunner.main(testCaseName);
}
public class TestBasicCookieAttribHandlers {
@Test
public void testBasicDomainParse() throws Exception {
BasicClientCookie cookie = new BasicClientCookie("name", "value");
CookieAttributeHandler h = new BasicDomainHandler();
h.parse(cookie, "www.somedomain.com");
assertEquals("www.somedomain.com", cookie.getDomain());
Assert.assertEquals("www.somedomain.com", cookie.getDomain());
}
public void testBasicDomainParseInvalid() throws Exception {
@Test(expected=MalformedCookieException.class)
public void testBasicDomainParseInvalid1() throws Exception {
BasicClientCookie cookie = new BasicClientCookie("name", "value");
CookieAttributeHandler h = new BasicDomainHandler();
try {
h.parse(cookie, "");
fail("MalformedCookieException should have been thrown");
} catch (MalformedCookieException ex) {
// expected
}
try {
h.parse(cookie, null);
fail("MalformedCookieException should have been thrown");
} catch (MalformedCookieException ex) {
// expected
}
h.parse(cookie, "");
}
@Test(expected=MalformedCookieException.class)
public void testBasicDomainParseInvalid2() throws Exception {
BasicClientCookie cookie = new BasicClientCookie("name", "value");
CookieAttributeHandler h = new BasicDomainHandler();
h.parse(cookie, null);
}
@Test
public void testBasicDomainValidate1() throws Exception {
BasicClientCookie cookie = new BasicClientCookie("name", "value");
CookieOrigin origin = new CookieOrigin("www.somedomain.com", 80, "/", false);
@ -102,19 +85,20 @@ public class TestBasicCookieAttribHandlers extends TestCase {
cookie.setDomain(".otherdomain.com");
try {
h.validate(cookie, origin);
fail("MalformedCookieException should have been thrown");
Assert.fail("MalformedCookieException should have been thrown");
} catch (MalformedCookieException ex) {
// expected
}
cookie.setDomain("www.otherdomain.com");
try {
h.validate(cookie, origin);
fail("MalformedCookieException should have been thrown");
Assert.fail("MalformedCookieException should have been thrown");
} catch (MalformedCookieException ex) {
// expected
}
}
@Test
public void testBasicDomainValidate2() throws Exception {
BasicClientCookie cookie = new BasicClientCookie("name", "value");
CookieOrigin origin = new CookieOrigin("somehost", 80, "/", false);
@ -126,12 +110,13 @@ public class TestBasicCookieAttribHandlers extends TestCase {
cookie.setDomain("otherhost");
try {
h.validate(cookie, origin);
fail("MalformedCookieException should have been thrown");
Assert.fail("MalformedCookieException should have been thrown");
} catch (MalformedCookieException ex) {
// expected
}
}
@Test
public void testBasicDomainValidate3() throws Exception {
BasicClientCookie cookie = new BasicClientCookie("name", "value");
CookieOrigin origin = new CookieOrigin("somedomain.com", 80, "/", false);
@ -141,6 +126,7 @@ public class TestBasicCookieAttribHandlers extends TestCase {
h.validate(cookie, origin);
}
@Test
public void testBasicDomainValidate4() throws Exception {
BasicClientCookie cookie = new BasicClientCookie("name", "value");
CookieOrigin origin = new CookieOrigin("somedomain.com", 80, "/", false);
@ -149,139 +135,151 @@ public class TestBasicCookieAttribHandlers extends TestCase {
cookie.setDomain(null);
try {
h.validate(cookie, origin);
fail("MalformedCookieException should have been thrown");
Assert.fail("MalformedCookieException should have been thrown");
} catch (MalformedCookieException ex) {
// expected
}
}
@Test
public void testBasicDomainMatch1() throws Exception {
BasicClientCookie cookie = new BasicClientCookie("name", "value");
CookieOrigin origin = new CookieOrigin("somedomain.com", 80, "/", false);
CookieAttributeHandler h = new BasicDomainHandler();
cookie.setDomain("somedomain.com");
assertTrue(h.match(cookie, origin));
Assert.assertTrue(h.match(cookie, origin));
cookie.setDomain(".somedomain.com");
assertTrue(h.match(cookie, origin));
Assert.assertTrue(h.match(cookie, origin));
}
@Test
public void testBasicDomainMatch2() throws Exception {
BasicClientCookie cookie = new BasicClientCookie("name", "value");
CookieOrigin origin = new CookieOrigin("www.somedomain.com", 80, "/", false);
CookieAttributeHandler h = new BasicDomainHandler();
cookie.setDomain("somedomain.com");
assertTrue(h.match(cookie, origin));
Assert.assertTrue(h.match(cookie, origin));
cookie.setDomain(".somedomain.com");
assertTrue(h.match(cookie, origin));
Assert.assertTrue(h.match(cookie, origin));
cookie.setDomain(null);
assertFalse(h.match(cookie, origin));
Assert.assertFalse(h.match(cookie, origin));
}
@Test
public void testBasicDomainInvalidInput() throws Exception {
CookieAttributeHandler h = new BasicDomainHandler();
try {
h.parse(null, null);
fail("IllegalArgumentException must have been thrown");
Assert.fail("IllegalArgumentException must have been thrown");
} catch (IllegalArgumentException ex) {
// expected
}
try {
h.validate(null, null);
fail("IllegalArgumentException must have been thrown");
Assert.fail("IllegalArgumentException must have been thrown");
} catch (IllegalArgumentException ex) {
// expected
}
try {
h.validate(new BasicClientCookie("name", "value"), null);
fail("IllegalArgumentException must have been thrown");
Assert.fail("IllegalArgumentException must have been thrown");
} catch (IllegalArgumentException ex) {
// expected
}
try {
h.match(null, null);
fail("IllegalArgumentException must have been thrown");
Assert.fail("IllegalArgumentException must have been thrown");
} catch (IllegalArgumentException ex) {
// expected
}
try {
h.match(new BasicClientCookie("name", "value"), null);
fail("IllegalArgumentException must have been thrown");
Assert.fail("IllegalArgumentException must have been thrown");
} catch (IllegalArgumentException ex) {
// expected
}
}
@Test
public void testBasicPathParse() throws Exception {
BasicClientCookie cookie = new BasicClientCookie("name", "value");
CookieAttributeHandler h = new BasicPathHandler();
h.parse(cookie, "stuff");
assertEquals("stuff", cookie.getPath());
Assert.assertEquals("stuff", cookie.getPath());
h.parse(cookie, "");
assertEquals("/", cookie.getPath());
Assert.assertEquals("/", cookie.getPath());
h.parse(cookie, null);
assertEquals("/", cookie.getPath());
Assert.assertEquals("/", cookie.getPath());
}
@Test
public void testBasicPathMatch1() throws Exception {
BasicClientCookie cookie = new BasicClientCookie("name", "value");
CookieOrigin origin = new CookieOrigin("somehost", 80, "/stuff", false);
CookieAttributeHandler h = new BasicPathHandler();
cookie.setPath("/stuff");
assertTrue(h.match(cookie, origin));
Assert.assertTrue(h.match(cookie, origin));
}
@Test
public void testBasicPathMatch2() throws Exception {
BasicClientCookie cookie = new BasicClientCookie("name", "value");
CookieOrigin origin = new CookieOrigin("somehost", 80, "/stuff/", false);
CookieAttributeHandler h = new BasicPathHandler();
cookie.setPath("/stuff");
assertTrue(h.match(cookie, origin));
Assert.assertTrue(h.match(cookie, origin));
}
@Test
public void testBasicPathMatch3() throws Exception {
BasicClientCookie cookie = new BasicClientCookie("name", "value");
CookieOrigin origin = new CookieOrigin("somehost", 80, "/stuff/more-stuff", false);
CookieAttributeHandler h = new BasicPathHandler();
cookie.setPath("/stuff");
assertTrue(h.match(cookie, origin));
Assert.assertTrue(h.match(cookie, origin));
}
@Test
public void testBasicPathMatch4() throws Exception {
BasicClientCookie cookie = new BasicClientCookie("name", "value");
CookieOrigin origin = new CookieOrigin("somehost", 80, "/stuffed", false);
CookieAttributeHandler h = new BasicPathHandler();
cookie.setPath("/stuff");
assertFalse(h.match(cookie, origin));
Assert.assertFalse(h.match(cookie, origin));
}
@Test
public void testBasicPathMatch5() throws Exception {
BasicClientCookie cookie = new BasicClientCookie("name", "value");
CookieOrigin origin = new CookieOrigin("somehost", 80, "/otherstuff", false);
CookieAttributeHandler h = new BasicPathHandler();
cookie.setPath("/stuff");
assertFalse(h.match(cookie, origin));
Assert.assertFalse(h.match(cookie, origin));
}
@Test
public void testBasicPathMatch6() throws Exception {
BasicClientCookie cookie = new BasicClientCookie("name", "value");
CookieOrigin origin = new CookieOrigin("somehost", 80, "/stuff", false);
CookieAttributeHandler h = new BasicPathHandler();
cookie.setPath("/stuff/");
assertTrue(h.match(cookie, origin));
Assert.assertTrue(h.match(cookie, origin));
}
@Test
public void testBasicPathMatch7() throws Exception {
BasicClientCookie cookie = new BasicClientCookie("name", "value");
CookieOrigin origin = new CookieOrigin("somehost", 80, "/stuff", false);
CookieAttributeHandler h = new BasicPathHandler();
assertTrue(h.match(cookie, origin));
Assert.assertTrue(h.match(cookie, origin));
}
@Test
public void testBasicPathValidate() throws Exception {
BasicClientCookie cookie = new BasicClientCookie("name", "value");
CookieOrigin origin = new CookieOrigin("somehost", 80, "/stuff", false);
@ -291,135 +289,145 @@ public class TestBasicCookieAttribHandlers extends TestCase {
cookie.setPath("/stuffed");
try {
h.validate(cookie, origin);
fail("MalformedCookieException must have been thrown");
Assert.fail("MalformedCookieException must have been thrown");
} catch (MalformedCookieException ex) {
// expected
}
}
@Test
public void testBasicPathInvalidInput() throws Exception {
CookieAttributeHandler h = new BasicPathHandler();
try {
h.parse(null, null);
fail("IllegalArgumentException must have been thrown");
Assert.fail("IllegalArgumentException must have been thrown");
} catch (IllegalArgumentException ex) {
// expected
}
try {
h.match(null, null);
fail("IllegalArgumentException must have been thrown");
Assert.fail("IllegalArgumentException must have been thrown");
} catch (IllegalArgumentException ex) {
// expected
}
try {
h.match(new BasicClientCookie("name", "value"), null);
fail("IllegalArgumentException must have been thrown");
Assert.fail("IllegalArgumentException must have been thrown");
} catch (IllegalArgumentException ex) {
// expected
}
}
@Test
public void testBasicMaxAgeParse() throws Exception {
BasicClientCookie cookie = new BasicClientCookie("name", "value");
CookieAttributeHandler h = new BasicMaxAgeHandler();
h.parse(cookie, "2000");
assertNotNull(cookie.getExpiryDate());
Assert.assertNotNull(cookie.getExpiryDate());
}
@Test
public void testBasicMaxAgeParseInvalid() throws Exception {
BasicClientCookie cookie = new BasicClientCookie("name", "value");
CookieAttributeHandler h = new BasicMaxAgeHandler();
try {
h.parse(cookie, "garbage");
fail("MalformedCookieException must have been thrown");
Assert.fail("MalformedCookieException must have been thrown");
} catch (MalformedCookieException ex) {
// expected
}
try {
h.parse(cookie, null);
fail("MalformedCookieException must have been thrown");
Assert.fail("MalformedCookieException must have been thrown");
} catch (MalformedCookieException ex) {
// expected
}
}
@Test
public void testBasicMaxAgeInvalidInput() throws Exception {
CookieAttributeHandler h = new BasicMaxAgeHandler();
try {
h.parse(null, null);
fail("IllegalArgumentException must have been thrown");
Assert.fail("IllegalArgumentException must have been thrown");
} catch (IllegalArgumentException ex) {
// expected
}
}
@Test
public void testBasicCommentParse() throws Exception {
BasicClientCookie cookie = new BasicClientCookie("name", "value");
CookieAttributeHandler h = new BasicCommentHandler();
h.parse(cookie, "whatever");
assertEquals("whatever", cookie.getComment());
Assert.assertEquals("whatever", cookie.getComment());
h.parse(cookie, null);
assertEquals(null, cookie.getComment());
Assert.assertEquals(null, cookie.getComment());
}
@Test
public void testBasicCommentInvalidInput() throws Exception {
CookieAttributeHandler h = new BasicCommentHandler();
try {
h.parse(null, null);
fail("IllegalArgumentException must have been thrown");
Assert.fail("IllegalArgumentException must have been thrown");
} catch (IllegalArgumentException ex) {
// expected
}
}
@Test
public void testBasicSecureParse() throws Exception {
BasicClientCookie cookie = new BasicClientCookie("name", "value");
CookieAttributeHandler h = new BasicSecureHandler();
h.parse(cookie, "whatever");
assertTrue(cookie.isSecure());
Assert.assertTrue(cookie.isSecure());
h.parse(cookie, null);
assertTrue(cookie.isSecure());
Assert.assertTrue(cookie.isSecure());
}
@Test
public void testBasicSecureMatch() throws Exception {
BasicClientCookie cookie = new BasicClientCookie("name", "value");
CookieAttributeHandler h = new BasicSecureHandler();
CookieOrigin origin1 = new CookieOrigin("somehost", 80, "/stuff", false);
cookie.setSecure(false);
assertTrue(h.match(cookie, origin1));
Assert.assertTrue(h.match(cookie, origin1));
cookie.setSecure(true);
assertFalse(h.match(cookie, origin1));
Assert.assertFalse(h.match(cookie, origin1));
CookieOrigin origin2 = new CookieOrigin("somehost", 80, "/stuff", true);
cookie.setSecure(false);
assertTrue(h.match(cookie, origin2));
Assert.assertTrue(h.match(cookie, origin2));
cookie.setSecure(true);
assertTrue(h.match(cookie, origin2));
Assert.assertTrue(h.match(cookie, origin2));
}
@Test
public void testBasicSecureInvalidInput() throws Exception {
CookieAttributeHandler h = new BasicSecureHandler();
try {
h.parse(null, null);
fail("IllegalArgumentException must have been thrown");
Assert.fail("IllegalArgumentException must have been thrown");
} catch (IllegalArgumentException ex) {
// expected
}
try {
h.match(null, null);
fail("IllegalArgumentException must have been thrown");
Assert.fail("IllegalArgumentException must have been thrown");
} catch (IllegalArgumentException ex) {
// expected
}
try {
h.match(new BasicClientCookie("name", "value"), null);
fail("IllegalArgumentException must have been thrown");
Assert.fail("IllegalArgumentException must have been thrown");
} catch (IllegalArgumentException ex) {
// expected
}
}
@Test
public void testBasicExpiresParse() throws Exception {
BasicClientCookie cookie = new BasicClientCookie("name", "value");
CookieAttributeHandler h = new BasicExpiresHandler(new String[] {DateUtils.PATTERN_RFC1123});
@ -430,42 +438,45 @@ public class TestBasicCookieAttribHandlers extends TestCase {
Date now = new Date();
h.parse(cookie, dateformat.format(now));
assertNotNull(cookie.getExpiryDate());
Assert.assertNotNull(cookie.getExpiryDate());
}
@Test
public void testBasicExpiresParseInvalid() throws Exception {
BasicClientCookie cookie = new BasicClientCookie("name", "value");
CookieAttributeHandler h = new BasicExpiresHandler(new String[] {DateUtils.PATTERN_RFC1123});
try {
h.parse(cookie, "garbage");
fail("MalformedCookieException must have been thrown");
Assert.fail("MalformedCookieException must have been thrown");
} catch (MalformedCookieException ex) {
// expected
}
try {
h.parse(cookie, null);
fail("MalformedCookieException must have been thrown");
Assert.fail("MalformedCookieException must have been thrown");
} catch (MalformedCookieException ex) {
// expected
}
}
@Test
public void testBasicExpiresInvalidInput() throws Exception {
try {
new BasicExpiresHandler(null);
fail("IllegalArgumentException must have been thrown");
Assert.fail("IllegalArgumentException must have been thrown");
} catch (IllegalArgumentException ex) {
// expected
}
CookieAttributeHandler h = new BasicExpiresHandler(new String[] {DateUtils.PATTERN_RFC1123});
try {
h.parse(null, null);
fail("IllegalArgumentException must have been thrown");
Assert.fail("IllegalArgumentException must have been thrown");
} catch (IllegalArgumentException ex) {
// expected
}
}
@Test
public void testPublicSuffixFilter() throws Exception {
BasicClientCookie cookie = new BasicClientCookie("name", "value");
@ -473,19 +484,19 @@ public class TestBasicCookieAttribHandlers extends TestCase {
h.setPublicSuffixes(Arrays.asList(new String[] { "co.uk", "com" }));
cookie.setDomain(".co.uk");
assertFalse(h.match(cookie, new CookieOrigin("apache.co.uk", 80, "/stuff", false)));
Assert.assertFalse(h.match(cookie, new CookieOrigin("apache.co.uk", 80, "/stuff", false)));
cookie.setDomain("co.uk");
assertFalse(h.match(cookie, new CookieOrigin("apache.co.uk", 80, "/stuff", false)));
Assert.assertFalse(h.match(cookie, new CookieOrigin("apache.co.uk", 80, "/stuff", false)));
cookie.setDomain(".com");
assertFalse(h.match(cookie, new CookieOrigin("apache.com", 80, "/stuff", false)));
Assert.assertFalse(h.match(cookie, new CookieOrigin("apache.com", 80, "/stuff", false)));
cookie.setDomain("com");
assertFalse(h.match(cookie, new CookieOrigin("apache.com", 80, "/stuff", false)));
Assert.assertFalse(h.match(cookie, new CookieOrigin("apache.com", 80, "/stuff", false)));
cookie.setDomain("localhost");
assertTrue(h.match(cookie, new CookieOrigin("localhost", 80, "/stuff", false)));
Assert.assertTrue(h.match(cookie, new CookieOrigin("localhost", 80, "/stuff", false)));
}
}

View File

@ -30,10 +30,6 @@ package org.apache.http.impl.cookie;
import java.util.ArrayList;
import java.util.List;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.apache.http.Header;
import org.apache.http.cookie.ClientCookie;
import org.apache.http.cookie.Cookie;
@ -42,26 +38,15 @@ import org.apache.http.cookie.CookieSpec;
import org.apache.http.cookie.MalformedCookieException;
import org.apache.http.cookie.SetCookie2;
import org.apache.http.message.BasicHeader;
import org.junit.Assert;
import org.junit.Test;
/**
* Test cases for 'best match' cookie policy
*
*
*/
public class TestCookieBestMatchSpec extends TestCase {
// ------------------------------------------------------------ Constructor
public TestCookieBestMatchSpec(String name) {
super(name);
}
// ------------------------------------------------------- TestCase Methods
public static Test suite() {
return new TestSuite(TestCookieBestMatchSpec.class);
}
public class TestCookieBestMatchSpec {
@Test
public void testCookieBrowserCompatParsing() throws Exception {
CookieSpec cookiespec = new BestMatchSpec();
CookieOrigin origin = new CookieOrigin("a.b.domain.com", 80, "/", false);
@ -76,6 +61,7 @@ public class TestCookieBestMatchSpec extends TestCase {
}
}
@Test
public void testNetscapeCookieParsing() throws Exception {
CookieSpec cookiespec = new BestMatchSpec();
CookieOrigin origin = new CookieOrigin("myhost.mydomain.com", 80, "/", false);
@ -90,12 +76,13 @@ public class TestCookieBestMatchSpec extends TestCase {
try {
cookies = cookiespec.parse(header, origin);
cookiespec.validate(cookies.get(0), origin);
fail("MalformedCookieException exception should have been thrown");
Assert.fail("MalformedCookieException exception should have been thrown");
} catch (MalformedCookieException e) {
// expected
}
}
@Test
public void testCookieStandardCompliantParsing() throws Exception {
CookieSpec cookiespec = new BestMatchSpec();
CookieOrigin origin = new CookieOrigin("a.b.domain.com", 80, "/", false);
@ -122,12 +109,13 @@ public class TestCookieBestMatchSpec extends TestCase {
try {
cookies = cookiespec.parse(header, origin);
cookiespec.validate(cookies.get(0), origin);
fail("MalformedCookieException exception should have been thrown");
Assert.fail("MalformedCookieException exception should have been thrown");
} catch (MalformedCookieException e) {
// expected
}
}
@Test
public void testCookieStandardCompliantParsingLocalHost() throws Exception {
CookieSpec cookiespec = new BestMatchSpec();
CookieOrigin origin = new CookieOrigin("localhost", 80, "/", false);
@ -138,11 +126,12 @@ public class TestCookieBestMatchSpec extends TestCase {
for (int i = 0; i < cookies.size(); i++) {
Cookie cookie = cookies.get(i);
cookiespec.validate(cookie, origin);
assertEquals("localhost", cookie.getDomain());
assertFalse(cookie instanceof SetCookie2);
Assert.assertEquals("localhost", cookie.getDomain());
Assert.assertFalse(cookie instanceof SetCookie2);
}
}
@Test
public void testCookieStandardCompliantParsingLocalHost2() throws Exception {
CookieSpec cookiespec = new BestMatchSpec();
CookieOrigin origin = new CookieOrigin("localhost", 80, "/", false);
@ -153,11 +142,12 @@ public class TestCookieBestMatchSpec extends TestCase {
for (int i = 0; i < cookies.size(); i++) {
Cookie cookie = cookies.get(i);
cookiespec.validate(cookie, origin);
assertEquals("localhost.local", cookie.getDomain());
assertTrue(cookie instanceof SetCookie2);
Assert.assertEquals("localhost.local", cookie.getDomain());
Assert.assertTrue(cookie instanceof SetCookie2);
}
}
@Test
public void testCookieBrowserCompatMatch() throws Exception {
CookieSpec cookiespec = new BestMatchSpec();
CookieOrigin origin = new CookieOrigin("a.b.domain.com", 80, "/", false);
@ -170,9 +160,10 @@ public class TestCookieBestMatchSpec extends TestCase {
cookie.setPath("/");
cookie.setAttribute(ClientCookie.PATH_ATTR, cookie.getPath());
assertTrue(cookiespec.match(cookie, origin));
Assert.assertTrue(cookiespec.match(cookie, origin));
}
@Test
public void testCookieStandardCompliantMatch() throws Exception {
CookieSpec cookiespec = new BestMatchSpec();
CookieOrigin origin = new CookieOrigin("a.b.domain.com", 80, "/", false);
@ -186,13 +177,14 @@ public class TestCookieBestMatchSpec extends TestCase {
cookie.setPath("/");
cookie.setAttribute(ClientCookie.PATH_ATTR, cookie.getPath());
assertFalse(cookiespec.match(cookie, origin));
Assert.assertFalse(cookiespec.match(cookie, origin));
cookie.setDomain(".b.domain.com");
assertTrue(cookiespec.match(cookie, origin));
Assert.assertTrue(cookiespec.match(cookie, origin));
}
@Test
public void testCookieBrowserCompatFormatting() throws Exception {
CookieSpec cookiespec = new BestMatchSpec();
@ -216,14 +208,15 @@ public class TestCookieBestMatchSpec extends TestCase {
cookies.add(cookie2);
List<Header> headers = cookiespec.formatCookies(cookies);
assertNotNull(headers);
assertEquals(1, headers.size());
Assert.assertNotNull(headers);
Assert.assertEquals(1, headers.size());
Header header = headers.get(0);
assertEquals("name1=value1; name2=value2", header.getValue());
Assert.assertEquals("name1=value1; name2=value2", header.getValue());
}
@Test
public void testCookieStandardCompliantFormatting() throws Exception {
CookieSpec cookiespec = new BestMatchSpec(null, true);
@ -248,40 +241,41 @@ public class TestCookieBestMatchSpec extends TestCase {
cookies.add(cookie2);
List<Header> headers = cookiespec.formatCookies(cookies);
assertNotNull(headers);
assertEquals(1, headers.size());
Assert.assertNotNull(headers);
Assert.assertEquals(1, headers.size());
Header header = headers.get(0);
assertEquals("$Version=1; name1=\"value1\"; $Path=\"/\"; $Domain=\".domain.com\"; " +
Assert.assertEquals("$Version=1; name1=\"value1\"; $Path=\"/\"; $Domain=\".domain.com\"; " +
"name2=\"value2\"; $Path=\"/\"; $Domain=\".domain.com\"",
header.getValue());
}
@Test
public void testInvalidInput() throws Exception {
CookieSpec cookiespec = new BestMatchSpec();
try {
cookiespec.parse(null, null);
fail("IllegalArgumentException must have been thrown");
Assert.fail("IllegalArgumentException must have been thrown");
} catch (IllegalArgumentException ex) {
// expected
}
try {
cookiespec.parse(new BasicHeader("Set-Cookie", "name=value"), null);
fail("IllegalArgumentException must have been thrown");
Assert.fail("IllegalArgumentException must have been thrown");
} catch (IllegalArgumentException ex) {
// expected
}
try {
cookiespec.formatCookies(null);
fail("IllegalArgumentException must have been thrown");
Assert.fail("IllegalArgumentException must have been thrown");
} catch (IllegalArgumentException ex) {
// expected
}
try {
List<Cookie> cookies = new ArrayList<Cookie>();
cookiespec.formatCookies(cookies);
fail("IllegalArgumentException must have been thrown");
Assert.fail("IllegalArgumentException must have been thrown");
} catch (IllegalArgumentException ex) {
// expected
}

View File

@ -32,10 +32,6 @@ import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.apache.http.Header;
import org.apache.http.cookie.ClientCookie;
import org.apache.http.cookie.Cookie;
@ -43,24 +39,15 @@ import org.apache.http.cookie.CookieOrigin;
import org.apache.http.cookie.CookieSpec;
import org.apache.http.cookie.MalformedCookieException;
import org.apache.http.message.BasicHeader;
import org.junit.Assert;
import org.junit.Test;
/**
* Test cases for Netscape cookie draft
*/
public class TestCookieNetscapeDraft extends TestCase {
// ------------------------------------------------------------ Constructor
public TestCookieNetscapeDraft(String name) {
super(name);
}
// ------------------------------------------------------- TestCase Methods
public static Test suite() {
return new TestSuite(TestCookieNetscapeDraft.class);
}
public class TestCookieNetscapeDraft {
@Test
public void testParseAbsPath() throws Exception {
Header header = new BasicHeader("Set-Cookie", "name1=value1;Path=/path/");
@ -70,13 +57,14 @@ public class TestCookieNetscapeDraft extends TestCase {
for (int i = 0; i < cookies.size(); i++) {
cookiespec.validate(cookies.get(i), origin);
}
assertEquals("Found 1 cookies.",1,cookies.size());
assertEquals("Name","name1",cookies.get(0).getName());
assertEquals("Value","value1",cookies.get(0).getValue());
assertEquals("Domain","host",cookies.get(0).getDomain());
assertEquals("Path","/path/",cookies.get(0).getPath());
Assert.assertEquals("Found 1 cookies.",1,cookies.size());
Assert.assertEquals("Name","name1",cookies.get(0).getName());
Assert.assertEquals("Value","value1",cookies.get(0).getValue());
Assert.assertEquals("Domain","host",cookies.get(0).getDomain());
Assert.assertEquals("Path","/path/",cookies.get(0).getPath());
}
@Test
public void testParseAbsPath2() throws Exception {
Header header = new BasicHeader("Set-Cookie", "name1=value1;Path=/");
@ -86,13 +74,14 @@ public class TestCookieNetscapeDraft extends TestCase {
for (int i = 0; i < cookies.size(); i++) {
cookiespec.validate(cookies.get(i), origin);
}
assertEquals("Found 1 cookies.",1,cookies.size());
assertEquals("Name","name1",cookies.get(0).getName());
assertEquals("Value","value1",cookies.get(0).getValue());
assertEquals("Domain","host",cookies.get(0).getDomain());
assertEquals("Path","/",cookies.get(0).getPath());
Assert.assertEquals("Found 1 cookies.",1,cookies.size());
Assert.assertEquals("Name","name1",cookies.get(0).getName());
Assert.assertEquals("Value","value1",cookies.get(0).getValue());
Assert.assertEquals("Domain","host",cookies.get(0).getDomain());
Assert.assertEquals("Path","/",cookies.get(0).getPath());
}
@Test
public void testParseRelativePath() throws Exception {
Header header = new BasicHeader("Set-Cookie", "name1=value1;Path=whatever");
@ -102,13 +91,14 @@ public class TestCookieNetscapeDraft extends TestCase {
for (int i = 0; i < cookies.size(); i++) {
cookiespec.validate(cookies.get(i), origin);
}
assertEquals("Found 1 cookies.",1,cookies.size());
assertEquals("Name","name1",cookies.get(0).getName());
assertEquals("Value","value1",cookies.get(0).getValue());
assertEquals("Domain","host",cookies.get(0).getDomain());
assertEquals("Path","whatever",cookies.get(0).getPath());
Assert.assertEquals("Found 1 cookies.",1,cookies.size());
Assert.assertEquals("Name","name1",cookies.get(0).getName());
Assert.assertEquals("Value","value1",cookies.get(0).getValue());
Assert.assertEquals("Domain","host",cookies.get(0).getDomain());
Assert.assertEquals("Path","whatever",cookies.get(0).getPath());
}
@Test
public void testParseWithIllegalNetscapeDomain1() throws Exception {
Header header = new BasicHeader("Set-Cookie","cookie-name=cookie-value; domain=.com");
@ -119,12 +109,13 @@ public class TestCookieNetscapeDraft extends TestCase {
for (int i = 0; i < cookies.size(); i++) {
cookiespec.validate(cookies.get(i), origin);
}
fail("MalformedCookieException exception should have been thrown");
Assert.fail("MalformedCookieException exception should have been thrown");
} catch (MalformedCookieException e) {
// expected
}
}
@Test
public void testParseWithWrongNetscapeDomain2() throws Exception {
Header header = new BasicHeader("Set-Cookie","cookie-name=cookie-value; domain=.y.z");
@ -135,7 +126,7 @@ public class TestCookieNetscapeDraft extends TestCase {
for (int i = 0; i < cookies.size(); i++) {
cookiespec.validate(cookies.get(i), origin);
}
fail("MalformedCookieException exception should have been thrown");
Assert.fail("MalformedCookieException exception should have been thrown");
} catch (MalformedCookieException e) {
// expected
}
@ -144,6 +135,7 @@ public class TestCookieNetscapeDraft extends TestCase {
/**
* Tests Netscape specific cookie formatting.
*/
@Test
public void testNetscapeCookieFormatting() throws Exception {
Header header = new BasicHeader(
"Set-Cookie", "name=value; path=/; domain=.mydomain.com");
@ -152,13 +144,14 @@ public class TestCookieNetscapeDraft extends TestCase {
List<Cookie> cookies = cookiespec.parse(header, origin);
cookiespec.validate(cookies.get(0), origin);
List<Header> headers = cookiespec.formatCookies(cookies);
assertEquals(1, headers.size());
assertEquals("name=value", headers.get(0).getValue());
Assert.assertEquals(1, headers.size());
Assert.assertEquals("name=value", headers.get(0).getValue());
}
/**
* Tests Netscape specific expire attribute parsing.
*/
@Test
public void testNetscapeCookieExpireAttribute() throws Exception {
CookieSpec cookiespec = new NetscapeDraftSpec();
Header header = new BasicHeader("Set-Cookie",
@ -166,19 +159,20 @@ public class TestCookieNetscapeDraft extends TestCase {
CookieOrigin origin = new CookieOrigin("myhost.mydomain.com", 80, "/", false);
List<Cookie> cookies = cookiespec.parse(header, origin);
cookiespec.validate(cookies.get(0), origin);
assertNotNull(cookies);
assertEquals(1, cookies.size());
Assert.assertNotNull(cookies);
Assert.assertEquals(1, cookies.size());
Cookie cookie = cookies.get(0);
Calendar c = Calendar.getInstance();
c.setTimeZone(TimeZone.getTimeZone("GMT"));
c.setTime(cookie.getExpiryDate());
int year = c.get(Calendar.YEAR);
assertEquals(2070, year);
Assert.assertEquals(2070, year);
}
/**
* Expire attribute with two digit year.
*/
@Test
public void testNetscapeCookieExpireAttributeTwoDigitYear() throws Exception {
CookieSpec cookiespec = new NetscapeDraftSpec();
Header header = new BasicHeader("Set-Cookie",
@ -186,19 +180,20 @@ public class TestCookieNetscapeDraft extends TestCase {
CookieOrigin origin = new CookieOrigin("myhost.mydomain.com", 80, "/", false);
List<Cookie> cookies = cookiespec.parse(header, origin);
cookiespec.validate(cookies.get(0), origin);
assertNotNull(cookies);
assertEquals(1, cookies.size());
Assert.assertNotNull(cookies);
Assert.assertEquals(1, cookies.size());
Cookie cookie = cookies.get(0);
Calendar c = Calendar.getInstance();
c.setTimeZone(TimeZone.getTimeZone("GMT"));
c.setTime(cookie.getExpiryDate());
int year = c.get(Calendar.YEAR);
assertEquals(2070, year);
Assert.assertEquals(2070, year);
}
/**
* Invalid expire attribute.
*/
@Test
public void testNetscapeCookieInvalidExpireAttribute() throws Exception {
CookieSpec cookiespec = new NetscapeDraftSpec();
CookieOrigin origin = new CookieOrigin("myhost.mydomain.com", 80, "/", false);
@ -207,7 +202,7 @@ public class TestCookieNetscapeDraft extends TestCase {
try {
List<Cookie> cookies = cookiespec.parse(header, origin);
cookiespec.validate(cookies.get(0), origin);
fail("MalformedCookieException exception should have been thrown");
Assert.fail("MalformedCookieException exception should have been thrown");
} catch (MalformedCookieException e) {
// expected
}
@ -216,6 +211,7 @@ public class TestCookieNetscapeDraft extends TestCase {
/**
* Tests Netscape specific expire attribute without a time zone.
*/
@Test
public void testNetscapeCookieExpireAttributeNoTimeZone() throws Exception {
CookieSpec cookiespec = new NetscapeDraftSpec();
Header header = new BasicHeader("Set-Cookie",
@ -223,7 +219,7 @@ public class TestCookieNetscapeDraft extends TestCase {
CookieOrigin origin = new CookieOrigin("myhost.mydomain.com", 80, "/", false);
try {
cookiespec.parse(header, origin);
fail("MalformedCookieException should have been thrown");
Assert.fail("MalformedCookieException should have been thrown");
} catch (MalformedCookieException ex) {
// expected
}
@ -232,17 +228,19 @@ public class TestCookieNetscapeDraft extends TestCase {
/**
* Tests if cookie values with embedded comma are handled correctly.
*/
@Test
public void testCookieWithComma() throws Exception {
Header header = new BasicHeader("Set-Cookie", "a=b,c");
CookieSpec cookiespec = new NetscapeDraftSpec();
CookieOrigin origin = new CookieOrigin("localhost", 80, "/", false);
List<Cookie> cookies = cookiespec.parse(header, origin);
assertEquals("number of cookies", 1, cookies.size());
assertEquals("a", cookies.get(0).getName());
assertEquals("b,c", cookies.get(0).getValue());
Assert.assertEquals("number of cookies", 1, cookies.size());
Assert.assertEquals("a", cookies.get(0).getName());
Assert.assertEquals("b,c", cookies.get(0).getValue());
}
@Test
public void testFormatCookies() throws Exception {
BasicClientCookie c1 = new BasicClientCookie("name1", "value1");
c1.setDomain(".whatever.com");
@ -259,35 +257,36 @@ public class TestCookieNetscapeDraft extends TestCase {
cookies.add(c2);
cookies.add(c3);
List<Header> headers = cookiespec.formatCookies(cookies);
assertNotNull(headers);
assertEquals(1, headers.size());
assertEquals("name1=value1; name2=value2; name3", headers.get(0).getValue());
Assert.assertNotNull(headers);
Assert.assertEquals(1, headers.size());
Assert.assertEquals("name1=value1; name2=value2; name3", headers.get(0).getValue());
}
@Test
public void testInvalidInput() throws Exception {
CookieSpec cookiespec = new NetscapeDraftSpec();
try {
cookiespec.parse(null, null);
fail("IllegalArgumentException must have been thrown");
Assert.fail("IllegalArgumentException must have been thrown");
} catch (IllegalArgumentException ex) {
// expected
}
try {
cookiespec.parse(new BasicHeader("Set-Cookie", "name=value"), null);
fail("IllegalArgumentException must have been thrown");
Assert.fail("IllegalArgumentException must have been thrown");
} catch (IllegalArgumentException ex) {
// expected
}
try {
cookiespec.formatCookies(null);
fail("IllegalArgumentException must have been thrown");
Assert.fail("IllegalArgumentException must have been thrown");
} catch (IllegalArgumentException ex) {
// expected
}
try {
List<Cookie> cookies = new ArrayList<Cookie>();
cookiespec.formatCookies(cookies);
fail("IllegalArgumentException must have been thrown");
Assert.fail("IllegalArgumentException must have been thrown");
} catch (IllegalArgumentException ex) {
// expected
}

View File

@ -30,10 +30,6 @@ package org.apache.http.impl.cookie;
import java.util.ArrayList;
import java.util.List;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.apache.http.Header;
import org.apache.http.cookie.ClientCookie;
import org.apache.http.cookie.Cookie;
@ -41,34 +37,22 @@ import org.apache.http.cookie.CookieOrigin;
import org.apache.http.cookie.CookieSpec;
import org.apache.http.cookie.MalformedCookieException;
import org.apache.http.message.BasicHeader;
import org.junit.Assert;
import org.junit.Test;
/**
* Test cases for RFC2109 cookie spec
*
*
*/
public class TestCookieRFC2109Spec extends TestCase {
// ------------------------------------------------------------ Constructor
public TestCookieRFC2109Spec(String name) {
super(name);
}
// ------------------------------------------------------- TestCase Methods
public static Test suite() {
return new TestSuite(TestCookieRFC2109Spec.class);
}
public class TestCookieRFC2109Spec {
@Test
public void testConstructor() throws Exception {
new RFC2109Spec();
new RFC2109Spec(null, false);
new RFC2109Spec(new String[] { DateUtils.PATTERN_RFC1036 }, false);
}
@Test
public void testParseVersion() throws Exception {
Header header = new BasicHeader("Set-Cookie","cookie-name=cookie-value; version=1");
@ -78,15 +62,16 @@ public class TestCookieRFC2109Spec extends TestCase {
for (int i = 0; i < cookies.size(); i++) {
cookiespec.validate(cookies.get(i), origin);
}
assertEquals("Found 1 cookie.",1,cookies.size());
assertEquals("Name","cookie-name",cookies.get(0).getName());
assertEquals("Value","cookie-value",cookies.get(0).getValue());
assertEquals("Version",1,cookies.get(0).getVersion());
Assert.assertEquals("Found 1 cookie.",1,cookies.size());
Assert.assertEquals("Name","cookie-name",cookies.get(0).getName());
Assert.assertEquals("Value","cookie-value",cookies.get(0).getValue());
Assert.assertEquals("Version",1,cookies.get(0).getVersion());
}
/**
* Test domain equals host
*/
@Test
public void testCookiesomainEqualsHost() throws Exception {
Header header = new BasicHeader("Set-Cookie",
"cookie-name=cookie-value; domain=www.b.com; version=1");
@ -97,14 +82,15 @@ public class TestCookieRFC2109Spec extends TestCase {
for (int i = 0; i < cookies.size(); i++) {
cookiespec.validate(cookies.get(i), origin);
}
assertNotNull(cookies);
assertEquals(1, cookies.size());
assertEquals("www.b.com", cookies.get(0).getDomain());
Assert.assertNotNull(cookies);
Assert.assertEquals(1, cookies.size());
Assert.assertEquals("www.b.com", cookies.get(0).getDomain());
}
/**
* Domain does not start with a dot
*/
@Test
public void testParseWithIllegalDomain1() throws Exception {
Header header = new BasicHeader("Set-Cookie",
"cookie-name=cookie-value; domain=a.b.com; version=1");
@ -116,7 +102,7 @@ public class TestCookieRFC2109Spec extends TestCase {
for (int i = 0; i < cookies.size(); i++) {
cookiespec.validate(cookies.get(i), origin);
}
fail("MalformedCookieException should have been thrown");
Assert.fail("MalformedCookieException should have been thrown");
} catch (MalformedCookieException e) {
// expected
}
@ -125,6 +111,7 @@ public class TestCookieRFC2109Spec extends TestCase {
/**
* Domain must have alt least one embedded dot
*/
@Test
public void testParseWithIllegalDomain2() throws Exception {
Header header = new BasicHeader("Set-Cookie",
"cookie-name=cookie-value; domain=.com; version=1");
@ -136,7 +123,7 @@ public class TestCookieRFC2109Spec extends TestCase {
for (int i = 0; i < cookies.size(); i++) {
cookiespec.validate(cookies.get(i), origin);
}
fail("MalformedCookieException should have been thrown");
Assert.fail("MalformedCookieException should have been thrown");
} catch (MalformedCookieException e) {
// expected
}
@ -145,6 +132,7 @@ public class TestCookieRFC2109Spec extends TestCase {
/**
* Host minus domain may not contain any dots
*/
@Test
public void testParseWithIllegalDomain4() throws Exception {
Header header = new BasicHeader("Set-Cookie",
"cookie-name=cookie-value; domain=.c.com; version=1");
@ -156,7 +144,7 @@ public class TestCookieRFC2109Spec extends TestCase {
for (int i = 0; i < cookies.size(); i++) {
cookiespec.validate(cookies.get(i), origin);
}
fail("MalformedCookieException should have been thrown");
Assert.fail("MalformedCookieException should have been thrown");
} catch (MalformedCookieException e) {
// expected
}
@ -167,6 +155,7 @@ public class TestCookieRFC2109Spec extends TestCase {
* rejected in the strict mode, but gets accepted in the
* browser compatibility mode.
*/
@Test
public void testSecondDomainLevelCookie() throws Exception {
BasicClientCookie cookie = new BasicClientCookie("name", null);
cookie.setDomain(".sourceforge.net");
@ -178,12 +167,13 @@ public class TestCookieRFC2109Spec extends TestCase {
CookieOrigin origin = new CookieOrigin("sourceforge.net", 80, "/", false);
try {
cookiespec.validate(cookie, origin);
fail("MalformedCookieException should have been thrown");
Assert.fail("MalformedCookieException should have been thrown");
} catch (MalformedCookieException e) {
// Expected
}
}
@Test
public void testSecondDomainLevelCookieMatch() throws Exception {
BasicClientCookie cookie = new BasicClientCookie("name", null);
cookie.setDomain(".sourceforge.net");
@ -193,9 +183,10 @@ public class TestCookieRFC2109Spec extends TestCase {
CookieSpec cookiespec = new RFC2109Spec();
CookieOrigin origin = new CookieOrigin("sourceforge.net", 80, "/", false);
assertFalse(cookiespec.match(cookie, origin));
Assert.assertFalse(cookiespec.match(cookie, origin));
}
@Test
public void testParseWithWrongPath() throws Exception {
Header header = new BasicHeader("Set-Cookie",
"cookie-name=cookie-value; domain=127.0.0.1; path=/not/just/root");
@ -207,7 +198,7 @@ public class TestCookieRFC2109Spec extends TestCase {
for (int i = 0; i < cookies.size(); i++) {
cookiespec.validate(cookies.get(i), origin);
}
fail("MalformedCookieException exception should have been thrown");
Assert.fail("MalformedCookieException exception should have been thrown");
} catch (MalformedCookieException e) {
// expected
}
@ -216,6 +207,7 @@ public class TestCookieRFC2109Spec extends TestCase {
/**
* Tests if cookie constructor rejects cookie name containing blanks.
*/
@Test
public void testCookieNameWithBlanks() throws Exception {
Header setcookie = new BasicHeader("Set-Cookie", "invalid name=");
CookieSpec cookiespec = new RFC2109Spec();
@ -225,7 +217,7 @@ public class TestCookieRFC2109Spec extends TestCase {
for (int i = 0; i < cookies.size(); i++) {
cookiespec.validate(cookies.get(i), origin);
}
fail("MalformedCookieException exception should have been thrown");
Assert.fail("MalformedCookieException exception should have been thrown");
} catch (MalformedCookieException e) {
// expected
}
@ -234,6 +226,7 @@ public class TestCookieRFC2109Spec extends TestCase {
/**
* Tests if cookie constructor rejects cookie name starting with $.
*/
@Test
public void testCookieNameStartingWithDollarSign() throws Exception {
Header setcookie = new BasicHeader("Set-Cookie", "$invalid_name=");
CookieSpec cookiespec = new RFC2109Spec();
@ -243,7 +236,7 @@ public class TestCookieRFC2109Spec extends TestCase {
for (int i = 0; i < cookies.size(); i++) {
cookiespec.validate(cookies.get(i), origin);
}
fail("MalformedCookieException exception should have been thrown");
Assert.fail("MalformedCookieException exception should have been thrown");
} catch (MalformedCookieException e) {
// expected
}
@ -253,6 +246,7 @@ public class TestCookieRFC2109Spec extends TestCase {
* Tests if default cookie validator rejects cookies originating from a host without domain
* where domain attribute does not match the host of origin
*/
@Test
public void testInvalidDomainWithSimpleHostName() throws Exception {
CookieSpec cookiespec = new RFC2109Spec();
Header header = new BasicHeader("Set-Cookie",
@ -261,7 +255,7 @@ public class TestCookieRFC2109Spec extends TestCase {
List<Cookie> cookies = cookiespec.parse(header, origin1);
try {
cookiespec.validate(cookies.get(0), origin1);
fail("MalformedCookieException must have thrown");
Assert.fail("MalformedCookieException must have thrown");
}
catch(MalformedCookieException expected) {
}
@ -271,7 +265,7 @@ public class TestCookieRFC2109Spec extends TestCase {
cookies = cookiespec.parse(header, origin2);
try {
cookiespec.validate(cookies.get(0), origin2);
fail("MalformedCookieException must have thrown");
Assert.fail("MalformedCookieException must have thrown");
}
catch(MalformedCookieException expected) {
}
@ -280,22 +274,24 @@ public class TestCookieRFC2109Spec extends TestCase {
/**
* Tests if cookie values with embedded comma are handled correctly.
*/
@Test
public void testCookieWithComma() throws Exception {
Header header = new BasicHeader("Set-Cookie", "a=b,c");
CookieSpec cookiespec = new RFC2109Spec();
CookieOrigin origin = new CookieOrigin("localhost", 80, "/", false);
List<Cookie> cookies = cookiespec.parse(header, origin);
assertEquals("number of cookies", 2, cookies.size());
assertEquals("a", cookies.get(0).getName());
assertEquals("b", cookies.get(0).getValue());
assertEquals("c", cookies.get(1).getName());
assertEquals(null, cookies.get(1).getValue());
Assert.assertEquals("number of cookies", 2, cookies.size());
Assert.assertEquals("a", cookies.get(0).getName());
Assert.assertEquals("b", cookies.get(0).getValue());
Assert.assertEquals("c", cookies.get(1).getName());
Assert.assertEquals(null, cookies.get(1).getValue());
}
/**
* Tests RFC 2109 compiant cookie formatting.
*/
@Test
public void testRFC2109CookieFormatting() throws Exception {
CookieSpec cookiespec = new RFC2109Spec(null, false);
Header header = new BasicHeader("Set-Cookie",
@ -304,9 +300,9 @@ public class TestCookieRFC2109Spec extends TestCase {
List<Cookie> cookies = cookiespec.parse(header, origin);
cookiespec.validate(cookies.get(0), origin);
List<Header> headers = cookiespec.formatCookies(cookies);
assertNotNull(headers);
assertEquals(1, headers.size());
assertEquals("$Version=1; name=\"value\"; $Path=\"/\"; $Domain=\".mydomain.com\"",
Assert.assertNotNull(headers);
Assert.assertEquals(1, headers.size());
Assert.assertEquals("$Version=1; name=\"value\"; $Path=\"/\"; $Domain=\".mydomain.com\"",
headers.get(0).getValue());
header = new BasicHeader( "Set-Cookie",
@ -314,12 +310,13 @@ public class TestCookieRFC2109Spec extends TestCase {
cookies = cookiespec.parse(header, origin);
cookiespec.validate(cookies.get(0), origin);
headers = cookiespec.formatCookies(cookies);
assertNotNull(headers);
assertEquals(1, headers.size());
assertEquals("$Version=0; name=value; $Path=/; $Domain=.mydomain.com",
Assert.assertNotNull(headers);
Assert.assertEquals(1, headers.size());
Assert.assertEquals("$Version=0; name=value; $Path=/; $Domain=.mydomain.com",
headers.get(0).getValue());
}
@Test
public void testRFC2109CookiesFormatting() throws Exception {
CookieSpec cookiespec = new RFC2109Spec(null, true);
Header header = new BasicHeader("Set-Cookie",
@ -330,12 +327,12 @@ public class TestCookieRFC2109Spec extends TestCase {
for (int i = 0; i < cookies.size(); i++) {
cookiespec.validate(cookies.get(i), origin);
}
assertNotNull(cookies);
assertEquals(2, cookies.size());
Assert.assertNotNull(cookies);
Assert.assertEquals(2, cookies.size());
List<Header> headers = cookiespec.formatCookies(cookies);
assertNotNull(headers);
assertEquals(1, headers.size());
assertEquals(
Assert.assertNotNull(headers);
Assert.assertEquals(1, headers.size());
Assert.assertEquals(
"$Version=0; name1=value1; $Path=/; $Domain=.mydomain.com; " +
"name2=value2; $Path=/; $Domain=.mydomain.com",
headers.get(0).getValue());
@ -347,10 +344,10 @@ public class TestCookieRFC2109Spec extends TestCase {
for (int i = 0; i < cookies.size(); i++) {
cookiespec.validate(cookies.get(i), origin);
}
assertNotNull(cookies);
assertEquals(2, cookies.size());
Assert.assertNotNull(cookies);
Assert.assertEquals(2, cookies.size());
headers = cookiespec.formatCookies(cookies);
assertEquals(
Assert.assertEquals(
"$Version=1; name1=\"value1\"; $Path=\"/\"; $Domain=\".mydomain.com\"; " +
"name2=\"value2\"; $Path=\"/\"; $Domain=\".mydomain.com\"",
headers.get(0).getValue());
@ -359,6 +356,7 @@ public class TestCookieRFC2109Spec extends TestCase {
/**
* Tests if null cookie values are handled correctly.
*/
@Test
public void testNullCookieValueFormatting() {
BasicClientCookie cookie = new BasicClientCookie("name", null);
cookie.setDomain(".whatever.com");
@ -370,21 +368,22 @@ public class TestCookieRFC2109Spec extends TestCase {
List<Cookie> cookies = new ArrayList<Cookie>();
cookies.add(cookie);
List<Header> headers = cookiespec.formatCookies(cookies);
assertNotNull(headers);
assertEquals(1, headers.size());
assertEquals("$Version=0; name=; $Path=/; $Domain=.whatever.com",
Assert.assertNotNull(headers);
Assert.assertEquals(1, headers.size());
Assert.assertEquals("$Version=0; name=; $Path=/; $Domain=.whatever.com",
headers.get(0).getValue());
cookie.setVersion(1);
cookies = new ArrayList<Cookie>();
cookies.add(cookie);
headers = cookiespec.formatCookies(cookies);
assertNotNull(headers);
assertEquals(1, headers.size());
assertEquals("$Version=1; name=; $Path=\"/\"; $Domain=\".whatever.com\"",
Assert.assertNotNull(headers);
Assert.assertEquals(1, headers.size());
Assert.assertEquals("$Version=1; name=; $Path=\"/\"; $Domain=\".whatever.com\"",
headers.get(0).getValue());
}
@Test
public void testCookieNullDomainNullPathFormatting() {
BasicClientCookie cookie = new BasicClientCookie("name", null);
cookie.setPath("/");
@ -394,20 +393,21 @@ public class TestCookieRFC2109Spec extends TestCase {
List<Cookie> cookies = new ArrayList<Cookie>();
cookies.add(cookie);
List<Header> headers = cookiespec.formatCookies(cookies);
assertNotNull(headers);
assertEquals(1, headers.size());
assertEquals("$Version=0; name=; $Path=/", headers.get(0).getValue());
Assert.assertNotNull(headers);
Assert.assertEquals(1, headers.size());
Assert.assertEquals("$Version=0; name=; $Path=/", headers.get(0).getValue());
cookie.setAttribute(ClientCookie.DOMAIN_ATTR, null);
cookie.setAttribute(ClientCookie.PATH_ATTR, null);
cookies = new ArrayList<Cookie>();
cookies.add(cookie);
headers = cookiespec.formatCookies(cookies);
assertNotNull(headers);
assertEquals(1, headers.size());
assertEquals("$Version=0; name=", headers.get(0).getValue());
Assert.assertNotNull(headers);
Assert.assertEquals(1, headers.size());
Assert.assertEquals("$Version=0; name=", headers.get(0).getValue());
}
@Test
public void testCookieOrderingByPath() {
BasicClientCookie c1 = new BasicClientCookie("name1", "value1");
c1.setPath("/a/b/c");
@ -429,44 +429,45 @@ public class TestCookieRFC2109Spec extends TestCase {
cookies.add(c1);
cookies.add(c3);
List<Header> headers = cookiespec.formatCookies(cookies);
assertNotNull(headers);
assertEquals(1, headers.size());
assertEquals("$Version=0; name1=value1; $Path=/a/b/c; " +
Assert.assertNotNull(headers);
Assert.assertEquals(1, headers.size());
Assert.assertEquals("$Version=0; name1=value1; $Path=/a/b/c; " +
"name2=value2; $Path=/a/b; " +
"name3=value3; $Path=/a; " +
"name4=value4; $Path=/", headers.get(0).getValue());
}
@Test
public void testInvalidInput() throws Exception {
CookieSpec cookiespec = new RFC2109Spec();
try {
cookiespec.parse(null, null);
fail("IllegalArgumentException must have been thrown");
Assert.fail("IllegalArgumentException must have been thrown");
} catch (IllegalArgumentException ex) {
// expected
}
try {
cookiespec.parse(new BasicHeader("Set-Cookie", "name=value"), null);
fail("IllegalArgumentException must have been thrown");
Assert.fail("IllegalArgumentException must have been thrown");
} catch (IllegalArgumentException ex) {
// expected
}
try {
cookiespec.validate(null, null);
fail("IllegalArgumentException must have been thrown");
Assert.fail("IllegalArgumentException must have been thrown");
} catch (IllegalArgumentException ex) {
// expected
}
try {
cookiespec.formatCookies(null);
fail("IllegalArgumentException must have been thrown");
Assert.fail("IllegalArgumentException must have been thrown");
} catch (IllegalArgumentException ex) {
// expected
}
try {
List<Cookie> cookies = new ArrayList<Cookie>();
cookiespec.formatCookies(cookies);
fail("IllegalArgumentException must have been thrown");
Assert.fail("IllegalArgumentException must have been thrown");
} catch (IllegalArgumentException ex) {
// expected
}

View File

@ -30,29 +30,15 @@ package org.apache.http.impl.cookie;
import java.util.Calendar;
import java.util.Date;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.junit.Assert;
import org.junit.Test;
/**
* Unit tests for {@link DateUtils}.
*
*/
public class TestDateUtils extends TestCase {
public TestDateUtils(String testName) {
super(testName);
}
public static void main(String args[]) {
String[] testCaseName = { TestDateUtils.class.getName() };
junit.textui.TestRunner.main(testCaseName);
}
public static Test suite() {
return new TestSuite(TestDateUtils.class);
}
public class TestDateUtils {
@Test
public void testBasicDateParse() throws Exception {
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(DateUtils.GMT);
@ -64,40 +50,42 @@ public class TestDateUtils extends TestCase {
DateUtils.PATTERN_RFC1123
};
Date date2 = DateUtils.parseDate("Fri, 14 Oct 2005 00:00:00 GMT", formats, null);
assertEquals(date1, date2);
Assert.assertEquals(date1, date2);
date2 = DateUtils.parseDate("Fri, 14 Oct 2005 00:00:00 GMT", formats);
assertEquals(date1, date2);
Assert.assertEquals(date1, date2);
date2 = DateUtils.parseDate("Fri, 14 Oct 2005 00:00:00 GMT");
assertEquals(date1, date2);
Assert.assertEquals(date1, date2);
}
@Test
public void testInvalidInput() throws Exception {
try {
DateUtils.parseDate(null, null, null);
fail("IllegalArgumentException should habe been thrown");
Assert.fail("IllegalArgumentException should habe been thrown");
} catch (IllegalArgumentException ex) {
// expected
}
try {
DateUtils.parseDate("Fri, 14 Oct 2005 00:00:00 GMT", new String[] {}, null);
fail("DateParseException should habe been thrown");
Assert.fail("DateParseException should habe been thrown");
} catch (DateParseException ex) {
// expected
}
try {
DateUtils.formatDate(null);
fail("IllegalArgumentException should habe been thrown");
Assert.fail("IllegalArgumentException should habe been thrown");
} catch (IllegalArgumentException ex) {
// expected
}
try {
DateUtils.formatDate(new Date(), null);
fail("IllegalArgumentException should habe been thrown");
Assert.fail("IllegalArgumentException should habe been thrown");
} catch (IllegalArgumentException ex) {
// expected
}
}
@Test
public void testTwoDigitYearDateParse() throws Exception {
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(DateUtils.GMT);
@ -109,7 +97,7 @@ public class TestDateUtils extends TestCase {
DateUtils.PATTERN_RFC1036
};
Date date2 = DateUtils.parseDate("Friday, 14-Oct-05 00:00:00 GMT", formats, null);
assertEquals(date1, date2);
Assert.assertEquals(date1, date2);
calendar.set(1900, Calendar.JANUARY, 0, 0, 0, 0);
calendar.set(Calendar.MILLISECOND, 0);
@ -120,9 +108,10 @@ public class TestDateUtils extends TestCase {
date1 = calendar.getTime();
date2 = DateUtils.parseDate("Friday, 14-Oct-05 00:00:00 GMT", formats, startDate);
assertEquals(date1, date2);
Assert.assertEquals(date1, date2);
}
@Test
public void testParseQuotedDate() throws Exception {
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(DateUtils.GMT);
@ -134,9 +123,10 @@ public class TestDateUtils extends TestCase {
DateUtils.PATTERN_RFC1123
};
Date date2 = DateUtils.parseDate("'Fri, 14 Oct 2005 00:00:00 GMT'", formats);
assertEquals(date1, date2);
Assert.assertEquals(date1, date2);
}
@Test
public void testBasicDateFormat() throws Exception {
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(DateUtils.GMT);
@ -144,10 +134,11 @@ public class TestDateUtils extends TestCase {
calendar.set(Calendar.MILLISECOND, 0);
Date date = calendar.getTime();
assertEquals("Fri, 14 Oct 2005 00:00:00 GMT", DateUtils.formatDate(date));
assertEquals("Fri, 14 Oct 2005 00:00:00 GMT", DateUtils.formatDate(date, DateUtils.PATTERN_RFC1123));
Assert.assertEquals("Fri, 14 Oct 2005 00:00:00 GMT", DateUtils.formatDate(date));
Assert.assertEquals("Fri, 14 Oct 2005 00:00:00 GMT", DateUtils.formatDate(date, DateUtils.PATTERN_RFC1123));
}
@Test
public void testConstructor() {
new DateParseException();
new DateParseException("Oppsie");

View File

@ -27,30 +27,15 @@
package org.apache.http.impl.cookie;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.apache.http.cookie.CookieAttributeHandler;
import org.apache.http.cookie.CookieOrigin;
import org.apache.http.cookie.MalformedCookieException;
import org.junit.Assert;
import org.junit.Test;
public class TestNetscapeCookieAttribHandlers extends TestCase {
public TestNetscapeCookieAttribHandlers(String testName) {
super(testName);
}
public static Test suite() {
return new TestSuite(TestNetscapeCookieAttribHandlers.class);
}
// ------------------------------------------------------------------- Main
public static void main(String args[]) {
String[] testCaseName = { TestNetscapeCookieAttribHandlers.class.getName() };
junit.textui.TestRunner.main(testCaseName);
}
public class TestNetscapeCookieAttribHandlers {
@Test
public void testNetscapeDomainValidate1() throws Exception {
BasicClientCookie cookie = new BasicClientCookie("name", "value");
CookieOrigin origin = new CookieOrigin("somehost", 80, "/", false);
@ -62,12 +47,13 @@ public class TestNetscapeCookieAttribHandlers extends TestCase {
cookie.setDomain("otherhost");
try {
h.validate(cookie, origin);
fail("MalformedCookieException should have been thrown");
Assert.fail("MalformedCookieException should have been thrown");
} catch (MalformedCookieException ex) {
// expected
}
}
@Test
public void testNetscapeDomainValidate2() throws Exception {
BasicClientCookie cookie = new BasicClientCookie("name", "value");
CookieOrigin origin = new CookieOrigin("www.somedomain.com", 80, "/", false);
@ -79,19 +65,20 @@ public class TestNetscapeCookieAttribHandlers extends TestCase {
cookie.setDomain(".otherdomain.com");
try {
h.validate(cookie, origin);
fail("MalformedCookieException should have been thrown");
Assert.fail("MalformedCookieException should have been thrown");
} catch (MalformedCookieException ex) {
// expected
}
cookie.setDomain("www.otherdomain.com");
try {
h.validate(cookie, origin);
fail("MalformedCookieException should have been thrown");
Assert.fail("MalformedCookieException should have been thrown");
} catch (MalformedCookieException ex) {
// expected
}
}
@Test
public void testNetscapeDomainValidate3() throws Exception {
BasicClientCookie cookie = new BasicClientCookie("name", "value");
CookieOrigin origin = new CookieOrigin("www.a.com", 80, "/", false);
@ -103,12 +90,13 @@ public class TestNetscapeCookieAttribHandlers extends TestCase {
cookie.setDomain(".com");
try {
h.validate(cookie, origin);
fail("MalformedCookieException should have been thrown");
Assert.fail("MalformedCookieException should have been thrown");
} catch (MalformedCookieException ex) {
// expected
}
}
@Test
public void testNetscapeDomainValidate4() throws Exception {
BasicClientCookie cookie = new BasicClientCookie("name", "value");
CookieOrigin origin = new CookieOrigin("www.a.b.c", 80, "/", false);
@ -120,44 +108,47 @@ public class TestNetscapeCookieAttribHandlers extends TestCase {
cookie.setDomain(".b.c");
try {
h.validate(cookie, origin);
fail("MalformedCookieException should have been thrown");
Assert.fail("MalformedCookieException should have been thrown");
} catch (MalformedCookieException ex) {
// expected
}
}
@Test
public void testNetscapeDomainMatch1() throws Exception {
BasicClientCookie cookie = new BasicClientCookie("name", "value");
CookieOrigin origin = new CookieOrigin("www.somedomain.com", 80, "/", false);
CookieAttributeHandler h = new NetscapeDomainHandler();
cookie.setDomain(null);
assertFalse(h.match(cookie, origin));
Assert.assertFalse(h.match(cookie, origin));
cookie.setDomain(".somedomain.com");
assertTrue(h.match(cookie, origin));
Assert.assertTrue(h.match(cookie, origin));
}
@Test
public void testNetscapeDomainMatch2() throws Exception {
BasicClientCookie cookie = new BasicClientCookie("name", "value");
CookieOrigin origin = new CookieOrigin("www.whatever.somedomain.com", 80, "/", false);
CookieAttributeHandler h = new NetscapeDomainHandler();
cookie.setDomain(".somedomain.com");
assertTrue(h.match(cookie, origin));
Assert.assertTrue(h.match(cookie, origin));
}
@Test
public void testNetscapeDomainInvalidInput() throws Exception {
CookieAttributeHandler h = new NetscapeDomainHandler();
try {
h.match(null, null);
fail("IllegalArgumentException must have been thrown");
Assert.fail("IllegalArgumentException must have been thrown");
} catch (IllegalArgumentException ex) {
// expected
}
try {
h.match(new BasicClientCookie("name", "value"), null);
fail("IllegalArgumentException must have been thrown");
Assert.fail("IllegalArgumentException must have been thrown");
} catch (IllegalArgumentException ex) {
// expected
}

View File

@ -31,30 +31,15 @@ import org.apache.http.HeaderElement;
import org.apache.http.NameValuePair;
import org.apache.http.message.ParserCursor;
import org.apache.http.util.CharArrayBuffer;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.junit.Assert;
import org.junit.Test;
/**
* Unit tests for {@link NetscapeDraftHeaderParser}.
*
*/
public class TestNetscapeDraftHeaderParser extends TestCase {
public TestNetscapeDraftHeaderParser(String testName) {
super(testName);
}
public static void main(String args[]) {
String[] testCaseName = { TestNetscapeDraftHeaderParser.class.getName() };
junit.textui.TestRunner.main(testCaseName);
}
public static Test suite() {
return new TestSuite(TestNetscapeDraftHeaderParser.class);
}
public class TestNetscapeDraftHeaderParser {
@Test
public void testNetscapeCookieParsing() throws Exception {
NetscapeDraftHeaderParser parser = NetscapeDraftHeaderParser.DEFAULT;
@ -65,27 +50,27 @@ public class TestNetscapeDraftHeaderParser extends TestCase {
ParserCursor cursor = new ParserCursor(0, s.length());
HeaderElement he = parser.parseHeader(buffer, cursor);
assertEquals("name", he.getName());
assertEquals("value", he.getValue());
Assert.assertEquals("name", he.getName());
Assert.assertEquals("value", he.getValue());
NameValuePair[] params = he.getParameters();
assertEquals("test", params[0].getName());
assertEquals(null, params[0].getValue());
assertEquals("test1", params[1].getName());
assertEquals("stuff,with,commas", params[1].getValue());
assertEquals("test2", params[2].getName());
assertEquals("stuff; stuff", params[2].getValue());
assertEquals("test3", params[3].getName());
assertEquals("\"stuff", params[3].getValue());
assertEquals(s.length(), cursor.getPos());
assertTrue(cursor.atEnd());
Assert.assertEquals("test", params[0].getName());
Assert.assertEquals(null, params[0].getValue());
Assert.assertEquals("test1", params[1].getName());
Assert.assertEquals("stuff,with,commas", params[1].getValue());
Assert.assertEquals("test2", params[2].getName());
Assert.assertEquals("stuff; stuff", params[2].getValue());
Assert.assertEquals("test3", params[3].getName());
Assert.assertEquals("\"stuff", params[3].getValue());
Assert.assertEquals(s.length(), cursor.getPos());
Assert.assertTrue(cursor.atEnd());
s = " ";
buffer = new CharArrayBuffer(16);
buffer.append(s);
cursor = new ParserCursor(0, s.length());
he = parser.parseHeader(buffer, cursor);
assertEquals("", he.getName());
assertEquals(null, he.getValue());
Assert.assertEquals("", he.getName());
Assert.assertEquals(null, he.getValue());
}
}

View File

@ -1,8 +1,4 @@
/*
* $HeadURL$
* $Revision$
* $Date$
*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@ -31,85 +27,75 @@
package org.apache.http.impl.cookie;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import junit.framework.Assert;
import org.apache.http.cookie.CookieOrigin;
import org.junit.Before;
import org.junit.Test;
public class TestPublicSuffixListParser extends TestCase {
public class TestPublicSuffixListParser {
private static final String LIST_FILE = "/suffixlist.txt";
private PublicSuffixFilter filter;
public TestPublicSuffixListParser(String testName) {
super(testName);
try {
Reader r = new InputStreamReader(getClass().getResourceAsStream(LIST_FILE), "UTF-8");
filter = new PublicSuffixFilter(new RFC2109DomainHandler());
PublicSuffixListParser parser = new PublicSuffixListParser(filter);
parser.parse(r);
} catch (IOException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
public static Test suite() {
return new TestSuite(TestPublicSuffixListParser.class);
}
public static void main(String args[]) {
String[] testCaseName = { TestPublicSuffixListParser.class.getName() };
junit.textui.TestRunner.main(testCaseName);
@Before
public void setUp() throws Exception {
Reader r = new InputStreamReader(getClass().getResourceAsStream(LIST_FILE), "UTF-8");
filter = new PublicSuffixFilter(new RFC2109DomainHandler());
PublicSuffixListParser parser = new PublicSuffixListParser(filter);
parser.parse(r);
}
@Test
public void testParse() throws Exception {
BasicClientCookie cookie = new BasicClientCookie("name", "value");
cookie.setDomain(".jp");
assertFalse(filter.match(cookie, new CookieOrigin("apache.jp", 80, "/stuff", false)));
Assert.assertFalse(filter.match(cookie, new CookieOrigin("apache.jp", 80, "/stuff", false)));
cookie.setDomain(".ac.jp");
assertFalse(filter.match(cookie, new CookieOrigin("apache.ac.jp", 80, "/stuff", false)));
Assert.assertFalse(filter.match(cookie, new CookieOrigin("apache.ac.jp", 80, "/stuff", false)));
cookie.setDomain(".any.tokyo.jp");
assertFalse(filter.match(cookie, new CookieOrigin("apache.any.tokyo.jp", 80, "/stuff", false)));
Assert.assertFalse(filter.match(cookie, new CookieOrigin("apache.any.tokyo.jp", 80, "/stuff", false)));
// exception
cookie.setDomain(".metro.tokyo.jp");
assertTrue(filter.match(cookie, new CookieOrigin("apache.metro.tokyo.jp", 80, "/stuff", false)));
Assert.assertTrue(filter.match(cookie, new CookieOrigin("apache.metro.tokyo.jp", 80, "/stuff", false)));
}
@Test
public void testUnicode() throws Exception {
BasicClientCookie cookie = new BasicClientCookie("name", "value");
cookie.setDomain(".h\u00E5.no"); // \u00E5 is <aring>
assertFalse(filter.match(cookie, new CookieOrigin("apache.h\u00E5.no", 80, "/stuff", false)));
Assert.assertFalse(filter.match(cookie, new CookieOrigin("apache.h\u00E5.no", 80, "/stuff", false)));
cookie.setDomain(".xn--h-2fa.no");
assertFalse(filter.match(cookie, new CookieOrigin("apache.xn--h-2fa.no", 80, "/stuff", false)));
Assert.assertFalse(filter.match(cookie, new CookieOrigin("apache.xn--h-2fa.no", 80, "/stuff", false)));
cookie.setDomain(".h\u00E5.no");
assertFalse(filter.match(cookie, new CookieOrigin("apache.xn--h-2fa.no", 80, "/stuff", false)));
Assert.assertFalse(filter.match(cookie, new CookieOrigin("apache.xn--h-2fa.no", 80, "/stuff", false)));
cookie.setDomain(".xn--h-2fa.no");
assertFalse(filter.match(cookie, new CookieOrigin("apache.h\u00E5.no", 80, "/stuff", false)));
Assert.assertFalse(filter.match(cookie, new CookieOrigin("apache.h\u00E5.no", 80, "/stuff", false)));
}
@Test
public void testWhitespace() throws Exception {
BasicClientCookie cookie = new BasicClientCookie("name", "value");
cookie.setDomain(".xx");
assertFalse(filter.match(cookie, new CookieOrigin("apache.xx", 80, "/stuff", false)));
Assert.assertFalse(filter.match(cookie, new CookieOrigin("apache.xx", 80, "/stuff", false)));
// yy appears after whitespace
cookie.setDomain(".yy");
assertTrue(filter.match(cookie, new CookieOrigin("apache.yy", 80, "/stuff", false)));
Assert.assertTrue(filter.match(cookie, new CookieOrigin("apache.yy", 80, "/stuff", false)));
// zz is commented
cookie.setDomain(".zz");
assertTrue(filter.match(cookie, new CookieOrigin("apache.zz", 80, "/stuff", false)));
Assert.assertTrue(filter.match(cookie, new CookieOrigin("apache.zz", 80, "/stuff", false)));
}
}

View File

@ -27,51 +27,37 @@
package org.apache.http.impl.cookie;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.apache.http.cookie.CookieAttributeHandler;
import org.apache.http.cookie.CookieOrigin;
import org.apache.http.cookie.MalformedCookieException;
import org.junit.Assert;
import org.junit.Test;
public class TestRFC2109CookieAttribHandlers extends TestCase {
public TestRFC2109CookieAttribHandlers(String testName) {
super(testName);
}
public static Test suite() {
return new TestSuite(TestRFC2109CookieAttribHandlers.class);
}
// ------------------------------------------------------------------- Main
public static void main(String args[]) {
String[] testCaseName = { TestRFC2109CookieAttribHandlers.class.getName() };
junit.textui.TestRunner.main(testCaseName);
}
public class TestRFC2109CookieAttribHandlers {
@Test
public void testRFC2109DomainParse() throws Exception {
BasicClientCookie cookie = new BasicClientCookie("name", "value");
CookieAttributeHandler h = new RFC2109DomainHandler();
h.parse(cookie, "somehost");
assertEquals("somehost", cookie.getDomain());
Assert.assertEquals("somehost", cookie.getDomain());
try {
h.parse(cookie, null);
fail("MalformedCookieException should have been thrown");
Assert.fail("MalformedCookieException should have been thrown");
} catch (MalformedCookieException ex) {
// expected
}
try {
h.parse(cookie, " ");
fail("MalformedCookieException should have been thrown");
Assert.fail("MalformedCookieException should have been thrown");
} catch (MalformedCookieException ex) {
// expected
}
}
@Test
public void testRFC2109DomainValidate1() throws Exception {
BasicClientCookie cookie = new BasicClientCookie("name", "value");
CookieOrigin origin = new CookieOrigin("somehost", 80, "/", false);
@ -83,19 +69,20 @@ public class TestRFC2109CookieAttribHandlers extends TestCase {
cookie.setDomain("otherhost");
try {
h.validate(cookie, origin);
fail("MalformedCookieException should have been thrown");
Assert.fail("MalformedCookieException should have been thrown");
} catch (MalformedCookieException ex) {
// expected
}
cookie.setDomain(null);
try {
h.validate(cookie, origin);
fail("MalformedCookieException should have been thrown");
Assert.fail("MalformedCookieException should have been thrown");
} catch (MalformedCookieException ex) {
// expected
}
}
@Test
public void testRFC2109DomainValidate2() throws Exception {
BasicClientCookie cookie = new BasicClientCookie("name", "value");
CookieOrigin origin = new CookieOrigin("www.somedomain.com", 80, "/", false);
@ -107,19 +94,20 @@ public class TestRFC2109CookieAttribHandlers extends TestCase {
cookie.setDomain(".otherdomain.com");
try {
h.validate(cookie, origin);
fail("MalformedCookieException should have been thrown");
Assert.fail("MalformedCookieException should have been thrown");
} catch (MalformedCookieException ex) {
// expected
}
cookie.setDomain("www.otherdomain.com");
try {
h.validate(cookie, origin);
fail("MalformedCookieException should have been thrown");
Assert.fail("MalformedCookieException should have been thrown");
} catch (MalformedCookieException ex) {
// expected
}
}
@Test
public void testRFC2109DomainValidate3() throws Exception {
BasicClientCookie cookie = new BasicClientCookie("name", "value");
CookieOrigin origin = new CookieOrigin("www.a.com", 80, "/", false);
@ -131,12 +119,13 @@ public class TestRFC2109CookieAttribHandlers extends TestCase {
cookie.setDomain(".com");
try {
h.validate(cookie, origin);
fail("MalformedCookieException should have been thrown");
Assert.fail("MalformedCookieException should have been thrown");
} catch (MalformedCookieException ex) {
// expected
}
}
@Test
public void testRFC2109DomainValidate4() throws Exception {
BasicClientCookie cookie = new BasicClientCookie("name", "value");
CookieOrigin origin = new CookieOrigin("www.a.b.c", 80, "/", false);
@ -148,122 +137,130 @@ public class TestRFC2109CookieAttribHandlers extends TestCase {
cookie.setDomain(".b.c");
try {
h.validate(cookie, origin);
fail("MalformedCookieException should have been thrown");
Assert.fail("MalformedCookieException should have been thrown");
} catch (MalformedCookieException ex) {
// expected
}
cookie.setDomain(".a.a.b.c");
try {
h.validate(cookie, origin);
fail("MalformedCookieException should have been thrown");
Assert.fail("MalformedCookieException should have been thrown");
} catch (MalformedCookieException ex) {
// expected
}
}
@Test
public void testRFC2109DomainMatch1() throws Exception {
BasicClientCookie cookie = new BasicClientCookie("name", "value");
CookieOrigin origin = new CookieOrigin("www.somedomain.com", 80, "/", false);
CookieAttributeHandler h = new RFC2109DomainHandler();
cookie.setDomain(null);
assertFalse(h.match(cookie, origin));
Assert.assertFalse(h.match(cookie, origin));
cookie.setDomain(".somedomain.com");
assertTrue(h.match(cookie, origin));
Assert.assertTrue(h.match(cookie, origin));
}
@Test
public void testRFC2109DomainMatch2() throws Exception {
BasicClientCookie cookie = new BasicClientCookie("name", "value");
CookieOrigin origin = new CookieOrigin("www.whatever.somedomain.com", 80, "/", false);
CookieAttributeHandler h = new RFC2109DomainHandler();
cookie.setDomain(".somedomain.com");
assertTrue(h.match(cookie, origin));
Assert.assertTrue(h.match(cookie, origin));
}
@Test
public void testRFC2109DomainMatch3() throws Exception {
BasicClientCookie cookie = new BasicClientCookie("name", "value");
CookieOrigin origin = new CookieOrigin("somedomain.com", 80, "/", false);
CookieAttributeHandler h = new RFC2109DomainHandler();
cookie.setDomain("somedomain.com");
assertTrue(h.match(cookie, origin));
Assert.assertTrue(h.match(cookie, origin));
}
@Test
public void testRFC2109DomainMatch4() throws Exception {
BasicClientCookie cookie = new BasicClientCookie("name", "value");
CookieOrigin origin = new CookieOrigin("www.somedomain.com", 80, "/", false);
CookieAttributeHandler h = new RFC2109DomainHandler();
cookie.setDomain("somedomain.com");
assertFalse(h.match(cookie, origin));
Assert.assertFalse(h.match(cookie, origin));
}
@Test
public void testRFC2109DomainInvalidInput() throws Exception {
CookieAttributeHandler h = new RFC2109DomainHandler();
try {
h.parse(null, null);
fail("IllegalArgumentException must have been thrown");
Assert.fail("IllegalArgumentException must have been thrown");
} catch (IllegalArgumentException ex) {
// expected
}
try {
h.validate(null, null);
fail("IllegalArgumentException must have been thrown");
Assert.fail("IllegalArgumentException must have been thrown");
} catch (IllegalArgumentException ex) {
// expected
}
try {
h.validate(new BasicClientCookie("name", "value"), null);
fail("IllegalArgumentException must have been thrown");
Assert.fail("IllegalArgumentException must have been thrown");
} catch (IllegalArgumentException ex) {
// expected
}
try {
h.match(null, null);
fail("IllegalArgumentException must have been thrown");
Assert.fail("IllegalArgumentException must have been thrown");
} catch (IllegalArgumentException ex) {
// expected
}
try {
h.match(new BasicClientCookie("name", "value"), null);
fail("IllegalArgumentException must have been thrown");
Assert.fail("IllegalArgumentException must have been thrown");
} catch (IllegalArgumentException ex) {
// expected
}
}
@Test
public void testRFC2109VersionParse() throws Exception {
BasicClientCookie cookie = new BasicClientCookie("name", "value");
CookieAttributeHandler h = new RFC2109VersionHandler();
h.parse(cookie, "12");
assertEquals(12, cookie.getVersion());
Assert.assertEquals(12, cookie.getVersion());
}
@Test
public void testRFC2109VersionParseInvalid() throws Exception {
BasicClientCookie cookie = new BasicClientCookie("name", "value");
CookieAttributeHandler h = new RFC2109VersionHandler();
try {
h.parse(cookie, "garbage");
fail("MalformedCookieException must have been thrown");
Assert.fail("MalformedCookieException must have been thrown");
} catch (MalformedCookieException ex) {
// expected
}
try {
h.parse(cookie, null);
fail("MalformedCookieException must have been thrown");
Assert.fail("MalformedCookieException must have been thrown");
} catch (MalformedCookieException ex) {
// expected
}
try {
h.parse(cookie, " ");
fail("MalformedCookieException must have been thrown");
Assert.fail("MalformedCookieException must have been thrown");
} catch (MalformedCookieException ex) {
// expected
}
}
@Test
public void testRFC2109VersionValidate() throws Exception {
BasicClientCookie cookie = new BasicClientCookie("name", "value");
CookieOrigin origin = new CookieOrigin("somedomain.com", 80, "/", false);
@ -275,23 +272,24 @@ public class TestRFC2109CookieAttribHandlers extends TestCase {
cookie.setVersion(-12);
try {
h.validate(cookie, origin);
fail("MalformedCookieException must have been thrown");
Assert.fail("MalformedCookieException must have been thrown");
} catch (MalformedCookieException ex) {
// expected
}
}
@Test
public void testRFC2109VersionInvalidInput() throws Exception {
CookieAttributeHandler h = new RFC2109VersionHandler();
try {
h.parse(null, null);
fail("IllegalArgumentException must have been thrown");
Assert.fail("IllegalArgumentException must have been thrown");
} catch (IllegalArgumentException ex) {
// expected
}
try {
h.validate(null, null);
fail("IllegalArgumentException must have been thrown");
Assert.fail("IllegalArgumentException must have been thrown");
} catch (IllegalArgumentException ex) {
// expected
}

View File

@ -29,25 +29,20 @@ package org.apache.http.localserver;
import java.net.InetSocketAddress;
import junit.framework.TestCase;
import org.apache.http.HttpHost;
import org.junit.After;
/**
* Base class for tests using {@link LocalTestServer}. The server will not be started
* per default.
*/
public abstract class BasicServerTestBase extends TestCase {
public abstract class BasicServerTestBase {
/** The local server for testing. */
protected LocalTestServer localServer;
protected BasicServerTestBase(String testName) {
super(testName);
}
@Override
protected void tearDown() throws Exception {
@After
public void tearDown() throws Exception {
if (localServer != null) {
localServer.stop();
}

View File

@ -46,6 +46,7 @@ import org.apache.http.protocol.BasicHttpProcessor;
import org.apache.http.protocol.HttpRequestExecutor;
import org.apache.http.protocol.RequestConnControl;
import org.apache.http.protocol.RequestContent;
import org.junit.Before;
/**
* Base class for tests using {@link LocalTestServer LocalTestServer}.
@ -72,13 +73,6 @@ public abstract class ServerTestBase extends BasicServerTestBase {
/** The request executor for the client side. */
protected HttpRequestExecutor httpExecutor;
protected ServerTestBase(String testName) {
super(testName);
}
/**
* Prepares the local server for testing.
* Derived classes that override this method MUST call
@ -101,8 +95,8 @@ public abstract class ServerTestBase extends BasicServerTestBase {
*
* @throws Exception in case of a problem
*/
@Override
protected void setUp() throws Exception {
@Before
public void setUp() throws Exception {
if (defaultParams == null) {
defaultParams = new SyncBasicHttpParams();
@ -189,5 +183,4 @@ public abstract class ServerTestBase extends BasicServerTestBase {
return conn;
}
} // class ServerTestBase
}

View File

@ -30,81 +30,65 @@ package org.apache.http.entity.mime;
import java.io.ByteArrayInputStream;
import java.nio.charset.Charset;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.entity.mime.content.StringBody;
import org.junit.Assert;
import org.junit.Test;
public class TestMultipartContentBody extends TestCase {
// ------------------------------------------------------------ Constructor
public TestMultipartContentBody(final String testName) {
super(testName);
}
// ------------------------------------------------------------------- Main
public static void main(String args[]) {
String[] testCaseName = { TestMultipartContentBody.class.getName() };
junit.textui.TestRunner.main(testCaseName);
}
// ------------------------------------------------------- TestCase Methods
public static Test suite() {
return new TestSuite(TestMultipartContentBody.class);
}
public class TestMultipartContentBody {
@Test
public void testStringBody() throws Exception {
StringBody b1 = new StringBody("text");
assertEquals(4, b1.getContentLength());
Assert.assertEquals(4, b1.getContentLength());
Charset defCharset = Charset.defaultCharset();
assertEquals(defCharset.name(), b1.getCharset());
Assert.assertEquals(defCharset.name(), b1.getCharset());
assertNull(b1.getFilename());
assertEquals("text/plain", b1.getMimeType());
assertEquals("text", b1.getMediaType());
assertEquals("plain", b1.getSubType());
Assert.assertNull(b1.getFilename());
Assert.assertEquals("text/plain", b1.getMimeType());
Assert.assertEquals("text", b1.getMediaType());
Assert.assertEquals("plain", b1.getSubType());
assertEquals(MIME.ENC_8BIT, b1.getTransferEncoding());
Assert.assertEquals(MIME.ENC_8BIT, b1.getTransferEncoding());
StringBody b2 = new StringBody("more text", "text/other", MIME.DEFAULT_CHARSET);
assertEquals(9, b2.getContentLength());
assertEquals(MIME.DEFAULT_CHARSET.name(), b2.getCharset());
Assert.assertEquals(9, b2.getContentLength());
Assert.assertEquals(MIME.DEFAULT_CHARSET.name(), b2.getCharset());
assertNull(b2.getFilename());
assertEquals("text/other", b2.getMimeType());
assertEquals("text", b2.getMediaType());
assertEquals("other", b2.getSubType());
Assert.assertNull(b2.getFilename());
Assert.assertEquals("text/other", b2.getMimeType());
Assert.assertEquals("text", b2.getMediaType());
Assert.assertEquals("other", b2.getSubType());
assertEquals(MIME.ENC_8BIT, b2.getTransferEncoding());
Assert.assertEquals(MIME.ENC_8BIT, b2.getTransferEncoding());
}
@Test
public void testInputStreamBody() throws Exception {
byte[] stuff = "Stuff".getBytes("US-ASCII");
InputStreamBody b1 = new InputStreamBody(new ByteArrayInputStream(stuff), "stuff");
assertEquals(-1, b1.getContentLength());
Assert.assertEquals(-1, b1.getContentLength());
assertNull(b1.getCharset());
assertEquals("stuff", b1.getFilename());
assertEquals("application/octet-stream", b1.getMimeType());
assertEquals("application", b1.getMediaType());
assertEquals("octet-stream", b1.getSubType());
Assert.assertNull(b1.getCharset());
Assert.assertEquals("stuff", b1.getFilename());
Assert.assertEquals("application/octet-stream", b1.getMimeType());
Assert.assertEquals("application", b1.getMediaType());
Assert.assertEquals("octet-stream", b1.getSubType());
assertEquals(MIME.ENC_BINARY, b1.getTransferEncoding());
Assert.assertEquals(MIME.ENC_BINARY, b1.getTransferEncoding());
InputStreamBody b2 = new InputStreamBody(
new ByteArrayInputStream(stuff), "some/stuff", "stuff");
assertEquals(-1, b2.getContentLength());
assertNull(b2.getCharset());
assertEquals("stuff", b2.getFilename());
assertEquals("some/stuff", b2.getMimeType());
assertEquals("some", b2.getMediaType());
assertEquals("stuff", b2.getSubType());
Assert.assertEquals(-1, b2.getContentLength());
Assert.assertNull(b2.getCharset());
Assert.assertEquals("stuff", b2.getFilename());
Assert.assertEquals("some/stuff", b2.getMimeType());
Assert.assertEquals("some", b2.getMediaType());
Assert.assertEquals("stuff", b2.getSubType());
assertEquals(MIME.ENC_BINARY, b2.getTransferEncoding());
Assert.assertEquals(MIME.ENC_BINARY, b2.getTransferEncoding());
}
}

View File

@ -34,36 +34,18 @@ import java.io.FileWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.apache.http.entity.mime.FormBodyPart;
import org.apache.http.entity.mime.HttpMultipart;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.entity.mime.content.StringBody;
import org.junit.Assert;
import org.junit.Test;
public class TestMultipartForm extends TestCase {
// ------------------------------------------------------------ Constructor
public TestMultipartForm(final String testName) {
super(testName);
}
// ------------------------------------------------------------------- Main
public static void main(String args[]) {
String[] testCaseName = { TestMultipartForm.class.getName() };
junit.textui.TestRunner.main(testCaseName);
}
// ------------------------------------------------------- TestCase Methods
public static Test suite() {
return new TestSuite(TestMultipartForm.class);
}
public class TestMultipartForm {
@Test
public void testMultipartFormStringParts() throws Exception {
HttpMultipart multipart = new HttpMultipart("form-data", "foo");
FormBodyPart p1 = new FormBodyPart(
@ -107,10 +89,11 @@ public class TestMultipartForm extends TestCase {
"all kind of stuff\r\n" +
"--foo--\r\n";
String s = out.toString("US-ASCII");
assertEquals(expected, s);
assertEquals(s.length(), multipart.getTotalLength());
Assert.assertEquals(expected, s);
Assert.assertEquals(s.length(), multipart.getTotalLength());
}
@Test
public void testMultipartFormBinaryParts() throws Exception {
File tmpfile = File.createTempFile("tmp", ".bin");
tmpfile.deleteOnExit();
@ -153,12 +136,13 @@ public class TestMultipartForm extends TestCase {
"some random whatever\r\n" +
"--foo--\r\n";
String s = out.toString("US-ASCII");
assertEquals(expected, s);
assertEquals(-1, multipart.getTotalLength());
Assert.assertEquals(expected, s);
Assert.assertEquals(-1, multipart.getTotalLength());
tmpfile.delete();
}
@Test
public void testMultipartFormBrowserCompatible() throws Exception {
File tmpfile = File.createTempFile("tmp", ".bin");
tmpfile.deleteOnExit();
@ -214,8 +198,8 @@ public class TestMultipartForm extends TestCase {
"some random whatever\r\n" +
"--foo--\r\n";
String s = out.toString("US-ASCII");
assertEquals(expected, s);
assertEquals(-1, multipart.getTotalLength());
Assert.assertEquals(expected, s);
Assert.assertEquals(-1, multipart.getTotalLength());
tmpfile.delete();
}
@ -239,6 +223,7 @@ public class TestMultipartForm extends TestCase {
return buffer.toString();
}
@Test
public void testMultipartFormBrowserCompatibleNonASCIIHeaders() throws Exception {
String s1 = constructString(SWISS_GERMAN_HELLO);
String s2 = constructString(RUSSIAN_HELLO);
@ -282,12 +267,13 @@ public class TestMultipartForm extends TestCase {
"some random whatever\r\n" +
"--foo--\r\n";
String s = out.toString("UTF-8");
assertEquals(expected, s);
assertEquals(-1, multipart.getTotalLength());
Assert.assertEquals(expected, s);
Assert.assertEquals(-1, multipart.getTotalLength());
tmpfile.delete();
}
@Test
public void testMultipartFormStringPartsMultiCharsets() throws Exception {
String s1 = constructString(SWISS_GERMAN_HELLO);
String s2 = constructString(RUSSIAN_HELLO);
@ -330,11 +316,11 @@ public class TestMultipartForm extends TestCase {
byte[] actual = out1.toByteArray();
byte[] expected = out2.toByteArray();
assertEquals(expected.length, actual.length);
Assert.assertEquals(expected.length, actual.length);
for (int i = 0; i < actual.length; i++) {
assertEquals(expected[i], actual[i]);
Assert.assertEquals(expected[i], actual[i]);
}
assertEquals(expected.length, multipart.getTotalLength());
Assert.assertEquals(expected.length, multipart.getTotalLength());
}
}

View File

@ -38,118 +38,103 @@ import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.entity.mime.content.StringBody;
import org.junit.Assert;
import org.junit.Test;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
public class TestMultipartFormHttpEntity extends TestCase {
// ------------------------------------------------------------ Constructor
public TestMultipartFormHttpEntity(final String testName) {
super(testName);
}
// ------------------------------------------------------------------- Main
public static void main(String args[]) {
String[] testCaseName = { TestMultipartFormHttpEntity.class.getName() };
junit.textui.TestRunner.main(testCaseName);
}
// ------------------------------------------------------- TestCase Methods
public static Test suite() {
return new TestSuite(TestMultipartFormHttpEntity.class);
}
public class TestMultipartFormHttpEntity {
@Test
public void testExplictContractorParams() throws Exception {
MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE,
"whatever",
Charset.forName("UTF-8"));
assertNull(entity.getContentEncoding());
assertNotNull(entity.getContentType());
Assert.assertNull(entity.getContentEncoding());
Assert.assertNotNull(entity.getContentType());
Header header = entity.getContentType();
HeaderElement[] elems = header.getElements();
assertNotNull(elems);
assertEquals(1, elems.length);
Assert.assertNotNull(elems);
Assert.assertEquals(1, elems.length);
HeaderElement elem = elems[0];
assertEquals("multipart/form-data", elem.getName());
Assert.assertEquals("multipart/form-data", elem.getName());
NameValuePair p1 = elem.getParameterByName("boundary");
assertNotNull(p1);
assertEquals("whatever", p1.getValue());
Assert.assertNotNull(p1);
Assert.assertEquals("whatever", p1.getValue());
NameValuePair p2 = elem.getParameterByName("charset");
assertNotNull(p2);
assertEquals("UTF-8", p2.getValue());
Assert.assertNotNull(p2);
Assert.assertEquals("UTF-8", p2.getValue());
}
@Test
public void testImplictContractorParams() throws Exception {
MultipartEntity entity = new MultipartEntity();
assertNull(entity.getContentEncoding());
assertNotNull(entity.getContentType());
Assert.assertNull(entity.getContentEncoding());
Assert.assertNotNull(entity.getContentType());
Header header = entity.getContentType();
HeaderElement[] elems = header.getElements();
assertNotNull(elems);
assertEquals(1, elems.length);
Assert.assertNotNull(elems);
Assert.assertEquals(1, elems.length);
HeaderElement elem = elems[0];
assertEquals("multipart/form-data", elem.getName());
Assert.assertEquals("multipart/form-data", elem.getName());
NameValuePair p1 = elem.getParameterByName("boundary");
assertNotNull(p1);
Assert.assertNotNull(p1);
String boundary = p1.getValue();
assertNotNull(boundary);
Assert.assertNotNull(boundary);
assertTrue(boundary.length() >= 30);
assertTrue(boundary.length() <= 40);
Assert.assertTrue(boundary.length() >= 30);
Assert.assertTrue(boundary.length() <= 40);
NameValuePair p2 = elem.getParameterByName("charset");
assertNull(p2);
Assert.assertNull(p2);
}
@Test
public void testRepeatable() throws Exception {
MultipartEntity entity = new MultipartEntity();
entity.addPart("p1", new StringBody("blah blah"));
entity.addPart("p2", new StringBody("yada yada"));
assertTrue(entity.isRepeatable());
assertFalse(entity.isChunked());
assertFalse(entity.isStreaming());
Assert.assertTrue(entity.isRepeatable());
Assert.assertFalse(entity.isChunked());
Assert.assertFalse(entity.isStreaming());
long len = entity.getContentLength();
assertTrue(len == entity.getContentLength());
Assert.assertTrue(len == entity.getContentLength());
ByteArrayOutputStream out = new ByteArrayOutputStream();
entity.writeTo(out);
out.close();
byte[] bytes = out.toByteArray();
assertNotNull(bytes);
assertTrue(bytes.length == len);
Assert.assertNotNull(bytes);
Assert.assertTrue(bytes.length == len);
assertTrue(len == entity.getContentLength());
Assert.assertTrue(len == entity.getContentLength());
out = new ByteArrayOutputStream();
entity.writeTo(out);
out.close();
bytes = out.toByteArray();
assertNotNull(bytes);
assertTrue(bytes.length == len);
Assert.assertNotNull(bytes);
Assert.assertTrue(bytes.length == len);
}
@Test
public void testNonRepeatable() throws Exception {
MultipartEntity entity = new MultipartEntity();
entity.addPart("p1", new InputStreamBody(
new ByteArrayInputStream("blah blah".getBytes()), null));
entity.addPart("p2", new InputStreamBody(
new ByteArrayInputStream("yada yada".getBytes()), null));
assertFalse(entity.isRepeatable());
assertTrue(entity.isChunked());
assertTrue(entity.isStreaming());
Assert.assertFalse(entity.isRepeatable());
Assert.assertTrue(entity.isChunked());
Assert.assertTrue(entity.isStreaming());
assertTrue(entity.getContentLength() == -1);
Assert.assertTrue(entity.getContentLength() == -1);
}
}

View File

@ -72,7 +72,7 @@
<commons-logging.version>1.1.1</commons-logging.version>
<commons-codec.version>1.4</commons-codec.version>
<mime4j.version>0.6</mime4j.version>
<junit.version>3.8.2</junit.version>
<junit.version>4.8.1</junit.version>
</properties>
<modules>