Skip to content
Merged
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Description>https://github.com/BHoM/Test_Toolkit</Description>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>disable</Nullable>
<FileVersion>10.0.0.0</FileVersion>
<AssemblyVersion>10.0.0.0</AssemblyVersion>
<IsPackable>false</IsPackable>
<Configurations>Debug;Release;Test</Configurations>
<RootNamespace>BH.Test.Engine.CodeCompliance</RootNamespace>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.1.0" />
<PackageReference Include="NUnit" Version="3.13.3" />
<PackageReference Include="NUnit3TestAdapter" Version="4.2.1" />
<PackageReference Include="NUnit.Analyzers" Version="3.3.0" />
<PackageReference Include="coverlet.collector" Version="3.1.2" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\..\CodeCompliance_oM\CodeComplianceTest_oM.csproj" />
<ProjectReference Include="..\..\..\CodeComplianceTest_Engine\CodeComplianceTest_Engine.csproj" />
</ItemGroup>

<ItemGroup>
<Reference Include="BHoM">
<HintPath>$(ProgramData)\BHoM\Assemblies\BHoM.dll</HintPath>
<Private>True</Private>
<SpecificVersion>false</SpecificVersion>
</Reference>
<Reference Include="BHoM_Engine">
<HintPath>$(ProgramData)\BHoM\Assemblies\BHoM_Engine.dll</HintPath>
<Private>True</Private>
<SpecificVersion>false</SpecificVersion>
</Reference>
<Reference Include="Reflection_Engine">
<HintPath>$(ProgramData)\BHoM\Assemblies\Reflection_Engine.dll</HintPath>
<Private>True</Private>
<SpecificVersion>false</SpecificVersion>
</Reference>
<Reference Include="Serialiser_Engine">
<HintPath>$(ProgramData)\BHoM\Assemblies\Serialiser_Engine.dll</HintPath>
<Private>True</Private>
<SpecificVersion>false</SpecificVersion>
</Reference>
<Reference Include="Test_oM">
<HintPath>$(ProgramData)\BHoM\Assemblies\Test_oM.dll</HintPath>
<Private>True</Private>
<SpecificVersion>false</SpecificVersion>
</Reference>
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,202 @@
/*
* This file is part of the Buildings and Habitats object Model (BHoM)
* Copyright (c) 2015 - 2026, the respective contributors. All rights reserved.
*
* Each contributor holds copyright over their respective contributions.
* The project versioning (Git) records all such contribution source information.
*
*
* The BHoM is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3.0 of the License, or
* (at your option) any later version.
*
* The BHoM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this code. If not, see <https://www.gnu.org/licenses/lgpl-3.0.html>.
*/

using BH.oM.Test.CodeCompliance;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using NUnit.Framework;
using System;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;

namespace BH.Test.Engine.CodeCompliance
{
public class IsDocumentationURLValidTests
{
/***************************************************/
/**** Setup ****/
/***************************************************/

[OneTimeSetUp]
[Description("Starts a local HTTP listener on a free port, so that the tests do not depend on any external website.")]
public void StartServer()
{
TcpListener portFinder = new TcpListener(IPAddress.Loopback, 0);
portFinder.Start();
int port = ((IPEndPoint)portFinder.LocalEndpoint).Port;
portFinder.Stop();

m_BaseUrl = $"http://localhost:{port}/";
m_Server = new HttpListener();
m_Server.Prefixes.Add(m_BaseUrl);
m_Server.Start();
m_ServerLoop = Task.Run(Serve);
}

/***************************************************/

[OneTimeTearDown]
[Description("Stops the local HTTP listener and waits up to five seconds for its request loop to finish.")]
public void StopServer()
{
//Guarded so that a failure in StartServer is reported rather than hidden behind a NullReferenceException here
if (m_Server?.IsListening == true)
m_Server.Stop();

m_Server?.Close();
m_ServerLoop?.Wait(TimeSpan.FromSeconds(5));
}

/***************************************************/
/**** Test Methods ****/
/***************************************************/

[Test]
[Description("Checks that a URL returning 200 OK passes.")]
public void OkResponsePasses()
{
Assert.That(Check(m_BaseUrl + "ok"), Is.Null);
}

/***************************************************/

[Test]
[Description("Checks that any successful response passes, using 204 No Content, rather than only 200 OK.")]
public void NoContentResponsePasses()
{
Assert.That(Check(m_BaseUrl + "nocontent"), Is.Null);
}

/***************************************************/

[Test]
[Description("Checks that a URL returning 404 Not Found is reported as a failure.")]
public void NotFoundResponseFails()
{
Assert.That(Check(m_BaseUrl + "missing"), Is.Not.Null);
}

/***************************************************/

[Test]
[Description("Checks that a site which refuses requests carrying no User-Agent passes, because the check sends one.")]
public void SiteRejectingRequestsWithoutUserAgentPasses()
{
Assert.That(Check(m_BaseUrl + "needs-user-agent"), Is.Null);
}

/***************************************************/

[Test]
[Description("Checks that the User-Agent sent by the check identifies it as the BHoM compliance check.")]
public void UserAgentIdentifiesTheCheck()
{
m_LastUserAgent = null;
Check(m_BaseUrl + "needs-user-agent");
Assert.That(m_LastUserAgent, Does.StartWith("BHoM-ComplianceCheck/"));
}

/***************************************************/

[Test]
[Description("Checks that a URL with a scheme other than HTTP or HTTPS is reported as a failure rather than throwing an exception.")]
public void NonHttpSchemeFailsWithoutThrowing()
{
Span result = null;
Assert.That(() => result = Check("ftp://example.com/"), Throws.Nothing);
Assert.That(result, Is.Not.Null);
}

/***************************************************/

//Relies on the .invalid top-level domain never resolving (RFC 6761). Behind an HTTP proxy the proxy's own error, such as a 502, still fails the check, so this passes for a different reason. A DNS resolver that answers for .invalid can make it fail.
[Test]
[Description("Checks that a URL whose host cannot be resolved is reported as a failure rather than throwing an exception.")]
public void UnresolvableHostFailsWithoutThrowing()
{
Span result = null;
Assert.That(() => result = Check("http://example.invalid/"), Throws.Nothing);
Assert.That(result, Is.Not.Null);
}

/***************************************************/
/**** Private Methods ****/
/***************************************************/

private static Span Check(string url)
{
string source = $"[DocumentationURL(\"{url}\", DocumentationType.Documentation)]\npublic enum Example {{ A }}";
AttributeSyntax attribute = CSharpSyntaxTree.ParseText(source).GetRoot().DescendantNodes().OfType<AttributeSyntax>().Single();
return BH.Engine.Test.CodeCompliance.Checks.Query.IsDocumentationURLValid(attribute);
}

/***************************************************/

private void Serve()
{
while (m_Server.IsListening)
{
HttpListenerContext context;
try
{
context = m_Server.GetContext();
}
catch (Exception e) when (e is HttpListenerException || e is ObjectDisposedException)
{
return; //Listener stopped by StopServer
}

string userAgent = context.Request.UserAgent;
switch (context.Request.Url.AbsolutePath)
{
case "/ok":
context.Response.StatusCode = 200;
break;
case "/nocontent":
context.Response.StatusCode = 204;
break;
case "/needs-user-agent":
m_LastUserAgent = userAgent;
context.Response.StatusCode = string.IsNullOrEmpty(userAgent) ? 403 : 200;
break;
default:
context.Response.StatusCode = 404;
break;
}
context.Response.Close();
}
}

/***************************************************/
/**** Private Fields ****/
/***************************************************/

private HttpListener m_Server;
private Task m_ServerLoop;
private string m_BaseUrl;
private string m_LastUserAgent;

/***************************************************/
}
}
24 changes: 24 additions & 0 deletions .ci/unit-tests/Test_Toolkit_Tests.sln
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,12 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NUnit_Engine_WrongReference
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Test_Engine_Tests", "Test_Engine_Tests\Test_Engine_Tests.csproj", "{239C75FE-B7D6-496E-9F7F-34C70E0F3579}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CodeComplianceTest_Engine_Tests", "CodeComplianceTest_Engine_Tests\CodeComplianceTest_Engine_Tests.csproj", "{19D29E58-4C05-41A4-B652-61FDF1B449CB}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CodeComplianceTest_oM", "..\..\CodeCompliance_oM\CodeComplianceTest_oM.csproj", "{F9302C5D-3950-4036-A23B-6D08DEE15A18}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CodeComplianceTest_Engine", "..\..\CodeComplianceTest_Engine\CodeComplianceTest_Engine.csproj", "{66457CD8-1335-4378-B0C3-CB634A409E2B}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -66,6 +72,24 @@ Global
{239C75FE-B7D6-496E-9F7F-34C70E0F3579}.Release|Any CPU.Build.0 = Release|Any CPU
{239C75FE-B7D6-496E-9F7F-34C70E0F3579}.Test|Any CPU.ActiveCfg = Debug|Any CPU
{239C75FE-B7D6-496E-9F7F-34C70E0F3579}.Test|Any CPU.Build.0 = Debug|Any CPU
{19D29E58-4C05-41A4-B652-61FDF1B449CB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{19D29E58-4C05-41A4-B652-61FDF1B449CB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{19D29E58-4C05-41A4-B652-61FDF1B449CB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{19D29E58-4C05-41A4-B652-61FDF1B449CB}.Release|Any CPU.Build.0 = Release|Any CPU
{19D29E58-4C05-41A4-B652-61FDF1B449CB}.Test|Any CPU.ActiveCfg = Debug|Any CPU
{19D29E58-4C05-41A4-B652-61FDF1B449CB}.Test|Any CPU.Build.0 = Debug|Any CPU
{F9302C5D-3950-4036-A23B-6D08DEE15A18}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F9302C5D-3950-4036-A23B-6D08DEE15A18}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F9302C5D-3950-4036-A23B-6D08DEE15A18}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F9302C5D-3950-4036-A23B-6D08DEE15A18}.Release|Any CPU.Build.0 = Release|Any CPU
{F9302C5D-3950-4036-A23B-6D08DEE15A18}.Test|Any CPU.ActiveCfg = Test|Any CPU
{F9302C5D-3950-4036-A23B-6D08DEE15A18}.Test|Any CPU.Build.0 = Test|Any CPU
{66457CD8-1335-4378-B0C3-CB634A409E2B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{66457CD8-1335-4378-B0C3-CB634A409E2B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{66457CD8-1335-4378-B0C3-CB634A409E2B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{66457CD8-1335-4378-B0C3-CB634A409E2B}.Release|Any CPU.Build.0 = Release|Any CPU
{66457CD8-1335-4378-B0C3-CB634A409E2B}.Test|Any CPU.ActiveCfg = Test|Any CPU
{66457CD8-1335-4378-B0C3-CB634A409E2B}.Test|Any CPU.Build.0 = Test|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
39 changes: 34 additions & 5 deletions CodeComplianceTest_Engine/Query/Checks/IsDocumentationURLValid.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,19 +25,25 @@
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using BH.oM.Test;

using System.Net;
using System.Net.Http;

namespace BH.Engine.Test.CodeCompliance.Checks
{
public static partial class Query
{
/***************************************************/
/**** Public Methods ****/
/***************************************************/

[Description("Checks that the URL in a DocumentationURL attribute can be reached.\n" +
"Fails if the request cannot be made, or if the response is not a success status.")]
[Message("Documentation link does not link to a valid web resource", "IsDocumentationURLValid")]
[ErrorLevel(TestStatus.Error)]
[Path(@"([a-zA-Z0-9]+)_(oM|Engine|Adapter)\\.*\.cs$")]
Expand All @@ -45,7 +51,7 @@
[Path(@"([a-zA-Z0-9]+)_Tests\\.*\.cs$", false)] //NUnit style projects
[Path(@"([a-zA-Z0-9]+)_Test\\.*\.cs$", false)] //Verification projects
[ComplianceType("documentation")]
public static Span IsDocumentationURLValid(this AttributeSyntax node)

Check warning on line 54 in CodeComplianceTest_Engine/Query/Checks/IsDocumentationURLValid.cs

View check run for this annotation

BHoMBot-CI / documentation-compliance

CodeComplianceTest_Engine/Query/Checks/IsDocumentationURLValid.cs#L54

Method must contain an Output or MultiOutput attribute - For more information see https://bhom.xyz/documentation/DevOps/Code%20Compliance%20and%20CI/Compliance%20Checks/HasOutputAttribute Input parameter requires a matching Input attribute - For more information see https://bhom.xyz/documentation/DevOps/Code%20Compliance%20and%20CI/Compliance%20Checks/IsInputAttributePresent
{
if (node == null)
return null;
Expand All @@ -57,10 +63,11 @@

try
{
HttpClient client = new HttpClient();
var checkingResponse = client.GetAsync(url).Result;
if (checkingResponse.StatusCode != HttpStatusCode.OK)
return node.Span.ToSpan();
using (HttpResponseMessage response = m_UrlClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead).GetAwaiter().GetResult())
{
if (!response.IsSuccessStatusCode)
return node.Span.ToSpan();
}
}
catch
{
Expand All @@ -69,6 +76,28 @@

return null;
}

/***************************************************/
/**** Private Methods ****/
/***************************************************/

private static HttpClient CreateUrlClient()
{
//Some sites refuse requests that carry no User-Agent, so identify the check and where to read about it
HttpClient client = new HttpClient { Timeout = TimeSpan.FromSeconds(30) };
client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "BHoM-ComplianceCheck/1.0 (+https://bhom.xyz/documentation/DevOps/Code%20Compliance%20and%20CI/Compliance%20Checks/IsDocumentationURLValid/)");
//A single client lives as long as the host process, so do not keep connections, and their DNS results, open between checks
client.DefaultRequestHeaders.ConnectionClose = true;
return client;
}

/***************************************************/
/**** Private Fields ****/
/***************************************************/

private static readonly HttpClient m_UrlClient = CreateUrlClient();

/***************************************************/
}
}

Expand Down
Loading