BAD MISC - playing with tests

This commit is contained in:
Reuben Bond 2023-04-28 14:49:57 -07:00
parent 1e4de70295
commit 146652ca6a
13 changed files with 88 additions and 101 deletions

View File

@ -1,7 +1,7 @@
namespace Microsoft.eShopOnContainers.Services.Basket.API.Controllers; namespace Microsoft.eShopOnContainers.Services.Basket.API.Controllers;
[Route("api/v1/[controller]")] [Route("api/v1/[controller]")]
[Authorize] //[Authorize]
[ApiController] [ApiController]
public class BasketController : ControllerBase public class BasketController : ControllerBase
{ {

View File

@ -1,9 +1,4 @@
using Autofac.Core; var builder = WebApplication.CreateBuilder(new WebApplicationOptions
using Microsoft.Azure.Amqp.Framing;
using Microsoft.Extensions.Configuration;
var appName = "Basket.API";
var builder = WebApplication.CreateBuilder(new WebApplicationOptions
{ {
Args = args, Args = args,
ApplicationName = typeof(Program).Assembly.FullName, ApplicationName = typeof(Program).Assembly.FullName,
@ -63,6 +58,7 @@ JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Remove("sub");
var identityUrl = builder.Configuration.GetValue<string>("IdentityUrl"); var identityUrl = builder.Configuration.GetValue<string>("IdentityUrl");
/*
builder.Services.AddAuthentication("Bearer").AddJwtBearer(options => builder.Services.AddAuthentication("Bearer").AddJwtBearer(options =>
{ {
options.Authority = identityUrl; options.Authority = identityUrl;
@ -78,6 +74,7 @@ builder.Services.AddAuthorization(options =>
policy.RequireClaim("scope", "basket"); policy.RequireClaim("scope", "basket");
}); });
}); });
*/
builder.Services.AddCustomHealthCheck(builder.Configuration); builder.Services.AddCustomHealthCheck(builder.Configuration);
@ -164,7 +161,6 @@ builder.WebHost.UseKestrel(options =>
}); });
}); });
builder.WebHost.CaptureStartupErrors(false);
builder.Host.UseSerilog(CreateSerilogLogger(builder.Configuration)); builder.Host.UseSerilog(CreateSerilogLogger(builder.Configuration));
builder.WebHost.UseFailing(options => builder.WebHost.UseFailing(options =>
{ {
@ -172,6 +168,7 @@ builder.WebHost.UseFailing(options =>
options.NotFilteredPaths.AddRange(new[] { "/hc", "/liveness" }); options.NotFilteredPaths.AddRange(new[] { "/hc", "/liveness" });
}); });
var app = builder.Build(); var app = builder.Build();
app.MapGet("hello", () => "hello");
if (app.Environment.IsDevelopment()) if (app.Environment.IsDevelopment())
{ {
@ -196,13 +193,19 @@ app.UseSwagger()
setup.OAuthAppName("Basket Swagger UI"); setup.OAuthAppName("Basket Swagger UI");
}); });
app.Use(del => ctx =>
{
ctx.Response.StatusCode = 200;
ctx.Response.WriteAsync("hello");
return Task.CompletedTask;
//return del(ctx);
});
app.UseRouting(); app.UseRouting();
app.UseCors("CorsPolicy"); app.UseCors("CorsPolicy");
app.UseAuthentication(); //app.UseAuthentication();
app.UseAuthorization(); //app.UseAuthorization();
app.UseStaticFiles(); app.UseStaticFiles();
app.MapGrpcService<BasketService>(); app.MapGrpcService<BasketService>();
app.MapDefaultControllerRoute(); app.MapDefaultControllerRoute();
app.MapControllers(); app.MapControllers();
@ -271,6 +274,7 @@ Serilog.ILogger CreateSerilogLogger(IConfiguration configuration)
var port = config.GetValue("PORT", 80); var port = config.GetValue("PORT", 80);
return (port, grpcPort); return (port, grpcPort);
} }
void ConfigureEventBus(IApplicationBuilder app) void ConfigureEventBus(IApplicationBuilder app)
{ {
var eventBus = app.ApplicationServices.GetRequiredService<IEventBus>(); var eventBus = app.ApplicationServices.GetRequiredService<IEventBus>();
@ -278,18 +282,15 @@ void ConfigureEventBus(IApplicationBuilder app)
eventBus.Subscribe<ProductPriceChangedIntegrationEvent, ProductPriceChangedIntegrationEventHandler>(); eventBus.Subscribe<ProductPriceChangedIntegrationEvent, ProductPriceChangedIntegrationEventHandler>();
eventBus.Subscribe<OrderStartedIntegrationEvent, OrderStartedIntegrationEventHandler>(); eventBus.Subscribe<OrderStartedIntegrationEvent, OrderStartedIntegrationEventHandler>();
} }
public partial class Program public partial class Program
{ {
private static string Namespace = typeof(Program).Assembly.GetName().Name;
public static string Namespace = typeof(Program).Assembly.GetName().Name;
public static string AppName = Namespace.Substring(Namespace.LastIndexOf('.', Namespace.LastIndexOf('.') - 1) + 1); public static string AppName = Namespace.Substring(Namespace.LastIndexOf('.', Namespace.LastIndexOf('.') - 1) + 1);
} }
public static class CustomExtensionMethods public static class CustomExtensionMethods
{ {
public static IServiceCollection RegisterEventBus(this IServiceCollection services, IConfiguration configuration) public static IServiceCollection RegisterEventBus(this IServiceCollection services, IConfiguration configuration)
{ {
if (configuration.GetValue<bool>("AzureServiceBusEnabled")) if (configuration.GetValue<bool>("AzureServiceBusEnabled"))

View File

@ -18,6 +18,7 @@ class AutoAuthorizeMiddleware
identity.AddClaim(new Claim("sub", IDENTITY_ID)); identity.AddClaim(new Claim("sub", IDENTITY_ID));
identity.AddClaim(new Claim("unique_name", IDENTITY_ID)); identity.AddClaim(new Claim("unique_name", IDENTITY_ID));
identity.AddClaim(new Claim(ClaimTypes.Name, IDENTITY_ID)); identity.AddClaim(new Claim(ClaimTypes.Name, IDENTITY_ID));
identity.AddClaim(new Claim("scope", "basket"));
httpContext.User.AddIdentity(identity); httpContext.User.AddIdentity(identity);

View File

@ -1,13 +0,0 @@
namespace Basket.FunctionalTests.Base;
static class HttpClientExtensions
{
public static HttpClient CreateIdempotentClient(this TestServer server)
{
var client = server.CreateClient();
client.DefaultRequestHeaders.Add("x-requestid", Guid.NewGuid().ToString());
return client;
}
}

View File

@ -1,15 +1,43 @@
namespace Basket.FunctionalTests; using System.Linq;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.Hosting;
public class BasketScenarios namespace Basket.FunctionalTests;
: BasketScenarioBase
public class TestWebApplicationFactory<TProgram> : WebApplicationFactory<TProgram> where TProgram : class
{ {
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
base.ConfigureWebHost(builder);
builder.Configure(app =>
{
app.UseMiddleware<AutoAuthorizeMiddleware>();
});
}
protected override IHost CreateHost(IHostBuilder builder)
{
return base.CreateHost(builder);
}
}
public class BasketScenarios : BasketScenarioBase, IClassFixture<TestWebApplicationFactory<Program>>
{
private readonly TestWebApplicationFactory<Program> _factory;
private readonly HttpClient _httpClient;
public BasketScenarios(TestWebApplicationFactory<Program> factory)
{
_factory = factory;
_httpClient = _factory.CreateClient();
}
[Fact] [Fact]
public async Task Post_basket_and_response_ok_status_code() public async Task Post_basket_and_response_ok_status_code()
{ {
using var server = CreateServer();
var content = new StringContent(BuildBasket(), UTF8Encoding.UTF8, "application/json"); var content = new StringContent(BuildBasket(), UTF8Encoding.UTF8, "application/json");
var response = await server.CreateClient() var uri = "/api/v1/basket/";
.PostAsync(Post.Basket, content); var response = await _httpClient.PostAsync(uri, content);
response.EnsureSuccessStatusCode(); response.EnsureSuccessStatusCode();
} }
@ -17,25 +45,25 @@ public class BasketScenarios
[Fact] [Fact]
public async Task Get_basket_and_response_ok_status_code() public async Task Get_basket_and_response_ok_status_code()
{ {
using var server = CreateServer(); var response = await _httpClient
var response = await server.CreateClient()
.GetAsync(Get.GetBasket(1)); .GetAsync(Get.GetBasket(1));
response.EnsureSuccessStatusCode(); response.EnsureSuccessStatusCode();
} }
[Fact] [Fact]
public async Task Send_Checkout_basket_and_response_ok_status_code() public async Task Send_Checkout_basket_and_response_ok_status_code()
{ {
using var server = CreateServer();
var contentBasket = new StringContent(BuildBasket(), UTF8Encoding.UTF8, "application/json"); var contentBasket = new StringContent(BuildBasket(), UTF8Encoding.UTF8, "application/json");
await server.CreateClient() await _httpClient
.PostAsync(Post.Basket, contentBasket); .PostAsync(Post.Basket, contentBasket);
var contentCheckout = new StringContent(BuildCheckout(), UTF8Encoding.UTF8, "application/json"); var contentCheckout = new StringContent(BuildCheckout(), UTF8Encoding.UTF8, "application/json")
{
Headers = { { "x-requestid", Guid.NewGuid().ToString() } }
};
var response = await server.CreateIdempotentClient() var response = await _httpClient
.PostAsync(Post.CheckoutOrder, contentCheckout); .PostAsync(Post.CheckoutOrder, contentCheckout);
response.EnsureSuccessStatusCode(); response.EnsureSuccessStatusCode();

View File

@ -1,11 +0,0 @@
namespace Ordering.FunctionalTests;
static class HttpClientExtensions
{
public static HttpClient CreateIdempotentClient(this TestServer server)
{
var client = server.CreateClient();
client.DefaultRequestHeaders.Add("x-requestid", Guid.NewGuid().ToString());
return client;
}
}

View File

@ -23,8 +23,11 @@ namespace Ordering.FunctionalTests
public async Task Cancel_order_no_order_created_bad_request_response() public async Task Cancel_order_no_order_created_bad_request_response()
{ {
using var server = CreateServer(); using var server = CreateServer();
var content = new StringContent(BuildOrder(), UTF8Encoding.UTF8, "application/json"); var content = new StringContent(BuildOrder(), UTF8Encoding.UTF8, "application/json")
var response = await server.CreateIdempotentClient() {
Headers = { { "x-requestid", Guid.NewGuid().ToString() } }
};
var response = await server.CreateClient()
.PutAsync(Put.CancelOrder, content); .PutAsync(Put.CancelOrder, content);
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
@ -34,8 +37,11 @@ namespace Ordering.FunctionalTests
public async Task Ship_order_no_order_created_bad_request_response() public async Task Ship_order_no_order_created_bad_request_response()
{ {
using var server = CreateServer(); using var server = CreateServer();
var content = new StringContent(BuildOrder(), UTF8Encoding.UTF8, "application/json"); var content = new StringContent(BuildOrder(), UTF8Encoding.UTF8, "application/json")
var response = await server.CreateIdempotentClient() {
Headers = { { "x-requestid", Guid.NewGuid().ToString() } }
};
var response = await server.CreateClient()
.PutAsync(Put.ShipOrder, content); .PutAsync(Put.ShipOrder, content);
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);

View File

@ -1,5 +1,4 @@
var appName = "Payment.API"; var builder = WebApplication.CreateBuilder(new WebApplicationOptions
var builder = WebApplication.CreateBuilder(new WebApplicationOptions
{ {
Args = args, Args = args,
ApplicationName = typeof(Program).Assembly.FullName, ApplicationName = typeof(Program).Assembly.FullName,
@ -165,27 +164,6 @@ Serilog.ILogger CreateSerilogLogger(IConfiguration configuration)
.CreateLogger(); .CreateLogger();
} }
IConfiguration GetConfiguration()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables();
var config = builder.Build();
if (config.GetValue<bool>("UseVault", false))
{
TokenCredential credential = new ClientSecretCredential(
config["Vault:TenantId"],
config["Vault:ClientId"],
config["Vault:ClientSecret"]);
builder.AddAzureKeyVault(new Uri($"https://{config["Vault:Name"]}.vault.azure.net/"), credential);
}
return builder.Build();
}
public partial class Program public partial class Program
{ {
public static string Namespace = typeof(Program).Assembly.GetName().Name; public static string Namespace = typeof(Program).Assembly.GetName().Name;

View File

@ -41,7 +41,7 @@
<PackageReference Include="Microsoft.NET.Test.Sdk" /> <PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="Microsoft.AspNetCore.TestHost" /> <PackageReference Include="Microsoft.AspNetCore.TestHost" />
<PackageReference Include="xunit" /> <PackageReference Include="xunit" />
<PackageReference Include="xunit.runner.visualstudio" > <PackageReference Include="xunit.runner.visualstudio">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference> </PackageReference>

View File

@ -1,11 +0,0 @@
namespace FunctionalTests.Extensions;
static class HttpClientExtensions
{
public static HttpClient CreateIdempotentClient(this TestServer server)
{
var client = server.CreateClient();
client.DefaultRequestHeaders.Add("x-requestid", Guid.NewGuid().ToString());
return client;
}
}

View File

@ -8,14 +8,11 @@ global using Microsoft.AspNetCore.Hosting;
global using Microsoft.Extensions.Configuration; global using Microsoft.Extensions.Configuration;
global using System.IO; global using System.IO;
global using System.Reflection; global using System.Reflection;
global using FunctionalTests.Middleware;
global using Microsoft.AspNetCore.Builder;
global using Microsoft.eShopOnContainers.BuildingBlocks.IntegrationEventLogEF; global using Microsoft.eShopOnContainers.BuildingBlocks.IntegrationEventLogEF;
global using Microsoft.eShopOnContainers.Services.Catalog.API.Infrastructure; global using Microsoft.eShopOnContainers.Services.Catalog.API.Infrastructure;
global using Microsoft.Extensions.DependencyInjection; global using Microsoft.Extensions.DependencyInjection;
global using Microsoft.Extensions.Logging; global using Microsoft.Extensions.Logging;
global using Microsoft.Extensions.Options; global using Microsoft.Extensions.Options;
global using FunctionalTests.Extensions;
global using FunctionalTests.Services.Basket; global using FunctionalTests.Services.Basket;
global using Microsoft.eShopOnContainers.Services.Basket.API.Model; global using Microsoft.eShopOnContainers.Services.Basket.API.Model;
global using Microsoft.eShopOnContainers.WebMVC.ViewModels; global using Microsoft.eShopOnContainers.WebMVC.ViewModels;

View File

@ -11,21 +11,32 @@ public class OrderingScenarios : OrderingScenariosBase
var cityExpected = $"city-{Guid.NewGuid()}"; var cityExpected = $"city-{Guid.NewGuid()}";
var orderStatusExpected = "cancelled"; var orderStatusExpected = "cancelled";
var basketClient = basketServer.CreateIdempotentClient(); var basketClient = basketServer.CreateClient();
var orderClient = orderServer.CreateIdempotentClient(); var orderClient = orderServer.CreateClient();
// GIVEN a basket is created // GIVEN a basket is created
var contentBasket = new StringContent(BuildBasket(), UTF8Encoding.UTF8, "application/json"); var contentBasket = new StringContent(BuildBasket(), UTF8Encoding.UTF8, "application/json")
{
Headers = { { "x-requestid", Guid.NewGuid().ToString() } }
};
await basketClient.PostAsync(BasketScenariosBase.Post.CreateBasket, contentBasket); await basketClient.PostAsync(BasketScenariosBase.Post.CreateBasket, contentBasket);
// AND basket checkout is sent // AND basket checkout is sent
await basketClient.PostAsync(BasketScenariosBase.Post.CheckoutOrder, new StringContent(BuildCheckout(cityExpected), UTF8Encoding.UTF8, "application/json")); await basketClient.PostAsync(
BasketScenariosBase.Post.CheckoutOrder,
new StringContent(BuildCheckout(cityExpected), UTF8Encoding.UTF8, "application/json")
{
Headers = { { "x-requestid", Guid.NewGuid().ToString() } }
});
// WHEN Order is created in Ordering.api // WHEN Order is created in Ordering.api
var newOrder = await TryGetNewOrderCreated(cityExpected, orderClient); var newOrder = await TryGetNewOrderCreated(cityExpected, orderClient);
// AND Order is cancelled in Ordering.api // AND Order is cancelled in Ordering.api
await orderClient.PutAsync(OrderingScenariosBase.Put.CancelOrder, new StringContent(BuildCancelOrder(newOrder.OrderNumber), UTF8Encoding.UTF8, "application/json")); await orderClient.PutAsync(OrderingScenariosBase.Put.CancelOrder, new StringContent(BuildCancelOrder(newOrder.OrderNumber), UTF8Encoding.UTF8, "application/json")
{
Headers = { { "x-requestid", Guid.NewGuid().ToString() } }
});
// AND the requested order is retrieved // AND the requested order is retrieved
var order = await TryGetOrder(newOrder.OrderNumber, orderClient); var order = await TryGetOrder(newOrder.OrderNumber, orderClient);

View File

@ -53,7 +53,7 @@ public class BasketService : IBasketService
var uri = API.Basket.CheckoutBasket(_basketByPassUrl); var uri = API.Basket.CheckoutBasket(_basketByPassUrl);
var basketContent = new StringContent(JsonSerializer.Serialize(basket), Encoding.UTF8, "application/json"); var basketContent = new StringContent(JsonSerializer.Serialize(basket), Encoding.UTF8, "application/json");
_logger.LogInformation("Uri chechout {uri}", uri); _logger.LogInformation("Uri checkout {uri}", uri);
var response = await _apiClient.PostAsync(uri, basketContent); var response = await _apiClient.PostAsync(uri, basketContent);