use of com.google.api.generator.engine.ast.Statement in project gapic-generator-java by googleapis.
the class JavaWriterVisitorTest method writeForStatement.
@Test
public void writeForStatement() {
AssignmentExpr assignExpr = createAssignmentExpr("x", "3", TypeNode.INT);
Statement assignExprStatement = ExprStatement.withExpr(assignExpr);
List<Statement> body = Arrays.asList(assignExprStatement, assignExprStatement);
VariableExpr varDeclExpr = createVariableDeclExpr("str", TypeNode.STRING);
Expr collectionExpr = MethodInvocationExpr.builder().setMethodName("getSomeStrings").build();
ForStatement forStatement = ForStatement.builder().setLocalVariableExpr(varDeclExpr).setCollectionExpr(collectionExpr).setBody(body).build();
forStatement.accept(writerVisitor);
assertEquals(String.format("%s%s%s%s", "for (String str : getSomeStrings()) {\n", "int x = 3;\n", "int x = 3;\n", "}\n"), writerVisitor.write());
}
use of com.google.api.generator.engine.ast.Statement in project gapic-generator-java by googleapis.
the class JavaWriterVisitorTest method writeWhileStatement_simple.
@Test
public void writeWhileStatement_simple() {
AssignmentExpr assignExpr = createAssignmentExpr("x", "3", TypeNode.INT);
Statement assignExprStatement = ExprStatement.withExpr(assignExpr);
List<Statement> whileBody = Arrays.asList(assignExprStatement, assignExprStatement);
VariableExpr condExpr = createVariableExpr("condition", TypeNode.BOOLEAN);
WhileStatement whileStatement = WhileStatement.builder().setConditionExpr(condExpr).setBody(whileBody).build();
whileStatement.accept(writerVisitor);
assertEquals(LineFormatter.lines("while (condition) {\n", "int x = 3;\n", "int x = 3;\n", "}\n"), writerVisitor.write());
}
use of com.google.api.generator.engine.ast.Statement in project gapic-generator-java by googleapis.
the class JavaWriterVisitorTest method writeGeneralForStatement_basicIsNotDecl.
@Test
public void writeGeneralForStatement_basicIsNotDecl() {
AssignmentExpr assignExpr = createAssignmentExpr("x", "3", TypeNode.INT);
Statement assignExprStatement = ExprStatement.withExpr(assignExpr);
List<Statement> body = Arrays.asList(assignExprStatement, assignExprStatement);
VariableExpr localVarExpr = createVariableExpr("i", TypeNode.INT);
ValueExpr initValueExpr = ValueExpr.withValue(PrimitiveValue.builder().setValue("1").setType(TypeNode.INT).build());
ValueExpr maxValueExpr = ValueExpr.withValue(PrimitiveValue.builder().setValue("10").setType(TypeNode.INT).build());
GeneralForStatement forStatement = GeneralForStatement.incrementWith(localVarExpr, initValueExpr, maxValueExpr, body);
forStatement.accept(writerVisitor);
assertEquals(String.format("%s%s%s%s", "for (i = 1; i < 10; i++) {\n", "int x = 3;\n", "int x = 3;\n", "}\n"), writerVisitor.write());
}
use of com.google.api.generator.engine.ast.Statement in project gapic-generator-java by googleapis.
the class JavaWriterVisitorTest method writeClassDefinition_commentsStatementsAndMethods.
@Test
public void writeClassDefinition_commentsStatementsAndMethods() {
LineComment lineComment = LineComment.withComment("AUTO-GENERATED DOCUMENTATION AND CLASS");
JavaDocComment javaDocComment = JavaDocComment.builder().addComment("Class to configure an instance of {@link LibraryServiceStub}.").addParagraph("The default instance has everything set to sensible defaults:").addUnorderedList(Arrays.asList("The default service address (library-example.googleapis.com) and default port" + " (1234) are used.", "Credentials are acquired automatically through Application Default" + " Credentials.", "Retries are configured for idempotent methods but not for non-idempotent" + " methods.")).build();
List<Reference> subGenerics = Arrays.asList(ConcreteReference.withClazz(String.class), ConcreteReference.withClazz(MethodDefinition.class));
Reference mapEntryReference = ConcreteReference.builder().setClazz(Map.Entry.class).setGenerics(subGenerics).build();
List<Reference> generics = Arrays.asList(ConcreteReference.withClazz(ClassDefinition.class), mapEntryReference);
Reference mapReference = ConcreteReference.builder().setClazz(Map.class).setGenerics(generics).build();
List<Statement> statements = Arrays.asList(ExprStatement.withExpr(VariableExpr.builder().setVariable(createVariable("x", TypeNode.withReference(ConcreteReference.withClazz(AssignmentExpr.class)))).setIsDecl(true).setScope(ScopeNode.PRIVATE).build()), ExprStatement.withExpr(VariableExpr.builder().setVariable(createVariable("y", TypeNode.withReference(mapReference))).setIsDecl(true).setScope(ScopeNode.PROTECTED).build()));
MethodDefinition methodOne = MethodDefinition.builder().setName("open").setScope(ScopeNode.PUBLIC).setReturnType(TypeNode.BOOLEAN).setReturnExpr(ValueExpr.builder().setValue(PrimitiveValue.builder().setType(TypeNode.BOOLEAN).setValue("true").build()).build()).build();
MethodDefinition methodTwo = MethodDefinition.builder().setName("close").setScope(ScopeNode.PUBLIC).setReturnType(TypeNode.VOID).setBody(Arrays.asList(ExprStatement.withExpr(createAssignmentExpr("foobar", "false", TypeNode.BOOLEAN)))).build();
List<MethodDefinition> methods = Arrays.asList(methodOne, methodTwo);
ClassDefinition nestedClassDef = ClassDefinition.builder().setName("IAmANestedClass").setIsNested(true).setScope(ScopeNode.PRIVATE).setIsStatic(true).setMethods(Arrays.asList(methodOne)).build();
ClassDefinition classDef = ClassDefinition.builder().setPackageString("com.google.example.library.v1.stub").setHeaderCommentStatements(Arrays.asList(CommentStatement.withComment(lineComment), CommentStatement.withComment(javaDocComment))).setName("LibraryServiceStub").setScope(ScopeNode.PUBLIC).setStatements(statements).setMethods(methods).setNestedClasses(Arrays.asList(nestedClassDef)).build();
classDef.accept(writerVisitor);
String expected = LineFormatter.lines("package com.google.example.library.v1.stub;\n", "\n", "import com.google.api.generator.engine.ast.AssignmentExpr;\n", "import com.google.api.generator.engine.ast.ClassDefinition;\n", "import com.google.api.generator.engine.ast.MethodDefinition;\n", "import java.util.Map;\n", "\n", "// AUTO-GENERATED DOCUMENTATION AND CLASS\n", "/**\n", " * Class to configure an instance of {{@literal @}link LibraryServiceStub}.\n", " *\n", " * <p>The default instance has everything set to sensible defaults:\n", " *\n", " * <ul>\n", " * <li>The default service address (library-example.googleapis.com) and default" + " port (1234) are\n", " * used.\n", " * <li>Credentials are acquired automatically through Application Default" + " Credentials.\n", " * <li>Retries are configured for idempotent methods but not for non-idempotent" + " methods.\n", " * </ul>\n", " */\n", "public class LibraryServiceStub {\n", " private AssignmentExpr x;\n", " protected Map<ClassDefinition, Map.Entry<String, MethodDefinition>> y;\n\n", " public boolean open() {\n", " return true;\n", " }\n\n", " public void close() {\n", " boolean foobar = false;\n", " }\n", "\n", " private static class IAmANestedClass {\n\n", " public boolean open() {\n", " return true;\n", " }\n", " }\n", "}\n");
assertEquals(expected, writerVisitor.write());
}
use of com.google.api.generator.engine.ast.Statement in project gapic-generator-java by googleapis.
the class AbstractServiceClientTestClassComposer method createRpcTestMethod.
/**
* Creates a test method for a given RPC, e.g. createAssetTest.
*
* @param method the RPC for which this test method is created.
* @param apiService the host service under test.
* @param rpcService the service that {@code method} belongs to. This is not equal to {@code
* apiService} only when {@code method} is a mixin, in which case {@code rpcService} is the
* mixed-in service. If {@code apiService} and {@code rpcService} are different, they will be
* used only for pagination. Otherwise, {@code rpcService} subsumes {@code apiService}.
* @param methodSignature the method signature of the RPC under test.
* @param variantIndex the nth variant of the RPC under test. This applies when we have
* polymorphism due to the presence of several method signature annotations in the proto.
* @param isRequestArg whether the RPC variant under test take only the request proto message.
* @param classMemberVarExprs the class members in the generated test class.
* @param resourceNames the resource names available for use.
* @param messageTypes the proto message types available for use.
*/
private MethodDefinition createRpcTestMethod(Method method, Service apiService, Service rpcService, List<MethodArgument> methodSignature, int variantIndex, boolean isRequestArg, Map<String, VariableExpr> classMemberVarExprs, Map<String, ResourceName> resourceNames, Map<String, Message> messageTypes) {
if (!method.stream().equals(Method.Stream.NONE)) {
return createStreamingRpcTestMethod(rpcService, method, classMemberVarExprs, resourceNames, messageTypes);
}
// Construct the expected response.
TypeNode methodOutputType = method.hasLro() ? method.lro().responseType() : method.outputType();
List<Expr> methodExprs = new ArrayList<>();
TypeNode repeatedResponseType = null;
VariableExpr responsesElementVarExpr = null;
String mockServiceVarName = getMockServiceVarName(rpcService);
if (method.isPaged()) {
Message methodOutputMessage = messageTypes.get(method.outputType().reference().fullName());
Field repeatedPagedResultsField = methodOutputMessage.findAndUnwrapPaginatedRepeatedField();
Preconditions.checkNotNull(repeatedPagedResultsField, String.format("No repeated field found for paged method %s with output message type %s", method.name(), methodOutputMessage.name()));
if (repeatedPagedResultsField.isMap()) {
repeatedResponseType = TypeNode.withReference(repeatedPagedResultsField.type().reference().generics().get(1));
} else {
// Must be a non-repeated type.
repeatedResponseType = repeatedPagedResultsField.type();
}
responsesElementVarExpr = VariableExpr.withVariable(Variable.builder().setType(repeatedResponseType).setName("responsesElement").build());
methodExprs.add(AssignmentExpr.builder().setVariableExpr(responsesElementVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(DefaultValueComposer.createValue(Field.builder().setType(repeatedResponseType).setName("responsesElement").setIsMessage(!repeatedResponseType.isProtoPrimitiveType()).build())).build());
}
VariableExpr expectedResponseVarExpr = VariableExpr.withVariable(Variable.builder().setType(methodOutputType).setName("expectedResponse").build());
Expr expectedResponseValExpr = null;
if (method.isPaged()) {
Message methodOutputMessage = messageTypes.get(method.outputType().reference().fullName());
Field firstRepeatedField = methodOutputMessage.findAndUnwrapPaginatedRepeatedField();
Preconditions.checkNotNull(firstRepeatedField, String.format("Expected paged RPC %s to have a repeated field in the response %s but found none", method.name(), methodOutputMessage.name()));
expectedResponseValExpr = DefaultValueComposer.createSimplePagedResponseValue(method.outputType(), firstRepeatedField.name(), responsesElementVarExpr, firstRepeatedField.isMap());
} else {
if (messageTypes.containsKey(methodOutputType.reference().fullName())) {
expectedResponseValExpr = DefaultValueComposer.createSimpleMessageBuilderValue(messageTypes.get(methodOutputType.reference().fullName()), resourceNames, messageTypes);
} else {
// Wrap this in a field so we don't have to split the helper into lots of different methods,
// or duplicate it for VariableExpr.
expectedResponseValExpr = DefaultValueComposer.createValue(Field.builder().setType(methodOutputType).setIsMessage(true).setName("expectedResponse").build());
}
}
methodExprs.add(AssignmentExpr.builder().setVariableExpr(expectedResponseVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(expectedResponseValExpr).build());
if (method.hasLro() && (method.lro().operationServiceStubType() == null || !method.lro().responseType().equals(method.outputType()))) {
VariableExpr resultOperationVarExpr = VariableExpr.withVariable(Variable.builder().setType(FIXED_TYPESTORE.get("Operation")).setName("resultOperation").build());
methodExprs.add(AssignmentExpr.builder().setVariableExpr(resultOperationVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(DefaultValueComposer.createSimpleOperationBuilderValue(String.format("%sTest", JavaStyle.toLowerCamelCase(method.name())), expectedResponseVarExpr)).build());
methodExprs.add(MethodInvocationExpr.builder().setExprReferenceExpr(classMemberVarExprs.get(mockServiceVarName)).setMethodName("addResponse").setArguments(resultOperationVarExpr).build());
} else {
methodExprs.add(MethodInvocationExpr.builder().setExprReferenceExpr(classMemberVarExprs.get(mockServiceVarName)).setMethodName("addResponse").setArguments(expectedResponseVarExpr).build());
}
List<Statement> methodStatements = new ArrayList<>();
methodStatements.addAll(methodExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList()));
methodExprs.clear();
methodStatements.add(EMPTY_LINE_STATEMENT);
// Construct the request or method arguments.
VariableExpr requestVarExpr = null;
Message requestMessage = null;
List<VariableExpr> argExprs = new ArrayList<>();
if (isRequestArg) {
requestVarExpr = VariableExpr.withVariable(Variable.builder().setType(method.inputType()).setName("request").build());
argExprs.add(requestVarExpr);
requestMessage = messageTypes.get(method.inputType().reference().fullName());
Preconditions.checkNotNull(requestMessage);
Map<String, String> pathParamValuePatterns = Collections.emptyMap();
if (getTransportContext().useValuePatterns() && method.hasHttpBindings()) {
pathParamValuePatterns = method.httpBindings().getPathParametersValuePatterns();
}
Expr valExpr = DefaultValueComposer.createSimpleMessageBuilderValue(requestMessage, resourceNames, messageTypes, pathParamValuePatterns);
methodExprs.add(AssignmentExpr.builder().setVariableExpr(requestVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(valExpr).build());
} else {
Map<String, String> valuePatterns = Collections.emptyMap();
if (getTransportContext().useValuePatterns() && method.hasHttpBindings()) {
valuePatterns = method.httpBindings().getPathParametersValuePatterns();
}
for (MethodArgument methodArg : methodSignature) {
String methodArgName = JavaStyle.toLowerCamelCase(methodArg.name());
VariableExpr varExpr = VariableExpr.withVariable(Variable.builder().setType(methodArg.type()).setName(methodArgName).build());
argExprs.add(varExpr);
Expr valExpr = DefaultValueComposer.createMethodArgValue(methodArg, resourceNames, messageTypes, valuePatterns);
methodExprs.add(AssignmentExpr.builder().setVariableExpr(varExpr.toBuilder().setIsDecl(true).build()).setValueExpr(valExpr).build());
}
}
methodStatements.addAll(methodExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList()));
methodExprs.clear();
methodStatements.add(EMPTY_LINE_STATEMENT);
// Call the RPC Java method.
VariableExpr actualResponseVarExpr = VariableExpr.withVariable(Variable.builder().setType(!method.isPaged() ? methodOutputType : // does not have a client.
getPagedResponseType(method, method.isMixin() ? apiService : rpcService)).setName(method.isPaged() ? "pagedListResponse" : "actualResponse").build());
Expr rpcJavaMethodInvocationExpr = MethodInvocationExpr.builder().setExprReferenceExpr(classMemberVarExprs.get("client")).setMethodName(JavaStyle.toLowerCamelCase(method.name()) + (method.hasLro() ? "Async" : "")).setArguments(argExprs.stream().map(e -> (Expr) e).collect(Collectors.toList())).setReturnType(actualResponseVarExpr.type()).build();
if (method.hasLro()) {
rpcJavaMethodInvocationExpr = MethodInvocationExpr.builder().setExprReferenceExpr(rpcJavaMethodInvocationExpr).setMethodName("get").setReturnType(rpcJavaMethodInvocationExpr.type()).build();
}
boolean returnsVoid = isProtoEmptyType(methodOutputType);
if (returnsVoid) {
methodExprs.add(rpcJavaMethodInvocationExpr);
} else {
methodExprs.add(AssignmentExpr.builder().setVariableExpr(actualResponseVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(rpcJavaMethodInvocationExpr).build());
}
if (method.isPaged()) {
Message methodOutputMessage = messageTypes.get(method.outputType().reference().fullName());
Field repeatedPagedResultsField = methodOutputMessage.findAndUnwrapPaginatedRepeatedField();
// Assign the resources variable.
VariableExpr resourcesVarExpr = VariableExpr.withVariable(Variable.builder().setType(TypeNode.withReference(ConcreteReference.builder().setClazz(List.class).setGenerics(Arrays.asList(repeatedPagedResultsField.type().reference())).build())).setName("resources").build());
Expr iterateAllExpr = MethodInvocationExpr.builder().setExprReferenceExpr(actualResponseVarExpr).setMethodName("iterateAll").build();
Expr resourcesValExpr = MethodInvocationExpr.builder().setStaticReferenceType(FIXED_TYPESTORE.get("Lists")).setMethodName("newArrayList").setArguments(iterateAllExpr).setReturnType(resourcesVarExpr.type()).build();
methodStatements.addAll(methodExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList()));
methodExprs.clear();
methodStatements.add(EMPTY_LINE_STATEMENT);
methodStatements.add(ExprStatement.withExpr(AssignmentExpr.builder().setVariableExpr(resourcesVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(resourcesValExpr).build()));
methodStatements.add(EMPTY_LINE_STATEMENT);
// Assert the size is equivalent.
methodExprs.add(MethodInvocationExpr.builder().setStaticReferenceType(FIXED_TYPESTORE.get("Assert")).setMethodName("assertEquals").setArguments(ValueExpr.withValue(PrimitiveValue.builder().setType(TypeNode.INT).setValue("1").build()), MethodInvocationExpr.builder().setExprReferenceExpr(resourcesVarExpr).setMethodName("size").setReturnType(TypeNode.INT).build()).build());
// Assert the responses are equivalent.
Preconditions.checkNotNull(repeatedPagedResultsField, String.format("No repeated field found for paged method %s with output message type %s", method.name(), methodOutputMessage.name()));
Expr zeroExpr = ValueExpr.withValue(PrimitiveValue.builder().setType(TypeNode.INT).setValue("0").build());
// Generated code:
// Assert.assertEquals(
// expectedResponse.getItemsMap().entrySet().iterator().next(), resources.get(0));
// )
Expr expectedPagedResponseExpr;
if (repeatedPagedResultsField.isMap()) {
expectedPagedResponseExpr = MethodInvocationExpr.builder().setMethodName("next").setExprReferenceExpr(MethodInvocationExpr.builder().setMethodName("iterator").setExprReferenceExpr(MethodInvocationExpr.builder().setMethodName("entrySet").setExprReferenceExpr(MethodInvocationExpr.builder().setExprReferenceExpr(expectedResponseVarExpr).setMethodName(String.format("get%sMap", JavaStyle.toUpperCamelCase(repeatedPagedResultsField.name()))).build()).build()).build()).build();
} else {
// Generated code:
// Assert.assertEquals(expectedResponse.getItemsList().get(0), resources.get(0));
expectedPagedResponseExpr = MethodInvocationExpr.builder().setExprReferenceExpr(expectedResponseVarExpr).setMethodName(String.format("get%sList", JavaStyle.toUpperCamelCase(repeatedPagedResultsField.name()))).build();
expectedPagedResponseExpr = MethodInvocationExpr.builder().setExprReferenceExpr(expectedPagedResponseExpr).setMethodName("get").setArguments(zeroExpr).build();
}
Expr actualPagedResponseExpr = MethodInvocationExpr.builder().setExprReferenceExpr(resourcesVarExpr).setMethodName("get").setArguments(zeroExpr).build();
methodExprs.add(MethodInvocationExpr.builder().setStaticReferenceType(FIXED_TYPESTORE.get("Assert")).setMethodName("assertEquals").setArguments(expectedPagedResponseExpr, actualPagedResponseExpr).build());
} else if (!returnsVoid) {
methodExprs.add(MethodInvocationExpr.builder().setStaticReferenceType(FIXED_TYPESTORE.get("Assert")).setMethodName("assertEquals").setArguments(expectedResponseVarExpr, actualResponseVarExpr).build());
}
methodStatements.addAll(methodExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList()));
methodExprs.clear();
methodStatements.add(EMPTY_LINE_STATEMENT);
methodStatements.addAll(methodExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList()));
methodExprs.clear();
methodStatements.addAll(constructRpcTestCheckerLogic(method, rpcService, isRequestArg, classMemberVarExprs, requestVarExpr, requestMessage, argExprs));
String testMethodName = String.format("%sTest%s", JavaStyle.toLowerCamelCase(method.name()), variantIndex > 0 ? variantIndex + 1 : "");
return MethodDefinition.builder().setAnnotations(Arrays.asList(TEST_ANNOTATION)).setScope(ScopeNode.PUBLIC).setReturnType(TypeNode.VOID).setName(testMethodName).setThrowsExceptions(Arrays.asList(TypeNode.withExceptionClazz(Exception.class))).setBody(methodStatements).build();
}
Aggregations