Search in sources :

Example 31 with Statement

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());
}
Also used : ReferenceConstructorExpr(com.google.api.generator.engine.ast.ReferenceConstructorExpr) LogicalOperationExpr(com.google.api.generator.engine.ast.LogicalOperationExpr) ValueExpr(com.google.api.generator.engine.ast.ValueExpr) EnumRefExpr(com.google.api.generator.engine.ast.EnumRefExpr) ReturnExpr(com.google.api.generator.engine.ast.ReturnExpr) NewObjectExpr(com.google.api.generator.engine.ast.NewObjectExpr) Expr(com.google.api.generator.engine.ast.Expr) TernaryExpr(com.google.api.generator.engine.ast.TernaryExpr) RelationalOperationExpr(com.google.api.generator.engine.ast.RelationalOperationExpr) UnaryOperationExpr(com.google.api.generator.engine.ast.UnaryOperationExpr) AssignmentExpr(com.google.api.generator.engine.ast.AssignmentExpr) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) InstanceofExpr(com.google.api.generator.engine.ast.InstanceofExpr) CastExpr(com.google.api.generator.engine.ast.CastExpr) ArithmeticOperationExpr(com.google.api.generator.engine.ast.ArithmeticOperationExpr) AnonymousClassExpr(com.google.api.generator.engine.ast.AnonymousClassExpr) LambdaExpr(com.google.api.generator.engine.ast.LambdaExpr) AssignmentOperationExpr(com.google.api.generator.engine.ast.AssignmentOperationExpr) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) ThrowExpr(com.google.api.generator.engine.ast.ThrowExpr) BlockStatement(com.google.api.generator.engine.ast.BlockStatement) BreakStatement(com.google.api.generator.engine.ast.BreakStatement) WhileStatement(com.google.api.generator.engine.ast.WhileStatement) ForStatement(com.google.api.generator.engine.ast.ForStatement) EmptyLineStatement(com.google.api.generator.engine.ast.EmptyLineStatement) IfStatement(com.google.api.generator.engine.ast.IfStatement) GeneralForStatement(com.google.api.generator.engine.ast.GeneralForStatement) TryCatchStatement(com.google.api.generator.engine.ast.TryCatchStatement) SynchronizedStatement(com.google.api.generator.engine.ast.SynchronizedStatement) CommentStatement(com.google.api.generator.engine.ast.CommentStatement) ExprStatement(com.google.api.generator.engine.ast.ExprStatement) Statement(com.google.api.generator.engine.ast.Statement) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) AssignmentExpr(com.google.api.generator.engine.ast.AssignmentExpr) ForStatement(com.google.api.generator.engine.ast.ForStatement) GeneralForStatement(com.google.api.generator.engine.ast.GeneralForStatement) Test(org.junit.Test)

Example 32 with Statement

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());
}
Also used : BlockStatement(com.google.api.generator.engine.ast.BlockStatement) BreakStatement(com.google.api.generator.engine.ast.BreakStatement) WhileStatement(com.google.api.generator.engine.ast.WhileStatement) ForStatement(com.google.api.generator.engine.ast.ForStatement) EmptyLineStatement(com.google.api.generator.engine.ast.EmptyLineStatement) IfStatement(com.google.api.generator.engine.ast.IfStatement) GeneralForStatement(com.google.api.generator.engine.ast.GeneralForStatement) TryCatchStatement(com.google.api.generator.engine.ast.TryCatchStatement) SynchronizedStatement(com.google.api.generator.engine.ast.SynchronizedStatement) CommentStatement(com.google.api.generator.engine.ast.CommentStatement) ExprStatement(com.google.api.generator.engine.ast.ExprStatement) Statement(com.google.api.generator.engine.ast.Statement) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) AssignmentExpr(com.google.api.generator.engine.ast.AssignmentExpr) WhileStatement(com.google.api.generator.engine.ast.WhileStatement) Test(org.junit.Test)

Example 33 with Statement

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());
}
Also used : ValueExpr(com.google.api.generator.engine.ast.ValueExpr) BlockStatement(com.google.api.generator.engine.ast.BlockStatement) BreakStatement(com.google.api.generator.engine.ast.BreakStatement) WhileStatement(com.google.api.generator.engine.ast.WhileStatement) ForStatement(com.google.api.generator.engine.ast.ForStatement) EmptyLineStatement(com.google.api.generator.engine.ast.EmptyLineStatement) IfStatement(com.google.api.generator.engine.ast.IfStatement) GeneralForStatement(com.google.api.generator.engine.ast.GeneralForStatement) TryCatchStatement(com.google.api.generator.engine.ast.TryCatchStatement) SynchronizedStatement(com.google.api.generator.engine.ast.SynchronizedStatement) CommentStatement(com.google.api.generator.engine.ast.CommentStatement) ExprStatement(com.google.api.generator.engine.ast.ExprStatement) Statement(com.google.api.generator.engine.ast.Statement) GeneralForStatement(com.google.api.generator.engine.ast.GeneralForStatement) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) AssignmentExpr(com.google.api.generator.engine.ast.AssignmentExpr) Test(org.junit.Test)

Example 34 with Statement

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());
}
Also used : JavaDocComment(com.google.api.generator.engine.ast.JavaDocComment) Reference(com.google.api.generator.engine.ast.Reference) ConcreteReference(com.google.api.generator.engine.ast.ConcreteReference) VaporReference(com.google.api.generator.engine.ast.VaporReference) MethodDefinition(com.google.api.generator.engine.ast.MethodDefinition) BlockStatement(com.google.api.generator.engine.ast.BlockStatement) BreakStatement(com.google.api.generator.engine.ast.BreakStatement) WhileStatement(com.google.api.generator.engine.ast.WhileStatement) ForStatement(com.google.api.generator.engine.ast.ForStatement) EmptyLineStatement(com.google.api.generator.engine.ast.EmptyLineStatement) IfStatement(com.google.api.generator.engine.ast.IfStatement) GeneralForStatement(com.google.api.generator.engine.ast.GeneralForStatement) TryCatchStatement(com.google.api.generator.engine.ast.TryCatchStatement) SynchronizedStatement(com.google.api.generator.engine.ast.SynchronizedStatement) CommentStatement(com.google.api.generator.engine.ast.CommentStatement) ExprStatement(com.google.api.generator.engine.ast.ExprStatement) Statement(com.google.api.generator.engine.ast.Statement) LineComment(com.google.api.generator.engine.ast.LineComment) ClassDefinition(com.google.api.generator.engine.ast.ClassDefinition) Map(java.util.Map) HashMap(java.util.HashMap) Test(org.junit.Test)

Example 35 with Statement

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();
}
Also used : AbstractMessage(com.google.protobuf.AbstractMessage) Message(com.google.api.generator.gapic.model.Message) MethodArgument(com.google.api.generator.gapic.model.MethodArgument) EmptyLineStatement(com.google.api.generator.engine.ast.EmptyLineStatement) TryCatchStatement(com.google.api.generator.engine.ast.TryCatchStatement) CommentStatement(com.google.api.generator.engine.ast.CommentStatement) ExprStatement(com.google.api.generator.engine.ast.ExprStatement) Statement(com.google.api.generator.engine.ast.Statement) ArrayList(java.util.ArrayList) Field(com.google.api.generator.gapic.model.Field) ValueExpr(com.google.api.generator.engine.ast.ValueExpr) Expr(com.google.api.generator.engine.ast.Expr) AssignmentExpr(com.google.api.generator.engine.ast.AssignmentExpr) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) List(java.util.List) ArrayList(java.util.ArrayList) TypeNode(com.google.api.generator.engine.ast.TypeNode)

Aggregations

ExprStatement (com.google.api.generator.engine.ast.ExprStatement)69 Statement (com.google.api.generator.engine.ast.Statement)69 VariableExpr (com.google.api.generator.engine.ast.VariableExpr)65 AssignmentExpr (com.google.api.generator.engine.ast.AssignmentExpr)58 MethodInvocationExpr (com.google.api.generator.engine.ast.MethodInvocationExpr)53 Expr (com.google.api.generator.engine.ast.Expr)48 ArrayList (java.util.ArrayList)46 ValueExpr (com.google.api.generator.engine.ast.ValueExpr)44 IfStatement (com.google.api.generator.engine.ast.IfStatement)43 TypeNode (com.google.api.generator.engine.ast.TypeNode)42 CommentStatement (com.google.api.generator.engine.ast.CommentStatement)41 TryCatchStatement (com.google.api.generator.engine.ast.TryCatchStatement)36 NewObjectExpr (com.google.api.generator.engine.ast.NewObjectExpr)32 List (java.util.List)30 ForStatement (com.google.api.generator.engine.ast.ForStatement)29 Message (com.google.api.generator.gapic.model.Message)25 Variable (com.google.api.generator.engine.ast.Variable)24 CastExpr (com.google.api.generator.engine.ast.CastExpr)23 ConcreteReference (com.google.api.generator.engine.ast.ConcreteReference)23 EmptyLineStatement (com.google.api.generator.engine.ast.EmptyLineStatement)23