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

XMLUnit regex matcher placeholders can be used for dynamic token replacement #404

Merged
merged 2 commits into from
Dec 9, 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 @@ -1446,10 +1446,7 @@ public void stubby4jIssue399_XmlUnit_Matcher() throws Exception {

final String httpResponseContent = httpResponse.parseAsString().trim();

// Unfortunately, when XMLUnit Matcher is used in the stubbed XML payload, i.e.: `${xmlunit.matchesRegex(.*)}`,
// this only helps with the XML regex matching. But, using XMLUnit Matcher does not capture the value of
// the ${xmlunit.matchesRegex(.*)} for token replacement.
final URL xmlActualContentResource = StubsPortalTest.class.getResource("/xml/response/xml_response_issue_399_stub_template.xml");
final URL xmlActualContentResource = StubsPortalTest.class.getResource("/xml/response/xml_response_issue_399_body.xml");
assertThat(xmlActualContentResource).isNotNull();
final String expectedResponseContent = StringUtils.inputStreamToString(xmlActualContentResource.openStream());

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@

import io.github.azagniotov.stubby4j.annotations.VisibleForTesting;
import io.github.azagniotov.stubby4j.cli.ANSITerminal;
import io.github.azagniotov.stubby4j.stubs.matching.Stubby4jMatchesRegexPlaceholderHandler;
import io.github.azagniotov.stubby4j.stubs.matching.Stubby4jXmlUnitPlaceholderDifferenceEvaluator;
import org.json.JSONException;
import org.skyscreamer.jsonassert.JSONCompare;
import org.skyscreamer.jsonassert.JSONCompareMode;
Expand All @@ -16,7 +18,6 @@
import org.xmlunit.diff.DifferenceEvaluator;
import org.xmlunit.diff.DifferenceEvaluators;
import org.xmlunit.diff.ElementSelectors;
import org.xmlunit.placeholder.PlaceholderDifferenceEvaluator;

import java.util.HashMap;
import java.util.List;
Expand Down Expand Up @@ -252,9 +253,11 @@ private boolean xmlMatch(final String stubbedXml, final String assertingXml, fin
// e.g.: ${xmlunit.matchesRegex(..)}, so let's do another comparison pass
// using PlaceholderDifferenceEvaluator.
// More info: https://github.com/azagniotov/stubby4j#regex-stubbing-for-xml-content
final Stubby4jMatchesRegexPlaceholderHandler matchesRegexPlaceholderHandler =
new Stubby4jMatchesRegexPlaceholderHandler(templateTokenName, this.regexGroups);
final DifferenceEvaluator differenceEvaluatorChain = DifferenceEvaluators.chain(
DifferenceEvaluators.Default,
new PlaceholderDifferenceEvaluator()
new Stubby4jXmlUnitPlaceholderDifferenceEvaluator(matchesRegexPlaceholderHandler)
);

final DiffBuilder xmlDiffBuilder = DiffBuilder
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/*
This file is licensed to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package io.github.azagniotov.stubby4j.stubs.matching;

import io.github.azagniotov.stubby4j.annotations.GeneratedCodeCoverageExclusion;
import org.xmlunit.XMLUnitException;
import org.xmlunit.diff.ComparisonResult;
import org.xmlunit.placeholder.PlaceholderHandler;

import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import static io.github.azagniotov.stubby4j.utils.StringUtils.buildToken;
import static org.xmlunit.diff.ComparisonResult.DIFFERENT;
import static org.xmlunit.diff.ComparisonResult.EQUAL;

/**
* Handler for the {@code matchesRegex()} placeholder keyword.
*
* @since 2.7.0
*/
@GeneratedCodeCoverageExclusion
public class Stubby4jMatchesRegexPlaceholderHandler implements PlaceholderHandler {
private static final String PLACEHOLDER_NAME = "matchesRegex";
private final String templateTokenName;
private final Map<String, String> stubbedRequestRegexGroups;
private AtomicInteger contentRegexGroupCounter;

public Stubby4jMatchesRegexPlaceholderHandler(final String templateTokenName, final Map<String, String> stubbedRequestRegexGroups) {
this.templateTokenName = templateTokenName;
this.stubbedRequestRegexGroups = stubbedRequestRegexGroups;
this.contentRegexGroupCounter = new AtomicInteger(1);
}

@Override
public String getKeyword() {
return PLACEHOLDER_NAME;
}

@Override
public ComparisonResult evaluate(String testText, String... param) {
if (param.length > 0 && param[0] != null && !param[0].equals("")) {
try {
final Pattern pattern = Pattern.compile(param[0].trim());
if (testText != null && evaluate(testText.trim(), pattern)) {
return EQUAL;
}
} catch (PatternSyntaxException e) {
throw new XMLUnitException(e.getMessage(), e);
}
}
return DIFFERENT;
}

private boolean evaluate(final String testText, final Pattern pattern) {
final Matcher matcher = pattern.matcher(testText);
final boolean isMatch = matcher.find();
if (isMatch) {
final int groupId = contentRegexGroupCounter.getAndIncrement();
this.stubbedRequestRegexGroups.put(buildToken(templateTokenName, groupId), matcher.group(0));
}
return isMatch;
}
}
Loading