Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(dotnet): unit tests coverage #1123

Open
wants to merge 13 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/dotnet.yml
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,4 @@ jobs:
# with:
# dotnet-version: '3.1.x' # SDK Version to use; x will use the latest version of the 3.1 channel
- run: make build
- run: make test
3 changes: 3 additions & 0 deletions packages/dotnet/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ build: clean ## Build the library (and run code standard checks)
clean: ## Clean out the currently built library
rm -rf ReadMe/bin/ ReadMe/obj

test:
dotnet test ReadMe.Tests/

install: ## Install the required dependencies to run .NET applications
brew install dotnet

Expand Down
1 change: 1 addition & 0 deletions packages/dotnet/ReadMe.Tests/GlobalUsings.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
global using NUnit.Framework;
99 changes: 99 additions & 0 deletions packages/dotnet/ReadMe.Tests/HarJsonBuilderTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
using NUnit.Framework;
using Moq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using ReadMe.HarJsonTranslationLogics;
using ReadMe.HarJsonObjectModels;
using System.IO;
using System.Net;
using Newtonsoft.Json;
using System.Collections.Generic;

namespace ReadMe.Tests
{
[TestFixture]
public class HarJsonBuilderTests
{
private Mock<RequestDelegate> nextMock;
private Mock<HttpContext> httpContextMock;
private Mock<IConfiguration> configurationMock;
private Mock<HttpResponse> responseMock;
private Mock<HttpRequest> requestMock;
private ConfigValues configValues;
private HarJsonBuilder builder;

[SetUp]
public void SetUp()
{
nextMock = new Mock<RequestDelegate>();
httpContextMock = new Mock<HttpContext>();
configurationMock = new Mock<IConfiguration>();

requestMock = new Mock<HttpRequest>();
responseMock = new Mock<HttpResponse>();
var connection = new Mock<ConnectionInfo>();

connection.Setup(c => c.RemoteIpAddress).Returns(IPAddress.Parse("127.0.0.1"));
httpContextMock.Setup(c => c.Request).Returns(requestMock.Object);
httpContextMock.Setup(c => c.Response).Returns(responseMock.Object);
httpContextMock.Setup(c => c.Connection).Returns(connection.Object);

responseMock.SetupProperty(r => r.Body, new MemoryStream());

configValues = new ConfigValues
{
options = new Options
{
development = true,
baseLogUrl = "http://example.com",
isAllowListEmpty = true,
isDenyListEmpty = true,
allowList = new List<string>(),
denyList = new List<string>(),
},
group = new Group
{
id = "group-id",
label = "group-label",
email = "[email protected]"
}
};

var requestHeaders = new HeaderDictionary();
requestMock.Setup(r => r.Headers).Returns(requestHeaders);
requestMock.SetupProperty(r => r.Scheme, "https");
requestMock.SetupProperty(r => r.Host, new HostString("localhost", 5000));
requestMock.Setup(r => r.Query.Count).Returns(0);
requestMock.Setup(r => r.Cookies.Count).Returns(0);

var responseHeaders = new HeaderDictionary();
responseMock.Setup(r => r.Headers).Returns(responseHeaders);
responseMock.SetupProperty(r => r.Body, new MemoryStream());

builder = new HarJsonBuilder(nextMock.Object, httpContextMock.Object, configurationMock.Object, configValues);
}

[Test]
public async Task BuildHar_ShouldReturnJsonWithExpectedStructure()
{
string result = await builder.BuildHar();

Assert.IsNotNull(result);
var deserializedResult = JsonConvert.DeserializeObject<List<Root>>(result);
Assert.IsNotEmpty(deserializedResult);

Check warning on line 84 in packages/dotnet/ReadMe.Tests/HarJsonBuilderTest.cs

View workflow job for this annotation

GitHub Actions / build

Possible null reference argument for parameter 'collection' in 'void Assert.IsNotEmpty(IEnumerable collection)'.

Assert.That(deserializedResult[0].group.label, Is.EqualTo(configValues.group.label));
Assert.That(deserializedResult[0].clientIPAddress, Is.EqualTo("127.0.0.1"));
}

[Test]
public async Task BuildHar_ShouldAddDocumentationUrlHeaderToResponse()
{
await builder.BuildHar();

Assert.IsTrue(responseMock.Object.Headers.ContainsKey("x-documentation-url"));
Assert.IsTrue(responseMock.Object.Headers["x-documentation-url"].ToString().StartsWith(configValues.options.baseLogUrl));
}
}
}
28 changes: 28 additions & 0 deletions packages/dotnet/ReadMe.Tests/ReadMe.Tests.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.6.0" />
<PackageReference Include="Moq" Version="4.20.72" />
<PackageReference Include="NUnit" Version="3.13.3" />
<PackageReference Include="NUnit3TestAdapter" Version="4.2.1" />
<PackageReference Include="NUnit.Analyzers" Version="3.6.1" />
<PackageReference Include="coverlet.collector" Version="6.0.2">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\ReadMe\ReadMe.csproj" />
</ItemGroup>

</Project>
40 changes: 40 additions & 0 deletions packages/dotnet/ReadMe.Tests/ReadmeApiCallerTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
using System;
using System.Text;
using Moq;
using NUnit.Framework;
using RestSharp;
using ReadMe.HarJsonTranslationLogics;

namespace ReadMe.Tests
{
public class ReadmeApiCallerTest
{
private const string testHarJsonObject = "{\"sample\":\"data\"}";
private const string testApiKey = "testApiKey";
private Mock<IRestClient> restClient;
private ReadMeApiCaller apiCaller;

[SetUp]
public void Setup()
{
restClient = new Mock<IRestClient>();
apiCaller = new ReadMeApiCaller(testHarJsonObject, testApiKey, restClient.Object);
}

[Test]
public void SendHarObjToReadMeApi_ShouldSendRequestWithCorrectHeadersAndBody()
{
var expectedApiKeyHeader = "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(testApiKey + ":"));
restClient.Setup(client => client.ExecuteAsync(It.IsAny<IRestRequest>(), It.IsAny<CancellationToken>())).Verifiable();

apiCaller.SendHarObjToReadMeApi();

restClient.Verify(client => client.ExecuteAsync(It.Is<RestRequest>(request =>
request.Method == Method.POST &&
request.Parameters.Exists(p => p.Name == "Content-Type" && (string?)p.Value == "application/json") &&
request.Parameters.Exists(p => p.Name == "Authorization" && (string?)p.Value == expectedApiKeyHeader) &&
request.Parameters.Exists(p => p.Type == ParameterType.RequestBody && (string?)p.Value == testHarJsonObject)
), It.IsAny<CancellationToken>()), Times.Once);
}
}
}
Loading