Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[SM-246] Use repository in integration test #2285

Merged
merged 8 commits into from
Sep 22, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 23 additions & 63 deletions test/Api.IntegrationTest/Controllers/SecretsControllerTests.cs
Original file line number Diff line number Diff line change
@@ -1,49 +1,51 @@
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using Bit.Api.IntegrationTest.Factories;
using Bit.Api.Models.Request.Organizations;
using Bit.Api.SecretManagerFeatures.Models.Request;
using Bit.Api.IntegrationTest.Helpers;
using Bit.Core.Entities;
using Bit.Core.Repositories;
using Xunit;

namespace Bit.Api.IntegrationTest.Controllers;

public class SecretsControllerTest : IClassFixture<ApiApplicationFactory>
{
private readonly string _mockEncryptedString = "2.3Uk+WNBIoU5xzmVFNcoWzz==|1MsPIYuRfdOHfu/0uY6H2Q==|/98sp4wb6pHP1VTZ9JcNCYgQjEUMFPlqJgCwRk1YXKg=";
private readonly string _mockEncryptedString =
"2.3Uk+WNBIoU5xzmVFNcoWzz==|1MsPIYuRfdOHfu/0uY6H2Q==|/98sp4wb6pHP1VTZ9JcNCYgQjEUMFPlqJgCwRk1YXKg=";

private readonly int _secretsToDelete = 3;
private readonly HttpClient _client;
private readonly ApiApplicationFactory _factory;
private readonly ISecretRepository _secretRepository;

public SecretsControllerTest(ApiApplicationFactory factory)
{
_factory = factory;
_client = _factory.CreateClient();
_secretRepository = _factory.GetService<ISecretRepository>();
}

[Fact]
public async Task DeleteSecrets()
{
var tokens = await _factory.LoginWithNewAccount();
var (organization, _) = await OrganizationTestHelpers.SignUpAsync(_factory);

var orgId = await CreateOrganization(tokens.Token);
var createdSecretIds = new List<Guid>();

foreach (var i in Enumerable.Range(0, _secretsToDelete))
var secretIds = new List<Guid>();
for (var i = 0; i < _secretsToDelete; i++)
{
var createdSecret = await CreateSecret(orgId, tokens.Token);
createdSecretIds.Add(createdSecret.Id);
var secret = await _secretRepository.CreateAsync(new Secret
{
OrganizationId = organization.Id,
Key = _mockEncryptedString,
Value = _mockEncryptedString,
Note = _mockEncryptedString
});
secretIds.Add(secret.Id);
}

using var message = new HttpRequestMessage(HttpMethod.Post, "/secrets/delete")
{
Content = new StringContent(JsonSerializer.Serialize(createdSecretIds),
Encoding.UTF8,
"application/json"),
};
message.Headers.Authorization = new AuthenticationHeaderValue("Bearer", tokens.Token);
var response = await _client.SendAsync(message);
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokens.Token);
var response = await _client.PostAsync("/secrets/delete", JsonContent.Create(secretIds));
response.EnsureSuccessStatusCode();

var content = await response.Content.ReadAsStringAsync();
Expand All @@ -53,54 +55,12 @@ public async Task DeleteSecrets()
var index = 0;
foreach (var element in jsonResult.RootElement.GetProperty("data").EnumerateArray())
{
Assert.Equal(createdSecretIds[index].ToString(), element.GetProperty("id").ToString());
Assert.Equal(secretIds[index].ToString(), element.GetProperty("id").ToString());
Assert.Empty(element.GetProperty("error").ToString());
index++;
}
}

private async Task<Secret> CreateSecret(Guid organizationId, string token)
{
var request = new SecretCreateRequestModel()
{
Key = _mockEncryptedString,
Value = _mockEncryptedString,
Note = _mockEncryptedString
};
using var message = new HttpRequestMessage(HttpMethod.Post, $"/organizations/{organizationId.ToString()}/secrets")
{
Content = new StringContent(
JsonSerializer.Serialize(request),
Encoding.UTF8,
"application/json")
};
message.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);

var response = await _client.SendAsync(message);
response.EnsureSuccessStatusCode();
return await response.Content.ReadFromJsonAsync<Secret>();
}

private async Task<Guid> CreateOrganization(string token)
{
var request = new OrganizationCreateRequestModel()
{
Name = "Integration Test Org",
BillingEmail = "[email protected]",
PlanType = Core.Enums.PlanType.Free,
Key = "test-key"
};
using var message = new HttpRequestMessage(HttpMethod.Post, $"/organizations")
{
Content = new StringContent(
JsonSerializer.Serialize(request),
Encoding.UTF8,
"application/json")
};
message.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
var response = await _client.SendAsync(message);
response.EnsureSuccessStatusCode();
var result = await response.Content.ReadAsStringAsync();
return new Guid(JsonDocument.Parse(result).RootElement.GetProperty("id").ToString());
var secrets = await _secretRepository.GetManyByIds(secretIds);
Assert.Empty(secrets);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ public class ApiApplicationFactory : WebApplicationFactoryBase<Startup>
public ApiApplicationFactory()
{
_identityApplicationFactory = new IdentityApplicationFactory();
_identityApplicationFactory.DatabaseName = DatabaseName;
}

protected override void ConfigureWebHost(IWebHostBuilder builder)
Expand Down
33 changes: 33 additions & 0 deletions test/Api.IntegrationTest/Helpers/OrganizationTestHelpers.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
using Bit.Core.Entities;
using Bit.Core.Enums;
using Bit.Core.Models.Business;
using Bit.Core.Repositories;
using Bit.Core.Services;
using Bit.IntegrationTestCommon.Factories;

namespace Bit.Api.IntegrationTest.Helpers;

public static class OrganizationTestHelpers
{
public static async Task<Tuple<Organization, OrganizationUser>> SignUpAsync<T>(WebApplicationFactoryBase<T> factory,
PlanType plan = PlanType.Free,
string ownerEmail = "[email protected]",
string name = "Integration Test Org",
string billingEmail = "[email protected]",
string ownerKey = "test-key") where T : class
{
var userRepository = factory.GetService<IUserRepository>();
var organizationService = factory.GetService<IOrganizationService>();

var owner = await userRepository.GetByEmailAsync(ownerEmail);

return await organizationService.SignUpAsync(new OrganizationSignup
Hinton marked this conversation as resolved.
Show resolved Hide resolved
{
Name = name,
BillingEmail = billingEmail,
Plan = plan,
OwnerKey = ownerKey,
Owner = owner,
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public abstract class WebApplicationFactoryBase<T> : WebApplicationFactory<T>
/// <remarks>
/// This will need to be set BEFORE using the <c>Server</c> property
/// </remarks>
public string DatabaseName { get; set; } = FactoryConstants.DefaultDatabaseName;
public string DatabaseName { get; set; } = Guid.NewGuid().ToString();

/// <summary>
/// Configure the web host to use an EF in memory database
Expand Down Expand Up @@ -107,5 +107,11 @@ public DatabaseContext GetDatabaseContext()
var scope = Services.CreateScope();
return scope.ServiceProvider.GetRequiredService<DatabaseContext>();
}

public T GetService<T>()
{
var scope = Services.CreateScope();
return scope.ServiceProvider.GetRequiredService<T>();
}
}
}