Skip to content
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

Fix when request body is empty string #1163

Merged
merged 3 commits into from
Sep 28, 2021
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
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apiguardian.api.API;
import org.zalando.logbook.BodyFilter;

Expand All @@ -28,6 +29,7 @@
import static org.zalando.logbook.json.JsonMediaType.JSON;

@API(status = EXPERIMENTAL)
@Slf4j
@NoArgsConstructor(access = PRIVATE)
public final class JsonPathBodyFilters {

Expand Down Expand Up @@ -97,12 +99,18 @@ private static class JsonPathBodyFilter implements BodyFilter {
public String filter(
@Nullable final String contentType, final String body) {

if (JSON.test(contentType)) {
if (body.isEmpty() || !JSON.test(contentType)) {
return body;
}

try {
final DocumentContext original = CONTEXT.parse(body);
return operation.filter(original).jsonString();
} catch (Exception e) {
log.trace("The body could not be filtered, the following exception {} has been thrown", e.getClass());
return body;
}

return body;
}

@Nullable
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -252,4 +252,23 @@ void replacesValuesDynamicallyWhenBodyIsUnwrappedArray() throws IOException {
.assertEquals("$.[1].name", "BMW")
.assertEquals("$.[2].name", "FIAT");
}

@Test
void doesNotFailWhenBodyIsEmpty() {
final BodyFilter unit = jsonPath("$.id").replace(compile("\\s+"), "XXX");

String actual = unit.filter(type, "");

assertThat(actual).isEmpty();
}

@Test
void shouldReturnSameBodyWhenBodyIsInvalidJson() {
String invalidBody = "{\"id\": 1, \"name\": \"Alice\",}";
final BodyFilter unit = jsonPath("$.id").replace(compile("\\s+"), "XXX");

String actual = unit.filter(type, invalidBody);

assertThat(actual).isEqualTo(invalidBody);
}
}