using System.Net; using System.Text; using FindAndDrive.API; using FindAndDrive.Domain.Helpers; using FindAndDrive.Domain.Models.DTO.Request; using FindAndDrive.Domain.Models.DTO.Response; using FindAndDrive.Domain.Models.Entities; using FindAndDrive.Persistence; using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json; namespace FindAndDrive.Tests.IntegrationTests.Controllers; public class ClientControllerTests : IClassFixture>, IAsyncLifetime { private readonly IntegrationTestAppFactory _factory; private Guid _clientId; private Guid _apiKeyId; private string _apiKeySecret; public ClientControllerTests(IntegrationTestAppFactory factory) { _factory = factory; } [Fact] public async Task AttemptApiCall() { var httpClient = _factory.CreateClient(); var payload = new TokenRequest { ApiSecret = _apiKeySecret, ApiKeyId = _apiKeyId.ToString() }; using var request = new HttpRequestMessage(HttpMethod.Post, "api/Authentication/token"); request.Content = new StringContent( JsonConvert.SerializeObject(payload), Encoding.UTF8, "application/json" ); var response = await httpClient.SendAsync(request); Assert.True(response.StatusCode == HttpStatusCode.OK); var body = await response.Content.ReadAsStringAsync(); var responseObject = JsonConvert.DeserializeObject(body); Assert.NotNull(responseObject); Assert.NotNull(responseObject.Token); Assert.NotEmpty(responseObject.Token); } public async Task InitializeAsync() { using var scope = _factory.Services.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var client = new Client { Active = true, ClientName = $"test client {Guid.NewGuid()}", CreatedAt = DateTime.Now, ModifiedAt = DateTime.Now }; db.Clients.Add(client); await db.SaveChangesAsync(); var adminRole = db.Roles.First(f => f.RoleName == "SystemAdmin"); _apiKeySecret = ApiKeyHelper.GenerateApiKey(); var apiKey = new ApiKey { ClientId = client.ClientId, KeySecretHash = ApiKeyHelper.HashString(_apiKeySecret), Revoked = false, RoleId = adminRole.RoleId, }; db.ApiKeys.Add(apiKey); await db.SaveChangesAsync(); _clientId = client.ClientId; _apiKeyId = apiKey.ApiKeyId; } async Task IAsyncLifetime.DisposeAsync() { using var scope = _factory.Services.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var apiKey = db.ApiKeys.First(f => f.ApiKeyId == _apiKeyId); var client = db.Clients.First(f => f.ClientId == _clientId); db.ApiKeys.Remove(apiKey); db.Clients.Remove(client); await db.SaveChangesAsync(); } }