Skip to content

Commit

Permalink
Merge pull request #39 from ruhan1/master-queryparam
Browse files Browse the repository at this point in the history
Take query params into account in expectation
  • Loading branch information
ruhan1 authored Nov 2, 2023
2 parents f89cc81 + 13ec891 commit d166a30
Show file tree
Hide file tree
Showing 2 changed files with 101 additions and 65 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,20 @@
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

@SuppressWarnings( "unused" )
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.commonjava.test.http.common.CommonMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public final class ExpectationServlet
extends HttpServlet
{
Expand Down Expand Up @@ -97,20 +104,17 @@ public String getAccessKey( final String method, final String path )
return method.toUpperCase() + " " + path;
}

private String getPath( final String path )
private String getPath( final String testUrl )
{
String realPath = path;
try
{
final URL u = new URL( path );
realPath = u.getPath();
return new URL( testUrl ).getFile(); // path plus query parameters
}
catch ( final MalformedURLException e )
{
//Do nothing
}

return realPath;
return testUrl;
}

public void expect( final String method, final String testUrl, final int responseCode, final String body )
Expand Down Expand Up @@ -144,28 +148,31 @@ public void expect( String method, String testUrl, ExpectationHandler handler )
protected void service( final HttpServletRequest req, final HttpServletResponse resp )
throws ServletException, IOException
{
String wholePath;
try
{
wholePath = new URI( req.getRequestURI() ).getPath();
}
catch ( final URISyntaxException e )
String wholePath = getWholePath( req );
String key = getAccessKey( req.getMethod(), wholePath );
accessesByPath.merge(key, 1, Integer::sum);

boolean handled = handle( key, req, resp );
if (!handled)
{
throw new ServletException( "Cannot parse request URI", e );
// try simple path
String simplePath = getSimplePath(req);
if (!simplePath.equals(wholePath))
{
key = getAccessKey(req.getMethod(), simplePath);
handled = handle(key, req, resp);
}
}

String path = wholePath;
if ( path.length() > 1 )
if (!handled)
{
path = path.substring( 1 );
resp.setStatus( 404 );
}
}

final String key = getAccessKey( req.getMethod(), wholePath );

logger.info( "Looking up expectation for: {}", key );

accessesByPath.merge( key, 1, Integer::sum );

private boolean handle(String key, HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException
{
logger.info( "Looking for error: '{}' in:\n{}", key, errors );
if ( errors.containsKey( key ) )
{
Expand All @@ -175,7 +182,6 @@ protected void service( final HttpServletRequest req, final HttpServletResponse
if ( error.handler() != null )
{
error.handler().handle( req, resp );
return;
}
else if ( error.body() != null )
{
Expand All @@ -190,21 +196,19 @@ else if ( error.bodyStream() != null )
{
resp.sendError( error.code() );
}

return;
return true;
}

logger.info( "Looking for expectation: '{}'", key );
final ContentResponse expectation = expectations.get( key );
if ( expectation != null )
if ( expectations.containsKey( key ) )
{
final ContentResponse expectation = expectations.get( key );
logger.info( "Responding via registered expectation: {}", expectation );

if ( expectation.handler() != null )
{
expectation.handler().handle( req, resp );
logger.info( "Using handler..." );
return;
}
else if ( expectation.body() != null )
{
Expand All @@ -225,11 +229,33 @@ else if ( expectation.bodyStream() != null )
resp.setStatus( expectation.code() );
logger.info( "Set status: {} with no body", expectation.code() );
}
return true;
}

return false;
}

/**
* Get path with query string.
*/
private String getWholePath( HttpServletRequest request )
{
String requestURI = request.getRequestURI();
String queryString = request.getQueryString();

return;
if ( queryString == null )
{
return requestURI;
}
else
{
return requestURI + "?" + queryString;
}
}

resp.setStatus( 404 );
private String getSimplePath( HttpServletRequest request )
{
return request.getRequestURI();
}

public String getAccessKey( final CommonMethod method, final String path )
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import org.junit.Rule;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;

import static org.hamcrest.CoreMatchers.equalTo;
Expand All @@ -50,45 +51,54 @@ public void simpleDownload()
final String path = server.formatPath( subPath );
server.expect( url, 200, content );

String result = getHttpContent( url );
assertThat(result, equalTo(content));

final String key = server.getAccessKey( CommonMethod.GET.name(), path );
System.out.println( "Getting accesses for: '" + key + "'" );
assertThat( server.getAccessesByPathKey().get( key ), equalTo( 1 ) );
}

@Test
public void downloadWithQueryParams()
throws Exception
{
final ExpectationServer server = serverRule.getServer();

final String subPath = "/path/to/something";
final String path1 = subPath + "?version=1.0";
final String path2 = subPath + "?version=2.0";

final String url1 = server.formatUrl(path1);
final String url2 = server.formatUrl(path2);

final String content1 = "this is a test version 1";
final String content2 = "this is a test version 2";

server.expect(url1, 200, content1);
server.expect(url2, 200, content2);

String result = getHttpContent(url1);
assertThat(result, equalTo(content1));

result = getHttpContent(url2);
assertThat(result, equalTo(content2));

}

private String getHttpContent(String url) throws IOException
{
final HttpGet request = new HttpGet( url );
final CloseableHttpClient client = HttpClients.createDefault();
CloseableHttpResponse response = null;

InputStream stream = null;
try
try(CloseableHttpResponse response = client.execute( request ))
{
response = client.execute( request );
stream = response.getEntity().getContent();
final String result = IOUtils.toString( stream );

assertThat( result, notNullValue() );
assertThat( result, equalTo( content ) );
InputStream stream = response.getEntity().getContent();
return IOUtils.toString( stream );
}
finally
{
IOUtils.closeQuietly( stream );
if ( response != null && response.getEntity() != null )
{
EntityUtils.consumeQuietly( response.getEntity() );
IOUtils.closeQuietly( response );
}

if ( request != null )
{
request.reset();
}

if ( client != null )
{
IOUtils.closeQuietly( client );
}
IOUtils.closeQuietly( client );
}

System.out.println( server.getAccessesByPathKey() );

final String key = server.getAccessKey( CommonMethod.GET.name(), path );
System.out.println( "Getting accesses for: '" + key + "'" );
assertThat( server.getAccessesByPathKey().get( key ), equalTo( 1 ) );
}

}

0 comments on commit d166a30

Please sign in to comment.