Skip to content

Improve error handling, fix base URL comparison bug #28

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Mar 23, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 20 additions & 2 deletions src/main/java/com/easypost/easyvcr/MatchRules.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import com.easypost.easyvcr.internal.Utilities;
import com.easypost.easyvcr.requestelements.Request;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
Expand Down Expand Up @@ -50,13 +51,30 @@ private void by(BiFunction<Request, Request, Boolean> rule) {
*/
public MatchRules byBaseUrl() {
by((received, recorded) -> {
String receivedUri = received.getUri().getPath();
String recordedUri = recorded.getUri().getPath();
String receivedUri = getBaseUrl(received.getUri());
String recordedUri = getBaseUrl(recorded.getUri());
return receivedUri.equalsIgnoreCase(recordedUri);
});
return this;
}

/**
* Extract the base URL from a URI.
*
* @param url The URI to extract the base URL from.
* @return The base URL.
*/
private static String getBaseUrl(URI url) {
String baseUrl = url.getScheme() + "://" + url.getHost();
if (url.getPort() != -1) {
baseUrl += ":" + url.getPort();
}
if (url.getPath() != null) {
baseUrl += url.getPath();
}
return baseUrl;
}

/**
* Add a rule to compare the bodies of the requests.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,17 @@ public RecordableHttpURLConnection(URL url, Cassette cassette, Mode mode)
this(url, cassette, mode, new AdvancedSettings());
}

/**
* Throws an exception if a matching interaction has not been cached.
*
* @throws VCRException If the interaction has not been cached.
*/
private void cachedInteractionExistsOtherwiseError() throws VCRException {
if (this.cachedInteraction == null) {
throw new VCRException("No matching interaction found.");
}
}

/**
* Get an object from the cache.
*
Expand Down Expand Up @@ -725,6 +736,8 @@ Based on this Sun source code for HttpURLConnection (seen below):
try {
buildCache();

cachedInteractionExistsOtherwiseError();

if (this.cachedInteraction.getResponse().getStatus().getCode() >= 400) {
// Client Error 4xx and Server Error 5xx
return createInputStream(this.cachedInteraction.getResponse().getBody());
Expand Down Expand Up @@ -1297,6 +1310,7 @@ public InputStream getInputStream() throws IOException {
}
try {
buildCache();
cachedInteractionExistsOtherwiseError();
return createInputStream(this.cachedInteraction.getResponse().getBody());
} catch (VCRException | RecordingExpirationException e) {
throw new RuntimeException(e);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,17 @@ public RecordableHttpsURLConnection(URL url, Cassette cassette, Mode mode)
this(url, cassette, mode, new AdvancedSettings());
}

/**
* Throws an exception if a matching interaction has not been cached.
*
* @throws VCRException If the interaction has not been cached.
*/
private void cachedInteractionExistsOtherwiseError() throws VCRException {
if (this.cachedInteraction == null) {
throw new VCRException("No matching interaction found.");
}
}

/**
* Get an object from the cache.
*
Expand Down Expand Up @@ -728,6 +739,8 @@ Based on this Sun source code for HttpURLConnection (seen below):
try {
buildCache();

cachedInteractionExistsOtherwiseError();

if (this.cachedInteraction.getResponse().getStatus().getCode() >= 400) {
// Client Error 4xx and Server Error 5xx
return createInputStream(this.cachedInteraction.getResponse().getBody());
Expand Down Expand Up @@ -1300,6 +1313,7 @@ public InputStream getInputStream() throws IOException {
}
try {
buildCache();
cachedInteractionExistsOtherwiseError();
return createInputStream(this.cachedInteraction.getResponse().getBody());
} catch (VCRException | RecordingExpirationException e) {
throw new RuntimeException(e);
Expand Down
39 changes: 39 additions & 0 deletions src/test/java/HttpUrlConnectionTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import com.easypost.easyvcr.Mode;
import com.easypost.easyvcr.RecordingExpirationException;
import com.easypost.easyvcr.TimeFrame;
import com.easypost.easyvcr.VCRException;
import com.easypost.easyvcr.clients.httpurlconnection.RecordableHttpsURLConnection;
import com.google.gson.JsonParseException;
import org.junit.Assert;
Expand Down Expand Up @@ -534,4 +535,42 @@ public void testReplayHttpError() throws Exception {
Assert.assertNotNull(clientAfterRequest);
Assert.assertNotNull(clientAfterRequest.getErrorStream());
}

@Test
public void testCachedInteractionDoesNotExist() throws Exception {
Cassette cassette = TestUtils.getCassette("test_cached_interaction_does_not_exist");
cassette.erase(); // Erase cassette before recording

final String url = "https://google.com/path/to/endpoint";

// make connection using Mode.Record
RecordableHttpsURLConnection connection =
(RecordableHttpsURLConnection) HttpClients.newClient(HttpClientType.HttpsUrlConnection,
url, cassette, Mode.Record);
// make HTTP call (record to cassette)
connection.connect();
Assert.assertTrue(cassette.numInteractions() > 0); // make sure we recorded something

// Attempt to replay a cached interaction that does not exist
// need to use strict matching to ensure we don't match a different interaction
AdvancedSettings advancedSettings = new AdvancedSettings();
advancedSettings.matchRules = MatchRules.strict();

connection = (RecordableHttpsURLConnection) HttpClients.newClient(HttpClientType.HttpsUrlConnection,
url + "1", cassette, Mode.Replay, advancedSettings);
// make HTTP call (attempt replay from cassette)
connection.connect();

// Attempt to pull data (e.g. body) from the response (via the input stream)
// this throws a RuntimeException because of the way the exceptions are coalesced internally
try {
connection.getInputStream();
// if we get here, the exception was not thrown as expected
Assert.fail();
} catch (Exception e) {
Assert.assertTrue(e instanceof RuntimeException);
Assert.assertTrue(e.getCause() instanceof VCRException);
Assert.assertEquals(e.getCause().getMessage(), "No matching interaction found.");
}
}
}