Implement DeleteManyByFeedbackReceiverIdAsync for TokensService.cs and FeedbackReceiversController.cs.

This commit is contained in:
Denis-Cosmin Nutiu 2021-07-04 14:05:53 +03:00
parent 56bbb68dda
commit ef15623b10
9 changed files with 206 additions and 61 deletions

View file

@ -31,5 +31,12 @@ namespace Retroactiune.Core.Interfaces
/// <param name="filters">Filters object for filtering results.</param> /// <param name="filters">Filters object for filtering results.</param>
/// <returns>A list of tokens matching the filters.</returns> /// <returns>A list of tokens matching the filters.</returns>
public Task<IEnumerable<Token>> ListTokens(TokenListFilters filters); public Task<IEnumerable<Token>> ListTokens(TokenListFilters filters);
/// <summary>
/// Deletes tokens, by their associated FeedbackReceiverId.
/// </summary>
/// <param name="feedbackReceiverIds">A list of FeedbackReceiverIDs.</param>
/// <returns>The result of the delete operation.</returns>
public Task DeleteManyByFeedbackReceiverIdAsync(IEnumerable<string> feedbackReceiverIds);
} }
} }

View file

@ -8,11 +8,11 @@ using Retroactiune.Core.Interfaces;
namespace Retroactiune.Core.Services namespace Retroactiune.Core.Services
{ {
public class TokenService : ITokensService public class TokensService : ITokensService
{ {
private readonly IMongoCollection<Token> _collection; private readonly IMongoCollection<Token> _collection;
public TokenService(IMongoClient client, IDatabaseSettings settings) public TokensService(IMongoClient client, IDatabaseSettings settings)
{ {
var database = client.GetDatabase(settings.DatabaseName); var database = client.GetDatabase(settings.DatabaseName);
_collection = database.GetCollection<Token>(settings.TokensCollectionName); _collection = database.GetCollection<Token>(settings.TokensCollectionName);
@ -106,5 +106,18 @@ namespace Retroactiune.Core.Services
var results = await _collection.FindAsync(tokensListFilter); var results = await _collection.FindAsync(tokensListFilter);
return await results.ToListAsync(); return await results.ToListAsync();
} }
public async Task DeleteManyByFeedbackReceiverIdAsync(IEnumerable<string> feedbackReceiverIds)
{
try
{
var filter = new FilterDefinitionBuilder<Token>();
await _collection.DeleteManyAsync(filter.In(i => i.FeedbackReceiverId, feedbackReceiverIds));
}
catch (Exception e)
{
throw new GenericServiceException($"Operation failed: {e.Message} {e.StackTrace}");
}
}
} }
} }

View file

@ -124,13 +124,10 @@ namespace Retroactiune.IntegrationTests.Retroactiune.WebAPI.Controllers
// Arrange // Arrange
await _mongoDb.DropAsync(); await _mongoDb.DropAsync();
var guids = new List<string>(); var guids = new List<string>();
byte index = 0;
var feedbackReceivers = items as FeedbackReceiver[] ?? items.ToArray(); var feedbackReceivers = items as FeedbackReceiver[] ?? items.ToArray();
foreach (var i in feedbackReceivers) foreach (var i in feedbackReceivers)
{ {
i.Id = new BsonObjectId(new ObjectId(new byte[] {1, 2, index, 4, 5, 6, 7, 8, 9, index, 11, 14})) i.Id = ObjectId.GenerateNewId().ToString();
.ToString();
index += 1;
guids.Add(i.Id); guids.Add(i.Id);
} }
@ -151,19 +148,49 @@ namespace Retroactiune.IntegrationTests.Retroactiune.WebAPI.Controllers
Assert.Equal(0L, docs); Assert.Equal(0L, docs);
} }
[Fact]
public async Task Test_Delete_OK_With_Tokens()
{
// Arrange
await _mongoDb.DropAsync();
var feedbackReceiver = new FeedbackReceiver
{
Id = ObjectId.GenerateNewId().ToString(),
Description = "blam",
CreatedAt = DateTime.UtcNow,
Name = "test"
};
await _mongoDb.FeedbackReceiverCollection.InsertOneAsync(feedbackReceiver);
// Test
var httpResponse = await _client.DeleteAsync($"/api/v1/FeedbackReceivers/{feedbackReceiver.Id}",
CancellationToken.None);
await _client.PostAsync("/api/v1/Tokens/",
new StringContent($"{{\"numberOfTokens\": 100, \"feedbackReceiverId\": \"{feedbackReceiver.Id}\"}}",
Encoding.UTF8,
"application/json"));
// Assert
Assert.Equal(HttpStatusCode.NoContent, httpResponse.StatusCode);
var feedbackReceivers =
await _mongoDb.FeedbackReceiverCollection.CountDocumentsAsync(FilterDefinition<FeedbackReceiver>.Empty);
var tokens = await _mongoDb.TokensCollection.CountDocumentsAsync(FilterDefinition<Token>.Empty);
Assert.Equal(0L, feedbackReceivers);
Assert.Equal(0L, tokens);
}
[Theory, AutoData] [Theory, AutoData]
public async Task Test_DeleteMany_OK(IEnumerable<FeedbackReceiver> items) public async Task Test_DeleteMany_OK(IEnumerable<FeedbackReceiver> items)
{ {
// Arrange // Arrange
await _mongoDb.DropAsync(); await _mongoDb.DropAsync();
var guids = new List<string>(); var guids = new List<string>();
byte index = 0;
var feedbackReceivers = items as FeedbackReceiver[] ?? items.ToArray(); var feedbackReceivers = items as FeedbackReceiver[] ?? items.ToArray();
foreach (var i in feedbackReceivers) foreach (var i in feedbackReceivers)
{ {
i.Id = new BsonObjectId(new ObjectId(new byte[] {1, 2, index, 4, 5, 6, 7, 8, 9, index, 11, 14})) i.Id = ObjectId.GenerateNewId().ToString();
.ToString();
index += 1;
guids.Add(i.Id); guids.Add(i.Id);
} }
@ -194,7 +221,7 @@ namespace Retroactiune.IntegrationTests.Retroactiune.WebAPI.Controllers
await _mongoDb.DropAsync(); await _mongoDb.DropAsync();
var feedbackReceiver = new FeedbackReceiver var feedbackReceiver = new FeedbackReceiver
{ {
Id = new BsonObjectId(new ObjectId(new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 14})).ToString(), Id = ObjectId.GenerateNewId().ToString(),
Name = "N4m3", Name = "N4m3",
Description = "something", Description = "something",
CreatedAt = DateTime.UnixEpoch CreatedAt = DateTime.UnixEpoch
@ -248,21 +275,21 @@ namespace Retroactiune.IntegrationTests.Retroactiune.WebAPI.Controllers
{ {
new FeedbackReceiver new FeedbackReceiver
{ {
Id = new BsonObjectId(new ObjectId(new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 14})).ToString(), Id = ObjectId.GenerateNewId().ToString(),
Name = "N4m3", Name = "N4m3",
Description = "something", Description = "something",
CreatedAt = DateTime.UnixEpoch CreatedAt = DateTime.UnixEpoch
}, },
new FeedbackReceiver new FeedbackReceiver
{ {
Id = new BsonObjectId(new ObjectId(new byte[] {2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 14})).ToString(), Id = ObjectId.GenerateNewId().ToString(),
Name = "N4m3_Two", Name = "N4m3_Two",
Description = "something", Description = "something",
CreatedAt = DateTime.UnixEpoch CreatedAt = DateTime.UnixEpoch
}, },
new FeedbackReceiver new FeedbackReceiver
{ {
Id = new BsonObjectId(new ObjectId(new byte[] {3, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 14})).ToString(), Id = ObjectId.GenerateNewId().ToString(),
Name = "N4m3_Three", Name = "N4m3_Three",
Description = "something", Description = "something",
CreatedAt = DateTime.UnixEpoch CreatedAt = DateTime.UnixEpoch
@ -294,21 +321,21 @@ namespace Retroactiune.IntegrationTests.Retroactiune.WebAPI.Controllers
{ {
new FeedbackReceiver new FeedbackReceiver
{ {
Id = new BsonObjectId(new ObjectId(new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 14})).ToString(), Id = ObjectId.GenerateNewId().ToString(),
Name = "N4m3", Name = "N4m3",
Description = "something", Description = "something",
CreatedAt = DateTime.UnixEpoch CreatedAt = DateTime.UnixEpoch
}, },
new FeedbackReceiver new FeedbackReceiver
{ {
Id = new BsonObjectId(new ObjectId(new byte[] {2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 14})).ToString(), Id = ObjectId.GenerateNewId().ToString(),
Name = "N4m3_Two", Name = "N4m3_Two",
Description = "something", Description = "something",
CreatedAt = DateTime.UnixEpoch CreatedAt = DateTime.UnixEpoch
}, },
new FeedbackReceiver new FeedbackReceiver
{ {
Id = new BsonObjectId(new ObjectId(new byte[] {3, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 14})).ToString(), Id = ObjectId.GenerateNewId().ToString(),
Name = "N4m3_Three", Name = "N4m3_Three",
Description = "something", Description = "something",
CreatedAt = DateTime.UnixEpoch CreatedAt = DateTime.UnixEpoch
@ -344,21 +371,21 @@ namespace Retroactiune.IntegrationTests.Retroactiune.WebAPI.Controllers
{ {
new FeedbackReceiver new FeedbackReceiver
{ {
Id = new BsonObjectId(new ObjectId(new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 14})).ToString(), Id = ObjectId.GenerateNewId().ToString(),
Name = "N4m3", Name = "N4m3",
Description = "something", Description = "something",
CreatedAt = DateTime.UnixEpoch CreatedAt = DateTime.UnixEpoch
}, },
new FeedbackReceiver new FeedbackReceiver
{ {
Id = new BsonObjectId(new ObjectId(new byte[] {2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 14})).ToString(), Id = ObjectId.GenerateNewId().ToString(),
Name = "N4m3_Two", Name = "N4m3_Two",
Description = "something", Description = "something",
CreatedAt = DateTime.UnixEpoch CreatedAt = DateTime.UnixEpoch
}, },
new FeedbackReceiver new FeedbackReceiver
{ {
Id = new BsonObjectId(new ObjectId(new byte[] {3, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 14})).ToString(), Id = ObjectId.GenerateNewId().ToString(),
Name = "N4m3_Three", Name = "N4m3_Three",
Description = "something", Description = "something",
CreatedAt = DateTime.UnixEpoch CreatedAt = DateTime.UnixEpoch

View file

@ -116,13 +116,10 @@ namespace Retroactiune.IntegrationTests.Retroactiune.WebAPI.Controllers
await _mongoDb.DropAsync(); await _mongoDb.DropAsync();
var guids = new List<string>(); var guids = new List<string>();
var tokensArr = tokens as Token[] ?? tokens.ToArray(); var tokensArr = tokens as Token[] ?? tokens.ToArray();
byte index = 0;
foreach (var i in tokensArr) foreach (var i in tokensArr)
{ {
i.Id = new BsonObjectId(new ObjectId(new byte[] {1, 2, index, 4, 5, 6, 7, 8, 9, index, 11, 14})) i.Id = ObjectId.GenerateNewId().ToString();
.ToString(); i.FeedbackReceiverId = ObjectId.GenerateNewId().ToString();
i.FeedbackReceiverId = i.Id;
index += 1;
guids.Add(i.Id); guids.Add(i.Id);
} }
@ -161,13 +158,10 @@ namespace Retroactiune.IntegrationTests.Retroactiune.WebAPI.Controllers
await _mongoDb.DropAsync(); await _mongoDb.DropAsync();
var guids = new List<string>(); var guids = new List<string>();
var tokensArr = tokens as Token[] ?? tokens.ToArray(); var tokensArr = tokens as Token[] ?? tokens.ToArray();
byte index = 0;
foreach (var i in tokensArr) foreach (var i in tokensArr)
{ {
i.Id = new BsonObjectId(new ObjectId(new byte[] {1, 2, index, 4, 5, 6, 7, 8, 9, index, 11, 14})) i.Id = ObjectId.GenerateNewId().ToString();
.ToString(); i.FeedbackReceiverId = ObjectId.GenerateNewId().ToString();
i.FeedbackReceiverId = i.Id;
index += 1;
guids.Add(i.Id); guids.Add(i.Id);
} }
@ -275,7 +269,7 @@ namespace Retroactiune.IntegrationTests.Retroactiune.WebAPI.Controllers
Assert.Single(items); Assert.Single(items);
Assert.Equal(expectedTokens[0], items[0]); Assert.Equal(expectedTokens[0], items[0]);
} }
[Fact] [Fact]
public async Task Test_ListTokens_Filter_Ids() public async Task Test_ListTokens_Filter_Ids()
{ {
@ -303,7 +297,7 @@ namespace Retroactiune.IntegrationTests.Retroactiune.WebAPI.Controllers
Assert.Single(items); Assert.Single(items);
Assert.Equal(expectedTokens[0], items[0]); Assert.Equal(expectedTokens[0], items[0]);
} }
[Fact] [Fact]
public async Task Test_ListTokens_Filter_CreatedRange() public async Task Test_ListTokens_Filter_CreatedRange()
{ {

View file

@ -36,7 +36,7 @@ namespace Retroactiune.Tests.Retroactiune.Core.Services
.Returns(mongoCollectionMock.Object); .Returns(mongoCollectionMock.Object);
// Test & Assert // Test & Assert
var service = new TokenService(mongoClientMock.Object, mongoSettingsMock.Object); var service = new TokensService(mongoClientMock.Object, mongoSettingsMock.Object);
await Assert.ThrowsAsync<ArgumentException>(async () => { await service.GenerateTokensAsync(-1, ""); }); await Assert.ThrowsAsync<ArgumentException>(async () => { await service.GenerateTokensAsync(-1, ""); });
} }
@ -64,7 +64,7 @@ namespace Retroactiune.Tests.Retroactiune.Core.Services
// Test // Test
var expiryTime = DateTime.UtcNow; var expiryTime = DateTime.UtcNow;
var service = new TokenService(mongoClientMock.Object, mongoSettingsMock.Object); var service = new TokensService(mongoClientMock.Object, mongoSettingsMock.Object);
await service.GenerateTokensAsync(3, "Hello", expiryTime); await service.GenerateTokensAsync(3, "Hello", expiryTime);
// Assert // Assert
@ -105,7 +105,7 @@ namespace Retroactiune.Tests.Retroactiune.Core.Services
.Returns(mongoCollectionMock.Object); .Returns(mongoCollectionMock.Object);
// Test // Test
var service = new TokenService(mongoClientMock.Object, mongoSettingsMock.Object); var service = new TokensService(mongoClientMock.Object, mongoSettingsMock.Object);
await service.DeleteTokens(new[] {"test_id"}); await service.DeleteTokens(new[] {"test_id"});
// Assert // Assert
@ -140,10 +140,11 @@ namespace Retroactiune.Tests.Retroactiune.Core.Services
.Returns(mongoCollectionMock.Object); .Returns(mongoCollectionMock.Object);
mongoCollectionMock.Setup(i => i.FindAsync(It.IsAny<FilterDefinition<Token>>(), mongoCollectionMock.Setup(i => i.FindAsync(It.IsAny<FilterDefinition<Token>>(),
It.IsAny<FindOptions<Token, Token>>(), It.IsAny<CancellationToken>())).ReturnsAsync(mongoCursorMock.Object); It.IsAny<FindOptions<Token, Token>>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(mongoCursorMock.Object);
// Test // Test
var service = new TokenService(mongoClientMock.Object, mongoSettingsMock.Object); var service = new TokensService(mongoClientMock.Object, mongoSettingsMock.Object);
var result = await service.ListTokens(new TokenListFilters()); var result = await service.ListTokens(new TokenListFilters());
// Assert // Assert
@ -154,7 +155,7 @@ namespace Retroactiune.Tests.Retroactiune.Core.Services
It.IsAny<FindOptions<Token, Token>>(), It.IsAny<FindOptions<Token, Token>>(),
It.IsAny<CancellationToken>()), Times.Once); It.IsAny<CancellationToken>()), Times.Once);
} }
[Fact] [Fact]
public async Task Test_ListTokens_Filters_Ok() public async Task Test_ListTokens_Filters_Ok()
{ {
@ -179,13 +180,14 @@ namespace Retroactiune.Tests.Retroactiune.Core.Services
.Returns(mongoCollectionMock.Object); .Returns(mongoCollectionMock.Object);
mongoCollectionMock.Setup(i => i.FindAsync(It.IsAny<FilterDefinition<Token>>(), mongoCollectionMock.Setup(i => i.FindAsync(It.IsAny<FilterDefinition<Token>>(),
It.IsAny<FindOptions<Token, Token>>(), It.IsAny<CancellationToken>())).ReturnsAsync(mongoCursorMock.Object); It.IsAny<FindOptions<Token, Token>>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(mongoCursorMock.Object);
// Test // Test
var service = new TokenService(mongoClientMock.Object, mongoSettingsMock.Object); var service = new TokensService(mongoClientMock.Object, mongoSettingsMock.Object);
var result = await service.ListTokens(new TokenListFilters var result = await service.ListTokens(new TokenListFilters
{ {
Ids = new []{"a", "b"}, Ids = new[] {"a", "b"},
FeedbackReceiverId = "abc", FeedbackReceiverId = "abc",
CreatedAfter = DateTime.UtcNow, CreatedAfter = DateTime.UtcNow,
CreatedBefore = DateTime.UtcNow, CreatedBefore = DateTime.UtcNow,
@ -201,5 +203,79 @@ namespace Retroactiune.Tests.Retroactiune.Core.Services
It.IsAny<FindOptions<Token, Token>>(), It.IsAny<FindOptions<Token, Token>>(),
It.IsAny<CancellationToken>()), Times.Once); It.IsAny<CancellationToken>()), Times.Once);
} }
[Fact]
public async Task Test_DeleteManyByFeedbackReceiverIdAsync_Ok()
{
// Setup
var mongoDatabaseMock = new Mock<IMongoDatabase>();
var mongoClientMock = new Mock<IMongoClient>();
var mongoSettingsMock = new Mock<IDatabaseSettings>();
var mongoCollectionMock = new Mock<IMongoCollection<Token>>();
mongoSettingsMock.SetupGet(i => i.DatabaseName).Returns("MyDB");
mongoSettingsMock.SetupGet(i => i.TokensCollectionName).Returns("tokens");
mongoClientMock
.Setup(stub => stub.GetDatabase(It.IsAny<string>(),
It.IsAny<MongoDatabaseSettings>()))
.Returns(mongoDatabaseMock.Object);
mongoDatabaseMock
.Setup(i => i.GetCollection<Token>(It.IsAny<string>(),
It.IsAny<MongoCollectionSettings>()))
.Returns(mongoCollectionMock.Object);
// Test
var service = new TokensService(mongoClientMock.Object, mongoSettingsMock.Object);
await service.DeleteManyByFeedbackReceiverIdAsync(new[] {"test_id"});
// Assert
mongoCollectionMock.Verify(
i
=> i.DeleteManyAsync(
It.IsAny<FilterDefinition<Token>>(),
It.IsAny<CancellationToken>()), Times.Once);
}
[Fact]
public async Task Test_DeleteManyByFeedbackReceiverIdAsync_Exception()
{
// Setup
var mongoDatabaseMock = new Mock<IMongoDatabase>();
var mongoClientMock = new Mock<IMongoClient>();
var mongoSettingsMock = new Mock<IDatabaseSettings>();
var mongoCollectionMock = new Mock<IMongoCollection<Token>>();
mongoSettingsMock.SetupGet(i => i.DatabaseName).Returns("MyDB");
mongoSettingsMock.SetupGet(i => i.TokensCollectionName).Returns("tokens");
mongoClientMock
.Setup(stub => stub.GetDatabase(It.IsAny<string>(),
It.IsAny<MongoDatabaseSettings>()))
.Returns(mongoDatabaseMock.Object);
mongoDatabaseMock
.Setup(i => i.GetCollection<Token>(It.IsAny<string>(),
It.IsAny<MongoCollectionSettings>()))
.Returns(mongoCollectionMock.Object);
mongoCollectionMock.Setup(i =>
i.DeleteManyAsync(It.IsAny<FilterDefinition<Token>>(), It.IsAny<CancellationToken>()))
.ThrowsAsync(new GenericServiceException("op failed"));
// Test
var service = new TokensService(mongoClientMock.Object, mongoSettingsMock.Object);
await Assert.ThrowsAsync<GenericServiceException>(async () =>
{
await service.DeleteManyByFeedbackReceiverIdAsync(new[] {"test_id"});
});
// Assert
mongoCollectionMock.Verify(
i
=> i.DeleteManyAsync(
It.IsAny<FilterDefinition<Token>>(),
It.IsAny<CancellationToken>()), Times.Once);
}
} }
} }

View file

@ -22,10 +22,12 @@ namespace Retroactiune.Tests.Retroactiune.WebAPI.Controllers
// Arrange // Arrange
var mapper = TestUtils.GetMapper(); var mapper = TestUtils.GetMapper();
var mockService = new Mock<IFeedbackReceiverService>(); var mockService = new Mock<IFeedbackReceiverService>();
var tokensService = new Mock<ITokensService>();
var logger = new Mock<ILogger<FeedbackReceiversController>>(); var logger = new Mock<ILogger<FeedbackReceiversController>>();
// Test // Test
var controller = new FeedbackReceiversController(mockService.Object, mapper, null, logger.Object); var controller = new FeedbackReceiversController(mockService.Object, tokensService.Object, mapper, null,
logger.Object);
var result = await controller.Post(new List<FeedbackReceiverInDto>()); var result = await controller.Post(new List<FeedbackReceiverInDto>());
// Assert, null because we don't have the ApiBehaviourOptions set, which would generate the IActionResult for the invalid input. // Assert, null because we don't have the ApiBehaviourOptions set, which would generate the IActionResult for the invalid input.
@ -39,10 +41,12 @@ namespace Retroactiune.Tests.Retroactiune.WebAPI.Controllers
// Arrange // Arrange
var mapper = TestUtils.GetMapper(); var mapper = TestUtils.GetMapper();
var mockService = new Mock<IFeedbackReceiverService>(); var mockService = new Mock<IFeedbackReceiverService>();
var tokensService = new Mock<ITokensService>();
var logger = new Mock<ILogger<FeedbackReceiversController>>(); var logger = new Mock<ILogger<FeedbackReceiversController>>();
// Test // Test
var controller = new FeedbackReceiversController(mockService.Object, mapper, null, logger.Object); var controller = new FeedbackReceiversController(mockService.Object, tokensService.Object, mapper, null,
logger.Object);
var result = await controller.Post(items); var result = await controller.Post(items);
// Assert // Assert
@ -56,16 +60,21 @@ namespace Retroactiune.Tests.Retroactiune.WebAPI.Controllers
// Arrange // Arrange
var mapper = TestUtils.GetMapper(); var mapper = TestUtils.GetMapper();
var mockService = new Mock<IFeedbackReceiverService>(); var mockService = new Mock<IFeedbackReceiverService>();
var tokensService = new Mock<ITokensService>();
var logger = new Mock<ILogger<FeedbackReceiversController>>(); var logger = new Mock<ILogger<FeedbackReceiversController>>();
// Test // Test
var controller = new FeedbackReceiversController(mockService.Object, mapper, null, logger.Object); var controller = new FeedbackReceiversController(mockService.Object, tokensService.Object, mapper, null,
logger.Object);
var result = await controller.Delete("bad_guid_but_unit_test_works_cause_validation_doesnt"); var result = await controller.Delete("bad_guid_but_unit_test_works_cause_validation_doesnt");
// Assert // Assert
Assert.IsType<NoContentResult>(result); Assert.IsType<NoContentResult>(result);
mockService.Verify(s => s.DeleteManyAsync(new[] {"bad_guid_but_unit_test_works_cause_validation_doesnt"}), mockService.Verify(s => s.DeleteManyAsync(new[] {"bad_guid_but_unit_test_works_cause_validation_doesnt"}),
Times.Once); Times.Once);
tokensService.Verify(
s => s.DeleteManyByFeedbackReceiverIdAsync(new[]
{"bad_guid_but_unit_test_works_cause_validation_doesnt"}), Times.Once);
} }
[Fact] [Fact]
@ -74,10 +83,12 @@ namespace Retroactiune.Tests.Retroactiune.WebAPI.Controllers
// Arrange // Arrange
var mapper = TestUtils.GetMapper(); var mapper = TestUtils.GetMapper();
var mockService = new Mock<IFeedbackReceiverService>(); var mockService = new Mock<IFeedbackReceiverService>();
var tokensService = new Mock<ITokensService>();
var logger = new Mock<ILogger<FeedbackReceiversController>>(); var logger = new Mock<ILogger<FeedbackReceiversController>>();
// Test // Test
var controller = new FeedbackReceiversController(mockService.Object, mapper, null, logger.Object); var controller = new FeedbackReceiversController(mockService.Object, tokensService.Object, mapper, null,
logger.Object);
var items = new[] {"bad_guid_but_unit_test_works_cause_validation_doesnt", "2", "3"}; var items = new[] {"bad_guid_but_unit_test_works_cause_validation_doesnt", "2", "3"};
var result = await controller.DeleteMany(items); var result = await controller.DeleteMany(items);
@ -85,6 +96,7 @@ namespace Retroactiune.Tests.Retroactiune.WebAPI.Controllers
Assert.IsType<NoContentResult>(result); Assert.IsType<NoContentResult>(result);
mockService.Verify(s => s.DeleteManyAsync(items), mockService.Verify(s => s.DeleteManyAsync(items),
Times.Once); Times.Once);
tokensService.Verify(s => s.DeleteManyByFeedbackReceiverIdAsync(items), Times.Once);
} }
[Fact] [Fact]
@ -93,19 +105,21 @@ namespace Retroactiune.Tests.Retroactiune.WebAPI.Controllers
// Arrange // Arrange
var mapper = TestUtils.GetMapper(); var mapper = TestUtils.GetMapper();
var mockService = new Mock<IFeedbackReceiverService>(); var mockService = new Mock<IFeedbackReceiverService>();
var tokensService = new Mock<ITokensService>();
var logger = new Mock<ILogger<FeedbackReceiversController>>(); var logger = new Mock<ILogger<FeedbackReceiversController>>();
mockService.Setup(i => i.DeleteManyAsync(It.IsAny<IEnumerable<string>>())) mockService.Setup(i => i.DeleteManyAsync(It.IsAny<IEnumerable<string>>()))
.ThrowsAsync(new GenericServiceException("op failed")); .ThrowsAsync(new GenericServiceException("op failed"));
// Test // Test
var controller = new FeedbackReceiversController(mockService.Object, mapper, null, logger.Object); var controller = new FeedbackReceiversController(mockService.Object, tokensService.Object, mapper, null,
logger.Object);
var items = new[] {"bad_guid_but_unit_test_works_cause_validation_doesnt", "2", "3"}; var items = new[] {"bad_guid_but_unit_test_works_cause_validation_doesnt", "2", "3"};
var result = await controller.DeleteMany(items); var result = await controller.DeleteMany(items);
// Assert // Assert
Assert.IsType<BadRequestObjectResult>(result); Assert.IsType<BadRequestObjectResult>(result);
mockService.Verify(s => s.DeleteManyAsync(items), mockService.Verify(s => s.DeleteManyAsync(items), Times.Once);
Times.Once); tokensService.Verify(s => s.DeleteManyByFeedbackReceiverIdAsync(items), Times.Once);
} }
[Fact] [Fact]
@ -114,12 +128,14 @@ namespace Retroactiune.Tests.Retroactiune.WebAPI.Controllers
// Arrange // Arrange
var mapper = TestUtils.GetMapper(); var mapper = TestUtils.GetMapper();
var mockService = new Mock<IFeedbackReceiverService>(); var mockService = new Mock<IFeedbackReceiverService>();
var tokensService = new Mock<ITokensService>();
var logger = new Mock<ILogger<FeedbackReceiversController>>(); var logger = new Mock<ILogger<FeedbackReceiversController>>();
mockService.Setup(i => i.FindAsync(It.IsAny<IEnumerable<string>>(), null, null)) mockService.Setup(i => i.FindAsync(It.IsAny<IEnumerable<string>>(), null, null))
.ReturnsAsync(new[] {new FeedbackReceiver()}); .ReturnsAsync(new[] {new FeedbackReceiver()});
// Test // Test
var controller = new FeedbackReceiversController(mockService.Object, mapper, null, logger.Object); var controller = new FeedbackReceiversController(mockService.Object, tokensService.Object, mapper, null,
logger.Object);
var result = await controller.Get("bad_guid_but_unit_test_works_cause_validation_doesnt"); var result = await controller.Get("bad_guid_but_unit_test_works_cause_validation_doesnt");
// Assert // Assert
@ -135,10 +151,12 @@ namespace Retroactiune.Tests.Retroactiune.WebAPI.Controllers
// Arrange // Arrange
var mapper = TestUtils.GetMapper(); var mapper = TestUtils.GetMapper();
var mockService = new Mock<IFeedbackReceiverService>(); var mockService = new Mock<IFeedbackReceiverService>();
var tokensService = new Mock<ITokensService>();
var logger = new Mock<ILogger<FeedbackReceiversController>>(); var logger = new Mock<ILogger<FeedbackReceiversController>>();
// Test // Test
var controller = new FeedbackReceiversController(mockService.Object, mapper, null, logger.Object); var controller = new FeedbackReceiversController(mockService.Object, tokensService.Object, mapper, null,
logger.Object);
var result = await controller.Get("bad_guid_but_unit_test_works_cause_validation_doesnt"); var result = await controller.Get("bad_guid_but_unit_test_works_cause_validation_doesnt");
// Assert // Assert
@ -154,11 +172,13 @@ namespace Retroactiune.Tests.Retroactiune.WebAPI.Controllers
// Arrange // Arrange
var mapper = TestUtils.GetMapper(); var mapper = TestUtils.GetMapper();
var mockService = new Mock<IFeedbackReceiverService>(); var mockService = new Mock<IFeedbackReceiverService>();
var tokensService = new Mock<ITokensService>();
var logger = new Mock<ILogger<FeedbackReceiversController>>(); var logger = new Mock<ILogger<FeedbackReceiversController>>();
var filterArr = filter as string[] ?? filter.ToArray(); var filterArr = filter as string[] ?? filter.ToArray();
// Test // Test
var controller = new FeedbackReceiversController(mockService.Object, mapper, null, logger.Object); var controller = new FeedbackReceiversController(mockService.Object, tokensService.Object, mapper, null,
logger.Object);
var result = await controller.List(filterArr, offset, limit); var result = await controller.List(filterArr, offset, limit);
Assert.IsType<OkObjectResult>(result); Assert.IsType<OkObjectResult>(result);

View file

@ -20,14 +20,19 @@ namespace Retroactiune.Controllers
public class FeedbackReceiversController : ControllerBase public class FeedbackReceiversController : ControllerBase
{ {
private readonly IOptions<ApiBehaviorOptions> _apiBehaviorOptions; private readonly IOptions<ApiBehaviorOptions> _apiBehaviorOptions;
private readonly IFeedbackReceiverService _service;
// Note: Probably refactor this to use an Aggregate object, need to learn more about aggregates..
private readonly IFeedbackReceiverService _feedbackReceiverService;
private readonly ITokensService _tokensService;
private readonly IMapper _mapper; private readonly IMapper _mapper;
private readonly ILogger _logger; private readonly ILogger _logger;
public FeedbackReceiversController(IFeedbackReceiverService service, IMapper mapper, public FeedbackReceiversController(IFeedbackReceiverService feedbackReceiverService,
ITokensService tokensService, IMapper mapper,
IOptions<ApiBehaviorOptions> apiBehaviorOptions, ILogger<FeedbackReceiversController> logger) IOptions<ApiBehaviorOptions> apiBehaviorOptions, ILogger<FeedbackReceiversController> logger)
{ {
_service = service; _feedbackReceiverService = feedbackReceiverService;
_tokensService = tokensService;
_mapper = mapper; _mapper = mapper;
_apiBehaviorOptions = apiBehaviorOptions; _apiBehaviorOptions = apiBehaviorOptions;
_logger = logger; _logger = logger;
@ -61,7 +66,7 @@ namespace Retroactiune.Controllers
return result; return result;
}); });
await _service.CreateManyAsync(mappedItems); await _feedbackReceiverService.CreateManyAsync(mappedItems);
return Ok(new BasicResponse() return Ok(new BasicResponse()
{ {
@ -83,7 +88,8 @@ namespace Retroactiune.Controllers
[StringLength(24, ErrorMessage = "invalid guid, must be 24 characters", MinimumLength = 24)] [StringLength(24, ErrorMessage = "invalid guid, must be 24 characters", MinimumLength = 24)]
string guid) string guid)
{ {
await _service.DeleteManyAsync(new[] {guid}); await Task.WhenAll(_feedbackReceiverService.DeleteManyAsync(new[] {guid}),
_tokensService.DeleteManyByFeedbackReceiverIdAsync(new[] {guid}));
return NoContent(); return NoContent();
} }
@ -103,7 +109,7 @@ namespace Retroactiune.Controllers
[StringLength(24, ErrorMessage = "invalid guid, must be 24 characters", MinimumLength = 24)] [StringLength(24, ErrorMessage = "invalid guid, must be 24 characters", MinimumLength = 24)]
string guid) string guid)
{ {
var result = await _service.FindAsync(new[] {guid}); var result = await _feedbackReceiverService.FindAsync(new[] {guid});
var feedbackReceivers = result as FeedbackReceiver[] ?? result.ToArray(); var feedbackReceivers = result as FeedbackReceiver[] ?? result.ToArray();
if (!feedbackReceivers.Any()) if (!feedbackReceivers.Any())
{ {
@ -134,7 +140,7 @@ namespace Retroactiune.Controllers
[RangeAttribute(1, 1000, ErrorMessage = "limit is out of range, allowed ranges [1-1000]"), FromQuery] [RangeAttribute(1, 1000, ErrorMessage = "limit is out of range, allowed ranges [1-1000]"), FromQuery]
int limit) int limit)
{ {
return Ok(await _service.FindAsync(filter, offset, limit)); return Ok(await _feedbackReceiverService.FindAsync(filter, offset, limit));
} }
/// <summary> /// <summary>
@ -151,7 +157,9 @@ namespace Retroactiune.Controllers
{ {
try try
{ {
await _service.DeleteManyAsync(ids); var feedbackReceiverIds = ids as string[] ?? ids.ToArray();
await Task.WhenAll(_feedbackReceiverService.DeleteManyAsync(feedbackReceiverIds),
_tokensService.DeleteManyByFeedbackReceiverIdAsync(feedbackReceiverIds));
return NoContent(); return NoContent();
} }
catch (GenericServiceException e) catch (GenericServiceException e)

View file

@ -39,7 +39,7 @@ namespace Retroactiune
// Services // Services
services.AddSingleton<IFeedbackReceiverService, FeedbackReceiverService>(); services.AddSingleton<IFeedbackReceiverService, FeedbackReceiverService>();
services.AddSingleton<ITokensService, TokenService>(); services.AddSingleton<ITokensService, TokensService>();
services.AddSingleton<IMongoClient, MongoClient>(i => services.AddSingleton<IMongoClient, MongoClient>(i =>
{ {
var settings = i.GetService<IOptions<DatabaseSettings>>(); var settings = i.GetService<IOptions<DatabaseSettings>>();

View file

@ -35,7 +35,7 @@ namespace Retroactiune
// Services // Services
services.AddSingleton<IFeedbackReceiverService, FeedbackReceiverService>(); services.AddSingleton<IFeedbackReceiverService, FeedbackReceiverService>();
services.AddSingleton<ITokensService, TokenService>(); services.AddSingleton<ITokensService, TokensService>();
services.AddSingleton<IMongoClient, MongoClient>(i => services.AddSingleton<IMongoClient, MongoClient>(i =>
{ {
var settings = i.GetService<IOptions<DatabaseSettings>>(); var settings = i.GetService<IOptions<DatabaseSettings>>();