diff --git a/src/main/java/com/google/api/generator/gapic/composer/ResourceNameTokenizer.java b/src/main/java/com/google/api/generator/gapic/composer/ResourceNameTokenizer.java index 67d295d1a5..190b0d6c86 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/ResourceNameTokenizer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/ResourceNameTokenizer.java @@ -17,7 +17,6 @@ import com.google.api.pathtemplate.PathTemplate; import com.google.common.base.Preconditions; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import java.util.Set; import java.util.stream.Collectors; @@ -31,50 +30,51 @@ public class ResourceNameTokenizer { private static final String EQUALS_WILDCARD = "=*"; private static final String EQUALS_PATH_WILDCARD = "=**"; - static List> parseTokenHierarchy(List patterns) { - List nonSlashSepStrings = Arrays.asList("}_{", "}-{", "}.{", "}~{"); + private static final String NON_SLASH_SEP_REGEX = "\\}(_|\\-|\\.|~)\\{"; + static List> parseTokenHierarchy(List patterns) { List> tokenHierachies = new ArrayList<>(); for (String pattern : patterns) { List hierarchy = new ArrayList<>(); Set vars = PathTemplate.create(pattern).vars(); - String[] patternTokens = pattern.split(SLASH); - for (String patternToken : patternTokens) { - if (patternToken.startsWith(LEFT_BRACE) && patternToken.endsWith(RIGHT_BRACE)) { - String processedPatternToken = - // Replacement order matters - ensure the first is not a subcomponent of the second. - patternToken.replace(EQUALS_PATH_WILDCARD, EMPTY).replace(EQUALS_WILDCARD, EMPTY); + String[] rawPatternTokens = pattern.split(SLASH); + List patternTokens = new ArrayList<>(); - // Handle non-slash separators. - if (nonSlashSepStrings.stream().anyMatch(s -> patternToken.contains(s))) { - for (String str : nonSlashSepStrings) { - processedPatternToken = processedPatternToken.replace(str, "_"); - } - } else { - final int processedPatternTokenLength = processedPatternToken.length(); - // Handles wildcards. - List candidateVars = - vars.stream() - // Check that the token size is within ~3 of the var, to avoid mismatching on - // variables with same-named subcomponents. - // Otherwise, "customer_client_link" will match with "customer". - .filter( - v -> - patternToken.contains(v) - // Accounting for braces. - && processedPatternTokenLength - v.length() < 3) - .collect(Collectors.toList()); - Preconditions.checkState( - !candidateVars.isEmpty(), - String.format( - "No variable candidates found for token %s in pattern %s", - processedPatternToken, pattern)); - processedPatternToken = candidateVars.get(0); + // Process variables. + for (String rawPatternToken : rawPatternTokens) { + if (!rawPatternToken.startsWith(LEFT_BRACE) || !rawPatternToken.endsWith(RIGHT_BRACE)) { + continue; + } + // Add any non-slash separated tokens in the order that they're seen. + for (String subToken : rawPatternToken.split(NON_SLASH_SEP_REGEX)) { + String processedSubToken = + subToken.replace(LEFT_BRACE, EMPTY).replace(RIGHT_BRACE, EMPTY); + if (!patternTokens.contains(processedSubToken)) { + patternTokens.add(processedSubToken); } - hierarchy.add( - processedPatternToken.replace(LEFT_BRACE, EMPTY).replace(RIGHT_BRACE, EMPTY)); } } + + for (String patternToken : patternTokens) { + // Handle wildcards. + final String processedPatternToken = + // Replacement order matters - ensure the first is not a subcomponent of the second. + patternToken.replace(EQUALS_PATH_WILDCARD, EMPTY).replace(EQUALS_WILDCARD, EMPTY); + + List candidateVars = + vars.stream() + // Check that the token matches the variable exactly, to avoid mismatching on + // variables with same-named subcomponents. + // Otherwise, "customer_client_link" will match with "customer". + .filter(v -> processedPatternToken.equals(v)) + .collect(Collectors.toList()); + Preconditions.checkState( + !candidateVars.isEmpty(), + String.format( + "No variable candidates found for token %s in pattern %s among variables %s", + processedPatternToken, pattern, vars)); + hierarchy.add(processedPatternToken); + } tokenHierachies.add(hierarchy); } return tokenHierachies; diff --git a/src/test/java/com/google/api/generator/gapic/composer/ResourceNameHelperClassComposerTest.java b/src/test/java/com/google/api/generator/gapic/composer/ResourceNameHelperClassComposerTest.java index f29ea0ec7e..5532738d73 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/ResourceNameHelperClassComposerTest.java +++ b/src/test/java/com/google/api/generator/gapic/composer/ResourceNameHelperClassComposerTest.java @@ -187,4 +187,33 @@ public void generateResourceNameClass_testingSessionOnePattern() { Path goldenFilePath = Paths.get(ComposerConstants.GOLDENFILES_DIRECTORY, "SessionName.golden"); Assert.assertCodeEquals(goldenFilePath, visitor.write()); } + + @Test + public void generateResourceNameClass_testingBlueprintPatternWithNonSlashSeparator() { + FileDescriptor testingFileDescriptor = TestingOuterClass.getDescriptor(); + ServiceDescriptor testingService = testingFileDescriptor.getServices().get(0); + assertEquals(testingService.getName(), "Testing"); + + Map messageTypes = Parser.parseMessages(testingFileDescriptor); + Map resourceNames = Parser.parseResourceNames(testingFileDescriptor); + Set outputResourceNames = new HashSet<>(); + List services = + Parser.parseService( + testingFileDescriptor, + messageTypes, + resourceNames, + Optional.empty(), + outputResourceNames); + + ResourceName testResname = resourceNames.get("showcase.googleapis.com/Test"); + assertThat(outputResourceNames).contains(testResname); + + GapicClass clazz = ResourceNameHelperClassComposer.instance().generate(testResname); + + JavaWriterVisitor visitor = new JavaWriterVisitor(); + clazz.classDefinition().accept(visitor); + Utils.saveCodegenToFile(this.getClass(), "TestName.golden", visitor.write()); + Path goldenFilePath = Paths.get(ComposerConstants.GOLDENFILES_DIRECTORY, "TestName.golden"); + Assert.assertCodeEquals(goldenFilePath, visitor.write()); + } } diff --git a/src/test/java/com/google/api/generator/gapic/composer/ResourceNameTokenizerTest.java b/src/test/java/com/google/api/generator/gapic/composer/ResourceNameTokenizerTest.java index 3c61e206ba..e7b5823725 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/ResourceNameTokenizerTest.java +++ b/src/test/java/com/google/api/generator/gapic/composer/ResourceNameTokenizerTest.java @@ -101,12 +101,12 @@ public void parseTokenHierarchy_singletonCollectionAndNonSlashSeparators() { List> tokenHierarchies = ResourceNameTokenizer.parseTokenHierarchy(patterns); assertEquals(6, tokenHierarchies.size()); - assertThat(tokenHierarchies.get(0)).containsExactly("user", "legacy_user_blurb"); + assertThat(tokenHierarchies.get(0)).containsExactly("user", "legacy_user", "blurb"); assertThat(tokenHierarchies.get(1)).containsExactly("user", "blurb"); assertThat(tokenHierarchies.get(2)).containsExactly("room", "blurb"); - assertThat(tokenHierarchies.get(3)).containsExactly("user", "legacy_document_blurb"); - assertThat(tokenHierarchies.get(4)).containsExactly("user", "legacy_book_blurb"); - assertThat(tokenHierarchies.get(5)).containsExactly("room", "legacy_room_blurb"); + assertThat(tokenHierarchies.get(3)).containsExactly("user", "legacy_document", "blurb"); + assertThat(tokenHierarchies.get(4)).containsExactly("user", "legacy_book", "blurb"); + assertThat(tokenHierarchies.get(5)).containsExactly("room", "legacy_room", "blurb"); } @Test diff --git a/src/test/java/com/google/api/generator/gapic/composer/ServiceClientTestClassComposerTest.java b/src/test/java/com/google/api/generator/gapic/composer/ServiceClientTestClassComposerTest.java index 358b830b5e..a2d576066f 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/ServiceClientTestClassComposerTest.java +++ b/src/test/java/com/google/api/generator/gapic/composer/ServiceClientTestClassComposerTest.java @@ -32,6 +32,7 @@ import com.google.protobuf.Descriptors.ServiceDescriptor; import com.google.pubsub.v1.PubsubProto; import com.google.showcase.v1beta1.EchoOuterClass; +import com.google.showcase.v1beta1.TestingOuterClass; import google.cloud.CommonResources; import java.nio.file.Path; import java.nio.file.Paths; @@ -71,6 +72,36 @@ public void generateClientTest_echoClient() { assertCodeEquals(goldenFilePath, visitor.write()); } + @Test + public void generateClientTest_testingClientResnameWithOnePatternWithNonSlashSepNames() { + FileDescriptor testingFileDescriptor = TestingOuterClass.getDescriptor(); + ServiceDescriptor testingService = testingFileDescriptor.getServices().get(0); + assertEquals(testingService.getName(), "Testing"); + + Map messageTypes = Parser.parseMessages(testingFileDescriptor); + Map resourceNames = Parser.parseResourceNames(testingFileDescriptor); + Set outputResourceNames = new HashSet<>(); + List services = + Parser.parseService( + testingFileDescriptor, + messageTypes, + resourceNames, + Optional.empty(), + outputResourceNames); + + Service testingProtoService = services.get(0); + GapicClass clazz = + ServiceClientTestClassComposer.instance() + .generate(testingProtoService, resourceNames, messageTypes); + + JavaWriterVisitor visitor = new JavaWriterVisitor(); + clazz.classDefinition().accept(visitor); + Utils.saveCodegenToFile(this.getClass(), "TestingClientTest.golden", visitor.write()); + Path goldenFilePath = + Paths.get(ComposerConstants.GOLDENFILES_DIRECTORY, "TestingClientTest.golden"); + assertCodeEquals(goldenFilePath, visitor.write()); + } + @Test public void generateClientTest_pubSubPublisherClient() { FileDescriptor serviceFileDescriptor = PubsubProto.getDescriptor(); diff --git a/src/test/java/com/google/api/generator/gapic/composer/goldens/GrpcTestingStub.golden b/src/test/java/com/google/api/generator/gapic/composer/goldens/GrpcTestingStub.golden index 8ab8396bb9..61ea7d1fa9 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/goldens/GrpcTestingStub.golden +++ b/src/test/java/com/google/api/generator/gapic/composer/goldens/GrpcTestingStub.golden @@ -17,6 +17,7 @@ import com.google.showcase.v1beta1.CreateSessionRequest; import com.google.showcase.v1beta1.DeleteSessionRequest; import com.google.showcase.v1beta1.DeleteTestRequest; import com.google.showcase.v1beta1.GetSessionRequest; +import com.google.showcase.v1beta1.GetTestRequest; import com.google.showcase.v1beta1.ListSessionsRequest; import com.google.showcase.v1beta1.ListSessionsResponse; import com.google.showcase.v1beta1.ListTestsRequest; @@ -24,6 +25,7 @@ import com.google.showcase.v1beta1.ListTestsResponse; import com.google.showcase.v1beta1.ReportSessionRequest; import com.google.showcase.v1beta1.ReportSessionResponse; import com.google.showcase.v1beta1.Session; +import com.google.showcase.v1beta1.Test; import com.google.showcase.v1beta1.VerifyTestRequest; import com.google.showcase.v1beta1.VerifyTestResponse; import io.grpc.MethodDescriptor; @@ -88,6 +90,14 @@ public class GrpcTestingStub extends TestingStub { ProtoUtils.marshaller(ReportSessionResponse.getDefaultInstance())) .build(); + private static final MethodDescriptor getTestMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.showcase.v1beta1.Testing/GetTest") + .setRequestMarshaller(ProtoUtils.marshaller(GetTestRequest.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(Test.getDefaultInstance())) + .build(); + private static final MethodDescriptor listTestsMethodDescriptor = MethodDescriptor.newBuilder() @@ -121,6 +131,7 @@ public class GrpcTestingStub extends TestingStub { listSessionsPagedCallable; private final UnaryCallable deleteSessionCallable; private final UnaryCallable reportSessionCallable; + private final UnaryCallable getTestCallable; private final UnaryCallable listTestsCallable; private final UnaryCallable listTestsPagedCallable; private final UnaryCallable deleteTestCallable; @@ -204,6 +215,19 @@ public class GrpcTestingStub extends TestingStub { } }) .build(); + GrpcCallSettings getTestTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(getTestMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(GetTestRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("name", String.valueOf(request.getName())); + return params.build(); + } + }) + .build(); GrpcCallSettings listTestsTransportSettings = GrpcCallSettings.newBuilder() .setMethodDescriptor(listTestsMethodDescriptor) @@ -262,6 +286,9 @@ public class GrpcTestingStub extends TestingStub { this.reportSessionCallable = callableFactory.createUnaryCallable( reportSessionTransportSettings, settings.reportSessionSettings(), clientContext); + this.getTestCallable = + callableFactory.createUnaryCallable( + getTestTransportSettings, settings.getTestSettings(), clientContext); this.listTestsCallable = callableFactory.createUnaryCallable( listTestsTransportSettings, settings.listTestsSettings(), clientContext); @@ -307,6 +334,10 @@ public class GrpcTestingStub extends TestingStub { return reportSessionCallable; } + public UnaryCallable getTestCallable() { + return getTestCallable; + } + public UnaryCallable listTestsCallable() { return listTestsCallable; } diff --git a/src/test/java/com/google/api/generator/gapic/composer/goldens/TestName.golden b/src/test/java/com/google/api/generator/gapic/composer/goldens/TestName.golden new file mode 100644 index 0000000000..f4a72ec1ad --- /dev/null +++ b/src/test/java/com/google/api/generator/gapic/composer/goldens/TestName.golden @@ -0,0 +1,199 @@ +package com.google.showcase.v1beta1; + +import com.google.api.pathtemplate.PathTemplate; +import com.google.api.resourcenames.ResourceName; +import com.google.common.base.Preconditions; +import com.google.common.collect.ImmutableMap; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import javax.annotation.Generated; + +// AUTO-GENERATED DOCUMENTATION AND CLASS. +@Generated("by gapic-generator-java") +public class TestName implements ResourceName { + private static final PathTemplate SESSION_SHARD_ID_TEST_ID = + PathTemplate.createWithoutUrlEncoding("sessions/{session}/tests/{shard_id}~{test_id}"); + private volatile Map fieldValuesMap; + private final String session; + private final String shardId; + private final String testId; + + private TestName(Builder builder) { + session = Preconditions.checkNotNull(builder.getSession()); + shardId = Preconditions.checkNotNull(builder.getShardId()); + testId = Preconditions.checkNotNull(builder.getTestId()); + } + + public String getSession() { + return session; + } + + public String getShardId() { + return shardId; + } + + public String getTestId() { + return testId; + } + + public static Builder newBuilder() { + return new Builder(); + } + + public Builder toBuilder() { + return new Builder(this); + } + + public static TestName of(String session, String shardId, String testId) { + return newBuilder().setSession(session).setShardId(shardId).setTestId(testId).build(); + } + + public static String format(String session, String shardId, String testId) { + return newBuilder() + .setSession(session) + .setShardId(shardId) + .setTestId(testId) + .build() + .toString(); + } + + public static TestName parse(String formattedString) { + if (formattedString.isEmpty()) { + return null; + } + Map matchMap = + SESSION_SHARD_ID_TEST_ID.validatedMatch( + formattedString, "TestName.parse: formattedString not in valid format"); + return of(matchMap.get("session"), matchMap.get("shard_id"), matchMap.get("test_id")); + } + + public static List parseList(List formattedStrings) { + List list = new ArrayList<>(formattedStrings.size()); + for (String formattedString : formattedStrings) { + list.add(parse(formattedString)); + } + return list; + } + + public static List toStringList(List values) { + List list = new ArrayList<>(values.size()); + for (TestName value : values) { + if (Objects.isNull(value)) { + list.add(""); + } else { + list.add(value.toString()); + } + } + return list; + } + + public static boolean isParsableFrom(String formattedString) { + return SESSION_SHARD_ID_TEST_ID.matches(formattedString); + } + + @Override + public Map getFieldValuesMap() { + if (Objects.isNull(fieldValuesMap)) { + synchronized (this) { + if (Objects.isNull(fieldValuesMap)) { + ImmutableMap.Builder fieldMapBuilder = ImmutableMap.builder(); + if (!Objects.isNull(session)) { + fieldMapBuilder.put("session", session); + } + if (!Objects.isNull(shardId)) { + fieldMapBuilder.put("shard_id", shardId); + } + if (!Objects.isNull(testId)) { + fieldMapBuilder.put("test_id", testId); + } + fieldValuesMap = fieldMapBuilder.build(); + } + } + } + return fieldValuesMap; + } + + public String getFieldValue(String fieldName) { + return getFieldValuesMap().get(fieldName); + } + + @Override + public String toString() { + return SESSION_SHARD_ID_TEST_ID.instantiate( + "session", session, "shard_id", shardId, "test_id", testId); + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (o != null || getClass() == o.getClass()) { + TestName that = ((TestName) o); + return Objects.equals(this.session, that.session) + && Objects.equals(this.shardId, that.shardId) + && Objects.equals(this.testId, that.testId); + } + return false; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= Objects.hashCode(session); + h *= 1000003; + h ^= Objects.hashCode(shardId); + h *= 1000003; + h ^= Objects.hashCode(testId); + return h; + } + + /** Builder for sessions/{session}/tests/{shard_id}~{test_id}. */ + public static class Builder { + private String session; + private String shardId; + private String testId; + + private Builder() {} + + public String getSession() { + return session; + } + + public String getShardId() { + return shardId; + } + + public String getTestId() { + return testId; + } + + public Builder setSession(String session) { + this.session = session; + return this; + } + + public Builder setShardId(String shardId) { + this.shardId = shardId; + return this; + } + + public Builder setTestId(String testId) { + this.testId = testId; + return this; + } + + private Builder(TestName testName) { + session = testName.session; + shardId = testName.shardId; + testId = testName.testId; + } + + public TestName build() { + return new TestName(this); + } + } +} diff --git a/src/test/java/com/google/api/generator/gapic/composer/goldens/TestingClientTest.golden b/src/test/java/com/google/api/generator/gapic/composer/goldens/TestingClientTest.golden new file mode 100644 index 0000000000..f1bdaeeff7 --- /dev/null +++ b/src/test/java/com/google/api/generator/gapic/composer/goldens/TestingClientTest.golden @@ -0,0 +1,504 @@ +package com.google.showcase.v1beta1; + +import static com.google.showcase.v1beta1.TestingClient.ListSessionsPagedResponse; +import static com.google.showcase.v1beta1.TestingClient.ListTestsPagedResponse; + +import com.google.api.gax.core.NoCredentialsProvider; +import com.google.api.gax.grpc.GaxGrpcProperties; +import com.google.api.gax.grpc.testing.LocalChannelProvider; +import com.google.api.gax.grpc.testing.MockGrpcService; +import com.google.api.gax.grpc.testing.MockServiceHelper; +import com.google.api.gax.rpc.ApiClientHeaderProvider; +import com.google.api.gax.rpc.InvalidArgumentException; +import com.google.common.collect.Lists; +import com.google.protobuf.AbstractMessage; +import com.google.protobuf.ByteString; +import com.google.protobuf.Empty; +import io.grpc.StatusRuntimeException; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.UUID; +import javax.annotation.Generated; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +@Generated("by gapic-generator-java") +public class TestingClientTest { + private static MockServiceHelper mockServiceHelper; + private TestingClient client; + private static MockTesting mockTesting; + private LocalChannelProvider channelProvider; + + @BeforeClass + public static void startStaticServer() { + mockTesting = new MockTesting(); + mockServiceHelper = + new MockServiceHelper( + UUID.randomUUID().toString(), Arrays.asList(mockTesting)); + mockServiceHelper.start(); + } + + @AfterClass + public static void stopServer() { + mockServiceHelper.stop(); + } + + @Before + public void setUp() throws IOException { + mockServiceHelper.reset(); + channelProvider = mockServiceHelper.createChannelProvider(); + TestingSettings settings = + TestingSettings.newBuilder() + .setTransportChannelProvider(channelProvider) + .setCredentialsProvider(NoCredentialsProvider.create()) + .build(); + client = TestingClient.create(settings); + } + + @After + public void tearDown() throws Exception { + client.close(); + } + + @Test + public void createSessionTest() throws Exception { + Session expectedResponse = + Session.newBuilder() + .setName(SessionName.of("[SESSION]").toString()) + .putAllSessionIdsToDescriptor(new HashMap()) + .build(); + mockTesting.addResponse(expectedResponse); + + Session session = Session.newBuilder().build(); + CreateSessionRequest.Blueprint blueprint = CreateSessionRequest.Blueprint.newBuilder().build(); + + Session actualResponse = client.createSession(session, blueprint); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockTesting.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + CreateSessionRequest actualRequest = ((CreateSessionRequest) actualRequests.get(0)); + + Assert.assertEquals(session, actualRequest.getSession()); + Assert.assertEquals(blueprint, actualRequest.getBlueprint()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void createSessionExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockTesting.addException(exception); + + try { + Session session = Session.newBuilder().build(); + CreateSessionRequest.Blueprint blueprint = + CreateSessionRequest.Blueprint.newBuilder().build(); + client.createSession(session, blueprint); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void getSessionTest() throws Exception { + Session expectedResponse = + Session.newBuilder() + .setName(SessionName.of("[SESSION]").toString()) + .putAllSessionIdsToDescriptor(new HashMap()) + .build(); + mockTesting.addResponse(expectedResponse); + + GetSessionRequest request = + GetSessionRequest.newBuilder().setName(SessionName.of("[SESSION]").toString()).build(); + + Session actualResponse = client.getSession(request); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockTesting.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + GetSessionRequest actualRequest = ((GetSessionRequest) actualRequests.get(0)); + + Assert.assertEquals(request.getName(), actualRequest.getName()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void getSessionExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockTesting.addException(exception); + + try { + GetSessionRequest request = + GetSessionRequest.newBuilder().setName(SessionName.of("[SESSION]").toString()).build(); + client.getSession(request); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void listSessionsTest() throws Exception { + Session responsesElement = Session.newBuilder().build(); + ListSessionsResponse expectedResponse = + ListSessionsResponse.newBuilder() + .setNextPageToken("") + .addAllSessions(Arrays.asList(responsesElement)) + .build(); + mockTesting.addResponse(expectedResponse); + + ListSessionsRequest request = + ListSessionsRequest.newBuilder() + .setPageSize(883849137) + .setPageToken("page_token1630607433") + .build(); + + ListSessionsPagedResponse pagedListResponse = client.listSessions(request); + + List resources = Lists.newArrayList(pagedListResponse.iterateAll()); + + Assert.assertEquals(1, resources.size()); + Assert.assertEquals(expectedResponse.getSessionsList().get(0), resources.get(0)); + + List actualRequests = mockTesting.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + ListSessionsRequest actualRequest = ((ListSessionsRequest) actualRequests.get(0)); + + Assert.assertEquals(request.getPageSize(), actualRequest.getPageSize()); + Assert.assertEquals(request.getPageToken(), actualRequest.getPageToken()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void listSessionsExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockTesting.addException(exception); + + try { + ListSessionsRequest request = + ListSessionsRequest.newBuilder() + .setPageSize(883849137) + .setPageToken("page_token1630607433") + .build(); + client.listSessions(request); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void deleteSessionTest() throws Exception { + Empty expectedResponse = Empty.newBuilder().build(); + mockTesting.addResponse(expectedResponse); + + DeleteSessionRequest request = + DeleteSessionRequest.newBuilder().setName(SessionName.of("[SESSION]").toString()).build(); + + Empty actualResponse = client.deleteSession(request); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockTesting.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + DeleteSessionRequest actualRequest = ((DeleteSessionRequest) actualRequests.get(0)); + + Assert.assertEquals(request.getName(), actualRequest.getName()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void deleteSessionExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockTesting.addException(exception); + + try { + DeleteSessionRequest request = + DeleteSessionRequest.newBuilder().setName(SessionName.of("[SESSION]").toString()).build(); + client.deleteSession(request); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void reportSessionTest() throws Exception { + ReportSessionResponse expectedResponse = + ReportSessionResponse.newBuilder().addAllTestRuns(new ArrayList()).build(); + mockTesting.addResponse(expectedResponse); + + ReportSessionRequest request = + ReportSessionRequest.newBuilder().setName(SessionName.of("[SESSION]").toString()).build(); + + ReportSessionResponse actualResponse = client.reportSession(request); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockTesting.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + ReportSessionRequest actualRequest = ((ReportSessionRequest) actualRequests.get(0)); + + Assert.assertEquals(request.getName(), actualRequest.getName()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void reportSessionExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockTesting.addException(exception); + + try { + ReportSessionRequest request = + ReportSessionRequest.newBuilder().setName(SessionName.of("[SESSION]").toString()).build(); + client.reportSession(request); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void getTestTest() throws Exception { + Test expectedResponse = + Test.newBuilder() + .setName(TestName.of("[SESSION]", "[SHARD_ID]", "[TEST_ID]").toString()) + .setDescription("description-1724546052") + .build(); + mockTesting.addResponse(expectedResponse); + + TestName name = TestName.of("[SESSION]", "[SHARD_ID]", "[TEST_ID]"); + + Test actualResponse = client.getTest(name); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockTesting.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + GetTestRequest actualRequest = ((GetTestRequest) actualRequests.get(0)); + + Assert.assertEquals(name.toString(), actualRequest.getName()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void getTestExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockTesting.addException(exception); + + try { + TestName name = TestName.of("[SESSION]", "[SHARD_ID]", "[TEST_ID]"); + client.getTest(name); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void getTestTest2() throws Exception { + Test expectedResponse = + Test.newBuilder() + .setName(TestName.of("[SESSION]", "[SHARD_ID]", "[TEST_ID]").toString()) + .setDescription("description-1724546052") + .build(); + mockTesting.addResponse(expectedResponse); + + String name = "name3373707"; + + Test actualResponse = client.getTest(name); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockTesting.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + GetTestRequest actualRequest = ((GetTestRequest) actualRequests.get(0)); + + Assert.assertEquals(name, actualRequest.getName()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void getTestExceptionTest2() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockTesting.addException(exception); + + try { + String name = "name3373707"; + client.getTest(name); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void listTestsTest() throws Exception { + Test responsesElement = Test.newBuilder().build(); + ListTestsResponse expectedResponse = + ListTestsResponse.newBuilder() + .setNextPageToken("") + .addAllTests(Arrays.asList(responsesElement)) + .build(); + mockTesting.addResponse(expectedResponse); + + ListTestsRequest request = + ListTestsRequest.newBuilder() + .setParent(SessionName.of("[SESSION]").toString()) + .setPageSize(883849137) + .setPageToken("page_token1630607433") + .build(); + + ListTestsPagedResponse pagedListResponse = client.listTests(request); + + List resources = Lists.newArrayList(pagedListResponse.iterateAll()); + + Assert.assertEquals(1, resources.size()); + Assert.assertEquals(expectedResponse.getTestsList().get(0), resources.get(0)); + + List actualRequests = mockTesting.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + ListTestsRequest actualRequest = ((ListTestsRequest) actualRequests.get(0)); + + Assert.assertEquals(request.getParent(), actualRequest.getParent()); + Assert.assertEquals(request.getPageSize(), actualRequest.getPageSize()); + Assert.assertEquals(request.getPageToken(), actualRequest.getPageToken()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void listTestsExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockTesting.addException(exception); + + try { + ListTestsRequest request = + ListTestsRequest.newBuilder() + .setParent(SessionName.of("[SESSION]").toString()) + .setPageSize(883849137) + .setPageToken("page_token1630607433") + .build(); + client.listTests(request); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void deleteTestTest() throws Exception { + Empty expectedResponse = Empty.newBuilder().build(); + mockTesting.addResponse(expectedResponse); + + DeleteTestRequest request = + DeleteTestRequest.newBuilder() + .setName(TestName.of("[SESSION]", "[SHARD_ID]", "[TEST_ID]").toString()) + .build(); + + Empty actualResponse = client.deleteTest(request); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockTesting.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + DeleteTestRequest actualRequest = ((DeleteTestRequest) actualRequests.get(0)); + + Assert.assertEquals(request.getName(), actualRequest.getName()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void deleteTestExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockTesting.addException(exception); + + try { + DeleteTestRequest request = + DeleteTestRequest.newBuilder() + .setName(TestName.of("[SESSION]", "[SHARD_ID]", "[TEST_ID]").toString()) + .build(); + client.deleteTest(request); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void verifyTestTest() throws Exception { + VerifyTestResponse expectedResponse = + VerifyTestResponse.newBuilder().setIssue(Issue.newBuilder().build()).build(); + mockTesting.addResponse(expectedResponse); + + VerifyTestRequest request = + VerifyTestRequest.newBuilder() + .setName(TestName.of("[SESSION]", "[SHARD_ID]", "[TEST_ID]").toString()) + .setAnswer(ByteString.EMPTY) + .addAllAnswers(new ArrayList()) + .build(); + + VerifyTestResponse actualResponse = client.verifyTest(request); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockTesting.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + VerifyTestRequest actualRequest = ((VerifyTestRequest) actualRequests.get(0)); + + Assert.assertEquals(request.getName(), actualRequest.getName()); + Assert.assertEquals(request.getAnswer(), actualRequest.getAnswer()); + Assert.assertEquals(request.getAnswersList(), actualRequest.getAnswersList()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void verifyTestExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockTesting.addException(exception); + + try { + VerifyTestRequest request = + VerifyTestRequest.newBuilder() + .setName(TestName.of("[SESSION]", "[SHARD_ID]", "[TEST_ID]").toString()) + .setAnswer(ByteString.EMPTY) + .addAllAnswers(new ArrayList()) + .build(); + client.verifyTest(request); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } +} diff --git a/src/test/java/com/google/api/generator/gapic/testdata/testing.proto b/src/test/java/com/google/api/generator/gapic/testdata/testing.proto index 5f8fdb2e5c..2fe4ad9f66 100644 --- a/src/test/java/com/google/api/generator/gapic/testdata/testing.proto +++ b/src/test/java/com/google/api/generator/gapic/testdata/testing.proto @@ -73,6 +73,14 @@ service Testing { }; } + // Gets a testing session. + rpc GetTest(GetTestRequest) returns (Test) { + option (google.api.http) = { + get: "/v1beta1/{name=tests/*}" + }; + option (google.api.method_signature) = "name"; + } + // List the tests of a sessesion. rpc ListTests(ListTestsRequest) returns (ListTestsResponse) { option (google.api.http) = { @@ -243,10 +251,16 @@ message ReportSessionResponse { repeated TestRun test_runs = 2; } +message GetTestRequest { + // The session to be retrieved. + string name = 1 + [(google.api.resource_reference).type = "showcase.googleapis.com/Test"]; +} + message Test { option (google.api.resource) = { type: "showcase.googleapis.com/Test" - pattern: "sessions/{session}/tests/{test}" + pattern: "sessions/{session}/tests/{shard_id}~{test_id}" }; // The name of the test.