Skip to content

Commit

Permalink
Merge pull request #298 from microsoft/240/unit-tests-review
Browse files Browse the repository at this point in the history
Updates and Improvements to Unit Tests
  • Loading branch information
vaughanknight authored Mar 21, 2023
2 parents 159f99c + 9d7230e commit 43de9b0
Show file tree
Hide file tree
Showing 16 changed files with 567 additions and 19 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,10 @@ public void AllPublicMethods_DoNotSwallowBadProxyExceptions()
Assert.ThrowsAsync<HttpRequestException>(async () => await client.GetForecastedCarbonIntensityAsync(TestLatitude, TestLongitude));
Assert.ThrowsAsync<HttpRequestException>(async () => await client.GetRecentCarbonIntensityHistoryAsync(TestZone));
Assert.ThrowsAsync<HttpRequestException>(async () => await client.GetRecentCarbonIntensityHistoryAsync(TestLatitude, TestLongitude));
var startDate = new DateTimeOffset(2022, 4, 18, 12, 32, 42, TimeSpan.FromHours(-6));
var endDate = startDate.AddMinutes(10);
Assert.ThrowsAsync<HttpRequestException>(async () => await client.GetPastRangeDataAsync(TestLatitude, TestLongitude, startDate, endDate));
Assert.ThrowsAsync<HttpRequestException>(async () => await client.GetPastRangeDataAsync(TestZone, startDate, endDate));
}

[Test]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,26 @@ namespace CarbonAware.DataSources.ElectricityMaps.Tests;
[TestFixture]
class ServiceCollectionExtensionTests
{
private readonly string ForecastDataSourceKey = $"DataSources:ForecastDataSource";
private readonly string ForecastDataSourceValue = $"ElectricityMapsTest";
private readonly string HeaderKey = $"DataSources:Configurations:ElectricityMapsTest:APITokenHeader";
private readonly string AuthHeader = "auth-token";
private readonly string TokenKey = $"DataSources:Configurations:ElectricityMapsTest:APIToken";
private readonly string DefaultTokenValue = "myDefaultToken123";
private readonly string UseProxyKey = $"DataSources:Configurations:ElectricityMapsTest:Proxy:UseProxy";
const string ForecastDataSourceKey = $"DataSources:ForecastDataSource";
const string EmissionsDataSourceKey = $"DataSources:EmissionsDataSource";
const string ForecastDataSourceValue = $"ElectricityMapsTest";
const string EmissionsDataSourceValue = $"ElectricityMapsTest";
const string HeaderKey = $"DataSources:Configurations:ElectricityMapsTest:APITokenHeader";
const string AuthHeader = "auth-token";
const string TokenKey = $"DataSources:Configurations:ElectricityMapsTest:APIToken";
const string DefaultTokenValue = "myDefaultToken123";
const string UseProxyKey = $"DataSources:Configurations:ElectricityMapsTest:Proxy:UseProxy";
const string ProxyUrl = $"DataSources:Configurations:ElectricityMapsTest:Proxy:Url";
const string ProxyUsername = $"DataSources:Configurations:ElectricityMapsTest:Proxy:Username";
const string ProxyPassword = $"DataSources:Configurations:ElectricityMapsTest:Proxy:Password";

[Test]
public void ClientProxyTest_With_Missing_ProxyURL_ThrowsException()
{
// Arrange
var settings = new Dictionary<string, string> {
{ ForecastDataSourceKey, ForecastDataSourceValue },
{ EmissionsDataSourceKey, EmissionsDataSourceValue },
{ HeaderKey, AuthHeader },
{ TokenKey, DefaultTokenValue },
{ UseProxyKey, "true" },
Expand All @@ -35,5 +41,41 @@ public void ClientProxyTest_With_Missing_ProxyURL_ThrowsException()

// Act & Assert
Assert.Throws<ConfigurationException>(() => serviceCollection.AddElectricityMapsForecastDataSource(configuration.DataSources()));
Assert.Throws<ConfigurationException>(() => serviceCollection.AddElectricityMapsEmissionsDataSource(configuration.DataSources()));
}

[TestCase(true, TestName = "ClientProxyTest, successful: denotes adding ElectricityMaps data sources using proxy.")]
[TestCase(false, TestName = "ClientProxyTest, successful: denotes adding ElectricityMaps data sources without using proxy.")]
public void ClientProxy_ConfigurationTest(bool withProxyUrl)
{
// Arrange
var settings = new Dictionary<string, string> {
{ ForecastDataSourceKey, ForecastDataSourceValue },
{ EmissionsDataSourceKey, EmissionsDataSourceValue },
{ HeaderKey, AuthHeader },
{ TokenKey, DefaultTokenValue },
{ UseProxyKey, withProxyUrl.ToString() }
};

if (withProxyUrl)
{
settings.Add(ProxyUrl, "http://fakeProxy");
settings.Add(ProxyUsername, "proxyUsername");
settings.Add(ProxyPassword, "proxyPassword");
}

var configuration = new ConfigurationBuilder()
.AddInMemoryCollection(settings)
.AddEnvironmentVariables()
.Build();
var serviceCollection = new ServiceCollection();

// Act
var forecastDataSource = serviceCollection.AddElectricityMapsForecastDataSource(configuration.DataSources());
var emissionsDataSource = serviceCollection.AddElectricityMapsEmissionsDataSource(configuration.DataSources());

// Assert
Assert.That(forecastDataSource, Is.Not.Null);
Assert.That(emissionsDataSource, Is.Not.Null);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,29 @@ public async Task GetCarbonIntensityAsync_ReturnsSingleDataPoint_WhenStartParamE
Assert.IsTrue(locations.Where(loc => loc.Name == r.Location).Any());
}
}

[Test]
public async Task GetCarbonIntensityAsync_ReturnsEmptyEmissionData()
{
var logger = Mock.Of<ILogger<JsonDataSource>>();
var monitor = Mock.Of<IOptionsMonitor<JsonDataSourceConfiguration>>();
var mockDataSource = new Mock<JsonDataSource>(logger, monitor);

mockDataSource.Protected()
.Setup<Task<List<EmissionsData>?>>("GetJsonDataAsync")
.ReturnsAsync(new List<EmissionsData>())
.Verifiable();

var location = new Location() { Name = "midwest" };
var locations = new List<Location>() { location };
var start = DateTimeOffset.Parse("2022-09-07T12:45:11+00:00");
var end = DateTimeOffset.Parse("2022-09-07T13:45:11+00:00");
var dataSource = mockDataSource.Object;
var result = await dataSource.GetCarbonIntensityAsync(locations, start, end);
Assert.That(result.Count(), Is.EqualTo(0));
Assert.That(!result.Any(), Is.True);
}

private Mock<JsonDataSource> SetupMockDataSource() {
var logger = Mock.Of<ILogger<JsonDataSource>>();
var monitor = Mock.Of<IOptionsMonitor<JsonDataSourceConfiguration>>();
Expand All @@ -94,6 +117,7 @@ private Mock<JsonDataSource> SetupMockDataSource() {

return mockDataSource;
}

private List<EmissionsData> GetTestEmissionData() {
// All the tests above correspond to values in this mock data. If the mock values are changed, the tests need to be updated
return new List<EmissionsData>() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,16 @@ namespace CarbonAware.DataSources.WattTime.Tests;
class ServiceCollectionExtensionTests
{
private readonly string ForecastDataSourceKey = $"DataSources:ForecastDataSource";
private readonly string EmissionsDataSourceKey = $"DataSources:EmissionsDataSource";
private readonly string ForecastDataSourceValue = $"WattTimeTest";
private readonly string EmissionsDataSourceValue = $"WattTimeTest";
private readonly string UsernameKey = $"DataSources:Configurations:WattTimeTest:Username";
private readonly string Username = "devuser";
private readonly string PasswordKey = $"DataSources:Configurations:WattTimeTest:Password";
private readonly string Password = "12345";
private readonly string ProxyUrl = $"DataSources:Configurations:WattTimeTest:Proxy:Url";
private readonly string ProxyUsername = $"DataSources:Configurations:WattTimeTest:Proxy:Username";
private readonly string ProxyPassword = $"DataSources:Configurations:WattTimeTest:Proxy:Password";
private readonly string UseProxyKey = $"DataSources:Configurations:WattTimeTest:Proxy:UseProxy";

[Test]
Expand All @@ -28,6 +32,7 @@ public void ClientProxyTest_With_Invalid_ProxyURL_ThrowsException()
// Arrange
var settings = new Dictionary<string, string> {
{ ForecastDataSourceKey, ForecastDataSourceValue },
{ EmissionsDataSourceKey, EmissionsDataSourceValue },
{ UsernameKey, Username },
{ PasswordKey, Password },
{ ProxyUrl, "http://fakeproxy:8080" },
Expand All @@ -53,6 +58,7 @@ public void ClientProxyTest_With_Missing_ProxyURL_ThrowsException()
// Arrange
var settings = new Dictionary<string, string> {
{ ForecastDataSourceKey, ForecastDataSourceValue },
{ EmissionsDataSourceKey, EmissionsDataSourceValue },
{ UsernameKey, Username },
{ PasswordKey, Password },
{ UseProxyKey, "true" },
Expand All @@ -66,5 +72,41 @@ public void ClientProxyTest_With_Missing_ProxyURL_ThrowsException()

// Act & Assert
Assert.Throws<ConfigurationException>(() => serviceCollection.AddWattTimeForecastDataSource(configuration.DataSources()));
Assert.Throws<ConfigurationException>(() => serviceCollection.AddWattTimeEmissionsDataSource(configuration.DataSources()));
}

[TestCase(true, TestName = "ClientProxyTest, successful: denotes adding WattTime data sources using proxy.")]
[TestCase(false, TestName = "ClientProxyTest, successful: denotes adding WattTime data sources without using proxy.")]
public void ClientProxyTest_AddsDataSource(bool withProxyUrl)
{
// Arrange
var settings = new Dictionary<string, string> {
{ ForecastDataSourceKey, ForecastDataSourceValue },
{ EmissionsDataSourceKey, EmissionsDataSourceValue },
{ UsernameKey, Username },
{ PasswordKey, Password },
{ UseProxyKey, withProxyUrl.ToString() }
};

if (withProxyUrl)
{
settings.Add(ProxyUrl, "http://10.10.10.1");
settings.Add(ProxyUsername, "proxyUsername");
settings.Add(ProxyPassword, "proxyPassword");
}

var configuration = new ConfigurationBuilder()
.AddInMemoryCollection(settings)
.AddEnvironmentVariables()
.Build();
var serviceCollection = new ServiceCollection();

// Act
var forecastDataSource = serviceCollection.AddWattTimeEmissionsDataSource(configuration.DataSources());
var emissionsDataSource = serviceCollection.AddWattTimeForecastDataSource(configuration.DataSources());

// Assert
Assert.That(forecastDataSource, Is.Not.Null);
Assert.That(emissionsDataSource, Is.Not.Null);
}
}
23 changes: 22 additions & 1 deletion src/CarbonAware.LocationSources/test/LocationSourceTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ namespace CarbonAware.LocationSources.Test;
[TestFixture]
class LocationSourceTest
{

private string _goodFile { get; set; }
private string _badFile { get; set; }
private string _dupFile { get; set; }
Expand Down Expand Up @@ -231,6 +230,28 @@ public async Task GeopositionLocation_ValidLocation_DupLocationKey()
});
}

[Test]
public async Task GetGeopositionLocationsAsync_ReturnsListOfLocations()
{
var configuration = new LocationDataSourcesConfiguration();
configuration.LocationSourceFiles.Add(new LocationSourceFile
{
Prefix = "prefix",
Delimiter = "-",
DataFileLocation = _goodFile
});
var options = new Mock<IOptionsMonitor<LocationDataSourcesConfiguration>>();
options.Setup(o => o.CurrentValue).Returns(() => configuration);
var logger = Mock.Of<ILogger<LocationSource>>();
var locationSource = new LocationSource(logger, options.Object);

var allLocations = await locationSource.GetGeopositionLocationsAsync();

Assert.That(allLocations.Count, Is.EqualTo(3));
AssertLocationsEqual(Constants.LocationEastUs, allLocations["prefix-test-eastus"]);
AssertLocationsEqual(Constants.LocationWestUs, allLocations["prefix-test-westus"]);
}

[OneTimeTearDown]
protected void RemoveTestLocationFiles()
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
using CarbonAware.WebApi.Configuration;
using NUnit.Framework;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using NUnit.Framework.Internal;

namespace CarbonAware.WepApi.UnitTests;

[TestFixture]
public class ServiceCollectionExtensionsTests
{
[Test]
public void AddMonitoringAndTelemetry_AddsServices_WithConnectionString()
{
// Arrange
var services = new ServiceCollection();

var inMemorySettings = new Dictionary<string, string>
{
{ "CarbonAwareVars:TelemetryProvider", "ApplicationInsights" },
{ "ApplicationInsights_Connection_String", "AppInsightsConnectionString" }
};
var configuration = new ConfigurationBuilder()
.AddInMemoryCollection(inMemorySettings)
.Build();

// Act & Assert
Assert.DoesNotThrow(() => services.AddMonitoringAndTelemetry(configuration));
}

[Test]
public void AddMonitoringAndTelemetry_AddsServices_WithInstrumentationKey()
{
// Arrange
var services = new ServiceCollection();

var inMemorySettings = new Dictionary<string, string>
{
{ "CarbonAwareVars:TelemetryProvider", "ApplicationInsights" },
{ "AppInsights_InstrumentationKey", "AppInsightsInstrumentationKey" }
};
var configuration = new ConfigurationBuilder()
.AddInMemoryCollection(inMemorySettings)
.Build();

// Act & Assert
Assert.DoesNotThrow(() => services.AddMonitoringAndTelemetry(configuration));
}

[Test]
public void AddMonitoringAndTelemetry_DoesNotAddServices_WithoutConfiguration()
{
// Arrange
var services = new ServiceCollection();

var inMemorySettings = new Dictionary<string, string>
{
{ "CarbonAwareVars:TelemetryProvider", "ApplicationInsights" }
};
var configuration = new ConfigurationBuilder()
.AddInMemoryCollection(inMemorySettings)
.Build();

// Act & Assert
Assert.DoesNotThrow(() => services.AddMonitoringAndTelemetry(configuration));
Assert.That(services.Count, Is.EqualTo(0));
}

[Test]
public void AddMonitoringAndTelemetry_DoesNotAddServices_WithoutTelemetryProvider()
{
// Arrange
var services = new ServiceCollection();

var inMemorySettings = new Dictionary<string, string>{};
var configuration = new ConfigurationBuilder()
.AddInMemoryCollection(inMemorySettings)
.Build();

// Act & Assert
Assert.DoesNotThrow(() => services.AddMonitoringAndTelemetry(configuration));
Assert.That(services.Count, Is.EqualTo(0));
}

[Test]
public void CreateConsoleLogger_ReturnsILogger()
{
// Arrange
var inMemorySettings = new Dictionary<string, string>
{
{ "Logging:LogLevel:Default", "Information" },
{ "Logging:LogLevel:Microsoft.AspNetCore", "Warning" }
};
var configuration = new ConfigurationBuilder()
.AddInMemoryCollection(inMemorySettings)
.Build();

// Act
Microsoft.Extensions.Logging.ILogger logger = ServiceCollectionExtensions.CreateConsoleLogger(configuration);

// Assert
Assert.That(logger, Is.Not.Null);
}
}
Loading

0 comments on commit 43de9b0

Please sign in to comment.