Files
octokit.net/Octokit.Tests.Integration/Helper.cs
Itai Bar-Haim 5ffc96995f Adding initial support for GitHub Apps. (#1738)
* Added authentication using bearer token.

* Added Installation and AccessToken clients.

* Added new clients to Reactive project

* added support for DateTime serialized as FileTime

* added support for StatusEventPayload

* added support for StatusEventPayload

* Added test for StatusEventPayload and fixed serializer to return that event payload type.

* WIP - added ApplicationClient and related Api Urls.

* Continued implementing Installations support.

* Fixing build (WIP)

* fixed build

* added Account property to Installation. prefer nameof(x) over literal "x".

* fixed according to code review.

* fixed build.

* switched Installation ID from int to long.

* added Permissions and Events properties to Installation.

* added documentation to Application and Installation properties in IGitHubClient.

* wip - added tests to new clients

* wip - fix build

* wip - fixed build.

* added InstallationsClient tests.

* added integration test for InstallationsClient.

* changes requested in code review.

* add Get method for App

* Create GitHubApp response model instead of re-using existing Application response model

* add Get method to observable client

* fixed build (both locally and failed test).

* Fixed documentation and added some missing XML docs.

* added DebuggerDisplay to StatusEventPayload

* updated XML docs and added some missing bits. prefer nameof(x) over literal "x".

* Add xml comments to AccessToken response model and use DateTimeOffset rather than DateTime

* Tidy up XmlComments and make consistent across client and observable client and interfaces

* fixup unit tests to independently verify preview header

* Implement GetInstallation method

* revert commits unrelated to GitHubApps - these can be done on a separate PR if required

* this extra authenticator class doesnt appear to be used anywhere

* undo project file change as it doesnt appear to be necessary

* Revert "Merge remote-tracking branch 'remote/GitHubApps' into GitHubApps"

This reverts commit c53cc110b8d807f62fdfeaa7df19e1532d050007, reversing
changes made to 0c9e413d420a4725738644ea5b13af6ec102d456.

* Revert "Revert "Merge remote-tracking branch 'remote/GitHubApps' into GitHubApps""

This reverts commit 02d52b8adf814b6945c60cb59a907a8cd34b1ce7.

* add XmlDoc comments to response models and flesh out installation permissions

* name AcceptHeaders member consistently

* accidentally lost changes to Credentials.cs

* Enhance Intergation test framework to handle GitHubApp settings and discoer tests appropriately
Get code ready for GitHubJWT nuget package but for now just hardcode a JWT in ENV VAR
Add 1 integration test for each method and ensure they are working!

* fixed compiler warnings.

* Added support for Installation=>Id field that arrives in a Pull Request Event payload.

(See the last field in the sample JSON of https://developer.github.com/v3/activity/events/types/#pullrequestevent)

* Change integration test project to netcoreapp2.0 so we can use GitHubJwt nuget package in integration tests

* First cut at some GitHubApp doco

* update mkdocs config

* Moved the Installation property to ActivityPayload, so it's available in all payloads.

This feature is not undocumented, unfortunately, but valid:
https://platform.github.community/t/determining-which-installation-an-event-came-from/539/11

* Split Installation to Installation and InstallationId, and added a comfort method for gaining its AccessToken.

* fixed InstallationId CreateAccessToken to receive IGitHubAppsClient. added (and fixed) docs.

* reverted object-oriented style comfort method and it's docs.

* update all test projects to netcoreapp2.0

* tweak build configs to use 2.0.3 SDK

* also need to update cake frosting build to netcoreapp2.0

* tweak docs some more

* fix convention test failures

* test projects still had some old runtime parts in them!

* travis osx image needs to be at least 10.12 for .NET Core 2.0

* shell script might need the same argument tweak for cake

* more doc tweaks

* Make sure compiler warning output isnt somehow causing Linux and OSX builds to fail

* moar logging for linux/OSX builds

* stop sourcelink on linux/OSX builds to see if that is the problem

* set verbosity to detailed for the dotnet build step

* try new sourcelink and list out remotes

* is travis being weird with git clone?

* SourceLink may be defaulting to true on CI server so explicitly set it as false rather than omitting it

* detailed is a bit too verbose for travis, try normal

* turn sourcelink back on for Linux/OSX

* fix compiler warning

* Try SourceLink.Create.CommandLine instead of SourceLink.Create.GitHub

* CliToolReferences did not update to latest versions

* remove debug origin info

* turn off msbuild output

* go back to SourceLink.Create.GitHub!

* time diff between dev PC and API causes issues if specifying a full 600 second token

* handle extra date format that Installation end point now returns

* field needs to be protected in order to be deserialized

* provide even more buffer for client vs server clock drift

* Update to latest GitHubJwt reference

* go back to SDK 1 since SDK 2 is having sporadic travisCI faliures in TestSourceLink build step

* get appveyor working

* update sourcelink back to latest, and use SDK 1.04 (runtime 1.0.5)
2018-04-16 20:42:23 +10:00

332 lines
11 KiB
C#

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
namespace Octokit.Tests.Integration
{
public static class Helper
{
static readonly Lazy<Credentials> _credentialsThunk = new Lazy<Credentials>(() =>
{
var githubUsername = Environment.GetEnvironmentVariable("OCTOKIT_GITHUBUSERNAME");
UserName = githubUsername;
Organization = Environment.GetEnvironmentVariable("OCTOKIT_GITHUBORGANIZATION");
var githubToken = Environment.GetEnvironmentVariable("OCTOKIT_OAUTHTOKEN");
if (githubToken != null)
return new Credentials(githubToken);
var githubPassword = Environment.GetEnvironmentVariable("OCTOKIT_GITHUBPASSWORD");
if (githubUsername == null || githubPassword == null)
return null;
return new Credentials(githubUsername, githubPassword);
});
static readonly Lazy<Credentials> _credentialsSecondUserThunk = new Lazy<Credentials>(() =>
{
var githubUsername = Environment.GetEnvironmentVariable("OCTOKIT_GITHUBUSERNAME_2");
var githubPassword = Environment.GetEnvironmentVariable("OCTOKIT_GITHUBPASSWORD_2");
if (githubUsername == null || githubPassword == null)
return null;
return new Credentials(githubUsername, githubPassword);
});
static readonly Lazy<Credentials> _oauthApplicationCredentials = new Lazy<Credentials>(() =>
{
var applicationClientId = ClientId;
var applicationClientSecret = ClientSecret;
if (applicationClientId == null || applicationClientSecret == null)
return null;
return new Credentials(applicationClientId, applicationClientSecret);
});
static readonly Lazy<Credentials> _basicAuthCredentials = new Lazy<Credentials>(() =>
{
var githubUsername = Environment.GetEnvironmentVariable("OCTOKIT_GITHUBUSERNAME");
UserName = githubUsername;
Organization = Environment.GetEnvironmentVariable("OCTOKIT_GITHUBORGANIZATION");
var githubPassword = Environment.GetEnvironmentVariable("OCTOKIT_GITHUBPASSWORD");
if (githubUsername == null || githubPassword == null)
return null;
return new Credentials(githubUsername, githubPassword);
});
static readonly Lazy<bool> _gitHubAppsEnabled = new Lazy<bool>(() =>
{
string enabled = Environment.GetEnvironmentVariable("OCTOKIT_GITHUBAPP_ENABLED");
return !String.IsNullOrWhiteSpace(enabled);
});
static readonly Lazy<Credentials> _githubAppCredentials = new Lazy<Credentials>(() =>
{
// GitHubJwt nuget package only available for netstandard2.0+
#if GITHUBJWT_HELPER_AVAILABLE
var generator = new GitHubJwt.GitHubJwtFactory(
new GitHubJwt.FilePrivateKeySource(GitHubAppPemFile),
new GitHubJwt.GitHubJwtFactoryOptions
{
AppIntegrationId = Convert.ToInt32(GitHubAppId),
ExpirationSeconds = 500
}
);
var jwtToken = generator.CreateEncodedJwtToken();
return new Credentials(jwtToken, AuthenticationType.Bearer);
#else
// return null, which will cause the [GitHubAppTest]'s to not be discovered
return null;
#endif
});
static readonly Lazy<Uri> _customUrl = new Lazy<Uri>(() =>
{
string uri = Environment.GetEnvironmentVariable("OCTOKIT_CUSTOMURL");
if (uri != null)
return new Uri(uri);
return null;
});
static Helper()
{
// Force reading of environment variables.
// This wasn't happening if UserName/Organization were
// retrieved before Credentials.
Debug.WriteIf(Credentials == null, "No credentials specified.");
}
public static string UserName { get; private set; }
public static string Organization { get; private set; }
/// <summary>
/// These credentials should be set to a test GitHub account using the powershell script configure-integration-tests.ps1
/// </summary>
public static Credentials Credentials { get { return _credentialsThunk.Value; } }
public static Credentials CredentialsSecondUser { get { return _credentialsSecondUserThunk.Value; } }
public static Credentials ApplicationCredentials { get { return _oauthApplicationCredentials.Value; } }
public static Credentials BasicAuthCredentials { get { return _basicAuthCredentials.Value; } }
public static Credentials GitHubAppCredentials { get { return _githubAppCredentials.Value; } }
public static Uri CustomUrl { get { return _customUrl.Value; } }
public static Uri TargetUrl { get { return CustomUrl ?? GitHubClient.GitHubApiUrl; } }
public static bool IsUsingToken
{
get
{
return !string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("OCTOKIT_OAUTHTOKEN"));
}
}
public static bool IsPaidAccount
{
get
{
return !string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("OCTOKIT_PRIVATEREPOSITORIES"));
}
}
public static string ClientId
{
get { return Environment.GetEnvironmentVariable("OCTOKIT_CLIENTID"); }
}
public static string ClientSecret
{
get { return Environment.GetEnvironmentVariable("OCTOKIT_CLIENTSECRET"); }
}
public static long GitHubAppId
{
get { return Convert.ToInt64(Environment.GetEnvironmentVariable("OCTOKIT_GITHUBAPP_ID")); }
}
public static string GitHubAppPemFile
{
get { return Environment.GetEnvironmentVariable("OCTOKIT_GITHUBAPP_PEMFILE"); }
}
public static string GitHubAppSlug
{
get { return Environment.GetEnvironmentVariable("OCTOKIT_GITHUBAPP_SLUG"); }
}
public static long GitHubAppInstallationId
{
get { return Convert.ToInt64(Environment.GetEnvironmentVariable("OCTOKIT_GITHUBAPP_INSTALLATIONID")); }
}
public static void DeleteRepo(IConnection connection, Repository repository)
{
if (repository != null)
DeleteRepo(connection, repository.Owner.Login, repository.Name);
}
public static void DeleteRepo(IConnection connection, string owner, string name)
{
try
{
var client = new GitHubClient(connection);
client.Repository.Delete(owner, name).Wait(TimeSpan.FromSeconds(15));
}
catch { }
}
public static void DeleteTeam(IConnection connection, Team team)
{
if (team != null)
DeleteTeam(connection, team.Id);
}
public static void DeleteTeam(IConnection connection, int teamId)
{
try
{
var client = new GitHubClient(connection);
client.Organization.Team.Delete(teamId).Wait(TimeSpan.FromSeconds(15));
}
catch { }
}
public static void DeleteKey(IConnection connection, PublicKey key)
{
if (key != null)
DeleteKey(connection, key.Id);
}
public static void DeleteKey(IConnection connection, int keyId)
{
try
{
var client = new GitHubClient(connection);
client.User.GitSshKey.Delete(keyId).Wait(TimeSpan.FromSeconds(15));
}
catch { }
}
public static void DeleteGpgKey(IConnection connection, GpgKey key)
{
if (key != null)
DeleteGpgKey(connection, key.Id);
}
public static void DeleteGpgKey(IConnection connection, int keyId)
{
try
{
var client = new GitHubClient(connection);
client.User.GpgKey.Delete(keyId).Wait(TimeSpan.FromSeconds(15));
}
catch { }
}
public static string MakeNameWithTimestamp(string name)
{
return string.Concat(name, "-", DateTime.UtcNow.ToString("yyyyMMddhhmmssfff"));
}
public static Stream LoadFixture(string fileName)
{
var key = "Octokit.Tests.Integration.fixtures." + fileName;
var stream = typeof(Helper).GetTypeInfo().Assembly.GetManifestResourceStream(key);
if (stream == null)
{
throw new InvalidOperationException(
"The file '" + fileName + "' was not found as an embedded resource in the assembly. Failing the test...");
}
return stream;
}
public static IGitHubClient GetAuthenticatedClient(bool useSecondUser = false)
{
return new GitHubClient(new ProductHeaderValue("OctokitTests"), TargetUrl)
{
Credentials = useSecondUser ? CredentialsSecondUser : Credentials
};
}
public static IGitHubClient GetBasicAuthClient()
{
return new GitHubClient(new ProductHeaderValue("OctokitTests"), TargetUrl)
{
Credentials = BasicAuthCredentials
};
}
public static GitHubClient GetAuthenticatedApplicationClient()
{
return new GitHubClient(new ProductHeaderValue("OctokitTests"), TargetUrl)
{
Credentials = ApplicationCredentials
};
}
public static IGitHubClient GetAnonymousClient()
{
return new GitHubClient(new ProductHeaderValue("OctokitTests"), TargetUrl);
}
public static IGitHubClient GetBadCredentialsClient()
{
return new GitHubClient(new ProductHeaderValue("OctokitTests"), TargetUrl)
{
Credentials = new Credentials(Guid.NewGuid().ToString(), "bad-password")
};
}
public static bool IsGitHubAppsEnabled { get { return _gitHubAppsEnabled.Value; } }
public static GitHubClient GetAuthenticatedGitHubAppsClient()
{
return new GitHubClient(new ProductHeaderValue("OctokitTests"), TargetUrl)
{
Credentials = GitHubAppCredentials
};
}
public static void DeleteInvitations(IConnection connection, List<string> invitees, int teamId)
{
try
{
foreach (var invitee in invitees)
{
connection.Delete(new Uri($"orgs/{Organization}/memberships/{invitee}", UriKind.Relative), null, AcceptHeaders.OrganizationMembershipPreview).Wait(TimeSpan.FromSeconds(15));
}
}
catch { }
}
public static string InviteMemberToTeam(IConnection connection, int teamId, string login)
{
try
{
var client = new GitHubClient(connection);
client.Organization.Team.AddMembership(teamId, login).Wait(TimeSpan.FromSeconds(15));
}
catch { }
return login;
}
}
}