Initial commit

This commit is contained in:
Pablo Fernandez committed 2010-09-05 17:01:30 -03:00
commit bfbe536886
59 files changed
+2540

No files matched your search

@@ -0,0 +1,45 @@
package org.scribe.extractors;
import static org.junit.Assert.*;
import org.junit.*;
import org.scribe.exceptions.*;
import org.scribe.model.*;
import org.scribe.model.Request.*;
import org.scribe.test.helpers.*;
public class BaseStringExtractorTest
{
private BaseStringExtractorImpl extractor;
private OAuthRequest request;
@Before
public void setup()
{
request = ObjectMother.createSampleOAuthRequest();
extractor = new BaseStringExtractorImpl();
}
@Test
public void shouldExtractBaseStringFromOAuthRequest()
{
String expected = "GET&http%3A%2F%2Fexample.com&oauth_callback%3Dhttp%253A%252F%252Fexample%252Fcallback%26oauth_consumer_key%3DAS%2523%2524%255E*%2540%2526%26oauth_signature%3DOAuth-Signature%26oauth_timestamp%3D123456";
String baseString = extractor.extract(request);
assertEquals(expected, baseString);
}
@Test(expected = IllegalArgumentException.class)
public void shouldThrowExceptionIfRquestIsNull()
{
OAuthRequest nullRequest = null;
extractor.extract(nullRequest);
}
@Test(expected = OAuthParametersMissingException.class)
public void shouldThrowExceptionIfRquestHasNoOAuthParameters()
{
OAuthRequest request = new OAuthRequest(Verb.GET, "http://example.com");
extractor.extract(request);
}
}
@@ -0,0 +1,46 @@
package org.scribe.extractors;
import static org.junit.Assert.*;
import org.junit.*;
import org.scribe.exceptions.*;
import org.scribe.model.*;
import org.scribe.model.Request.*;
import org.scribe.test.helpers.*;
public class HeaderExtractorTest
{
private HeaderExtractorImpl extractor;
private OAuthRequest request;
@Before
public void setup()
{
request = ObjectMother.createSampleOAuthRequest();
extractor = new HeaderExtractorImpl();
}
@Test
public void shouldExtractStandardHeader()
{
String expected = "OAuth oauth_callback=\"http%3A%2F%2Fexample%2Fcallback\", " + "oauth_signature=\"OAuth-Signature\", "
+ "oauth_consumer_key=\"AS%23%24%5E*%40%26\", " + "oauth_timestamp=\"123456\"";
String header = extractor.extract(request);
assertEquals(expected, header);
}
@Test(expected = IllegalArgumentException.class)
public void shouldExceptionIfRequestIsNull()
{
OAuthRequest nullRequest = null;
extractor.extract(nullRequest);
}
@Test(expected = OAuthParametersMissingException.class)
public void shouldExceptionIfRequestHasNoOAuthParams()
{
OAuthRequest emptyRequest = new OAuthRequest(Verb.GET, "http://example.com");
extractor.extract(emptyRequest);
}
}
@@ -0,0 +1,65 @@
package org.scribe.extractors;
import static org.junit.Assert.*;
import org.junit.*;
import org.scribe.exceptions.*;
import org.scribe.model.*;
public class TokenExtractorTest
{
private TokenExtractorImpl extractor;
@Before
public void setup()
{
extractor = new TokenExtractorImpl();
}
@Test
public void shouldExtractTokenFromOAuthStandardResponse()
{
String response = "oauth_token=hh5s93j4hdidpola&oauth_token_secret=hdhd0244k9j7ao03";
Token extracted = extractor.extract(response);
assertEquals("hh5s93j4hdidpola", extracted.getToken());
assertEquals("hdhd0244k9j7ao03", extracted.getSecret());
}
@Test
public void shouldExtractTokenFromResponseWithCallbackConfirmed()
{
String response = "oauth_token=hh5s93j4hdidpola&oauth_token_secret=hdhd0244k9j7ao03&callback_confirmed=true";
Token extracted = extractor.extract(response);
assertEquals("hh5s93j4hdidpola", extracted.getToken());
assertEquals("hdhd0244k9j7ao03", extracted.getSecret());
}
@Test(expected = OAuthException.class)
public void shouldThrowExceptionIfTokenIsAbsent()
{
String response = "oauth_secret=hh5s93j4hdidpola&callback_confirmed=true";
extractor.extract(response);
}
@Test(expected = OAuthException.class)
public void shouldThrowExceptionIfSecretIsAbsent()
{
String response = "oauth_token=hh5s93j4hdidpola&callback_confirmed=true";
extractor.extract(response);
}
@Test(expected = IllegalArgumentException.class)
public void shouldThrowExceptionIfResponseIsNull()
{
String response = null;
extractor.extract(response);
}
@Test(expected = IllegalArgumentException.class)
public void shouldThrowExceptionIfResponseIsEmptyString()
{
String response = "";
extractor.extract(response);
}
}
@@ -0,0 +1,80 @@
package org.scribe.model;
import java.io.*;
import java.net.*;
import java.util.*;
public class ConnectionStub extends HttpURLConnection
{
private Map<String, String> headers = new HashMap<String, String>();
private Map<String, List<String>> responseHeaders = new HashMap<String, List<String>>();
private int inputStreamCalled = 0;
public ConnectionStub() throws Exception
{
super(new URL("http://example.com"));
}
@Override
public void setRequestProperty(String key, String value)
{
headers.put(key, value);
}
public Map<String, String> getHeaders()
{
return headers;
}
@Override
public int getResponseCode() throws IOException
{
return 200;
}
@Override
public InputStream getInputStream() throws IOException
{
inputStreamCalled++;
return new ByteArrayInputStream("contents".getBytes());
}
public int getTimesCalledInpuStream()
{
return inputStreamCalled;
}
@Override
public OutputStream getOutputStream() throws IOException
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write("contents".getBytes());
return baos;
}
@Override
public Map<String, List<String>> getHeaderFields()
{
return responseHeaders;
}
public void addResponseHeader(String key, String value)
{
responseHeaders.put(key, Arrays.asList(value));
}
public void connect() throws IOException
{
}
public void disconnect()
{
}
public boolean usingProxy()
{
return false;
}
}
@@ -0,0 +1,32 @@
package org.scribe.model;
import static org.junit.Assert.*;
import org.junit.*;
import org.scribe.model.Request.*;
public class OAuthConfigTest
{
@Test
public void shouldReturnDefaultValuesIfNotSet()
{
OAuthConfig config = new OAuthConfig();
assertEquals(Verb.GET, config.getAccessTokenVerb());
assertEquals(Verb.GET, config.getRequestTokenVerb());
assertEquals(OAuthConstants.OUT_OF_BAND, config.getCallback());
}
@Test
public void shouldOverrideDefaultsIfSet()
{
OAuthConfig config = new OAuthConfig();
config.setCallback("http://callback");
config.setAccessTokenVerb(Verb.POST);
config.setRequestTokenVerb(Verb.POST);
assertEquals("http://callback", config.getCallback());
assertEquals(Verb.POST, config.getAccessTokenVerb());
assertEquals(Verb.POST, config.getRequestTokenVerb());
}
}
@@ -0,0 +1,34 @@
package org.scribe.model;
import static org.junit.Assert.*;
import org.junit.*;
import org.scribe.model.Request.*;
public class OAuthRequestTest
{
private OAuthRequest request;
@Before
public void setup()
{
request = new OAuthRequest(Verb.GET, "http://example.com");
}
@Test
public void shouldAddOAuthParamters()
{
request.addOAuthParameter(OAuthConstants.TOKEN, "token");
request.addOAuthParameter(OAuthConstants.NONCE, "nonce");
request.addOAuthParameter(OAuthConstants.TIMESTAMP, "ts");
assertEquals(3, request.getOauthParameters().size());
}
@Test(expected = IllegalArgumentException.class)
public void shouldThrowExceptionIfParameterIsNotOAuth()
{
request.addOAuthParameter("otherParam", "value");
}
}
@@ -0,0 +1,69 @@
package org.scribe.model;
import static org.junit.Assert.*;
import org.junit.*;
import org.scribe.model.Request.*;
public class RequestTest
{
private Request getRequest;
private Request postRequest;
private ConnectionStub connection;
@Before
public void setup() throws Exception
{
connection = new ConnectionStub();
postRequest = new Request(Verb.POST, "http://example.com");
postRequest.setConnection(connection);
getRequest = new Request(Verb.GET, "http://example.com?qsparam=value&other=value+with+spaces");
getRequest.setConnection(connection);
}
@Test
public void shouldSetRequestVerb()
{
getRequest.send();
assertEquals("GET", connection.getRequestMethod());
}
@Test
public void shouldGetQueryStringParameters()
{
assertEquals(2, getRequest.getQueryStringParams().size());
assertEquals(0, postRequest.getQueryStringParams().size());
assertTrue(getRequest.getQueryStringParams().containsKey("qsparam"));
}
@Test
public void shouldAddRequestHeaders()
{
getRequest.addHeader("Header", "1");
getRequest.addHeader("Header2", "2");
getRequest.send();
assertEquals(2, getRequest.getHeaders().size());
assertEquals(2, connection.getHeaders().size());
}
@Test
public void shouldSetBodyParamsAndHeaders()
{
postRequest.addBodyParameter("param", "value");
postRequest.addBodyParameter("param two", "value with spaces");
postRequest.send();
assertEquals("param+two=value+with+spaces&param=value", postRequest.getBodyContents());
assertTrue(connection.getHeaders().containsKey("Content-Length"));
}
@Test
public void shouldSetPayloadAndHeaders()
{
postRequest.addPayload("PAYLOAD");
postRequest.send();
assertEquals("PAYLOAD", postRequest.getBodyContents());
assertTrue(connection.getHeaders().containsKey("Content-Length"));
}
}
@@ -0,0 +1,75 @@
package org.scribe.model;
import static org.junit.Assert.*;
import java.io.*;
import org.junit.*;
public class ResponseTest
{
private Response response;
private ConnectionStub connection;
@Before
public void setup() throws Exception
{
connection = new ConnectionStub();
connection.addResponseHeader("one", "one");
connection.addResponseHeader("two", "two");
response = new Response(connection);
}
@Test
public void shouldPopulateResponseHeaders()
{
assertEquals(2, response.getHeaders().size());
assertEquals("one", response.getHeader("one"));
}
@Test
public void shouldParseBodyContents()
{
assertEquals("contents", response.getBody());
assertEquals(1, connection.getTimesCalledInpuStream());
}
@Test
public void shouldParseBodyContentsOnlyOnce()
{
assertEquals("contents", response.getBody());
assertEquals("contents", response.getBody());
assertEquals("contents", response.getBody());
assertEquals(1, connection.getTimesCalledInpuStream());
}
@Test
public void shouldHandleAConnectionWithErrors() throws Exception
{
Response errResponse = new Response(new FaultyConnection());
assertEquals(400, errResponse.getCode());
assertEquals("errors", errResponse.getBody());
}
private static class FaultyConnection extends ConnectionStub
{
public FaultyConnection() throws Exception
{
super();
}
@Override
public InputStream getErrorStream()
{
return new ByteArrayInputStream("errors".getBytes());
}
@Override
public int getResponseCode() throws IOException
{
return 400;
}
}
}
@@ -0,0 +1,59 @@
package org.scribe.services;
import static org.junit.Assert.*;
import org.junit.*;
import org.scribe.exceptions.OAuthException;
public class HMACSha1SignatureServiceTest
{
private HMACSha1SignatureService service;
@Before
public void setup()
{
service = new HMACSha1SignatureService();
}
@Test
public void shouldReturnSignatureMethodString()
{
String expected = "HMAC-SHA1";
assertEquals(expected, service.getSignatureMethod());
}
@Test
public void shouldReturnSignature()
{
String apiSecret = "api secret";
String tokenSecret = "token secret";
String baseString = "base string";
String signature = "cyxvUDZY/5cQBcBiKulaNgnhN/w=";
assertEquals(signature, service.getSignature(baseString, apiSecret, tokenSecret));
}
@Test(expected = OAuthException.class)
public void shouldThrowExceptionIfBaseStringIsNull()
{
service.getSignature(null, "apiSecret", "tokenSecret");
}
@Test(expected = OAuthException.class)
public void shouldThrowExceptionIfBaseStringIsEmpty()
{
service.getSignature(" ", "apiSecret", "tokenSecret");
}
@Test(expected = OAuthException.class)
public void shouldThrowExceptionIfApiSecretIsNull()
{
service.getSignature("base string", null, "tokenSecret");
}
@Test(expected = OAuthException.class)
public void shouldThrowExceptionIfApiSecretIsEmpty()
{
service.getSignature("base string", " ", "tokenSecret");
}
}
@@ -0,0 +1,50 @@
package org.scribe.services;
import static org.junit.Assert.*;
import org.junit.*;
public class TimestampServiceTest
{
private TimestampServiceImpl service;
private TimestampServiceImpl.Timer timerStub;
@Before
public void setup()
{
service = new TimestampServiceImpl();
timerStub = new TimerStub();
service.setTimer(timerStub);
}
@Test
public void shouldReturnTimestampInSeconds()
{
String expected = "1000";
assertEquals(expected, service.getTimestampInSeconds());
}
@Test
public void shouldReturnNonce()
{
String expected = "1042";
assertEquals(expected, service.getNonce());
}
private static class TimerStub extends TimestampServiceImpl.Timer
{
@Override
public Long getMilis()
{
return 1000000L;
}
@Override
public Integer getRandomInteger()
{
return 42;
}
}
}
@@ -0,0 +1,63 @@
package org.scribe.specs;
import java.util.Scanner;
import org.scribe.builder.*;
import org.scribe.builder.api.*;
import org.scribe.model.*;
import org.scribe.model.Request.*;
import org.scribe.oauth.*;
public class LinkedInSpec
{
private static final String AUTHORIZE_URL = "https://api.linkedin.com/uas/oauth/authorize?oauth_token=";
private static final String PROTECTED_RESOURCE_URL = "http://api.linkedin.com/v1/people/~/connections:(id,last-name)";
public static void main(String[] args)
{
OAuthService service = new ServiceBuilder()
.provider(LinkedInApi.class)
.apiKey("CiEgwWDkA5BFpNrc0RfGyVuSlOh4tig5kOTZ9q97qcXNrFl7zqk-Ts7DqRGaKDCV")
.apiSecret("dhho4dfoCmiQXrkw4yslork5XWLFnPSuMR-8gscPVjY4jqFFHPYWJKgpFl4uLTM6")
.build();
Scanner in = new Scanner(System.in);
System.out.println("=== LinkedIn's OAuth Workflow ===");
System.out.println();
// Obtain the Request Token
System.out.println("Fetching the Request Token...");
Token requestToken = service.getRequestToken();
System.out.println("Got the Request Token!");
System.out.println();
System.out.println("Now go and authorize Scribe here:");
System.out.println(AUTHORIZE_URL + requestToken.getToken());
System.out.println("And paste the verifier here");
System.out.print(">>");
Verifier verifier = new Verifier(in.nextLine());
System.out.println();
// Trade the Request Token and Verfier for the Access Token
System.out.println("Trading the Request Token for an Access Token...");
Token accessToken = service.getAccessToken(requestToken, verifier);
System.out.println("Got the Access Token!");
System.out.println("(if your curious it looks like this: " + accessToken + " )");
System.out.println();
// Now let's go and ask for a protected resource!
System.out.println("Now we're going to access a protected resource...");
OAuthRequest request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL);
service.signRequest(accessToken, request);
Response response = request.send();
System.out.println("Got it! Lets see what we found...");
System.out.println();
System.out.println(response.getBody());
System.out.println();
System.out.println("Thats it man! Go and build something awesome with Scribe! :)");
System.out.println(service.getRequestToken());
}
}
@@ -0,0 +1,61 @@
package org.scribe.specs;
import java.util.Scanner;
import org.scribe.builder.*;
import org.scribe.builder.api.*;
import org.scribe.model.*;
import org.scribe.model.Request.*;
import org.scribe.oauth.*;
public class TwitterSpec
{
private static final String AUTHORIZE_URL = "https://twitter.com/oauth/authorize?oauth_token=";
private static final String PROTECTED_RESOURCE_URL = "http://api.twitter.com/1/account/verify_credentials.xml";
public static void main(String[] args)
{
OAuthService service = new ServiceBuilder()
.provider(TwitterApi.class)
.apiKey("6icbcAXyZx67r8uTAUM5Qw")
.apiSecret("SCCAdUUc6LXxiazxH3N0QfpNUvlUy84mZ2XZKiv39s")
.build();
Scanner in = new Scanner(System.in);
System.out.println("=== Twitter's OAuth Workflow ===");
System.out.println();
// Obtain the Request Token
System.out.println("Fetching the Request Token...");
Token requestToken = service.getRequestToken();
System.out.println("Got the Request Token!");
System.out.println();
System.out.println("Now go and authorize Resin here:");
System.out.println(AUTHORIZE_URL + requestToken.getToken());
System.out.println("And paste the verifier here");
System.out.print(">>");
Verifier verifier = new Verifier(in.nextLine());
System.out.println();
// Trade the Request Token and Verfier for the Access Token
System.out.println("Trading the Request Token for an Access Token...");
Token accessToken = service.getAccessToken(requestToken, verifier);
System.out.println("Got the Access Token!");
System.out.println("(if your curious it looks like this: " + accessToken + " )");
System.out.println();
// Now let's go and ask for a protected resource!
System.out.println("Now we're going to access a protected resource...");
OAuthRequest request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL);
service.signRequest(accessToken, request);
Response response = request.send();
System.out.println("Got it! Lets see what we found...");
System.out.println();
System.out.println(response.getBody());
System.out.println();
System.out.println("Thats it man! Go and build something awesome with Resin! :)");
}
}
@@ -0,0 +1,63 @@
package org.scribe.specs;
import java.util.Scanner;
import org.scribe.builder.*;
import org.scribe.builder.api.*;
import org.scribe.model.*;
import org.scribe.model.Request.*;
import org.scribe.oauth.*;
public class YahooSpec
{
private static final String NETWORK_NAME = "Yahoo";
private static final String AUTHORIZE_URL = "https://api.login.yahoo.com/oauth/v2/request_auth?oauth_token=";
private static final String PROTECTED_RESOURCE_URL = "http://social.yahooapis.com/v1/user/A6ROU63MXWDCW3Y5MGCYWVHDJI/profile/status?format=json";
public static void main(String[] args)
{
OAuthService service = new ServiceBuilder()
.provider(YahooApi.class)
.apiKey("dj0yJmk9TXZDWVpNVVdGaVFmJmQ9WVdrOWMweHZXbkZLTkhVbWNHbzlNVEl5TWprd05qUTJNZy0tJnM9Y29uc3VtZXJzZWNyZXQmeD0wMw--")
.apiSecret("262be559f92a2be20c4c039419018f2b48cdfce9")
.build();
Scanner in = new Scanner(System.in);
System.out.println("=== " + NETWORK_NAME + "'s OAuth Workflow ===");
System.out.println();
// Obtain the Request Token
System.out.println("Fetching the Request Token...");
Token requestToken = service.getRequestToken();
System.out.println("Got the Request Token!");
System.out.println();
System.out.println("Now go and authorize Scribe here:");
System.out.println(AUTHORIZE_URL + requestToken.getToken());
System.out.println("And paste the verifier here");
System.out.print(">>");
Verifier verifier = new Verifier(in.nextLine());
System.out.println();
// Trade the Request Token and Verfier for the Access Token
System.out.println("Trading the Request Token for an Access Token...");
Token accessToken = service.getAccessToken(requestToken, verifier);
System.out.println("Got the Access Token!");
System.out.println("(if your curious it looks like this: " + accessToken + " )");
System.out.println();
// Now let's go and ask for a protected resource!
System.out.println("Now we're going to access a protected resource...");
OAuthRequest request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL);
service.signRequest(accessToken, request);
Response response = request.send();
System.out.println("Got it! Lets see what we found...");
System.out.println();
System.out.println(response.getCode());
System.out.println(response.getBody());
System.out.println();
System.out.println("Thats it man! Go and build something awesome with Scribe! :)");
}
}
@@ -0,0 +1,18 @@
package org.scribe.test.helpers;
import org.scribe.model.*;
import org.scribe.model.Request.*;
public class ObjectMother
{
public static OAuthRequest createSampleOAuthRequest()
{
OAuthRequest request = new OAuthRequest(Verb.GET, "http://example.com");
request.addOAuthParameter(OAuthConstants.TIMESTAMP, "123456");
request.addOAuthParameter(OAuthConstants.CONSUMER_KEY, "AS#$^*@&");
request.addOAuthParameter(OAuthConstants.CALLBACK, "http://example/callback");
request.addOAuthParameter(OAuthConstants.SIGNATURE, "OAuth-Signature");
return request;
}
}
@@ -0,0 +1,53 @@
package org.scribe.utils;
import static org.junit.Assert.*;
import java.util.*;
import org.junit.*;
public class MapUtilsTest
{
private Map<String, String> unsorted;
@Before
public void setup()
{
unsorted = new LinkedHashMap<String, String>();
unsorted.put("d", "fourth");
unsorted.put("a", "first");
unsorted.put("c", "third");
unsorted.put("b", "second");
}
@Test
public void shouldSortMap()
{
Map<String, String> sorted = MapUtils.sort(unsorted);
List<String> values = new ArrayList<String>(sorted.values());
assertEquals("first", values.get(0));
assertEquals("second", values.get(1));
assertEquals("third", values.get(2));
assertEquals("fourth", values.get(3));
}
@Test
public void shouldNotModifyTheOriginalMap()
{
Map<String, String> sorted = MapUtils.sort(unsorted);
assertNotSame(sorted, unsorted);
List<String> values = new ArrayList<String>(unsorted.values());
assertEquals("fourth", values.get(0));
assertEquals("first", values.get(1));
assertEquals("third", values.get(2));
assertEquals("second", values.get(3));
}
@Test(expected = IllegalArgumentException.class)
public void shouldThrowExceptionForNullMap()
{
MapUtils.sort(null);
}
}
@@ -0,0 +1,60 @@
package org.scribe.utils;
import org.junit.*;
public class PreconditionsTest
{
private static final String ERROR_MSG = "";
@Test(expected = IllegalArgumentException.class)
public void shouldThrowExceptionForNullObjects()
{
Preconditions.checkNotNull(null, ERROR_MSG);
}
@Test(expected = IllegalArgumentException.class)
public void shouldThrowExceptionForNullStrings()
{
Preconditions.checkEmptyString(null, ERROR_MSG);
}
@Test(expected = IllegalArgumentException.class)
public void shouldThrowExceptionForEmptyStrings()
{
Preconditions.checkEmptyString("", ERROR_MSG);
}
@Test(expected = IllegalArgumentException.class)
public void shouldThrowExceptionForSpacesOnlyStrings()
{
Preconditions.checkEmptyString(" ", ERROR_MSG);
}
@Test(expected = IllegalArgumentException.class)
public void shouldThrowExceptionForInvalidUrls()
{
Preconditions.checkValidUrl("this/is/not/a/valid/url", ERROR_MSG);
}
@Test(expected = IllegalArgumentException.class)
public void shouldThrowExceptionForNullUrls()
{
Preconditions.checkValidUrl(null, ERROR_MSG);
}
public void shouldAllowValidUrls()
{
Preconditions.checkValidUrl("http://www.example.com", ERROR_MSG);
}
public void shouldAllowSSLUrls()
{
Preconditions.checkValidUrl("https://www.example.com", ERROR_MSG);
}
public void shouldAllowOutOfBandAsValidCallbackValue()
{
Preconditions.checkValidOAuthCallback("oob", ERROR_MSG);
}
}
@@ -0,0 +1,29 @@
package org.scribe.utils;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import org.junit.Test;
import static org.junit.Assert.*;
public class StreamUtilsTest
{
@Test
public void shouldCorrectlyDecodeAStream()
{
String value = "expected";
InputStream is = new ByteArrayInputStream(value.getBytes());
String decoded = StreamUtils.getStreamContents(is);
assertEquals("expected", decoded);
}
@Test(expected = IllegalArgumentException.class)
public void shouldFailForNullParameter()
{
InputStream is = null;
StreamUtils.getStreamContents(is);
fail("Must throw exception before getting here");
}
}
@@ -0,0 +1,75 @@
package org.scribe.utils;
import static org.junit.Assert.*;
import java.util.*;
import org.junit.*;
public class URLUtilsTest
{
@Before
public void setup()
{
}
@Test
public void shouldPercentEncodeMap()
{
Map<String, String> params = new LinkedHashMap<String, String>();
params.put("key", "value");
params.put("key with spaces", "value with spaces");
params.put("&symbols!", "#!");
String expected = "key=value&key+with+spaces=value+with+spaces&%26symbols%21=%23%21";
assertEquals(expected, URLUtils.formURLEncodeMap(params));
}
@Test
public void shouldReturnEmptyStringForEmptyMap()
{
Map<String, String> params = new LinkedHashMap<String, String>();
String expected = "";
assertEquals(expected, URLUtils.formURLEncodeMap(params));
}
@Test
public void shouldPercentEncodeString()
{
String toEncode = "this is a test &^";
String expected = "this+is+a+test+%26%5E";
assertEquals(expected, URLUtils.percentEncode(toEncode));
}
@Test
public void shouldPercentDecodeString()
{
String toDecode = "this+is+a+test+%26%5E";
String expected = "this is a test &^";
assertEquals(expected, URLUtils.percentDecode(toDecode));
}
@Test(expected = IllegalArgumentException.class)
public void shouldThrowExceptionIfMapIsNull()
{
Map<String, String> nullMap = null;
URLUtils.formURLEncodeMap(nullMap);
}
@Test(expected = IllegalArgumentException.class)
public void shouldThrowExceptionIfStringToEncodeIsNull()
{
String toEncode = null;
URLUtils.percentEncode(toEncode);
}
@Test(expected = IllegalArgumentException.class)
public void shouldThrowExceptionIfStringToDecodeIsNull()
{
String toDecode = null;
URLUtils.percentDecode(toDecode);
}
}