8000 fix(compute): fixed compute_reservation_create_shared sample and test… · invertase/java-docs-samples@3b9ac56 · GitHub
[go: up one dir, main page]

Skip to content

Commit 3b9ac56

Browse files
fix(compute): fixed compute_reservation_create_shared sample and test to use mocked client (GoogleCloudPlatform#9840)
* Fixed sample and test to use mocked client * Fixed code as requested in the comments
1 parent 230665f commit 3b9ac56

File tree

2 files changed

+73
-94
lines changed

2 files changed

+73
-94
lines changed

compute/cloud-client/src/main/java/compute/reservation/CreateSharedReservation.java

Lines changed: 46 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,9 @@
1818

1919
// [START compute_reservation_create_shared]
2020
import com.google.cloud.compute.v1.AllocationSpecificSKUReservation;
21+
import com.google.cloud.compute.v1.InsertReservationRequest;
2122
import com.google.cloud.compute.v1.Operation;
23+
import com.google.cloud.compute.v1.Operation.Status;
2224
import com.google.cloud.compute.v1.Reservation;
2325
import com.google.cloud.compute.v1.ReservationsClient;
2426
import com.google.cloud.compute.v1.ShareSettings;
@@ -29,12 +31,6 @@
2931
import java.util.concurrent.TimeoutException;
3032

3133
public class CreateSharedReservation {
32-
private final ReservationsClient reservationsClient;
33-
34-
// Constructor to inject the ReservationsClient
35-
public CreateSharedReservation(ReservationsClient reservationsClient) {
36-
this.reservationsClient = reservationsClient;
37-
}
3834

3935
public static void main(String[] args)
4036
throws IOException, ExecutionException, InterruptedException, TimeoutException {
@@ -48,62 +44,66 @@ public static void main(String[] args)
4844
// For more information visit this page:
4945
// https://cloud.google.com/compute/docs/instances/reservations-shared#shared_reservation_constraint
5046
String projectId = "YOUR_PROJECT_ID";
51-
// Zone in which the reservation resides.
47+
// Zone in which to reserve resources.
5248
String zone = "us-central1-a";
5349
// Name of the reservation to be created.
5450
String reservationName = "YOUR_RESERVATION_NAME";
5551
// The URI of the global instance template to be used for creating the reservation.
5652
String instanceTemplateUri = String.format(
57-
"projects/%s/global/instanceTemplates/YOUR_INSTANCE_TEMPLATE_NAME", projectId);
53+
"projects/%s/global/instanceTemplates/%s", projectId, "YOUR_INSTANCE_TEMPLATE_NAME");
5854
// Number of instances for which capacity needs to be reserved.
5955
int vmCount = 3;
60-
// In your main method, create ReservationsClient
61-
ReservationsClient client = ReservationsClient.create();
62-
// Create an instance of your class, passing in the client
63-
CreateSharedReservation creator = new CreateSharedReservation(client);
6456

65-
creator.createSharedReservation(projectId, zone, reservationName, instanceTemplateUri, vmCount);
57+
createSharedReservation(projectId, zone, reservationName, instanceTemplateUri, vmCount);
6658
}
6759

6860
// Creates a shared reservation with the given name in the given zone.
69-
public void createSharedReservation(
70-
String projectId, String zone,
71-
String reservationN ED4F ame, String instanceTemplateUri, int vmCount)
72-
throws ExecutionException, InterruptedException, TimeoutException {
61+
public static Status createSharedReservation(
62+
String projectId, String zone,
63+
String reservationName, String instanceTemplateUri, int vmCount)
64+
throws ExecutionException, InterruptedException, TimeoutException, IOException {
65+
66+
// Initialize client that will be used to send requests. This client only needs to be created
67+
// once, and can be reused for multiple requests.
68+
try (ReservationsClient reservationsClient = ReservationsClient.create()) {
69+
ShareSettings shareSettings = ShareSettings.newBuilder()
70+
.setShareType(String.valueOf(ShareSettings.ShareType.SPECIFIC_PROJECTS))
71+
// The IDs of projects that can consume this reservation. You can include up to
72+
// 100 consumer projects. These projects must be in the same organization as
73+
// the owner project. Don't include the owner project.
74+
// By default, it is already allowed to consume the reservation.
75+
.putProjectMap("CONSUMER_PROJECT_1", ShareSettingsProjectConfig.newBuilder().build())
76+
.putProjectMap("CONSUMER_PROJECT_2", ShareSettingsProjectConfig.newBuilder().build())
77+
.build();
7378

74-
ShareSettings shareSettings = ShareSettings.newBuilder()
75-
.setShareType(String.valueOf(ShareSettings.ShareType.SPECIFIC_PROJECTS))
76-
// The IDs of projects that can consume this reservation. You can include up to 100
77-
// consumer projects. These projects must be in the same organization as
78-
// the owner project. Don't include the owner project. By default, it is already allowed
79-
// to consume the reservation.
80-
.putProjectMap("CONSUMER_PROJECT_ID_1", ShareSettingsProjectConfig.newBuilder().build())
81-
.putProjectMap("CONSUMER_PROJECT_ID_2", ShareSettingsProjectConfig.newBuilder().build())
82-
.build();
79+
Reservation reservationResource =
80+
Reservation.newBuilder()
81+
.setName(reservationName)
82+
.setZone(zone)
83+
.setSpecificReservationRequired(true)
84+
.setShareSettings(shareSettings)
85+
.setSpecificReservation(
86+
AllocationSpecificSKUReservation.newBuilder()
87+
.setCount(vmCount)
88+
.setSourceInstanceTemplate(instanceTemplateUri)
89+
.build())
90+
.build();
8391

84-
// Create the reservation.
85-
Reservation reservation =
86-
Reservation.newBuilder()
87-
.setName(reservationName)
88-
.setZone(zone)
89-
.setSpecificReservationRequired(true)
90-
.setShareSettings(shareSettings)
91-
.setSpecificReservation(
92-
AllocationSpecificSKUReservation.newBuilder()
93-
.setCount(vmCount)
94-
.setSourceInstanceTemplate(instanceTemplateUri)
95-
.build())
96-
.build();
92+
InsertReservationRequest request =
93+
InsertReservationRequest.newBuilder()
94+
.setProject(projectId)
95+
.setZone(zone)
96+
.setReservationResource(reservationResource)
97+
.build();
9798

98-
// Wait for the create reservation operation to complete.
99-
Operation response =
100-
this.reservationsClient.insertAsync(projectId, zone, reservation).get(3, TimeUnit.MINUTES);
99+
Operation response = reservationsClient.insertAsync(request)
100+
.get(3, TimeUnit.MINUTES);
101101

102-
if (response.hasError()) {
103-
System.out.println("Reservation creation failed!" + response);
104-
return;
102+
if (response.hasError()) {
103+
throw new Error("Reservation creation failed!!" + response);
104+
}
105+
return response.getStatus();
105106
}
106-
System.out.println("Reservation created. Operation Status: " + response.getStatus());
107107
}
108108
}
109109
// [END compute_reservation_create_shared]

compute/cloud-client/src/test/java/compute/reservation/ReservationIT.java

Lines changed: 27 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -18,21 +18,23 @@
1818

1919
import static com.google.common.truth.Truth.assertThat;
2020
import static com.google.common.truth.Truth.assertWithMessage;
21+
import static org.junit.Assert.assertEquals;
2122
import static org.junit.Assert.assertNotNull;
23+
import static org.mockito.ArgumentMatchers.any;
24+
import static org.mockito.ArgumentMatchers.anyLong;
2225
import static org.mockito.Mockito.mock;
26+
import static org.mockito.Mockito.mockStatic;
2327
import static org.mockito.Mockito.times;
2428
import static org.mockito.Mockito.verify;
2529
import static org.mockito.Mockito.when;
2630

2731
import com.google.api.gax.longrunning.OperationFuture;
2832
import com.google.api.gax.rpc.NotFoundException;
29-
import com.google.cloud.compute.v1.AllocationSpecificSKUReservation;
33+
import com.google.cloud.compute.v1.InsertReservationRequest;
3034
import com.google.cloud.compute.v1.Operation;
3135
import com.google.cloud.compute.v1.Operation.Status;
3236
import com.google.cloud.compute.v1.Reservation;
3337
import com.google.cloud.compute.v1.ReservationsClient;
34-
import com.google.cloud.compute.v1.ShareSettings;
35-
import com.google.cloud.compute.v1.ShareSettingsProjectConfig;
3638
import compute.CreateInstanceTemplate;
3739
import compute.CreateRegionalInstanceTemplate;
3840
import compute.DeleteInstanceTemplate;
@@ -53,6 +55,7 @@
5355
import org.junit.jupiter.api.Timeout;
5456
import org.junit.runner.RunWith;
5557
import org.junit.runners.JUnit4;
58+
import org.mockito.MockedStatic;
5659

5760
@RunWith(JUnit4.class)
5861
@Timeout(value = 6, unit = TimeUnit.MINUTES)
@@ -184,50 +187,26 @@ public void testCreateReservationWithRegionInstanceTemplate()
184187

185188
@Test
186189
public void testCreateSharedReservation()
187-
throws ExecutionException, InterruptedException, TimeoutException {
188-
// Mock the ReservationsClient
189-
ReservationsClient mockReservationsClient = mock(ReservationsClient.class);
190-
191-
// This test require projects in the test environment to share reservation with,
192-
// therefore the operation should be mocked. If you want to make a real test,
193-
// please set the CONSUMER_PROJECT_ID_1 and CONSUMER_PROJECT_ID_2 accordingly.
194-
// Make sure that base project has proper permissions to share reservations.
195-
// See: https://cloud.google.com/compute/docs/instances/reservations-shared#shared_reservation_constraint
196-
ShareSettings shareSettings = ShareSettings.newBuilder()
197-
.setShareType(String.valueOf(ShareSettings.ShareType.SPECIFIC_PROJECTS))
198-
.putProjectMap("CONSUMER_PROJECT_ID_1", ShareSettingsProjectConfig.newBuilder().build())
199-
.putProjectMap("CONSUMER_PROJECT_ID_2", ShareSettingsProjectConfig.newBuilder().build())
200-
.build();
201-
202-
Reservation reservation =
203-
Reservation.newBuilder()
204-
.setName(RESERVATION_NAME_SHARED)
205-
.setZone(ZONE)
206-
.setSpecificReservationRequired(true)
207-
.setShareSettings(shareSettings)
208-
.setSpecificReservation(
209-
AllocationSpecificSKUReservation.newBuilder()
210-
.setCount(NUMBER_OF_VMS)
211-
.setSourceInstanceTemplate(INSTANCE_TEMPLATE_SHARED_RESERV_URI)
212-
.build())
213-
.build();
214-
215-
OperationFuture mockFuture = mock(OperationFuture.class);
216-
when(mockReservationsClient.insertAsync(PROJECT_ID, ZONE, reservation))
217-
.thenReturn(mockFuture);
218-
Operation mockOperation = mock(Operation.class);
219-
when(mockFuture.get(3, TimeUnit.MINUTES)).thenReturn(mockOperation);
220-
when(mockOperation.hasError()).thenReturn(false);
221-
when(mockOperation.getStatus()).thenReturn(Status.DONE);
222-
223-
// Create an instance, passing in the mock client
224-
CreateSharedReservation creator = new CreateSharedReservation(mockReservationsClient);
225-
226-
creator.createSharedReservation(PROJECT_ID, ZONE,
227-
RESERVATION_NAME_SHARED, INSTANCE_TEMPLATE_SHARED_RESERV_URI, NUMBER_OF_VMS);
228-
229-
verify(mockReservationsClient, times(1))
230-
.insertAsync(PROJECT_ID, ZONE, reservation);
231-
assertThat(stdOut.toString()).contains("Reservation created. Operation Status: DONE");
190+
throws ExecutionException, InterruptedException, TimeoutException, IOException {
191+
try (MockedStatic<ReservationsClient> mockReservationsClient =
192+
mockStatic(ReservationsClient.class)) {
193+
ReservationsClient mockClient = mock(ReservationsClient.class);
194+
OperationFuture mockFuture = mock(OperationFuture.class);
195+
Operation mockOperation = mock(Operation.class);
196+
197+
mockReservationsClient.when(ReservationsClient::create).thenReturn(mockClient);
198+
when(mockClient.insertAsync(any(InsertReservationRequest.class)))
199+
.thenReturn(mockFuture);
200+
when(mockFuture.get(3, TimeUnit.MINUTES)).thenReturn(mockOperation);
201+
when(mockOperation.getStatus()).thenReturn(Status.DONE);
202+
203+
Status status = CreateSharedReservation.createSharedReservation(PROJECT_ID, ZONE,
204+
RESERVATION_NAME_SHARED, INSTANCE_TEMPLATE_SHARED_RESERV_URI, NUMBER_OF_VMS);
205+
206+
verify(mockClient, times(1)).insertAsync(any(InsertReservationRequest.class));
207+
verify(mockFuture, times(1)).get(anyLong(), any(TimeUnit.class));
208+
assertEquals(Status.DONE, status);
209+
210+
}
232211
}
233212
}

0 commit comments

Comments
 (0)
0