Skip to content

Commit

Permalink
Add basic type conversion for YAML tests
Browse files Browse the repository at this point in the history
Our yaml rest tests parse expected values based on basic yaml parsing
rules, which don't draw a distinction between float and double values.

If there's a mismatch between the types of the expected and actual
values in an assertion, we should try parsing the actual value to the
expected type. For now, I just added support for the 32- and 64-bit
integer and floating point types.

Signed-off-by: Michael Froh <[email protected]>
  • Loading branch information
msfroh committed May 29, 2024
1 parent 4d8457e commit 8c9ac3c
Showing 1 changed file with 39 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@
import java.io.IOException;
import java.util.Map;

import static org.junit.Assert.fail;

/**
* Base class for executable sections that hold assertions
*/
Expand Down Expand Up @@ -73,10 +75,45 @@ protected final Object resolveExpectedValue(ClientYamlTestExecutionContext execu
}

protected final Object getActualValue(ClientYamlTestExecutionContext executionContext) throws IOException {
Object actualValue;
if (executionContext.stash().containsStashedValue(field)) {
return executionContext.stash().getValue(field);
actualValue = executionContext.stash().getValue(field);
} else {
actualValue = executionContext.response(field);
}
// Expected/actual values have the same type. Can just return.
if (expectedValue.getClass().isAssignableFrom(actualValue.getClass())) {
return actualValue;
}
if (actualValue instanceof Number && expectedValue instanceof Number) {
if (expectedValue instanceof Float) {
return Float.parseFloat(actualValue.toString());
} else if (expectedValue instanceof Double) {
return Double.parseDouble(actualValue.toString());
} else if (expectedValue instanceof Integer) {
return Integer.parseInt(actualValue.toString());
} else if (expectedValue instanceof Long) {
return Long.parseLong(actualValue.toString());
}
}
// Force a class cast exception here, so developers can flesh out the above logic as needed.
try {
expectedValue.getClass().cast(actualValue);
} catch (ClassCastException e) {
fail(
"Type mismatch: Expected value ("
+ expectedValue
+ ") has type "
+ expectedValue.getClass()
+ ". "
+ "Actual value ("
+ actualValue
+ ") has type "
+ actualValue.getClass()
+ "."
);
}
return executionContext.response(field);
return actualValue;
}

@Override
Expand Down

0 comments on commit 8c9ac3c

Please sign in to comment.