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

fix(mocks): Use java.lang.Object if there are protos named 'Object' [ggj] #760

Merged
merged 8 commits into from
Jun 10, 2021
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import com.google.api.generator.engine.ast.MethodDefinition;
import com.google.api.generator.engine.ast.MethodInvocationExpr;
import com.google.api.generator.engine.ast.NewObjectExpr;
import com.google.api.generator.engine.ast.Reference;
import com.google.api.generator.engine.ast.RelationalOperationExpr;
import com.google.api.generator.engine.ast.ScopeNode;
import com.google.api.generator.engine.ast.Statement;
Expand Down Expand Up @@ -78,17 +79,9 @@ public class MockServiceImplClassComposer implements ClassComposer {
Arrays.asList(FIXED_TYPESTORE.get("AbstractMessage").reference()))
.build()))
.build());
private static final VariableExpr responsesVarExpr =
VariableExpr.withVariable(
Variable.builder()
.setName("responses")
.setType(
TypeNode.withReference(
ConcreteReference.builder()
.setClazz(Queue.class)
.setGenerics(Arrays.asList(ConcreteReference.withClazz(Object.class)))
.build()))
.build());

private static Reference javaObjectReference = ConcreteReference.withClazz(Object.class);
private static VariableExpr responsesVarExpr;

private MockServiceImplClassComposer() {}

Expand All @@ -97,12 +90,34 @@ public static MockServiceImplClassComposer instance() {
}

@Override
public GapicClass generate(GapicContext ignored, Service service) {
public GapicClass generate(GapicContext context, Service service) {
TypeStore typeStore = createDynamicTypes(service);
String className = ClassNames.getMockServiceImplClassName(service);
GapicClass.Kind kind = Kind.TEST;
String pakkage = service.pakkage();

// Use the full name java.lang.Object if there is a proto message that is also named "Object".
// Affects GCS.
if (context.messages().keySet().stream()
.map(s -> s.substring(Math.max(0, s.lastIndexOf(".") + 1), s.length()))
miraleung marked this conversation as resolved.
Show resolved Hide resolved
.collect(Collectors.toSet())
miraleung marked this conversation as resolved.
Show resolved Hide resolved
.contains("Object")) {
javaObjectReference =
ConcreteReference.builder().setClazz(Object.class).setUseFullName(true).build();
}

responsesVarExpr =
VariableExpr.withVariable(
Variable.builder()
.setName("responses")
.setType(
TypeNode.withReference(
ConcreteReference.builder()
.setClazz(Queue.class)
.setGenerics(Arrays.asList(javaObjectReference))
.build()))
.build());

ClassDefinition classDef =
ClassDefinition.builder()
.setPackageString(pakkage)
Expand Down Expand Up @@ -201,8 +216,7 @@ private static MethodDefinition createSetResponsesMethod(Service service) {
Expr responseAssignExpr =
AssignmentExpr.builder()
.setVariableExpr(
responsesVarExpr
.toBuilder()
responsesVarExpr.toBuilder()
.setExprReferenceExpr(
ValueExpr.withValue(ThisObjectValue.withType(getThisClassType(service))))
.build())
Expand All @@ -212,8 +226,7 @@ private static MethodDefinition createSetResponsesMethod(Service service) {
TypeNode.withReference(
ConcreteReference.builder()
.setClazz(LinkedList.class)
.setGenerics(
Arrays.asList(ConcreteReference.withClazz(Object.class)))
.setGenerics(Arrays.asList(javaObjectReference))
.build()))
.setArguments(Arrays.asList(responsesArgVarExpr))
.build())
Expand Down Expand Up @@ -267,7 +280,7 @@ private static List<MethodDefinition> createProtoMethodOverrides(Service service

private static MethodDefinition createGenericProtoMethodOverride(Method protoMethod) {
ConcreteReference streamObserverRef = ConcreteReference.withClazz(StreamObserver.class);
TypeNode objectType = TypeNode.withReference(ConcreteReference.withClazz(Object.class));
TypeNode objectType = TypeNode.withReference(javaObjectReference);
VariableExpr localResponseVarExpr =
VariableExpr.withVariable(
Variable.builder().setName("response").setType(objectType).build());
Expand Down Expand Up @@ -372,7 +385,7 @@ private static MethodDefinition createOnNextJavaMethod(
VariableExpr valueVarExpr =
VariableExpr.withVariable(
Variable.builder().setName("value").setType(protoMethod.inputType()).build());
TypeNode objectType = TypeNode.withReference(ConcreteReference.withClazz(Object.class));
TypeNode objectType = TypeNode.withReference(javaObjectReference);

Statement addValueToRequestsStatement =
ExprStatement.withExpr(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -769,6 +769,53 @@ public class EchoClient implements BackgroundResource {
return stub.blockCallable();
}

// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Sample code:
*
* <pre>{@code
* try (EchoClient echoClient = EchoClient.create()) {
* EchoRequest request =
* EchoRequest.newBuilder()
* .setName(FoobarName.ofProjectFoobarName("[PROJECT]", "[FOOBAR]").toString())
* .setParent(FoobarName.ofProjectFoobarName("[PROJECT]", "[FOOBAR]").toString())
* .setSeverity(Severity.forNumber(0))
* .setFoobar(Foobar.newBuilder().build())
* .build();
* Object response = echoClient.collideName(request);
* }
* }</pre>
*
* @param request The request object containing all of the parameters for the API call.
* @throws com.google.api.gax.rpc.ApiException if the remote call fails
*/
public final Object collideName(EchoRequest request) {
return collideNameCallable().call(request);
}

// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Sample code:
*
* <pre>{@code
* try (EchoClient echoClient = EchoClient.create()) {
* EchoRequest request =
* EchoRequest.newBuilder()
* .setName(FoobarName.ofProjectFoobarName("[PROJECT]", "[FOOBAR]").toString())
* .setParent(FoobarName.ofProjectFoobarName("[PROJECT]", "[FOOBAR]").toString())
* .setSeverity(Severity.forNumber(0))
* .setFoobar(Foobar.newBuilder().build())
* .build();
* ApiFuture<Object> future = echoClient.collideNameCallable().futureCall(request);
* // Do something.
* Object response = future.get();
* }
* }</pre>
*/
public final UnaryCallable<EchoRequest, Object> collideNameCallable() {
return stub.collideNameCallable();
}

@Override
public final void close() {
stub.close();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import com.google.showcase.v1beta1.BlockResponse;
import com.google.showcase.v1beta1.EchoRequest;
import com.google.showcase.v1beta1.EchoResponse;
import com.google.showcase.v1beta1.ExpandRequest;
import com.google.showcase.v1beta1.Object;
import com.google.showcase.v1beta1.PagedExpandRequest;
import com.google.showcase.v1beta1.PagedExpandResponse;
import com.google.showcase.v1beta1.WaitMetadata;
Expand Down Expand Up @@ -87,6 +88,10 @@ public abstract class EchoStub implements BackgroundResource {
throw new UnsupportedOperationException("Not implemented: blockCallable()");
}

public UnaryCallable<EchoRequest, Object> collideNameCallable() {
throw new UnsupportedOperationException("Not implemented: collideNameCallable()");
}

@Override
public abstract void close();
}
Original file line number Diff line number Diff line change
Expand Up @@ -838,4 +838,56 @@ public class EchoClientTest {
// Expected exception.
}
}

@Test
public void collideNameTest() throws Exception {
Object expectedResponse = Object.newBuilder().setContent("content951530617").build();
mockEcho.addResponse(expectedResponse);

EchoRequest request =
EchoRequest.newBuilder()
.setName(FoobarName.ofProjectFoobarName("[PROJECT]", "[FOOBAR]").toString())
.setParent(FoobarName.ofProjectFoobarName("[PROJECT]", "[FOOBAR]").toString())
.setSeverity(Severity.forNumber(0))
.setFoobar(Foobar.newBuilder().build())
.build();

Object actualResponse = client.collideName(request);
Assert.assertEquals(expectedResponse, actualResponse);

List<AbstractMessage> actualRequests = mockEcho.getRequests();
Assert.assertEquals(1, actualRequests.size());
EchoRequest actualRequest = ((EchoRequest) actualRequests.get(0));

Assert.assertEquals(request.getName(), actualRequest.getName());
Assert.assertEquals(request.getParent(), actualRequest.getParent());
Assert.assertEquals(request.getContent(), actualRequest.getContent());
Assert.assertEquals(request.getError(), actualRequest.getError());
Assert.assertEquals(request.getSeverity(), actualRequest.getSeverity());
Assert.assertEquals(request.getFoobar(), actualRequest.getFoobar());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}

@Test
public void collideNameExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockEcho.addException(exception);

try {
EchoRequest request =
EchoRequest.newBuilder()
.setName(FoobarName.ofProjectFoobarName("[PROJECT]", "[FOOBAR]").toString())
.setParent(FoobarName.ofProjectFoobarName("[PROJECT]", "[FOOBAR]").toString())
.setSeverity(Severity.forNumber(0))
.setFoobar(Foobar.newBuilder().build())
.build();
client.collideName(request);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,11 @@ public class EchoSettings extends ClientSettings<EchoSettings> {
return ((EchoStubSettings) getStubSettings()).blockSettings();
}

/** Returns the object with the settings used for calls to collideName. */
public UnaryCallSettings<EchoRequest, Object> collideNameSettings() {
return ((EchoStubSettings) getStubSettings()).collideNameSettings();
}

public static final EchoSettings create(EchoStubSettings stub) throws IOException {
return new EchoSettings.Builder(stub.toBuilder()).build();
}
Expand Down Expand Up @@ -263,6 +268,11 @@ public class EchoSettings extends ClientSettings<EchoSettings> {
return getStubSettingsBuilder().blockSettings();
}

/** Returns the builder for the settings used for calls to collideName. */
public UnaryCallSettings.Builder<EchoRequest, Object> collideNameSettings() {
return getStubSettingsBuilder().collideNameSettings();
}

@Override
public EchoSettings build() throws IOException {
return new EchoSettings(this);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ import com.google.showcase.v1beta1.BlockResponse;
import com.google.showcase.v1beta1.EchoRequest;
import com.google.showcase.v1beta1.EchoResponse;
import com.google.showcase.v1beta1.ExpandRequest;
import com.google.showcase.v1beta1.Object;
import com.google.showcase.v1beta1.PagedExpandRequest;
import com.google.showcase.v1beta1.PagedExpandResponse;
import com.google.showcase.v1beta1.WaitMetadata;
Expand Down Expand Up @@ -103,6 +104,7 @@ public class EchoStubSettings extends StubSettings<EchoStubSettings> {
private final OperationCallSettings<WaitRequest, WaitResponse, WaitMetadata>
waitOperationSettings;
private final UnaryCallSettings<BlockRequest, BlockResponse> blockSettings;
private final UnaryCallSettings<EchoRequest, Object> collideNameSettings;

private static final PagedListDescriptor<PagedExpandRequest, PagedExpandResponse, EchoResponse>
PAGED_EXPAND_PAGE_STR_DESC =
Expand Down Expand Up @@ -262,6 +264,11 @@ public class EchoStubSettings extends StubSettings<EchoStubSettings> {
return blockSettings;
}

/** Returns the object with the settings used for calls to collideName. */
public UnaryCallSettings<EchoRequest, Object> collideNameSettings() {
return collideNameSettings;
}

@BetaApi("A restructuring of stub classes is planned, so this may break in the future")
public EchoStub createStub() throws IOException {
if (getTransportChannelProvider()
Expand Down Expand Up @@ -345,6 +352,7 @@ public class EchoStubSettings extends StubSettings<EchoStubSettings> {
waitSettings = settingsBuilder.waitSettings().build();
waitOperationSettings = settingsBuilder.waitOperationSettings().build();
blockSettings = settingsBuilder.blockSettings().build();
collideNameSettings = settingsBuilder.collideNameSettings().build();
}

/** Builder for EchoStubSettings. */
Expand All @@ -365,6 +373,7 @@ public class EchoStubSettings extends StubSettings<EchoStubSettings> {
private final OperationCallSettings.Builder<WaitRequest, WaitResponse, WaitMetadata>
waitOperationSettings;
private final UnaryCallSettings.Builder<BlockRequest, BlockResponse> blockSettings;
private final UnaryCallSettings.Builder<EchoRequest, Object> collideNameSettings;
private static final ImmutableMap<String, ImmutableSet<StatusCode.Code>>
RETRYABLE_CODE_DEFINITIONS;

Expand Down Expand Up @@ -425,14 +434,16 @@ public class EchoStubSettings extends StubSettings<EchoStubSettings> {
waitSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
waitOperationSettings = OperationCallSettings.newBuilder();
blockSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
collideNameSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();

unaryMethodSettingsBuilders =
ImmutableList.<UnaryCallSettings.Builder<?, ?>>of(
echoSettings,
pagedExpandSettings,
simplePagedExpandSettings,
waitSettings,
blockSettings);
blockSettings,
collideNameSettings);
initDefaults(this);
}

Expand All @@ -449,14 +460,16 @@ public class EchoStubSettings extends StubSettings<EchoStubSettings> {
waitSettings = settings.waitSettings.toBuilder();
waitOperationSettings = settings.waitOperationSettings.toBuilder();
blockSettings = settings.blockSettings.toBuilder();
collideNameSettings = settings.collideNameSettings.toBuilder();

unaryMethodSettingsBuilders =
ImmutableList.<UnaryCallSettings.Builder<?, ?>>of(
echoSettings,
pagedExpandSettings,
simplePagedExpandSettings,
waitSettings,
blockSettings);
blockSettings,
collideNameSettings);
}

private static Builder createDefault() {
Expand Down Expand Up @@ -503,6 +516,11 @@ public class EchoStubSettings extends StubSettings<EchoStubSettings> {
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params"));

builder
.collideNameSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params"));

builder
.waitOperationSettings()
.setInitialCallSettings(
Expand Down Expand Up @@ -602,6 +620,11 @@ public class EchoStubSettings extends StubSettings<EchoStubSettings> {
return blockSettings;
}

/** Returns the builder for the settings used for calls to collideName. */
public UnaryCallSettings.Builder<EchoRequest, Object> collideNameSettings() {
return collideNameSettings;
}

@Override
public EchoStubSettings build() throws IOException {
return new EchoStubSettings(this);
Expand Down
Loading