Browse Source

BAD MISC - playing with tests

rebond/dev
Reuben Bond 1 year ago
parent
commit
146652ca6a
13 changed files with 88 additions and 101 deletions
  1. +1
    -1
      src/Services/Basket/Basket.API/Controllers/BasketController.cs
  2. +16
    -15
      src/Services/Basket/Basket.API/Program.cs
  3. +1
    -0
      src/Services/Basket/Basket.FunctionalTests/Base/AutoAuthorizeMiddleware.cs
  4. +0
    -13
      src/Services/Basket/Basket.FunctionalTests/Base/HttpClientExtensions.cs
  5. +41
    -13
      src/Services/Basket/Basket.FunctionalTests/BasketScenarios.cs
  6. +0
    -11
      src/Services/Ordering/Ordering.FunctionalTests/HttpClientExtensions.cs
  7. +10
    -4
      src/Services/Ordering/Ordering.FunctionalTests/OrderingScenarios.cs
  8. +1
    -23
      src/Services/Payment/Payment.API/Program.cs
  9. +1
    -1
      src/Tests/Services/Application.FunctionalTests/Application.FunctionalTests.csproj
  10. +0
    -11
      src/Tests/Services/Application.FunctionalTests/Extensions/HttpClientExtensions.cs
  11. +0
    -3
      src/Tests/Services/Application.FunctionalTests/GlobalUsings.cs
  12. +16
    -5
      src/Tests/Services/Application.FunctionalTests/Services/Ordering/OrderingScenarios.cs
  13. +1
    -1
      src/Web/WebMVC/Services/BasketService.cs

+ 1
- 1
src/Services/Basket/Basket.API/Controllers/BasketController.cs View File

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


+ 16
- 15
src/Services/Basket/Basket.API/Program.cs View File

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


+ 1
- 0
src/Services/Basket/Basket.FunctionalTests/Base/AutoAuthorizeMiddleware.cs View File

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


+ 0
- 13
src/Services/Basket/Basket.FunctionalTests/Base/HttpClientExtensions.cs 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;
}
}

+ 41
- 13
src/Services/Basket/Basket.FunctionalTests/BasketScenarios.cs View File

@ -1,15 +1,43 @@
namespace Basket.FunctionalTests;
using System.Linq;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.Hosting;
public class BasketScenarios
: BasketScenarioBase
namespace Basket.FunctionalTests;
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]
public async Task Post_basket_and_response_ok_status_code()
{
using var server = CreateServer();
var content = new StringContent(BuildBasket(), UTF8Encoding.UTF8, "application/json");
var response = await server.CreateClient()
.PostAsync(Post.Basket, content);
var uri = "/api/v1/basket/";
var response = await _httpClient.PostAsync(uri, content);
response.EnsureSuccessStatusCode();
}
@ -17,25 +45,25 @@ public class BasketScenarios
[Fact]
public async Task Get_basket_and_response_ok_status_code()
{
using var server = CreateServer();
var response = await server.CreateClient()
var response = await _httpClient
.GetAsync(Get.GetBasket(1));
response.EnsureSuccessStatusCode();
}
[Fact]
public async Task Send_Checkout_basket_and_response_ok_status_code()
{
using var server = CreateServer();
var contentBasket = new StringContent(BuildBasket(), UTF8Encoding.UTF8, "application/json");
await server.CreateClient()
await _httpClient
.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);
response.EnsureSuccessStatusCode();


+ 0
- 11
src/Services/Ordering/Ordering.FunctionalTests/HttpClientExtensions.cs 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;
}
}

+ 10
- 4
src/Services/Ordering/Ordering.FunctionalTests/OrderingScenarios.cs View File

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


+ 1
- 23
src/Services/Payment/Payment.API/Program.cs View File

@ -1,5 +1,4 @@
var appName = "Payment.API";
var builder = WebApplication.CreateBuilder(new WebApplicationOptions
var builder = WebApplication.CreateBuilder(new WebApplicationOptions
{
Args = args,
ApplicationName = typeof(Program).Assembly.FullName,
@ -165,27 +164,6 @@ Serilog.ILogger CreateSerilogLogger(IConfiguration configuration)
.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 static string Namespace = typeof(Program).Assembly.GetName().Name;


+ 1
- 1
src/Tests/Services/Application.FunctionalTests/Application.FunctionalTests.csproj View File

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


+ 0
- 11
src/Tests/Services/Application.FunctionalTests/Extensions/HttpClientExtensions.cs 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;
}
}

+ 0
- 3
src/Tests/Services/Application.FunctionalTests/GlobalUsings.cs View File

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


+ 16
- 5
src/Tests/Services/Application.FunctionalTests/Services/Ordering/OrderingScenarios.cs View File

@ -11,21 +11,32 @@ public class OrderingScenarios : OrderingScenariosBase
var cityExpected = $"city-{Guid.NewGuid()}";
var orderStatusExpected = "cancelled";
var basketClient = basketServer.CreateIdempotentClient();
var orderClient = orderServer.CreateIdempotentClient();
var basketClient = basketServer.CreateClient();
var orderClient = orderServer.CreateClient();
// 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);
// 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
var newOrder = await TryGetNewOrderCreated(cityExpected, orderClient);
// 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
var order = await TryGetOrder(newOrder.OrderNumber, orderClient);


+ 1
- 1
src/Web/WebMVC/Services/BasketService.cs View File

@ -53,7 +53,7 @@ public class BasketService : IBasketService
var uri = API.Basket.CheckoutBasket(_basketByPassUrl);
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);


Loading…
Cancel
Save