Skip to content

Commit ac5f8d4

Browse files
author
Daniel Wang
committed
api: Add a convenience factory that builds GoogleJsonResponseException instances for testing. Also migrate ComputeCredential to point to the "v1" endpoint.
https://codereview.appspot.com/66560045/
1 parent 7a48c38 commit ac5f8d4

File tree

5 files changed

+158
-8
lines changed

5 files changed

+158
-8
lines changed

google-api-client/src/main/java/com/google/api/client/googleapis/compute/ComputeCredential.java

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ public class ComputeCredential extends Credential {
6161

6262
/** Metadata Service Account token server encoded URL. */
6363
public static final String TOKEN_SERVER_ENCODED_URL =
64-
"http://metadata/computeMetadata/v1beta1/instance/service-accounts/default/token";
64+
"http://metadata/computeMetadata/v1/instance/service-accounts/default/token";
6565

6666
/**
6767
* @param transport HTTP transport
@@ -83,6 +83,7 @@ protected TokenResponse executeRefreshToken() throws IOException {
8383
GenericUrl tokenUrl = new GenericUrl(getTokenServerEncodedUrl());
8484
HttpRequest request = getTransport().createRequestFactory().buildGetRequest(tokenUrl);
8585
request.setParser(new JsonObjectParser(getJsonFactory()));
86+
request.getHeaders().set("X-Google-Metadata-Request", true);
8687
return request.execute().parseAs(TokenResponse.class);
8788
}
8889

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
/*
2+
* Copyright (c) 2013 Google Inc.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5+
* in compliance with the License. You may obtain a copy of the License at
6+
*
7+
* http://www.apache.org/licenses/LICENSE-2.0
8+
*
9+
* Unless required by applicable law or agreed to in writing, software distributed under the License
10+
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11+
* or implied. See the License for the specific language governing permissions and limitations under
12+
* the License.
13+
*/
14+
15+
package com.google.api.client.googleapis.testing.json;
16+
17+
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
18+
import com.google.api.client.http.HttpRequest;
19+
import com.google.api.client.http.HttpResponse;
20+
import com.google.api.client.json.JsonFactory;
21+
import com.google.api.client.testing.http.HttpTesting;
22+
import com.google.api.client.testing.http.MockHttpTransport;
23+
import com.google.api.client.testing.http.MockLowLevelHttpResponse;
24+
import com.google.api.client.util.Beta;
25+
26+
import java.io.IOException;
27+
28+
/**
29+
* {@link Beta} <br/>
30+
* Factory class that builds {@link GoogleJsonResponseException} instances for
31+
* testing.
32+
*
33+
* @since 1.18
34+
*/
35+
@Beta
36+
public final class GoogleJsonResponseExceptionFactoryTesting {
37+
38+
/**
39+
* Convenience factory method that builds a {@link GoogleJsonResponseException}
40+
* from its arguments. The method builds a dummy {@link HttpRequest} and
41+
* {@link HttpResponse}, sets the response's status to a user-specified HTTP
42+
* error code, suppresses exceptions, and executes the request. This forces
43+
* the underlying framework to create, but not throw, a
44+
* {@link GoogleJsonResponseException}, which the method retrieves and returns
45+
* to the invoker.
46+
*
47+
* @param jsonFactory the JSON factory that will create all JSON required
48+
* by the underlying framework
49+
* @param httpCode the desired HTTP error code. Note: do nut specify any codes
50+
* that indicate successful completion, e.g. 2XX.
51+
* @param reasonPhrase the HTTP reason code that explains the error. For example,
52+
* if {@code httpCode} is {@code 404}, the reason phrase should be
53+
* {@code NOT FOUND}.
54+
* @return the generated {@link GoogleJsonResponseException}, as specified.
55+
* @throws IOException if request transport fails.
56+
*/
57+
public static GoogleJsonResponseException newMock(JsonFactory jsonFactory,
58+
int httpCode, String reasonPhrase) throws IOException {
59+
MockLowLevelHttpResponse otherServiceUnavaiableLowLevelResponse =
60+
new MockLowLevelHttpResponse()
61+
.setStatusCode(httpCode)
62+
.setReasonPhrase(reasonPhrase);
63+
MockHttpTransport otherTransport = MockHttpTransport.builder()
64+
.setLowLevelHttpResponse(otherServiceUnavaiableLowLevelResponse)
65+
.build();
66+
HttpRequest otherRequest = otherTransport
67+
.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
68+
otherRequest.setThrowExceptionOnExecuteError(false);
69+
HttpResponse otherServiceUnavailableResponse = otherRequest.execute();
70+
return GoogleJsonResponseException.from(jsonFactory, otherServiceUnavailableResponse);
71+
}
72+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
/*
2+
* Copyright (c) 2013 Google Inc.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5+
* in compliance with the License. You may obtain a copy of the License at
6+
*
7+
* http://www.apache.org/licenses/LICENSE-2.0
8+
*
9+
* Unless required by applicable law or agreed to in writing, software distributed under the License
10+
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11+
* or implied. See the License for the specific language governing permissions and limitations under
12+
* the License.
13+
*/
14+
15+
/**
16+
* {@link com.google.api.client.util.Beta} <br/>
17+
* Test utilities for the {@code com.google.api.client.googleapis.json} package.
18+
*
19+
* @since 1.18
20+
*/
21+
@com.google.api.client.util.Beta
22+
package com.google.api.client.googleapis.testing.json;
23+

google-api-client/src/test/java/com/google/api/client/googleapis/compute/ComputeCredentialTest.java

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@
1414

1515
package com.google.api.client.googleapis.compute;
1616

17+
import static com.google.common.collect.Iterables.getOnlyElement;
18+
1719
import com.google.api.client.auth.oauth2.TokenResponse;
1820
import com.google.api.client.http.HttpTransport;
1921
import com.google.api.client.http.LowLevelHttpRequest;
@@ -38,27 +40,36 @@ public class ComputeCredentialTest extends TestCase {
3840

3941
static final String TOKEN_TYPE = "Bearer";
4042

43+
static final String URL =
44+
"http://metadata/computeMetadata/v1/instance/service-accounts/default/token";
45+
4146
public void testExecuteRefreshToken() throws Exception {
42-
HttpTransport transport = new MockHttpTransport() {
47+
String content = "{" + "\"access_token\":\"" + ACCESS_TOKEN + "\"," + "\"expires_in\":"
48+
+ EXPIRES_IN_SECONDS + "," + "\"token_type\":\"" + TOKEN_TYPE + "\"" + "}";
49+
final MockLowLevelHttpRequest request = new MockLowLevelHttpRequest(URL).setResponse(
50+
new MockLowLevelHttpResponse().setContent(content).setContentType(Json.MEDIA_TYPE));
4351

52+
HttpTransport transport = new MockHttpTransport() {
4453
private int count = 0;
4554

4655
@Override
4756
public LowLevelHttpRequest buildRequest(String method, String url) {
4857
assertEquals(1, ++count);
4958
assertEquals("GET", method);
50-
assertEquals(
51-
"http://metadata/computeMetadata/v1beta1/instance/service-accounts/default/token", url);
52-
String content = "{" + "\"access_token\":\"" + ACCESS_TOKEN + "\"," + "\"expires_in\":"
53-
+ EXPIRES_IN_SECONDS + "," + "\"token_type\":\"" + TOKEN_TYPE + "\"" + "}";
54-
return new MockLowLevelHttpRequest(url).setResponse(
55-
new MockLowLevelHttpResponse().setContent(content).setContentType(Json.MEDIA_TYPE));
59+
assertEquals(URL, url);
60+
61+
return request;
5662
}
5763
};
64+
5865
ComputeCredential cred = new ComputeCredential(transport, new JacksonFactory());
5966
TokenResponse response = cred.executeRefreshToken();
6067
assertEquals(ACCESS_TOKEN, response.getAccessToken());
6168
assertEquals(EXPIRES_IN_SECONDS, response.getExpiresInSeconds().longValue());
6269
assertEquals(TOKEN_TYPE, response.getTokenType());
70+
71+
// Verify that the request had the metadata-request header configured properly
72+
assertEquals("true", getOnlyElement(request.getHeaderValues(
73+
"X-Google-Metadata-Request")));
6374
}
6475
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/*
2+
* Copyright (c) 2013 Google Inc.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5+
* in compliance with the License. You may obtain a copy of the License at
6+
*
7+
* http://www.apache.org/licenses/LICENSE-2.0
8+
*
9+
* Unless required by applicable law or agreed to in writing, software distributed under the License
10+
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11+
* or implied. See the License for the specific language governing permissions and limitations under
12+
* the License.
13+
*/
14+
15+
package com.google.api.client.googleapis.testing.json;
16+
17+
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
18+
import com.google.api.client.json.JsonFactory;
19+
import com.google.api.client.json.jackson.JacksonFactory;
20+
21+
import junit.framework.TestCase;
22+
23+
import java.io.IOException;
24+
25+
/**
26+
* Tests {@link GoogleJsonResponseExceptionFactoryTesting}
27+
*
28+
* @author Eric Mintz
29+
*/
30+
public class GoogleJsonResponseExceptionFactoryTestingTest extends TestCase {
31+
32+
private static final JsonFactory JSON_FACTORY = new JacksonFactory();
33+
private static final int HTTP_CODE_NOT_FOUND = 404;
34+
private static final String REASON_PHRASE_NOT_FOUND = "NOT FOUND";
35+
36+
public void testCreateException() throws IOException {
37+
GoogleJsonResponseException exception =
38+
GoogleJsonResponseExceptionFactoryTesting.newMock(
39+
JSON_FACTORY, HTTP_CODE_NOT_FOUND, REASON_PHRASE_NOT_FOUND);
40+
assertEquals(HTTP_CODE_NOT_FOUND, exception.getStatusCode());
41+
assertEquals(REASON_PHRASE_NOT_FOUND, exception.getStatusMessage());
42+
}
43+
}

0 commit comments

Comments
 (0)