Skip to content

Commit 3a080fe

Browse files
Added IntegrationTests
1 parent 0a0e304 commit 3a080fe

File tree

4 files changed

+173
-10
lines changed

4 files changed

+173
-10
lines changed

CICD.Tools.GitHubToCatalogYamlTests/CICD.Tools.GitHubToCatalogYamlTests.csproj

+4
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,14 @@
77

88
<IsPackable>false</IsPackable>
99
<IsTestProject>true</IsTestProject>
10+
<UserSecretsId>3e21edee-380f-4472-b894-74dc8e5f482e</UserSecretsId>
1011
</PropertyGroup>
1112

1213
<ItemGroup>
1314
<PackageReference Include="FluentAssertions" Version="6.12.1" />
15+
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
16+
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="8.0.0" />
17+
<PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="8.0.0" />
1418
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.6.0" />
1519
<PackageReference Include="Moq" Version="4.20.72" />
1620
<PackageReference Include="MSTest.TestAdapter" Version="3.0.4" />
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
namespace Skyline.DataMiner.CICD.Tools.GitHubToCatalogYaml.Tests
2+
{
3+
using System;
4+
using System.Collections.Generic;
5+
using System.Net.Http;
6+
using System.Threading.Tasks;
7+
8+
using FluentAssertions;
9+
10+
using Microsoft.Extensions.Configuration;
11+
using Microsoft.Extensions.Logging;
12+
using Microsoft.VisualStudio.TestTools.UnitTesting;
13+
14+
using Serilog;
15+
16+
using Skyline.DataMiner.CICD.Tools.GitHubToCatalogYaml;
17+
18+
/// <summary>
19+
/// These tests require setting up a secret to run and will perform actual HTTP calls to GitHub.
20+
/// Make sure you provide a valid GitHub API key and repository for these tests to succeed.
21+
///
22+
/// Right-click on the project in Visual Studio and select "Manage User Secrets", then add the following JSON structure to store your secrets:
23+
///
24+
/// <code>
25+
/// {
26+
/// "GitHubToken": "&lt;YOUR_GITHUB_TOKEN&gt;",
27+
/// "GitHubRepository": "&lt;OWNER/REPOSITORY&gt;"
28+
/// }
29+
/// </code>
30+
/// </summary>
31+
[TestClass]
32+
public class GitHubServiceIntegrationTests
33+
{
34+
private GitHubService _service;
35+
private string _githubToken;
36+
private string _githubRepository;
37+
38+
[TestInitialize]
39+
public void Setup()
40+
{
41+
// Use ConfigurationBuilder to read the secrets from User Secrets
42+
var config = new ConfigurationBuilder()
43+
.AddUserSecrets<GitHubServiceIntegrationTests>() // Load secrets for this class's assembly
44+
.AddEnvironmentVariables()
45+
.Build();
46+
47+
// Retrieve the GitHub token and repository from the secrets
48+
_githubToken = config["GitHubToken"];
49+
_githubRepository = config["GitHubRepository"];
50+
51+
if (string.IsNullOrEmpty(_githubToken) || string.IsNullOrEmpty(_githubRepository))
52+
{
53+
throw new InvalidOperationException("GitHubToken and GitHubRepository must be provided in User Secrets.");
54+
}
55+
56+
var httpClient = new HttpClient();
57+
58+
// Configure Serilog for logging
59+
var loggerConfig = new LoggerConfiguration().WriteTo.Console();
60+
var serilogLogger = loggerConfig.CreateLogger();
61+
using var loggerFactory = LoggerFactory.Create(builder => builder.AddSerilog(serilogLogger));
62+
var logger = loggerFactory.CreateLogger("GitHubService");
63+
64+
// Create an instance of the GitHubService
65+
_service = new GitHubService(httpClient, logger, _githubToken, _githubRepository);
66+
}
67+
68+
/// <summary>
69+
/// Integration test for creating and getting a catalog identifier variable in the GitHub repository.
70+
/// </summary>
71+
[TestMethod]
72+
public async Task CreateAndGetCatalogIdentifierAsyncTest()
73+
{
74+
// Arrange
75+
var guid = Guid.NewGuid().ToString();
76+
77+
// Act
78+
var createdOK = await _service.CreateCatalogIdentifierAsync(guid);
79+
Thread.Sleep(1000);
80+
var returnedGuid = await _service.GetCatalogIdentifierAsync();
81+
bool deleted = await _service.DeleteCatalogIdentifierAsync();
82+
83+
// Assert
84+
Assert.IsTrue(createdOK, "The catalog identifier was not successfully created in the GitHub repository.");
85+
Assert.IsNotNull(returnedGuid, "Failed to retrieve the catalog identifier from the GitHub repository.");
86+
returnedGuid.Should().Be(guid);
87+
deleted.Should().BeTrue();
88+
}
89+
90+
91+
/// <summary>
92+
/// Integration test for retrieving the repository description from the GitHub repository.
93+
/// </summary>
94+
[TestMethod]
95+
public async Task GetRepositoryDescriptionAsyncTest()
96+
{
97+
// Act
98+
var description = await _service.GetRepositoryDescriptionAsync();
99+
100+
// Assert
101+
Assert.IsNotNull(description, "Failed to retrieve the repository description from the GitHub repository.");
102+
description.Should().Be("This repository is used by integration tests for the github to yaml dotnet tool.");
103+
}
104+
105+
/// <summary>
106+
/// Integration test for retrieving the topics (tags) from the GitHub repository's ABOUT section.
107+
/// </summary>
108+
[TestMethod]
109+
public async Task GetRepositoryTopicsAsyncTest()
110+
{
111+
// Act
112+
var topics = await _service.GetRepositoryTopicsAsync();
113+
114+
List<string> expected = new List<string>() { "blablabla", "testing", "automationscript" };
115+
// Assert
116+
Assert.IsNotNull(topics, "Failed to retrieve the repository topics from the GitHub repository.");
117+
Assert.IsTrue(topics.Count > 0, "The repository should have at least one topic.");
118+
topics.Should().BeEquivalentTo(expected);
119+
}
120+
}
121+
}

Skyline.DataMiner.CICD.Tools.GitHubToCatalogYaml/GitHubService.cs

+42-10
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ public GitHubService(HttpClient httpClient, ILogger logger, string key, string g
2929
this.key = key;
3030
_logger = logger;
3131
_httpClient = httpClient;
32-
githubRoot = $"https://api.github.com/repos/{githubRepository}/";
32+
githubRoot = $"https://api.github.com/repos/{githubRepository}";
3333
}
3434

3535
/// <summary>
@@ -39,7 +39,7 @@ public GitHubService(HttpClient httpClient, ILogger logger, string key, string g
3939
/// <returns>A task representing the asynchronous operation, containing a boolean indicating whether the operation was successful.</returns>
4040
public async Task<bool> CreateCatalogIdentifierAsync(string catalogIdentifier)
4141
{
42-
var requestUrl = $"{githubRoot}actions/variables";
42+
var requestUrl = $"{githubRoot}/actions/variables";
4343
var content = new StringContent(JsonSerializer.Serialize(new
4444
{
4545
name = "catalogIdentifier",
@@ -51,7 +51,7 @@ public async Task<bool> CreateCatalogIdentifierAsync(string catalogIdentifier)
5151
Content = content
5252
};
5353
request.Headers.Add("Authorization", $"Bearer {key}");
54-
request.Headers.Add("User-Agent", "HttpClientFactory-Sample");
54+
request.Headers.Add("User-Agent", "GitHubToCatalogYaml");
5555

5656
var response = await _httpClient.SendAsync(request);
5757
if (response.IsSuccessStatusCode)
@@ -70,10 +70,10 @@ public async Task<bool> CreateCatalogIdentifierAsync(string catalogIdentifier)
7070
/// <returns>A task representing the asynchronous operation, containing the catalog identifier as a string, or null if the retrieval fails.</returns>
7171
public async Task<string> GetCatalogIdentifierAsync()
7272
{
73-
var requestUrl = $"{githubRoot}actions/variables/catalogIdentifier";
73+
var requestUrl = $"{githubRoot}/actions/variables/catalogIdentifier";
7474
var request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
7575
request.Headers.Add("Authorization", $"Bearer {key}");
76-
request.Headers.Add("User-Agent", "HttpClientFactory-Sample");
76+
request.Headers.Add("User-Agent", "GitHubToCatalogYaml");
7777

7878
var response = await _httpClient.SendAsync(request);
7979
if (response.IsSuccessStatusCode)
@@ -90,16 +90,40 @@ public async Task<string> GetCatalogIdentifierAsync()
9090
return null;
9191
}
9292

93+
/// <summary>
94+
/// Deletes a GitHub repository variable named 'catalogIdentifier'.
95+
/// </summary>
96+
/// <returns>A task representing the asynchronous operation, containing a boolean indicating whether the operation was successful.</returns>
97+
public async Task<bool> DeleteCatalogIdentifierAsync()
98+
{
99+
var requestUrl = $"{githubRoot}/actions/variables/catalogIdentifier";
100+
101+
var request = new HttpRequestMessage(HttpMethod.Delete, requestUrl);
102+
request.Headers.Add("Authorization", $"Bearer {key}");
103+
request.Headers.Add("User-Agent", "GitHubToCatalogYaml");
104+
105+
var response = await _httpClient.SendAsync(request);
106+
if (response.IsSuccessStatusCode)
107+
{
108+
_logger.LogInformation("Successfully deleted catalogIdentifier in GitHub repository.");
109+
return true;
110+
}
111+
112+
_logger.LogError($"Failed to delete catalogIdentifier in GitHub repository: {response.StatusCode}");
113+
return false;
114+
}
115+
116+
93117
/// <summary>
94118
/// Retrieves the repository description from the GitHub repository.
95119
/// </summary>
96120
/// <returns>A task representing the asynchronous operation, containing the repository description as a string, or null if the retrieval fails.</returns>
97121
public async Task<string> GetRepositoryDescriptionAsync()
98122
{
99-
var requestUrl = $"{githubRoot}";
123+
var requestUrl = $"{githubRoot}"; // URL should already be in the format 'https://api.github.com/repos/{owner}/{repo}/'
100124
var request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
101125
request.Headers.Add("Authorization", $"Bearer {key}");
102-
request.Headers.Add("User-Agent", "HttpClientFactory-Sample");
126+
request.Headers.Add("User-Agent", "GitHubToCatalogYaml");
103127

104128
var response = await _httpClient.SendAsync(request);
105129
if (response.IsSuccessStatusCode)
@@ -110,23 +134,31 @@ public async Task<string> GetRepositoryDescriptionAsync()
110134
{
111135
return description.GetString();
112136
}
137+
else
138+
{
139+
_logger.LogWarning("Repository description not found in the response.");
140+
}
141+
}
142+
else
143+
{
144+
_logger.LogError($"Failed to retrieve repository description: {response.StatusCode} - {response.ReasonPhrase}");
113145
}
114146

115-
_logger.LogError($"Failed to retrieve repository description: {response.StatusCode}");
116147
return null;
117148
}
118149

150+
119151
/// <summary>
120152
/// Retrieves the topics (tags) from the GitHub repository's ABOUT section.
121153
/// </summary>
122154
/// <returns>A task representing the asynchronous operation, containing a list of repository topics (tags), or null if the retrieval fails.</returns>
123155
public async Task<List<string>> GetRepositoryTopicsAsync()
124156
{
125-
var requestUrl = $"{githubRoot}topics";
157+
var requestUrl = $"{githubRoot}/topics";
126158
var request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
127159
request.Headers.Add("Authorization", $"Bearer {key}");
128160
request.Headers.Add("Accept", "application/vnd.github.mercy-preview+json");
129-
request.Headers.Add("User-Agent", "HttpClientFactory-Sample");
161+
request.Headers.Add("User-Agent", "GitHubToCatalogYaml");
130162

131163
var response = await _httpClient.SendAsync(request);
132164
if (response.IsSuccessStatusCode)

Skyline.DataMiner.CICD.Tools.GitHubToCatalogYaml/IGitHubService.cs

+6
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,12 @@ public interface IGitHubService
1515
/// <returns>A task representing the asynchronous operation, containing a boolean indicating whether the operation was successful.</returns>
1616
Task<bool> CreateCatalogIdentifierAsync(string catalogIdentifier);
1717

18+
/// <summary>
19+
/// Deletes a GitHub repository variable named 'catalogIdentifier'.
20+
/// </summary>
21+
/// <returns>A task representing the asynchronous operation, containing a boolean indicating whether the operation was successful.</returns>
22+
Task<bool> DeleteCatalogIdentifierAsync();
23+
1824
/// <summary>
1925
/// Retrieves the 'catalogIdentifier' variable from the GitHub repository.
2026
/// </summary>

0 commit comments

Comments
 (0)