Skip to content

Commit

Permalink
Removes redundant database call
Browse files Browse the repository at this point in the history
  • Loading branch information
A-Guldborg committed Nov 27, 2023
1 parent 636d6ae commit 04b4419
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 7 deletions.
9 changes: 2 additions & 7 deletions coffeecard/CoffeeCard.Library/Services/v2/ProductService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -81,18 +81,13 @@ public async Task<ChangedProductResponse> AddProduct(AddProductRequest newProduc
Visible = newProduct.Visible
};

_context.Products.Add(product);
await _context.SaveChangesAsync();

var productUserGroups = newProduct.AllowedUserGroups.Select(userGroup => new ProductUserGroup
product.ProductUserGroup = newProduct.AllowedUserGroups.Select(userGroup => new ProductUserGroup
{
ProductId = product.Id,
UserGroup = userGroup
}).ToList();

_context.ProductUserGroups.AddRange(productUserGroups);


_context.Products.Add(product);
await _context.SaveChangesAsync();

var result = new ChangedProductResponse
Expand Down
43 changes: 43 additions & 0 deletions coffeecard/CoffeeCard.Tests.Unit/Services/v2/ProductServiceTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -81,5 +81,48 @@ await productService.UpdateProduct(new UpdateProductRequest()
e => e.Equals(UserGroup.Customer),
e => e.Equals(UserGroup.Board));
}

[Fact(DisplayName = "AddProduct adds only selected user groups")]
public async Task AddProduct_Sets_Correct_UserGroups()
{
var builder = new DbContextOptionsBuilder<CoffeeCardContext>()
.UseInMemoryDatabase(nameof(AddProduct_Sets_Correct_UserGroups));

var databaseSettings = new DatabaseSettings
{
SchemaName = "test"
};
var environmentSettings = new EnvironmentSettings()
{
EnvironmentType = EnvironmentType.Test
};

await using var context = new CoffeeCardContext(builder.Options, databaseSettings, environmentSettings);

using var productService = new ProductService(context);

var p = new AddProductRequest
{
Name = "Coffee",
Description = "Coffee Clip card",
NumberOfTickets = 10,
Price = 10,
Visible = true,
AllowedUserGroups = new List<UserGroup> { UserGroup.Manager, UserGroup.Board }
};

await productService.AddProduct(p);

var expected = new List<UserGroup>
{
UserGroup.Manager, UserGroup.Board
};

var result = await productService.GetProductAsync(1);

Assert.Collection<UserGroup>(expected,
e => e.Equals(UserGroup.Customer),
e => e.Equals(UserGroup.Board));
}
}
}

0 comments on commit 04b4419

Please sign in to comment.