diff --git a/EntityFramework_LoL/Sources/API_LoL_Project/Controllers/Request/PageRequest.cs b/EntityFramework_LoL/Sources/API_LoL_Project/Controllers/Request/PageRequest.cs index 69f2237..30e7031 100644 --- a/EntityFramework_LoL/Sources/API_LoL_Project/Controllers/Request/PageRequest.cs +++ b/EntityFramework_LoL/Sources/API_LoL_Project/Controllers/Request/PageRequest.cs @@ -5,7 +5,7 @@ public string? orderingPropertyName { get; set; } = null; public bool? descending { get; set; } = false; public int index { get; set; } = 0; - public int count { get; set; } = 1; + public int count { get; set; } = 0; } diff --git a/EntityFramework_LoL/Sources/API_LoL_Project/Controllers/version2/ChampionsController.cs b/EntityFramework_LoL/Sources/API_LoL_Project/Controllers/version2/ChampionsController.cs index 58fa3c9..d922a9a 100644 --- a/EntityFramework_LoL/Sources/API_LoL_Project/Controllers/version2/ChampionsController.cs +++ b/EntityFramework_LoL/Sources/API_LoL_Project/Controllers/version2/ChampionsController.cs @@ -9,7 +9,8 @@ using System.Linq; using System.Text.Json; using System.Xml.Linq; using ApiMappeur; - +using Shared; +using Microsoft.OpenApi.Extensions; namespace API_LoL_Project.Controllers.version2 { @@ -42,8 +43,9 @@ namespace API_LoL_Project.Controllers.version2 return BadRequest("To many object is asked the max is : " + totalcount); } - _logger.LogInformation("Executing {Action} with parameters: {Parameters}", nameof(Get), request); ; - var champions = await dataManager.GetItems(request.index, request.count, request.orderingPropertyName, request.descending == null ? false : (bool)request.descending); + _logger.LogInformation("Executing {Action} with parameters: {Parameters}", nameof(Get), request); + + var champions = await dataManager.GetItems(request.index, request.count == 0 ? totalcount : (int)request.count , request.orderingPropertyName, request.descending == null ? false : (bool)request.descending); IEnumerable res = champions.Select(c => c.ToDTO()); if (res.Count() <= 0 || res == null) { @@ -158,7 +160,7 @@ namespace API_LoL_Project.Controllers.version2 return BadRequest("No chamions found with this name: " + name + "in the dataContext"); } var champion = await dataManager.GetItemsByName(name, 0, totalcount); - _logger.LogError($"========================= {champion} ================================================"); ; + _logger.LogInformation($"========================= {champion} ================================================"); ; if (champion.Count() <= 0 || champion == null) { @@ -172,10 +174,14 @@ namespace API_LoL_Project.Controllers.version2 r, new List { - EndPointLink.To($"/api/[controller]/{r.Name}/{nameof(GetChampionsImage)}", "self"), - EndPointLink.To($"/api/[controller]/{r.Name}/{nameof(GetChampionsByName)}", "self"), - EndPointLink.To($"/api/[controller]/{r.Name}/{nameof(Post)}", "self","POST"), - EndPointLink.To($"/api/[controller]/{r.Name}/{nameof(Put)}", "self","PUT"), + EndPointLink.To($"/api/[controller]/{r.Name}", "self"), + EndPointLink.To($"/api/[controller]/{r.Name}", "self"), + EndPointLink.To($"/api/[controller]/{r.Name}", "self","POST"), + EndPointLink.To($"/api/[controller]/{r.Name}", "self","PUT"), + EndPointLink.To($"/api/[controller]/{r.Name}/characteristic", "self"), + EndPointLink.To($"/api/[controller]/{r.Name}/characteristic", "self"), + + } )); @@ -233,12 +239,22 @@ namespace API_LoL_Project.Controllers.version2 { try { + if (value == null) { var message = string.Format("Can not get champions image without the name (is empty)"); _logger.LogWarning(message); ; return BadRequest(message); } + /* + * cannot use this GetNbItemsByName and GetItemsByName use Contains and not equals + * var totalcount = await dataManager.GetNbItemsByName(value.Name); + if (totalcount >= 0) + { + _logger.LogError("champions found with this name {name} in the dataContext | cannot add an champions with the same Name", value.Name); ; + return BadRequest("chamions this name: " + value.Name + " already exist in the dataContext champions need to have unique name"); + }*/ + // generic validation check if all field is good var newChampion = value.ToModel(); await dataManager.AddItem(newChampion); @@ -256,7 +272,7 @@ namespace API_LoL_Project.Controllers.version2 catch (Exception e) { _logger.LogError("Somthing goes wrong caching the Champions controller : " + e.Message); - return BadRequest(e.Message); + return BadRequest(e.Message + e.InnerException); } @@ -390,6 +406,83 @@ namespace API_LoL_Project.Controllers.version2 var nbChampions = await dataManager.GetNbItems(); return Ok(nbChampions); } + [HttpGet("count/class/{championClass}")] + public async Task> GetChampionCountByClass(ChampionClass championClass) + { + try + { + _logger.LogInformation("Executing {Action} with parameters: {Parameters}", nameof(GetChampionCountByClass), championClass.GetDisplayName()); + + var count = await dataManager.GetNbItemsByClass(championClass); + + + return Ok(count); + } + catch (Exception e) + { + _logger.LogError("Something went wrong while fetching the count of champions by class in the controller: " + e.Message); + return BadRequest(e.Message); + } + } + + [HttpGet("count/name/{substring}")] + public async Task> GetNbItemsByName(string substring) + { + try + { + _logger.LogInformation("Executing {Action} with parameters: {Substring}", nameof(GetNbItemsByName), substring); + + var count = await dataManager.GetNbItemsByName(substring); + + return Ok(count); + } + catch (Exception e) + { + _logger.LogError("Something went wrong in {Action} action: {ErrorMessage}", nameof(GetNbItemsByName), e.Message); + return BadRequest(e.Message); + } + } + + + [HttpGet("characteristic/{characteristic}")] + public async Task>> GetChampionByCharacteristic(string characteristic, [FromQuery] Request.PageRequest request) + { + try + { + _logger.LogInformation("Executing {Action} with parameters: {Parameters} ", nameof(GetChampionByCharacteristic), characteristic + " / " + request); + + var champions = await dataManager.GetItemsByCharacteristic(characteristic, request.index, request.count == 0 ? await dataManager.GetNbItems() : (int)request.count, request.orderingPropertyName, request.descending == null ? false : (bool)request.descending); + + IEnumerable res = champions.Select(c => c.ToDTO()); + if (res.Count() <= 0 || res == null) + { + _logger.LogError("No champions found for characteristic {Characteristic}", characteristic); + return BadRequest("No champions found for characteristic : " + characteristic); + } + + var respList = res.Select(r => new LolResponse + ( + r, + new List + { + EndPointLink.To($"/api/[controller]/{r.Name}/{nameof(GetChampionsImage)}", "self"), + EndPointLink.To($"/api/[controller]/{r.Name}/{nameof(GetChampionsByName)}", "self"), + EndPointLink.To($"/api/[controller]/{r.Name}/{nameof(Post)}", "self","POST"), + EndPointLink.To($"/api/[controller]/{r.Name}/{nameof(Put)}", "self","PUT"), + } + )); + + var totalcount = await dataManager.GetNbItemsByCharacteristic(characteristic); + var pageResponse = new PageResponse(respList, request.index, request.count, totalcount); + + return Ok(pageResponse); + } + catch (Exception e) + { + _logger.LogError("Somthing goes wrong caching the Champions controller : " + e.Message); + return BadRequest(e.Message); + } + } diff --git a/EntityFramework_LoL/Sources/API_LoL_Project/Entities.LolDatabase.db b/EntityFramework_LoL/Sources/API_LoL_Project/Entities.LolDatabase.db index c7e68ec..9126739 100644 Binary files a/EntityFramework_LoL/Sources/API_LoL_Project/Entities.LolDatabase.db and b/EntityFramework_LoL/Sources/API_LoL_Project/Entities.LolDatabase.db differ diff --git a/EntityFramework_LoL/Sources/API_LoL_Project/Entities.LolDatabase.db-shm b/EntityFramework_LoL/Sources/API_LoL_Project/Entities.LolDatabase.db-shm index d13c8ac..e06efcc 100644 Binary files a/EntityFramework_LoL/Sources/API_LoL_Project/Entities.LolDatabase.db-shm and b/EntityFramework_LoL/Sources/API_LoL_Project/Entities.LolDatabase.db-shm differ diff --git a/EntityFramework_LoL/Sources/API_LoL_Project/Entities.LolDatabase.db-wal b/EntityFramework_LoL/Sources/API_LoL_Project/Entities.LolDatabase.db-wal index 4e1e31d..ed5971c 100644 Binary files a/EntityFramework_LoL/Sources/API_LoL_Project/Entities.LolDatabase.db-wal and b/EntityFramework_LoL/Sources/API_LoL_Project/Entities.LolDatabase.db-wal differ diff --git a/EntityFramework_LoL/Sources/ApiLib/ApiManager.cs b/EntityFramework_LoL/Sources/ApiLib/ApiManager.cs index a479a2c..dd4b776 100644 --- a/EntityFramework_LoL/Sources/ApiLib/ApiManager.cs +++ b/EntityFramework_LoL/Sources/ApiLib/ApiManager.cs @@ -11,14 +11,14 @@ namespace ApiLib public ApiManager(HttpClient httpClient) { ChampionsMgr = new ChampionsManager(this); - /* SkinsMgr = new SkinsManager(this); - RunesMgr = new RunesManager(this); + SkinsMgr = new SkinsManager(this); + /*RunesMgr = new RunesManager(this); RunePagesMgr = new RunePagesManager(this);*/ HttpClient = httpClient; -/* HttpClient.BaseAddress = new Uri("https://codefirst.iut.uca.fr/containers/arthurvalin-lolcontainer/api"); -*/ + HttpClient.BaseAddress = new Uri("https://codefirst.iut.uca.fr/containers/arthurvalin-lolcontainer/api/v2"); + } public IChampionsManager ChampionsMgr { get; } diff --git a/EntityFramework_LoL/Sources/ApiLib/ChampionsManager.cs b/EntityFramework_LoL/Sources/ApiLib/ChampionsManager.cs index 9aa2f56..f56b0f0 100644 --- a/EntityFramework_LoL/Sources/ApiLib/ChampionsManager.cs +++ b/EntityFramework_LoL/Sources/ApiLib/ChampionsManager.cs @@ -30,7 +30,9 @@ namespace ApiLib { try { - var response = await parent.HttpClient.PostAsJsonAsync("champions", item.toFullDTO()); + if (item == null) throw new ArgumentNullException("Champions is null cannot add empty"); + + var response = await parent.HttpClient.PostAsJsonAsync("/champions", item.toFullDTO()); if (response.IsSuccessStatusCode || response.StatusCode == HttpStatusCode.Created)// mayby changer to check the status code is more secure i think { @@ -72,11 +74,13 @@ namespace ApiLib { try { - HttpResponseMessage response = await parent.HttpClient.DeleteAsync($"https://localhost:7234/api/Crafting/{item?.Name}"); + if (item == null) throw new ArgumentNullException("Champions is null cannot add empty"); + + HttpResponseMessage response = await parent.HttpClient.DeleteAsync($"champions/{item.Name}"); if (response.IsSuccessStatusCode) { - Console.WriteLine("Champion {0} deleted", item?.Name); + Console.WriteLine("Champion {0} deleted", item.Name); return true; } else @@ -115,7 +119,7 @@ namespace ApiLib } } - var response = await parent.HttpClient.GetAsync($"https://codefirst.iut.uca.fr/containers/arthurvalin-lolcontainer/api/champions{queryString}"); + var response = await parent.HttpClient.GetAsync($"/champions{queryString}"); if (response.IsSuccessStatusCode) { @@ -152,13 +156,16 @@ namespace ApiLib { try { - HttpResponseMessage response = await parent.HttpClient.GetAsync($"https://localhost:7234/api/Crafting/characteristic/{charName}?index={index}&count={count}&orderingPropertyName={orderingPropertyName}&descending={descending}"); + HttpResponseMessage response = await parent.HttpClient.GetAsync($"/champions/characteristic/{charName}?index={index}&count={count}&orderingPropertyName={orderingPropertyName}&descending={descending}"); if (response.IsSuccessStatusCode) { - List champions = await response.Content.ReadFromJsonAsync>(); + + List champions = await response.Content.ReadFromJsonAsync>(); Console.WriteLine($"Retrieved {champions.Count} champions with characteristic {charName}"); - return champions; + IEnumerable res = champions.Select(c => c.ToModel()); + + return res; } else { @@ -186,7 +193,7 @@ namespace ApiLib public async Task> GetItemsByClass(ChampionClass championClass, int index, int count, string? orderingPropertyName = null, bool descending = false) { var queryString = new StringBuilder(); - queryString.Append($"Class={championClass}"); + queryString.Append($"class={championClass}"); queryString.Append($"&Index={index}"); queryString.Append($"&Count={count}"); @@ -196,7 +203,7 @@ namespace ApiLib queryString.Append($"&Descending={descending}"); } - var uri = new UriBuilder("https://localhost:7234/api/Crafting") + var uri = new UriBuilder("/champions/") { Query = queryString.ToString() }.Uri; @@ -207,8 +214,10 @@ namespace ApiLib var response = await parent.HttpClient.GetAsync(uri); if (response.IsSuccessStatusCode) { - var champions = await response.Content.ReadFromJsonAsync>(); - return champions; + var champions = await response.Content.ReadFromJsonAsync>(); + IEnumerable res = champions.Select(c => c.ToModel()); + + return res; } else { @@ -249,7 +258,7 @@ namespace ApiLib } }*/ - Uri uri = new Uri($"https://codefirst.iut.uca.fr/containers/arthurvalin-lolcontainer/api/champions/{substring}"); + Uri uri = new Uri($"/champions/{substring}"); var response = await parent.HttpClient.GetAsync(uri); if (response.IsSuccessStatusCode) @@ -314,7 +323,7 @@ namespace ApiLib queryString += $"&{runePageQueryString}"; } } - Uri uri = new Uri($"https://localhost:7234/api/Crafting{queryString}"); + Uri uri = new Uri($"/champions/runePage{queryString}"); var response = await parent.HttpClient.GetAsync(uri); @@ -363,7 +372,7 @@ namespace ApiLib int count = 0; try { - var response = await parent.HttpClient.GetAsync("https://localhost:7234/api/Crafting/Count"); + var response = await parent.HttpClient.GetAsync("/champions/count"); if (response.IsSuccessStatusCode) { @@ -388,7 +397,7 @@ namespace ApiLib try { - var response = await parent.HttpClient.GetAsync($"https://localhost:7234/api/Champion/CountByCharacteristic/{charName}"); + var response = await parent.HttpClient.GetAsync($"/champions/count/characteristic/{charName}"); if (response.IsSuccessStatusCode) { string responseBody = await response.Content.ReadAsStringAsync(); @@ -420,7 +429,7 @@ namespace ApiLib try { - var response = await parent.HttpClient.GetAsync($"https://localhost:7234/api/Champion/CountByClass/{championClass}"); + var response = await parent.HttpClient.GetAsync($"/champions/count/class/{championClass}"); if (response.IsSuccessStatusCode) { string responseBody = await response.Content.ReadAsStringAsync(); @@ -452,7 +461,7 @@ namespace ApiLib try { - var response = await parent.HttpClient.GetAsync($"https://localhost:7234/api/Champion/CountByName/{substring}"); + var response = await parent.HttpClient.GetAsync($"champions/count/name/{substring}"); if (response.IsSuccessStatusCode) { string responseBody = await response.Content.ReadAsStringAsync(); @@ -485,7 +494,7 @@ namespace ApiLib try { - string requestUri = "https://localhost:7234/api/Champion/CountByRunePage"; + string requestUri = "/champions/count/runePage"; if (runePage != null) { @@ -547,7 +556,7 @@ namespace ApiLib } try { - var response = await parent.HttpClient.PutAsJsonAsync($"https://localhost:7234/api/Champion/{oldItem.Name}", newItem); + var response = await parent.HttpClient.PutAsJsonAsync($"/champions/{oldItem.Name}", newItem); if (response.IsSuccessStatusCode) { var updatedChampion = await response.Content.ReadFromJsonAsync(); diff --git a/EntityFramework_LoL/Sources/ApiLib/SkinsManager.cs b/EntityFramework_LoL/Sources/ApiLib/SkinsManager.cs new file mode 100644 index 0000000..db4eed5 --- /dev/null +++ b/EntityFramework_LoL/Sources/ApiLib/SkinsManager.cs @@ -0,0 +1,201 @@ +using Model; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http.Json; +using System.Net; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +using DTO; +using ApiMappeur; + +namespace ApiLib +{ + public partial class ApiManager + { + public class SkinsManager : ISkinsManager + { + private readonly ApiManager parent; + + public SkinsManager(ApiManager parent) + => this.parent = parent; + + public async Task AddItem(Skin? item) + { + try + { + if (item == null) throw new ArgumentNullException("Skin is null cannot add empty"); + + var response = await parent.HttpClient.PostAsJsonAsync("/skins", item); + + if (response.IsSuccessStatusCode || response.StatusCode == HttpStatusCode.Created) + { + Skin newSkin = await response.Content.ReadFromJsonAsync(); + + Console.WriteLine("Skin {0} inserted", newSkin.Name); + return newSkin; + } + else + { + Console.WriteLine($"Failed to add item. Status code: {response.StatusCode}. Reason: {response.ReasonPhrase}"); + return null; + } + } + catch (HttpRequestException ex) + { + Console.WriteLine($"Failed to add item. {ex.Message}"); + return null; + } + catch (JsonException ex) + { + Console.WriteLine($"Failed to add item. Error while serializing JSON data. {ex.Message}"); + return null; + } + catch (Exception ex) + { + Console.WriteLine($"Failed to add item. {ex.Message}"); + return null; + } + } + + public async Task DeleteItem(Skin? item) + { + try + { + if (item == null) throw new ArgumentNullException("Skin is null cannot delete empty"); + + var response = await parent.HttpClient.DeleteAsync($"/skins/{item.Name}"); + + if (response.IsSuccessStatusCode) + { + Console.WriteLine("Skin {0} deleted", item.Name); + return true; + } + else + { + Console.WriteLine($"Failed to delete item. Status code: {response.StatusCode}. Reason: {response.ReasonPhrase}"); + return false; + } + } + catch (HttpRequestException ex) + { + Console.WriteLine($"Failed to delete item. {ex.Message}"); + return false; + } + catch (Exception ex) + { + Console.WriteLine($"Failed to delete item. {ex.Message}"); + return false; + } + } + + public async Task> GetItems(int index, int count, string? orderingPropertyName = null, bool descending = false) + { + try + { + string uri = $"/skins?index={index}&count={count}"; + if (!string.IsNullOrEmpty(orderingPropertyName)) + { + uri += $"&orderingPropertyName={orderingPropertyName}&descending={descending}"; + } + + var response = await parent.HttpClient.GetAsync(uri); + + if (response.IsSuccessStatusCode) + { + IEnumerable skins = await response.Content.ReadFromJsonAsync>(); + return skins; + } + else + { + Console.WriteLine($"Failed to get items. Status code: {response.StatusCode}. Reason: {response.ReasonPhrase}"); + return Enumerable.Empty(); + } + } + catch (HttpRequestException ex) + { + Console.WriteLine($"Failed to get items. {ex.Message}"); + return Enumerable.Empty(); + } + catch (Exception ex) + { + Console.WriteLine($"Failed to get items. {ex.Message}"); + return Enumerable.Empty(); + } + } + + public async Task> GetItemsByChampion(Champion? champion, int index, int count, string? orderingPropertyName = null, bool descending = false) + { + try + { + if (champion == null) throw new ArgumentNullException(nameof(champion), "Champion is null"); + + // Build the query string with the specified parameters + string queryString = $"?champion={champion.Name}&index={index}&count={count}"; + if (!string.IsNullOrEmpty(orderingPropertyName)) queryString += $"&orderingPropertyName={orderingPropertyName}&descending={descending}"; + + var response = await parent.HttpClient.GetAsync($"/skins{queryString}"); + + if (response.IsSuccessStatusCode) + { + IEnumerable skins = await response.Content.ReadFromJsonAsync>(); + IEnumerable res = skins.Select(s => s.ToModel()); + + return res; + + } + else + { + // Log the error status code and reason phrase + Console.WriteLine($"Failed to get items by champion. Status code: {response.StatusCode}. Reason: {response.ReasonPhrase}"); + return null; + } + } + catch (HttpRequestException ex) + { + // Log the error message from the HttpClient exception + Console.WriteLine($"Failed to get items by champion. {ex.Message}"); + return null; + } + catch (JsonException ex) + { + // Log the error message from the JSON serialization exception + Console.WriteLine($"Failed to get items by champion. Error while deserializing JSON data. {ex.Message}"); + return null; + } + catch (Exception ex) + { + // Log any other exceptions that may occur + Console.WriteLine($"Failed to get items by champion. {ex.Message}"); + return null; + } + } + + public Task> GetItemsByName(string substring, int index, int count, string? orderingPropertyName = null, bool descending = false) + { + throw new NotImplementedException(); + } + + public Task GetNbItems() + { + throw new NotImplementedException(); + } + + public Task GetNbItemsByChampion(Champion? champion) + { + throw new NotImplementedException(); + } + + public Task GetNbItemsByName(string substring) + { + throw new NotImplementedException(); + } + + public Task UpdateItem(Skin? oldItem, Skin? newItem) + { + throw new NotImplementedException(); + } + } + } +} diff --git a/EntityFramework_LoL/Sources/ApiMappeur/ChampionMapper.cs b/EntityFramework_LoL/Sources/ApiMappeur/ChampionMapper.cs index 83481f1..43d10b6 100644 --- a/EntityFramework_LoL/Sources/ApiMappeur/ChampionMapper.cs +++ b/EntityFramework_LoL/Sources/ApiMappeur/ChampionMapper.cs @@ -51,12 +51,14 @@ namespace ApiMappeur return new ChampionFullDTO() { Name = item.Name, + Characteristics = item.Characteristics, Bio = item.Bio, Skills = item.Skills, Class = item.Class, Skins = item.Skins.Select(i => i.ToDto()), - LargeImage = item.Image.ToDTO() - + LargeImage = item.Image.ToDTO(), + Icon = item.Icon, + }; } @@ -71,10 +73,29 @@ namespace ApiMappeur throw new Exception(message); } - return new Champion(dto.Name, dto.Class, dto.Icon, dto.LargeImage.base64, dto.Bio); + var champion = new Champion(dto.Name, dto.Class, dto.Icon,dto?.LargeImage?.base64 ?? "", dto.Bio); + + champion.AddCharacteristics(dto.Characteristics?.Select(kv => Tuple.Create(kv.Key, kv.Value)).ToArray() ?? Array.Empty>()); + + if (dto.Skills != null) + { + foreach (var skill in dto.Skills) + { + champion.AddSkill(skill); + } + } + + /* if (dto.Skins != null) + { + foreach (var skinDto in dto.Skins) + { + var skin = new Skin(skinDto.Name, dto.ToModel()); + champion.AddSkin(skin); + } + }*/ + return champion; - ; } public static Champion ToModel(this ChampionDTO dto) { diff --git a/EntityFramework_LoL/Sources/ApiMappeur/SkinMapper.cs b/EntityFramework_LoL/Sources/ApiMappeur/SkinMapper.cs index a325e26..e9d1c3f 100644 --- a/EntityFramework_LoL/Sources/ApiMappeur/SkinMapper.cs +++ b/EntityFramework_LoL/Sources/ApiMappeur/SkinMapper.cs @@ -18,12 +18,20 @@ namespace ApiMappeur return new SkinDto() { Name = item.Name, + LargeImage = item.Image.ToDTO(), Description = item.Description, Icon = item.Icon, - Price = item.Price + Price = item.Price, + Champion = item.Champion.Name }; } + public static Skin ToModel(this SkinDto item) + { + + var image = item?.LargeImage?.base64 ?? ""; + return new(item?.Name ?? "", null, item?.Price ?? -1, image, item?.Description ?? ""); + } } } diff --git a/EntityFramework_LoL/Sources/DTO/SkinDto.cs b/EntityFramework_LoL/Sources/DTO/SkinDto.cs index 2c3962b..c4ae667 100644 --- a/EntityFramework_LoL/Sources/DTO/SkinDto.cs +++ b/EntityFramework_LoL/Sources/DTO/SkinDto.cs @@ -8,10 +8,13 @@ namespace DTO { public class SkinDto { + public string Champion { get; set; } public string Name { get; set; } public string Description { get; set; } public string Icon { get; set; } public float Price { get; set; } + public ImageDTO LargeImage { get; set; } + } } diff --git a/EntityFramework_LoL/Sources/Model/Champion.cs b/EntityFramework_LoL/Sources/Model/Champion.cs index 9b7e96d..16fdd3c 100644 --- a/EntityFramework_LoL/Sources/Model/Champion.cs +++ b/EntityFramework_LoL/Sources/Model/Champion.cs @@ -63,7 +63,7 @@ public class Champion : IEquatable public ImmutableHashSet Skills => skills.ToImmutableHashSet(); private HashSet skills = new HashSet(); - internal bool AddSkin(Skin skin) + public bool AddSkin(Skin skin) { if (skins.Contains(skin)) return false; diff --git a/EntityFramework_LoL/Sources/StubLib/StubData.Champions.cs b/EntityFramework_LoL/Sources/StubLib/StubData.Champions.cs index 8ed1220..728c006 100644 --- a/EntityFramework_LoL/Sources/StubLib/StubData.Champions.cs +++ b/EntityFramework_LoL/Sources/StubLib/StubData.Champions.cs @@ -15,8 +15,9 @@ namespace StubLib new Champion("Bard", ChampionClass.Support), new Champion("Alistar", ChampionClass.Tank), }; + - public class ChampionsManager : IChampionsManager + public class ChampionsManager : IChampionsManager { private readonly StubData parent; diff --git a/EntityFramework_LoL/Sources/StubLib/StubData.cs b/EntityFramework_LoL/Sources/StubLib/StubData.cs index 8e34486..493062a 100644 --- a/EntityFramework_LoL/Sources/StubLib/StubData.cs +++ b/EntityFramework_LoL/Sources/StubLib/StubData.cs @@ -29,7 +29,5 @@ public partial class StubData : IDataManager championsAndRunePages.Add(Tuple.Create(champions[0], runePages[0])); } - - } diff --git a/EntityFramework_LoL/Sources/Test_Api/ChampionControllerTest.cs b/EntityFramework_LoL/Sources/Test_Api/ChampionControllerTest.cs index 68beed7..7e274ba 100644 --- a/EntityFramework_LoL/Sources/Test_Api/ChampionControllerTest.cs +++ b/EntityFramework_LoL/Sources/Test_Api/ChampionControllerTest.cs @@ -8,6 +8,7 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Model; +using Shared; using StubLib; using System.Net; @@ -27,11 +28,12 @@ namespace Test_Api championCtrl = new ChampionsController(stubMgr, logger); } - /* [TestMethod] + [TestMethod] public async Task TestGetChampions() { + var totalcountTest = await stubMgr.ChampionsMgr.GetNbItems(); - + // Arrange var request = new PageRequest { index = 0, @@ -40,101 +42,115 @@ namespace Test_Api descending = false }; - var totalcountTest = await stubMgr.ChampionsMgr.GetNbItems(); + // Create some test data + var champions = new List + { + + new Champion("Brand", ChampionClass.Mage), + new Champion("Caitlyn", ChampionClass.Marksman), + new Champion("Cassiopeia", ChampionClass.Mage) + }; + foreach (var c in champions) + { + await stubMgr.ChampionsMgr.AddItem(c); + } // Act - var getResult = await championCtrl.Get(request); - - // Assert - Assert.IsInstanceOfType(getResult, typeof(OkObjectResult)); + Assert.IsInstanceOfType(getResult.Result, typeof(OkObjectResult)); var objectRes = getResult.Result as OkObjectResult; - Assert.AreEqual(200, objectRes.StatusCode); - Assert.IsNotNull(objectRes); - var champions = objectRes?.Value as IEnumerable; - - Assert.IsNotNull(champions); - - Assert.IsInstanceOfType(objectRes.Value, typeof(PageResponse)); var pageResponse = objectRes.Value as PageResponse; - Assert.AreEqual(totalcountTest, pageResponse.TotalCount); - Assert.AreEqual(totalcountTest, pageResponse.Data.Count()); - + Assert.IsNotNull(pageResponse); + Assert.IsInstanceOfType(pageResponse, typeof(PageResponse)); + Assert.AreEqual(totalcountTest + champions.Count, pageResponse.TotalCount); + Assert.AreEqual(totalcountTest + champions.Count, pageResponse.Data.Count()); - *//* Assert.AreEqual(1, pageResponse.Data[.Data.Id); - *//* Assert.AreEqual("Champion1", pageResponse.Items[0].Data.Name); - *//* Assert.AreEqual(2, pageResponse.Items[1].Data.Id); - *//* Assert.AreEqual("Champion2", pageResponse.Items[1].Data.Name); - */ - /* - Assert.AreEqual(champions.Count(), await stubMgr.ChampionsMgr.GetNbItems());*//* + var endpoints = pageResponse.Data.Select(r => r.Links); + foreach (var endpointList in endpoints) + { + Assert.AreEqual(4, endpointList.Count()); + Assert.IsTrue(endpointList.Any(e => e.Href.Contains("/api/[controller]/"))); + } + var championsDTO = pageResponse.Data.Select(r => r.Data); + foreach (var c in championsDTO) + { + Assert.IsInstanceOfType(c, typeof(ChampionDTO)); + } } + [TestMethod] + public async Task TestGetChampions_When_Count_Index_Too_High() + { - [TestMethod] - public async Task TestGetChampions_When_Count_Index_Too_High() - { - - var totalcountTest = await stubMgr.ChampionsMgr.GetNbItems(); + var totalcountTest = await stubMgr.ChampionsMgr.GetNbItems(); - var request = new PageRequest - { - index = 999, - count = 9, - orderingPropertyName = "Name", - descending = false - }; - + var request = new PageRequest + { + index = 999, + count = 9, + orderingPropertyName = "Name", + descending = false + }; + // Act + var getResult = await championCtrl.Get(request); + // Assert + var badRequestResult = getResult.Result as BadRequestObjectResult; + Assert.IsNotNull(badRequestResult); + Assert.AreEqual($"To many object is asked the max is : {totalcountTest}", badRequestResult.Value); + } - // Act - var getResult = await championCtrl.Get(request); + [TestMethod] + public async Task TestGetBadRequest_WhenNoChampionsFound() + { - // Assert - var badRequestResult = getResult.Result as BadRequestObjectResult; - Assert.IsNotNull(badRequestResult); - Assert.AreEqual("To many object is asked the max is : {totalcountTest}", badRequestResult.Value); + // need to be empty + List champions = new() + { + new Champion("Akali", ChampionClass.Assassin), + new Champion("Aatrox", ChampionClass.Fighter), + new Champion("Ahri", ChampionClass.Mage), + new Champion("Akshan", ChampionClass.Marksman), + new Champion("Bard", ChampionClass.Support), + new Champion("Alistar", ChampionClass.Tank), + }; + foreach(var c in champions) + { + stubMgr.ChampionsMgr.DeleteItem(c); } + - - [TestMethod] - public async Task TestGetBadRequest_WhenNoChampionsFound() + var request = new PageRequest { - - var totalcountTest = await stubMgr.ChampionsMgr.GetNbItems(); - // need to be empty - - var request = new PageRequest - { - index = 0, - count = 10, - orderingPropertyName = "Name", - descending = false - }; + index = 0, + count = 10, + orderingPropertyName = "Name", + descending = false + }; - // Act + // Act - var getResult = await championCtrl.Get(request); - Console.WriteLine(getResult); - // Assert - var badRequestResult = getResult.Result as BadRequestObjectResult; - Assert.IsNotNull(badRequestResult); - Assert.AreEqual("No chamions found : totalcount is : 0", badRequestResult.Value); - } + var getResult = await championCtrl.Get(request); + Console.WriteLine(getResult); + // Assert + var badRequestResult = getResult.Result as BadRequestObjectResult; + Assert.IsNotNull(badRequestResult); + Assert.AreEqual("To many object is asked the max is : 0", badRequestResult.Value); + } - */ + - /* + /* [TestMethod] public async Task TestPostChampions() { @@ -191,6 +207,17 @@ namespace Test_Api } + + + + + + + + + + + */