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

Updates for latest protocol tests #246

Merged
merged 6 commits into from
Dec 14, 2020
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
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ target/
build/
*/out/
*/*/out/
wrapper/

# Visual Studio Code
.vscode/*
.vscode/*
2 changes: 1 addition & 1 deletion build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ plugins {

allprojects {
group = "software.amazon.smithy"
version = "0.2.0"
version = "0.3.0"
}

// The root project doesn't produce a JAR.
Expand Down
4 changes: 2 additions & 2 deletions smithy-typescript-codegen-test/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ extra["moduleName"] = "software.amazon.smithy.typescript.codegen.test"
tasks["jar"].enabled = false

plugins {
id("software.amazon.smithy").version("0.5.1")
id("software.amazon.smithy").version("0.5.2")
}

repositories {
Expand All @@ -29,5 +29,5 @@ repositories {

dependencies {
implementation(project(":smithy-typescript-codegen"))
implementation("software.amazon.smithy:smithy-protocol-test-traits:[1.0.8, 2.0[")
implementation("software.amazon.smithy:smithy-protocol-test-traits:[1.5.0, 2.0[")
}
1 change: 1 addition & 0 deletions smithy-typescript-codegen-test/model/main.smithy
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,7 @@ union Precipitation {

structure OtherStructure {}

@suppress(["EnumNamesPresent"])
@enum([{value: "YES"}, {value: "NO"}])
string SimpleYesNo

Expand Down
4 changes: 2 additions & 2 deletions smithy-typescript-codegen/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,6 @@ extra["displayName"] = "Smithy :: Typescript :: Codegen"
extra["moduleName"] = "software.amazon.smithy.typescript.codegen"

dependencies {
api("software.amazon.smithy:smithy-codegen-core:[1.0.8, 2.0[")
implementation("software.amazon.smithy:smithy-protocol-test-traits:[1.0.8, 2.0[")
api("software.amazon.smithy:smithy-codegen-core:[1.5.0, 2.0[")
implementation("software.amazon.smithy:smithy-protocol-test-traits:[1.5.0, 2.0[")
}
Original file line number Diff line number Diff line change
Expand Up @@ -51,12 +51,14 @@
import software.amazon.smithy.model.traits.ErrorTrait;
import software.amazon.smithy.model.traits.HttpPrefixHeadersTrait;
import software.amazon.smithy.model.traits.IdempotencyTokenTrait;
import software.amazon.smithy.model.traits.StreamingTrait;
import software.amazon.smithy.protocoltests.traits.HttpMessageTestCase;
import software.amazon.smithy.protocoltests.traits.HttpRequestTestCase;
import software.amazon.smithy.protocoltests.traits.HttpRequestTestsTrait;
import software.amazon.smithy.protocoltests.traits.HttpResponseTestCase;
import software.amazon.smithy.protocoltests.traits.HttpResponseTestsTrait;
import software.amazon.smithy.utils.IoUtils;
import software.amazon.smithy.utils.ListUtils;
import software.amazon.smithy.utils.MapUtils;
import software.amazon.smithy.utils.Pair;

Expand All @@ -77,6 +79,10 @@ final class HttpProtocolTestGenerator implements Runnable {
private static final Logger LOGGER = Logger.getLogger(HttpProtocolTestGenerator.class.getName());
private static final String TEST_CASE_FILE_TEMPLATE = "tests/functional/%s.spec.ts";

// Headers that are generated by other sources that need to be normalized in the
// test cases to match.
private static final List<String> HEADERS_TO_NORMALIZE = ListUtils.of("content-length", "content-type");

private final TypeScriptSettings settings;
private final Model model;
private final ShapeId protocol;
Expand Down Expand Up @@ -248,21 +254,31 @@ private void writeRequestQueryAssertions(HttpRequestTestCase testCase) {
}

private void writeRequestHeaderAssertions(HttpRequestTestCase testCase) {
testCase.getRequireHeaders().forEach(requiredHeader ->
writer.write("expect(r.headers[$S]).toBeDefined();", requiredHeader));
testCase.getRequireHeaders().forEach(requiredHeader -> {
writer.write("expect(r.headers[$S]).toBeDefined();", normalizeHeaderName(requiredHeader));
});
writer.write("");

testCase.getForbidHeaders().forEach(forbidHeader ->
writer.write("expect(r.headers[$S]).toBeUndefined();", forbidHeader));
writer.write("expect(r.headers[$S]).toBeUndefined();", normalizeHeaderName(forbidHeader)));
writer.write("");

testCase.getHeaders().forEach((header, value) -> {
header = normalizeHeaderName(header);
writer.write("expect(r.headers[$S]).toBeDefined();", header);
writer.write("expect(r.headers[$S]).toBe($S);", header, value);
});
writer.write("");
}

private String normalizeHeaderName(String headerName) {
if (HEADERS_TO_NORMALIZE.contains(headerName.toLowerCase())) {
return headerName.toLowerCase();
}

return headerName;
}

private void writeRequestBodyAssertions(OperationShape operation, HttpRequestTestCase testCase) {
testCase.getBody().ifPresent(body -> {
// If we expect an empty body, expect it to be falsy.
Expand Down Expand Up @@ -433,9 +449,50 @@ private void writeParamAssertions(Shape operationOrError, HttpResponseTestCase t
.call(() -> params.accept(new CommandOutputNodeVisitor(testOutputShape)))
.write("][0];");

// Extract a payload binding if present.
Optional<HttpBinding> payloadBinding = operationOrError.asOperationShape()
kstich marked this conversation as resolved.
Show resolved Hide resolved
.map(operationShape -> {
HttpBindingIndex index = HttpBindingIndex.of(model);
List<HttpBinding> payloadBindings = index.getResponseBindings(operationOrError,
Location.PAYLOAD);
if (!payloadBindings.isEmpty()) {
return payloadBindings.get(0);
}
return null;
});

// If we have a streaming payload blob, we need to collect it to something that
// can be compared with the test contents. This emulates the customer experience.
boolean hasStreamingPayloadBlob = payloadBinding
.map(binding ->
model.getShape(binding.getMember().getTarget())
.filter(Shape::isBlobShape)
.filter(s -> s.hasTrait(StreamingTrait.ID))
.isPresent())
.orElse(false);

// Do the collection for payload blobs.
if (hasStreamingPayloadBlob) {
writer.write("const comparableBlob = await client.config.streamCollector(r[$S]);",
payloadBinding.get().getMemberName());
}

// Perform parameter comparisons.
writer.openBlock("Object.keys(paramsToValidate).forEach(param => {", "});", () -> {
writer.write("expect(r[param]).toBeDefined();");
if (hasStreamingPayloadBlob) {
writer.openBlock("if (param === $S) {", "} else {", payloadBinding.get().getMemberName(), () ->
writer.write("expect(equivalentContents(comparableBlob, "
+ "paramsToValidate[param])).toBe(true);"));
writer.indent();
}

writer.write("expect(equivalentContents(r[param], paramsToValidate[param])).toBe(true);");

if (hasStreamingPayloadBlob) {
writer.dedent();
writer.write("}");
}
});
}
}
Expand Down Expand Up @@ -486,8 +543,7 @@ public Void booleanNode(BooleanNode node) {

@Override
public Void nullNode(NullNode node) {
// Handle nulls being literal "undefined" in JS.
writer.write("undefined,");
writer.write("null,");
trivikr marked this conversation as resolved.
Show resolved Hide resolved
return null;
}

Expand All @@ -505,19 +561,30 @@ public Void numberNode(NumberNode node) {

@Override
public Void objectNode(ObjectNode node) {
// Short circuit document types, as the direct value is what we want.
if (workingShape.isDocumentShape()) {
writer.writeInline(Node.prettyPrintJson(node));
return null;
}

// Both objects and maps can use a majority of the same logic.
// Use "as any" to have TS complain less about undefined entries.
writer.openBlock("{", "} as any,\n", () -> {
Shape wrapperShape = this.workingShape;
node.getMembers().forEach((keyNode, valueNode) -> {
writer.write("$L: ", keyNode.getValue());
writer.writeInline("$L: ", keyNode.getValue());

// Grab the correct member related to the node member we have.
MemberShape memberShape;
if (wrapperShape.isStructureShape()) {
memberShape = wrapperShape.asStructureShape().get().getMember(keyNode.getValue()).get();
} else {
} else if (wrapperShape.isUnionShape()) {
memberShape = wrapperShape.asUnionShape().get().getMember(keyNode.getValue()).get();
} else if (wrapperShape.isMapShape()) {
memberShape = wrapperShape.asMapShape().get().getValue();
} else {
throw new CodegenException("Unknown shape type for object node when "
+ "generating protocol test input: " + wrapperShape.getType());
}

// Handle auto-filling idempotency token values to the explicit value.
Expand Down Expand Up @@ -631,6 +698,12 @@ public Void numberNode(NumberNode node) {

@Override
public Void objectNode(ObjectNode node) {
// Short circuit document types, as the direct value is what we want.
if (workingShape.isDocumentShape()) {
writer.writeInline(Node.prettyPrintJson(node));
return null;
}

// Both objects and maps can use a majority of the same logic.
// Use "as any" to have TS complain less about undefined entries.
writer.openBlock("{", "},\n", () -> {
Expand All @@ -640,8 +713,13 @@ public Void objectNode(ObjectNode node) {
MemberShape memberShape;
if (wrapperShape.isStructureShape()) {
memberShape = wrapperShape.asStructureShape().get().getMember(keyNode.getValue()).get();
} else {
} else if (wrapperShape.isUnionShape()) {
memberShape = wrapperShape.asUnionShape().get().getMember(keyNode.getValue()).get();
} else if (wrapperShape.isMapShape()) {
memberShape = wrapperShape.asMapShape().get().getValue();
} else {
throw new CodegenException("Unknown shape type for object node when "
+ "generating protocol test output: " + wrapperShape.getType());
}

// Handle error standardization to the down-cased "message".
Expand Down
Loading