Skip to content

Commit bce4c2e

Browse files
authored
refactor: increase test coverage (#111)
- removed unused methods - added tests for configruation errors - corrected casting for StateRequestMatchers - added tests for standalone extension initialization - simplified handlebar helper configuration check <!-- Please describe your pull request here. --> ## References - TODO <!-- References to relevant GitHub issues and pull requests, esp. upstream and downstream changes --> ## Submitter checklist - [ ] Recommended: Join [WireMock Slack](https://slack.wiremock.org/) to get any help in `#help-contributing` or a project-specific channel like `#wiremock-java` - [ ] The PR request is well described and justified, including the body and the references - [ ] The PR title represents the desired changelog entry - [ ] The repository's code style is followed (see the contributing guide) - [ ] Test coverage that demonstrates that the change works as expected - [ ] For new features, there's necessary documentation in this pull request or in a subsequent PR to [wiremock.org](https://github.com/wiremock/wiremock.org) <!-- Put an `x` into the [ ] to show you have filled the information. The template comes from https://github.com/wiremock/.github/blob/main/.github/pull_request_template.md You can override it by creating .github/pull_request_template.md in your own repository -->
1 parent af4474a commit bce4c2e

File tree

9 files changed

+130
-152
lines changed

9 files changed

+130
-152
lines changed

src/main/java/org/wiremock/extensions/state/extensions/DeleteStateEventListener.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -199,7 +199,7 @@ private void deleteWhere(DeleteStateParameters.ListParameters listConfig, String
199199
private String createContextName(String rawContext) {
200200
var context = Optional.ofNullable(rawContext).filter(StringUtils::isNotBlank)
201201
.map(it -> renderTemplate(model, it))
202-
.orElseThrow(() -> new ConfigurationException("no context specified"));
202+
.orElseThrow(() -> new ConfigurationException("No context specified"));
203203
if (StringUtils.isBlank(context)) {
204204
throw createConfigurationError("Context cannot be blank");
205205
}

src/main/java/org/wiremock/extensions/state/extensions/StateHandlerbarHelper.java

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -58,10 +58,7 @@ public Object apply(Object o, Options options) {
5858
if (StringUtils.isEmpty(contextName)) {
5959
return handleError("'context' cannot be empty");
6060
}
61-
if (StringUtils.isBlank(property) && StringUtils.isBlank(list)) {
62-
return handleError("Either 'property' or 'list' has to be set");
63-
}
64-
if (StringUtils.isNotBlank(property) && StringUtils.isNotBlank(list)) {
61+
if (StringUtils.isNotBlank(property) == StringUtils.isNotBlank(list)) {
6562
return handleError("Either 'property' or 'list' has to be set");
6663
}
6764
if (StringUtils.isNotBlank(property)) {

src/main/java/org/wiremock/extensions/state/extensions/StateRequestMatcher.java

Lines changed: 24 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -24,10 +24,10 @@
2424
import com.github.tomakehurst.wiremock.matching.MatchResult;
2525
import com.github.tomakehurst.wiremock.matching.RequestMatcherExtension;
2626
import com.github.tomakehurst.wiremock.matching.StringValuePattern;
27-
import org.wiremock.extensions.state.internal.model.Context;
2827
import org.wiremock.extensions.state.internal.ContextManager;
29-
import org.wiremock.extensions.state.internal.model.ContextTemplateModel;
3028
import org.wiremock.extensions.state.internal.StateExtensionMixin;
29+
import org.wiremock.extensions.state.internal.model.Context;
30+
import org.wiremock.extensions.state.internal.model.ContextTemplateModel;
3131

3232
import java.util.Arrays;
3333
import java.util.Collection;
@@ -67,23 +67,23 @@ private static List<Map.Entry<ContextMatcher, Object>> getMatchers(Parameters pa
6767
.collect(Collectors.toUnmodifiableList());
6868
}
6969

70-
private static <T> T cast(Object object) {
70+
private static <T> T mapToObject(Map<String, Object> map, Class<T> klass) {
7171
try {
72-
//noinspection unchecked
73-
return (T) object;
74-
} catch (ClassCastException ex) {
75-
var msg = String.format("Configuration has invalid type: %s", ex.getMessage());
72+
return Json.mapToObject(map, klass);
73+
} catch (Exception ex) {
74+
var msg = String.format("Cannot create pattern matcher: %s", ex.getMessage());
7675
var prefixed = String.format("%s: %s", "StateRequestMatcher", msg);
7776
notifier().error(prefixed);
7877
throw new ConfigurationException(prefixed);
7978
}
8079
}
8180

82-
private static <T> T mapToObject(Map<String, Object> map, Class<T> klass) {
81+
private static <T> T cast(Object object, Class<T> target) {
8382
try {
84-
return Json.mapToObject(map, klass);
85-
} catch (Exception ex) {
86-
var msg = String.format("Cannot create pattern matcher: %s", ex.getMessage());
83+
//noinspection unchecked
84+
return target.cast(object);
85+
} catch (ClassCastException ex) {
86+
var msg = String.format("Configuration has invalid type: %s", ex.getMessage());
8787
var prefixed = String.format("%s: %s", "StateRequestMatcher", msg);
8888
notifier().error(prefixed);
8989
throw new ConfigurationException(prefixed);
@@ -144,11 +144,11 @@ String renderTemplate(Object context, String value) {
144144

145145
Object renderTemplateRecursively(Object context, Object value) {
146146
if (value instanceof Collection) {
147-
Collection<Object> castedCollection = cast(value);
147+
Collection<Object> castedCollection = cast(value, Collection.class);
148148
return castedCollection.stream().map(it -> renderTemplateRecursively(context, it)).collect(Collectors.toList());
149149
} else if (value instanceof Map) {
150150
var newMap = new HashMap<String, Object>();
151-
Map<String, Object> castedMap = cast(value);
151+
Map<String, Object> castedMap = cast(value, Map.class);
152152
castedMap.forEach((k, v) -> newMap.put(
153153
renderTemplate(context, k),
154154
renderTemplateRecursively(context, v)
@@ -162,7 +162,7 @@ Object renderTemplateRecursively(Object context, Object value) {
162162
private enum ContextMatcher {
163163

164164
property((Context c, Object object) -> {
165-
Map<String, Map<String, Object>> mapValue = cast(object);
165+
Map<String, Map<String, Object>> mapValue = cast(object, Map.class);
166166
var results = mapValue.entrySet().stream().map(entry -> {
167167
var patterns = mapToObject(entry.getValue(), StringValuePattern.class);
168168
var propertyValue = c.getProperties().get(entry.getKey());
@@ -177,7 +177,7 @@ private enum ContextMatcher {
177177
}),
178178

179179
list((Context c, Object object) -> {
180-
Map<String, Map<String, Map<String, Object>>> mapValue = cast(object);
180+
Map<String, Map<String, Map<String, Object>>> mapValue = cast(object, Map.class);
181181
var allResults = mapValue.entrySet().stream().map(listIndexEntry -> {
182182
Map<String, String> listEntry;
183183
switch (listIndexEntry.getKey()) {
@@ -194,7 +194,7 @@ private enum ContextMatcher {
194194
if (listEntry == null) {
195195
return MatchResult.noMatch();
196196
} else {
197-
var results = listIndexEntry.getValue().entrySet().stream().map(entry -> {
197+
List<MatchResult> results = listIndexEntry.getValue().entrySet().stream().map(entry -> {
198198
var patterns = mapToObject(entry.getValue(), StringValuePattern.class);
199199
var propertyValue = listEntry.get(entry.getKey());
200200
return patterns.match(propertyValue);
@@ -210,35 +210,35 @@ private enum ContextMatcher {
210210
return MatchResult.aggregate(allResults);
211211
}),
212212
hasProperty((Context c, Object object) -> {
213-
String stringValue = cast(object);
213+
String stringValue = cast(object, String.class);
214214
return toMatchResult(c.getProperties().containsKey(stringValue));
215215
}),
216216
hasNotProperty((Context c, Object object) -> {
217-
String stringValue = cast(object);
217+
String stringValue = cast(object, String.class);
218218
return toMatchResult(!c.getProperties().containsKey(stringValue));
219219
}),
220220
updateCountEqualTo((Context c, Object object) -> {
221-
String stringValue = cast(object);
221+
String stringValue = cast(object, String.class);
222222
return toMatchResult(withConvertedNumber(c, stringValue, (context, value) -> context.getUpdateCount().equals(value)));
223223
}),
224224
updateCountLessThan((Context c, Object object) -> {
225-
String stringValue = cast(object);
225+
String stringValue = cast(object, String.class);
226226
return toMatchResult(withConvertedNumber(c, stringValue, (context, value) -> context.getUpdateCount() < value));
227227
}),
228228
updateCountMoreThan((Context c, Object object) -> {
229-
String stringValue = cast(object);
229+
String stringValue = cast(object, String.class);
230230
return toMatchResult(withConvertedNumber(c, stringValue, (context, value) -> context.getUpdateCount() > value));
231231
}),
232232
listSizeEqualTo((Context c, Object object) -> {
233-
String stringValue = cast(object);
233+
String stringValue = cast(object, String.class);
234234
return toMatchResult(withConvertedNumber(c, stringValue, (context, value) -> context.getList().size() == value));
235235
}),
236236
listSizeLessThan((Context c, Object object) -> {
237-
String stringValue = cast(object);
237+
String stringValue = cast(object, String.class);
238238
return toMatchResult(withConvertedNumber(c, stringValue, (context, value) -> context.getList().size() < value));
239239
}),
240240
listSizeMoreThan((Context c, Object object) -> {
241-
String stringValue = cast(object);
241+
String stringValue = cast(object, String.class);
242242
return toMatchResult(withConvertedNumber(c, stringValue, (context, value) -> context.getList().size() > value));
243243
});
244244

src/main/java/org/wiremock/extensions/state/internal/TransactionManager.java

Lines changed: 0 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -33,20 +33,6 @@ public TransactionManager(Store<String, Object> store) {
3333
this.store = store;
3434
}
3535

36-
public <T> T withTransaction(String requestId, String contextName, Function<Transaction, T> function) {
37-
var transactionKey = createTransactionKey(requestId);
38-
synchronized (store) {
39-
@SuppressWarnings("unchecked") var requestTransactions = store.get(transactionKey).map(it -> (Map<String, Transaction>) it).orElse(new HashMap<>());
40-
var contextTransaction = requestTransactions.getOrDefault(contextName, new Transaction(contextName));
41-
try {
42-
return function.apply(contextTransaction);
43-
} finally {
44-
requestTransactions.put(contextName, contextTransaction);
45-
store.put(transactionKey, requestTransactions);
46-
}
47-
}
48-
}
49-
5036
public void withTransaction(String requestId, String contextName, Consumer<Transaction> consumer) {
5137
var transactionKey = createTransactionKey(requestId);
5238
synchronized (store) {
@@ -80,6 +66,4 @@ public Set<String> getContextNamesByRequestId(String requestId) {
8066
private String createTransactionKey(String requestId) {
8167
return TRANSACTION_KEY_PREFIX + requestId;
8268
}
83-
84-
8569
}

src/main/java/org/wiremock/extensions/state/internal/api/StateRequestMatcherParameters.java

Lines changed: 0 additions & 95 deletions
This file was deleted.

src/test/java/org/wiremock/extensions/state/functionality/DeleteStateEventListenerTest.java

Lines changed: 35 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -751,30 +751,53 @@ public void test_ignoreUnknownExtraProperty() {
751751
assertThat(contextManager.getContextCopy(contextName)).isEmpty();
752752
}
753753

754-
private void assertListConfigurationError() {
754+
private void assertConfigurationError(String errorMessage) {
755755
getContext(contextName, HttpStatus.SC_INTERNAL_SERVER_ERROR,
756756
(result) -> assertThat(result)
757757
.hasEntrySatisfying(
758758
"message",
759759
message ->
760760
assertThat(message)
761761
.asInstanceOf(STRING)
762-
.contains("Missing/invalid configuration for list")
762+
.contains(errorMessage)
763763
)
764764
);
765765
}
766766

767+
private void assertListConfigurationError() {
768+
assertConfigurationError("Missing/invalid configuration for list");
769+
}
770+
767771
private void assertContextDeletionConfigurationError() {
768-
getContext(contextName, HttpStatus.SC_INTERNAL_SERVER_ERROR,
769-
(result) -> assertThat(result)
770-
.hasEntrySatisfying(
771-
"message",
772-
message ->
773-
assertThat(message)
774-
.asInstanceOf(STRING)
775-
.contains("Missing/invalid configuration for context deletion")
776-
)
777-
);
772+
assertConfigurationError("Missing/invalid configuration for context deletion");
773+
}
774+
775+
@Nested
776+
public class ContextName {
777+
778+
@DisplayName("fails on missing context name")
779+
@Test
780+
public void test_missingContextName_fail() {
781+
createGetStub(Map.of());
782+
783+
assertConfigurationError("Missing/invalid configuration for context deletion");
784+
}
785+
786+
@DisplayName("fails on empty context name")
787+
@Test
788+
public void test_emptyContextName_fail() {
789+
createGetStub(Map.of("context", ""));
790+
791+
assertConfigurationError("No context specified");
792+
}
793+
794+
@DisplayName("fails on template resulting in empty context name")
795+
@Test
796+
public void test_templateToEmptyContextName_fail() {
797+
createGetStub(Map.of("context", "{{jsonPath '{}' '$.empty'}}"));
798+
799+
assertConfigurationError("Context cannot be blank");
800+
}
778801
}
779802

780803
@DisplayName("with array exact match")
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package org.wiremock.extensions.state.functionality;
2+
3+
import com.github.tomakehurst.wiremock.junit5.WireMockExtension;
4+
import org.junit.jupiter.api.Test;
5+
import org.junit.jupiter.api.extension.RegisterExtension;
6+
import org.wiremock.extensions.state.StandaloneStateExtension;
7+
8+
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
9+
import static org.assertj.core.api.Assertions.assertThat;
10+
11+
public class StandaloneExtensionTest {
12+
13+
14+
@RegisterExtension
15+
public static WireMockExtension wm = WireMockExtension.newInstance()
16+
.options(
17+
wireMockConfig().dynamicPort().dynamicHttpsPort().templatingEnabled(true).globalTemplating(true)
18+
.extensions(new StandaloneStateExtension())
19+
)
20+
.build();
21+
22+
@Test
23+
public void test_initialized_ok() {
24+
assertThat(wm.getOptions().getDeclaredExtensions().getFactories()).anySatisfy(it -> {
25+
assertThat(it).isInstanceOf(StandaloneStateExtension.class);
26+
});
27+
}
28+
29+
}

src/test/java/org/wiremock/extensions/state/functionality/StateRequestMatcherTest.java

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -418,6 +418,13 @@ void setup() {
418418
postAndAssertContextValue(context, contextValueThree);
419419
}
420420

421+
@DisplayName("fails on invalid configuration")
422+
@Test
423+
void test_invalidConfiguration_fail() {
424+
createGetStub("list", "invalid");
425+
getAndAssertContextMatcher(context, HttpStatus.SC_INTERNAL_SERVER_ERROR);
426+
}
427+
421428
@DisplayName("fails on invalid built-in matchers")
422429
@Test
423430
void test_evaluateBuiltinMatchers_fail() {

0 commit comments

Comments
 (0)