Skip to content

Commit

Permalink
add support for listing repositories accessible to an app installation (
Browse files Browse the repository at this point in the history
#42)

* add method to list repos accessible to a Github App

this change implements support for
https://docs.github.com/en/free-pro-team@latest/rest/reference/apps#list-repositories-accessible-to-the-app-installation

I believe though, that in this initial form, the response is limited to
only the first page of results returned by the Github API:
#41

* add GithubAppClientTest#listAccessibleRepositories and refactor other tests

This commit refactors GithubAppClientTest so that it tests the actual
methods in GithubAppClient and adds a test of the new method
`listAccessibleRepositories()`.

Previously the test did not actually test any logic in GithubAppClient
but rather the tests were of the deserialization logic for some of the
types used in the class.

I moved the test related to deserializing an AccessToken to a new
AccessTokenTest, and replaced the other tests so that they use a
MockWebServer to actually be able to test the HTTP requests/responses.

* minor: unnecessary type arguments

* forgot to teardown MockWebServer

use it as a Rule instead to make things a little simpler

* squash: remove redundant toCompletableFuture() calls
  • Loading branch information
mattnworb authored Oct 29, 2020
1 parent 32b0bf5 commit 0a3da44
Show file tree
Hide file tree
Showing 11 changed files with 491 additions and 118 deletions.
6 changes: 6 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,12 @@
<version>0.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
<version>2.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/*-
* -\-\-
* github-client
* --
* Copyright (C) 2016 - 2020 Spotify AB
* --
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* -/-/-
*/

package com.spotify.github.v3.apps;

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.spotify.github.GithubStyle;
import com.spotify.github.v3.repos.Repository;
import java.util.List;
import org.immutables.value.Value;

/**
* Response for requests to "List repositories accessible to the app installation"
*
* https://docs.github.com/en/free-pro-team@latest/rest/reference/apps#list-repositories-accessible-to-the-app-installation
*/
@Value.Immutable
@GithubStyle
@JsonDeserialize(as = ImmutableInstallationRepositoriesResponse.class)
public interface InstallationRepositoriesResponse {
int totalCount();

List<Repository> repositories();
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,13 @@

import com.fasterxml.jackson.core.type.TypeReference;
import com.spotify.github.jackson.Json;
import com.spotify.github.v3.prs.Review;
import com.spotify.github.v3.checks.AccessToken;
import com.spotify.github.v3.comment.Comment;
import com.spotify.github.v3.exceptions.ReadOnlyRepositoryException;
import com.spotify.github.v3.exceptions.RequestNotOkException;
import com.spotify.github.v3.git.Reference;
import com.spotify.github.v3.prs.PullRequestItem;
import com.spotify.github.v3.prs.Review;
import com.spotify.github.v3.prs.ReviewRequests;
import com.spotify.github.v3.repos.Branch;
import com.spotify.github.v3.repos.CommitItem;
Expand Down
19 changes: 17 additions & 2 deletions src/main/java/com/spotify/github/v3/clients/GithubAppClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@

import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.collect.ImmutableMap;
import com.spotify.github.v3.apps.InstallationRepositoriesResponse;
import com.spotify.github.v3.checks.AccessToken;
import com.spotify.github.v3.checks.Installation;
import java.util.List;
Expand All @@ -35,6 +36,7 @@ public class GithubAppClient {
private static final String GET_ACCESS_TOKEN_URL = "/app/installations/%s/access_tokens";
private static final String GET_INSTALLATIONS_URL = "/app/installations?per_page=100";
private static final String GET_INSTALLATION_REPO_URL = "/repos/%s/%s/installation";
private static final String LIST_ACCESSIBLE_REPOS_URL = "/installation/repositories";

private final GitHubClient github;
private final String owner;
Expand All @@ -44,7 +46,7 @@ public class GithubAppClient {
ImmutableMap.of(HttpHeaders.ACCEPT, "application/vnd.github.machine-man-preview+json");

private static final TypeReference<List<Installation>> INSTALLATION_LIST_TYPE_REFERENCE =
new TypeReference<List<Installation>>() {};
new TypeReference<>() {};

GithubAppClient(final GitHubClient github, final String owner, final String repo) {
this.github = github;
Expand All @@ -62,7 +64,7 @@ public CompletableFuture<List<Installation>> getInstallations() {
}

/**
* Get Installation of a.repo
* Get Installation of a repo
*
* @return a list of Installation
*/
Expand All @@ -80,4 +82,17 @@ public CompletableFuture<AccessToken> getAccessToken(final Integer installationI
final String path = String.format(GET_ACCESS_TOKEN_URL, installationId);
return github.post(path, "", AccessToken.class, extraHeaders);
}

/**
* Lists the repositories that an app installation can access.
*
* <p>see
* https://docs.github.com/en/free-pro-team@latest/rest/reference/apps#list-repositories-accessible-to-the-app-installation
*/
public CompletableFuture<InstallationRepositoriesResponse> listAccessibleRepositories(
final int installationId) {

return GitHubClient.scopeForInstallationId(github, installationId)
.request(LIST_ACCESSIBLE_REPOS_URL, InstallationRepositoriesResponse.class, extraHeaders);
}
}
13 changes: 13 additions & 0 deletions src/test/java/com/spotify/github/FixtureHelper.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,11 @@
import static java.nio.charset.Charset.defaultCharset;

import com.google.common.io.Resources;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.URISyntaxException;
import java.net.URL;

public class FixtureHelper {

Expand All @@ -38,4 +41,14 @@ public static String loadFixture(final String path) {
throw new UncheckedIOException(e);
}
}

/** Return a File pointing to the resource on the classpath */
public static File loadFile(final String path) {
URL resource = getResource(FIXTURE_ROOT + path);
try {
return new File(resource.toURI());
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
}
42 changes: 42 additions & 0 deletions src/test/java/com/spotify/github/v3/checks/AccessTokenTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/*-
* -\-\-
* github-client
* --
* Copyright (C) 2016 - 2020 Spotify AB
* --
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* -/-/-
*/

package com.spotify.github.v3.checks;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;

import com.spotify.github.FixtureHelper;
import com.spotify.github.jackson.Json;
import java.io.IOException;
import java.time.ZonedDateTime;
import org.junit.Test;

public class AccessTokenTest {
private final Json json = Json.create();

@Test
public void canDeserializeToken() throws IOException {
final AccessToken accessToken =
json.fromJson(FixtureHelper.loadFixture("checks/access-token.json"), AccessToken.class);
assertThat(accessToken.token(), is("v1.1f699f1069f60xxx"));
assertThat(accessToken.expiresAt(), is(ZonedDateTime.parse("2016-07-11T22:14:10Z")));
}
}
121 changes: 83 additions & 38 deletions src/test/java/com/spotify/github/v3/clients/GithubAppClientTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,61 +20,106 @@

package com.spotify.github.v3.clients;

import static java.nio.charset.StandardCharsets.UTF_8;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.core.Is.is;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import com.google.common.io.Resources;
import com.spotify.github.jackson.Json;
import com.spotify.github.v3.checks.AccessToken;
import com.spotify.github.v3.checks.InstallationList;
import java.io.IOException;
import java.io.UncheckedIOException;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.spotify.github.FixtureHelper;
import com.spotify.github.v3.apps.InstallationRepositoriesResponse;
import com.spotify.github.v3.checks.Installation;
import java.io.File;
import java.net.URI;
import java.time.ZonedDateTime;
import java.util.List;
import java.util.concurrent.TimeUnit;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;

public class GithubAppClientTest {

private static final String FIXTURES_PATH = "com/spotify/github/v3/githubapp/";
private Json json;
@Rule
public final MockWebServer mockServer = new MockWebServer();

public static String loadResource(final String path) {
try {
return Resources.toString(Resources.getResource(path), UTF_8);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private final ObjectMapper objectMapper = new ObjectMapper();
private final int appId = 42;
private GithubAppClient client;

@Before
public void setUp() {
final GitHubClient github = mock(GitHubClient.class);
final GithubAppClient client = new GithubAppClient(github, "org", "repo");
json = Json.create();
when(github.json()).thenReturn(json);
public void setUp() throws Exception {
URI uri = mockServer.url("").uri();
File key = FixtureHelper.loadFile("githubapp/key.pem");

GitHubClient rootclient = GitHubClient.create(uri, key, appId);
client = rootclient.createRepositoryClient("", "").createGithubAppClient();
}

@Test
public void getInstallationsList() throws Exception {
final InstallationList installations =
json.fromJson(
loadResource(FIXTURES_PATH + "installations-list.json"), InstallationList.class);

assertThat(installations.totalCount(), is(2));
assertThat(installations.installations().get(0).account().login(), is("github"));
assertThat(installations.installations().get(0).id(), is(1));
assertThat(installations.installations().get(1).account().login(), is("octocat"));
assertThat(installations.installations().get(1).id(), is(3));
mockServer.enqueue(
new MockResponse()
.setResponseCode(200)
.setBody(FixtureHelper.loadFixture("githubapp/installations-list.json")));

List<Installation> installations = client.getInstallations().join();

assertThat(installations.size(), is(2));
assertThat(installations.get(0).account().login(), is("github"));
assertThat(installations.get(0).id(), is(1));
assertThat(installations.get(1).account().login(), is("octocat"));
assertThat(installations.get(1).id(), is(3));

RecordedRequest recordedRequest = mockServer.takeRequest(1, TimeUnit.MILLISECONDS);
assertThat(recordedRequest.getRequestUrl().encodedPath(), is("/app/installations"));
assertThat(recordedRequest.getRequestUrl().queryParameter("per_page"), is("100"));

assertThat(
recordedRequest.getHeaders().values("Accept"),
containsInAnyOrder("application/json", "application/vnd.github.machine-man-preview+json"));
}

@Test
public void canDeserializeToken() throws IOException {
final AccessToken accessToken =
json.fromJson(loadResource(FIXTURES_PATH + "access-token.json"), AccessToken.class);
assertThat(accessToken.token(), is("v1.1f699f1069f60xxx"));
assertThat(accessToken.expiresAt(), is(ZonedDateTime.parse("2016-07-11T22:14:10Z")));
public void listAccessibleRepositories() throws Exception {
// response for POST /app/installations/:id/access_tokens
final String installationAccessToken = "abc123-secret";
mockServer.enqueue(
new MockResponse()
.setResponseCode(201)
// this might not serialize 100% the same as the Json class's ObjectMapper but should be
// fine for this test
.setBody(
objectMapper
.createObjectNode()
.put("token", installationAccessToken)
.put("expires_at", ZonedDateTime.now().plusHours(1).toString())
.toString()));

// response for GET /installation/repositories
mockServer.enqueue(
new MockResponse()
.setResponseCode(200)
.setBody(FixtureHelper.loadFixture("githubapp/accessible-repositories.json")));

InstallationRepositoriesResponse response =
client.listAccessibleRepositories(1234).join();

assertThat(response.totalCount(), is(2));
assertThat(response.repositories().size(), is(2));
assertThat(response.repositories().get(0).id(), is(1));
assertThat(response.repositories().get(1).id(), is(2));

RecordedRequest accessTokenRequest = mockServer.takeRequest(1, TimeUnit.MILLISECONDS);
assertThat(accessTokenRequest.getMethod(), is("POST"));
assertThat(
accessTokenRequest.getRequestUrl().encodedPath(),
is("/app/installations/1234/access_tokens"));

RecordedRequest listReposRequest = mockServer.takeRequest(1, TimeUnit.MILLISECONDS);
assertThat(listReposRequest.getMethod(), is("GET"));
assertThat(listReposRequest.getRequestUrl().encodedPath(), is("/installation/repositories"));
}
}
Loading

0 comments on commit 0a3da44

Please sign in to comment.