Skip to content

Commit

Permalink
Clean up, refactoring, and more APIs
Browse files Browse the repository at this point in the history
  • Loading branch information
IEvangelist committed Aug 2, 2023
1 parent d89edbf commit 7fa6c18
Show file tree
Hide file tree
Showing 25 changed files with 749 additions and 150 deletions.
3 changes: 3 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"dotnet.defaultSolution": "jwst.sln"
}
66 changes: 0 additions & 66 deletions Jwst.Client.Tests/GetVersionsTests.cs

This file was deleted.

5 changes: 5 additions & 0 deletions Jwst.Client.Tests/GlobalUsings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,14 @@

global using System.Text.Json;

global using Jwst.Client.Extensions;
global using Jwst.Client.Json;
global using Jwst.Client.Options;

global using Microsoft.Extensions.Configuration;
global using Microsoft.Extensions.DependencyInjection;
global using Microsoft.Extensions.Http.AutoClient;
global using Microsoft.Extensions.Options;

global using Xunit;
global using Xunit.Abstractions;
99 changes: 99 additions & 0 deletions Jwst.Client.Tests/JamesWebbClientTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
// Copyright (c) David Pine. All rights reserved.
// Licensed under the MIT License.

namespace Jwst.Client.Tests;

public class JamesWebbClientTests
{
private readonly ITestOutputHelper _output;

public JamesWebbClientTests(ITestOutputHelper output) => _output = output;

[Fact]
public async Task GetVersionReturnsSuccessfullyTest()
{
var httpClient = new HttpClient
{
BaseAddress = new("https://api.jwstapi.com")
};

var options = new AutoClientOptions
{
JsonSerializerOptions = new(JsonSerializerDefaults.Web)
{
PropertyNameCaseInsensitive = true,
PropertyNamingPolicy = SnakeOrCamelCaseNamingPolicy.Instance
}
};

var client = new JamesWebbClient(httpClient, options);

var version = await client.GetVersionAsync(CancellationToken.None);

_output.WriteLine("Version: {0}", version);

Assert.NotNull(version);
Assert.Equal(200, version.StatusCode);
Assert.Empty(version.Error ?? string.Empty);
Assert.NotNull(version.Body);
}

[Fact]
public async Task RoutesRequiringAuthHeadersFailWithoutHeaderTest()
{
var httpClient = new HttpClient
{
BaseAddress = new("https://api.jwstapi.com")
};

var options = new AutoClientOptions
{
JsonSerializerOptions = new(JsonSerializerDefaults.Web)
{
PropertyNameCaseInsensitive = true,
PropertyNamingPolicy = SnakeOrCamelCaseNamingPolicy.Instance
}
};

var client = new JamesWebbClient(httpClient, options);

await Assert.ThrowsAsync<AutoClientException>(
() => client.GetAllByFileTypeAsync("", 1, 10, CancellationToken.None));
await Assert.ThrowsAsync<AutoClientException>(
() => client.GetAllBySuffixAsync("", 1, 10, CancellationToken.None));
await Assert.ThrowsAsync<AutoClientException>(
() => client.GetByObservationIdAsync("", 1, 10, CancellationToken.None));
await Assert.ThrowsAsync<AutoClientException>(
() => client.GetByProgramIdAsync(2731, 1, 10, CancellationToken.None));
await Assert.ThrowsAsync<AutoClientException>(
() => client.GetProgramListAsync(CancellationToken.None));
await Assert.ThrowsAsync<AutoClientException>(
() => client.GetSuffixListAsync(CancellationToken.None));
}

[Fact]
public async Task GetVersionRespectsCancellationsTest()
{
var httpClient = new HttpClient
{
BaseAddress = new("https://api.jwstapi.com")
};

var options = new AutoClientOptions
{
JsonSerializerOptions = new(JsonSerializerDefaults.Web)
{
PropertyNameCaseInsensitive = true,
PropertyNamingPolicy = SnakeOrCamelCaseNamingPolicy.Instance
}
};

var client = new JamesWebbClient(httpClient, options);

// Create a cancellation token, that is already canceled
var cancellationToken = new CancellationToken(true);

await Assert.ThrowsAsync<TaskCanceledException>(
testCode: async () => await client.GetVersionAsync(cancellationToken));
}
}
147 changes: 147 additions & 0 deletions Jwst.Client.Tests/ServiceCollectionExtensionTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
// Copyright (c) David Pine. All rights reserved.
// Licensed under the MIT License.

namespace Jwst.Client.Tests;

public class ServiceCollectionExtensionTests
{
private readonly ITestOutputHelper _output;

public ServiceCollectionExtensionTests(ITestOutputHelper output) => _output = output;

[Fact]

public void AddJamesWebbClientServicesCorrectlyRegistersServicesTest()
{
const string expected = "test-api-key";

var services = new ServiceCollection();
var configuration = new ConfigurationBuilder()
.AddInMemoryCollection(
initialData: new Dictionary<string, string?>()
{
[$"{JamesWebbApiSettings.SectionName}:Key"] = expected
})
.Build();

services.AddJamesWebbClientServices(configuration);

var provider = services.BuildServiceProvider();

var options =
provider.GetRequiredService<IOptions<JamesWebbApiSettings>>();
Assert.NotNull(options);

var actual = options.Value.Key;
Assert.Equal(expected, actual);

Assert.NotNull(provider.GetRequiredService<IJamesWebbClient>());
}

[Fact(Skip = "Integration test.")]

public async void AddJamesWebbClientServicesCorrectlyResolvesClientTest()
{
var expected = Environment.GetEnvironmentVariable(
$"{JamesWebbApiSettings.SectionName}__Key");
Assert.True(expected is { Length: > 0 });

var services = new ServiceCollection();
var configuration = new ConfigurationBuilder()
.AddEnvironmentVariables()
.Build();

services.AddJamesWebbClientServices(configuration);

var provider = services.BuildServiceProvider();

var options =
provider.GetRequiredService<IOptions<JamesWebbApiSettings>>();
Assert.NotNull(options);

var actual = options.Value.Key;
Assert.Equal(expected, actual);

var client = provider.GetRequiredService<IJamesWebbClient>();
Assert.NotNull(client);

// Let's query as many observations as we can for 10 seconds.
// After ten seconds, we'll cancel the request and assert that
// the request was canceled.

// Tally the total number for reference.
var runningTotal = 0;
await Assert.ThrowsAsync<TaskCanceledException>(async () =>
{
using var cancellationTokenSource =
new CancellationTokenSource(TimeSpan.FromSeconds(1));
CancellationToken cancellationToken = cancellationTokenSource.Token;
await foreach (var (program, observation) in
client.GetAllByProgramAsAsyncEnumerable(200, cancellationToken))
{
_output.WriteLine(
$"[Program.Id = {program.Program}] {observation}");
++ runningTotal;
}
});

Assert.True(runningTotal is > 0);

_output.WriteLine($"Retrieved a total of {runningTotal} observations.");
}

[Fact(Skip = "Integration test.")]

public async void AddJamesWebbClientServicesReturnsFunctioningClient()
{
var expected = Environment.GetEnvironmentVariable(
$"{JamesWebbApiSettings.SectionName}__Key");
Assert.True(expected is { Length: > 0 });

var services = new ServiceCollection();
var configuration = new ConfigurationBuilder()
.AddEnvironmentVariables()
.Build();

services.AddJamesWebbClientServices(configuration);

var provider = services.BuildServiceProvider();

var options =
provider.GetRequiredService<IOptions<JamesWebbApiSettings>>();
Assert.NotNull(options);

var actual = options.Value.Key;
Assert.Equal(expected, actual);

var client = provider.GetRequiredService<IJamesWebbClient>();
Assert.NotNull(client);

// Let's query as many observations as we can for 10 seconds.
// After ten seconds, we'll cancel the request and assert that
// the request was canceled.

// Tally the total number for reference.
var runningTotal = 0;
using var cancellationTokenSource =
new CancellationTokenSource(TimeSpan.FromSeconds(30));

CancellationToken cancellationToken = cancellationTokenSource.Token;

await foreach (var (suffix, observation) in
client.GetAllBySuffixAsAsyncEnumerable(200, cancellationToken))
{
_output.WriteLine(
$"[Suffix = {suffix.Suffix}] {observation}");

++ runningTotal;
}

Assert.True(runningTotal is > 0);

_output.WriteLine($"Retrieved a total of {runningTotal} observations.");
}
}
31 changes: 31 additions & 0 deletions Jwst.Client.Tests/SnakeOrCamelCaseNamingPolicyTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// Copyright (c) David Pine. All rights reserved.
// Licensed under the MIT License.

namespace Jwst.Client.Tests;

public class SnakeOrCamelCaseNamingPolicyTests
{
[Fact]
public void ConvertNameNullNameThrows()
{
var policy = new SnakeOrCamelCaseNamingPolicy();
Assert.Throws<ArgumentNullException>(() => policy.ConvertName(null!));
}

[Theory]
[InlineData("statusCode", "StatusCode")]
[InlineData("observation_id", "ObservationId")]
[InlineData("file_type", "FileType")]
[InlineData("error", "Error")]
public void ConvertNameCorrectlyConverts(string name, string expected)
{
// Arrange
var policy = new SnakeOrCamelCaseNamingPolicy();

// Act
var actual = policy.ConvertName(name);

// Assert
Assert.Equal(expected, actual);
}
}
Loading

0 comments on commit 7fa6c18

Please sign in to comment.