test ci
continuous-integration/drone/push Build is passing Details

Dave_more
David D'ALMEIDA 2 years ago
parent 60dec6265d
commit 70ffad9cbb

@ -5,7 +5,7 @@
public string? orderingPropertyName { get; set; } = null; public string? orderingPropertyName { get; set; } = null;
public bool? descending { get; set; } = false; public bool? descending { get; set; } = false;
public int index { get; set; } = 0; public int index { get; set; } = 0;
public int count { get; set; } = 1; public int count { get; set; } = 0;
} }

@ -9,7 +9,8 @@ using System.Linq;
using System.Text.Json; using System.Text.Json;
using System.Xml.Linq; using System.Xml.Linq;
using ApiMappeur; using ApiMappeur;
using Shared;
using Microsoft.OpenApi.Extensions;
namespace API_LoL_Project.Controllers.version2 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); return BadRequest("To many object is asked the max is : " + totalcount);
} }
_logger.LogInformation("Executing {Action} with parameters: {Parameters}", nameof(Get), request); ; _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);
var champions = await dataManager.GetItems(request.index, request.count == 0 ? totalcount : (int)request.count , request.orderingPropertyName, request.descending == null ? false : (bool)request.descending);
IEnumerable<ChampionDTO> res = champions.Select(c => c.ToDTO()); IEnumerable<ChampionDTO> res = champions.Select(c => c.ToDTO());
if (res.Count() <= 0 || res == null) 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"); return BadRequest("No chamions found with this name: " + name + "in the dataContext");
} }
var champion = await dataManager.GetItemsByName(name, 0, totalcount); var champion = await dataManager.GetItemsByName(name, 0, totalcount);
_logger.LogError($"========================= {champion} ================================================"); ; _logger.LogInformation($"========================= {champion} ================================================"); ;
if (champion.Count() <= 0 || champion == null) if (champion.Count() <= 0 || champion == null)
{ {
@ -172,10 +174,14 @@ namespace API_LoL_Project.Controllers.version2
r, r,
new List<EndPointLink> new List<EndPointLink>
{ {
EndPointLink.To($"/api/[controller]/{r.Name}/{nameof(GetChampionsImage)}", "self"), EndPointLink.To($"/api/[controller]/{r.Name}", "self"),
EndPointLink.To($"/api/[controller]/{r.Name}/{nameof(GetChampionsByName)}", "self"), EndPointLink.To($"/api/[controller]/{r.Name}", "self"),
EndPointLink.To($"/api/[controller]/{r.Name}/{nameof(Post)}", "self","POST"), EndPointLink.To($"/api/[controller]/{r.Name}", "self","POST"),
EndPointLink.To($"/api/[controller]/{r.Name}/{nameof(Put)}", "self","PUT"), 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 try
{ {
if (value == null) if (value == null)
{ {
var message = string.Format("Can not get champions image without the name (is empty)"); var message = string.Format("Can not get champions image without the name (is empty)");
_logger.LogWarning(message); ; _logger.LogWarning(message); ;
return BadRequest(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 // generic validation check if all field is good
var newChampion = value.ToModel(); var newChampion = value.ToModel();
await dataManager.AddItem(newChampion); await dataManager.AddItem(newChampion);
@ -256,7 +272,7 @@ namespace API_LoL_Project.Controllers.version2
catch (Exception e) catch (Exception e)
{ {
_logger.LogError("Somthing goes wrong caching the Champions controller : " + e.Message); _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(); var nbChampions = await dataManager.GetNbItems();
return Ok(nbChampions); return Ok(nbChampions);
} }
[HttpGet("count/class/{championClass}")]
public async Task<ActionResult<int>> 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<ActionResult<int>> 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<ActionResult<PageResponse<ChampionDTO>>> 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<ChampionDTO> 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<ChampionDTO>
(
r,
new List<EndPointLink>
{
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<ChampionDTO>(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);
}
}

@ -11,14 +11,14 @@ namespace ApiLib
public ApiManager(HttpClient httpClient) public ApiManager(HttpClient httpClient)
{ {
ChampionsMgr = new ChampionsManager(this); ChampionsMgr = new ChampionsManager(this);
/* SkinsMgr = new SkinsManager(this); SkinsMgr = new SkinsManager(this);
RunesMgr = new RunesManager(this); /*RunesMgr = new RunesManager(this);
RunePagesMgr = new RunePagesManager(this);*/ RunePagesMgr = new RunePagesManager(this);*/
HttpClient = httpClient; 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; } public IChampionsManager ChampionsMgr { get; }

@ -30,7 +30,9 @@ namespace ApiLib
{ {
try 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 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 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) if (response.IsSuccessStatusCode)
{ {
Console.WriteLine("Champion {0} deleted", item?.Name); Console.WriteLine("Champion {0} deleted", item.Name);
return true; return true;
} }
else 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) if (response.IsSuccessStatusCode)
{ {
@ -152,13 +156,16 @@ namespace ApiLib
{ {
try 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) if (response.IsSuccessStatusCode)
{ {
List<Champion> champions = await response.Content.ReadFromJsonAsync<List<Champion>>();
List<ChampionDTO?> champions = await response.Content.ReadFromJsonAsync<List<ChampionDTO>>();
Console.WriteLine($"Retrieved {champions.Count} champions with characteristic {charName}"); Console.WriteLine($"Retrieved {champions.Count} champions with characteristic {charName}");
return champions; IEnumerable<Champion> res = champions.Select(c => c.ToModel());
return res;
} }
else else
{ {
@ -186,7 +193,7 @@ namespace ApiLib
public async Task<IEnumerable<Champion?>> GetItemsByClass(ChampionClass championClass, int index, int count, string? orderingPropertyName = null, bool descending = false) public async Task<IEnumerable<Champion?>> GetItemsByClass(ChampionClass championClass, int index, int count, string? orderingPropertyName = null, bool descending = false)
{ {
var queryString = new StringBuilder(); var queryString = new StringBuilder();
queryString.Append($"Class={championClass}"); queryString.Append($"class={championClass}");
queryString.Append($"&Index={index}"); queryString.Append($"&Index={index}");
queryString.Append($"&Count={count}"); queryString.Append($"&Count={count}");
@ -196,7 +203,7 @@ namespace ApiLib
queryString.Append($"&Descending={descending}"); queryString.Append($"&Descending={descending}");
} }
var uri = new UriBuilder("https://localhost:7234/api/Crafting") var uri = new UriBuilder("/champions/")
{ {
Query = queryString.ToString() Query = queryString.ToString()
}.Uri; }.Uri;
@ -207,8 +214,10 @@ namespace ApiLib
var response = await parent.HttpClient.GetAsync(uri); var response = await parent.HttpClient.GetAsync(uri);
if (response.IsSuccessStatusCode) if (response.IsSuccessStatusCode)
{ {
var champions = await response.Content.ReadFromJsonAsync<IEnumerable<Champion?>>(); var champions = await response.Content.ReadFromJsonAsync<IEnumerable<ChampionDTO?>>();
return champions; IEnumerable<Champion> res = champions.Select(c => c.ToModel());
return res;
} }
else 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); var response = await parent.HttpClient.GetAsync(uri);
if (response.IsSuccessStatusCode) if (response.IsSuccessStatusCode)
@ -314,7 +323,7 @@ namespace ApiLib
queryString += $"&{runePageQueryString}"; 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); var response = await parent.HttpClient.GetAsync(uri);
@ -363,7 +372,7 @@ namespace ApiLib
int count = 0; int count = 0;
try try
{ {
var response = await parent.HttpClient.GetAsync("https://localhost:7234/api/Crafting/Count"); var response = await parent.HttpClient.GetAsync("/champions/count");
if (response.IsSuccessStatusCode) if (response.IsSuccessStatusCode)
{ {
@ -388,7 +397,7 @@ namespace ApiLib
try 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) if (response.IsSuccessStatusCode)
{ {
string responseBody = await response.Content.ReadAsStringAsync(); string responseBody = await response.Content.ReadAsStringAsync();
@ -420,7 +429,7 @@ namespace ApiLib
try 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) if (response.IsSuccessStatusCode)
{ {
string responseBody = await response.Content.ReadAsStringAsync(); string responseBody = await response.Content.ReadAsStringAsync();
@ -452,7 +461,7 @@ namespace ApiLib
try 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) if (response.IsSuccessStatusCode)
{ {
string responseBody = await response.Content.ReadAsStringAsync(); string responseBody = await response.Content.ReadAsStringAsync();
@ -485,7 +494,7 @@ namespace ApiLib
try try
{ {
string requestUri = "https://localhost:7234/api/Champion/CountByRunePage"; string requestUri = "/champions/count/runePage";
if (runePage != null) if (runePage != null)
{ {
@ -547,7 +556,7 @@ namespace ApiLib
} }
try 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) if (response.IsSuccessStatusCode)
{ {
var updatedChampion = await response.Content.ReadFromJsonAsync<Champion>(); var updatedChampion = await response.Content.ReadFromJsonAsync<Champion>();

@ -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<Skin?> 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<Skin>();
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<bool> 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<IEnumerable<Skin?>> 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<Skin> skins = await response.Content.ReadFromJsonAsync<IEnumerable<Skin>>();
return skins;
}
else
{
Console.WriteLine($"Failed to get items. Status code: {response.StatusCode}. Reason: {response.ReasonPhrase}");
return Enumerable.Empty<Skin>();
}
}
catch (HttpRequestException ex)
{
Console.WriteLine($"Failed to get items. {ex.Message}");
return Enumerable.Empty<Skin>();
}
catch (Exception ex)
{
Console.WriteLine($"Failed to get items. {ex.Message}");
return Enumerable.Empty<Skin>();
}
}
public async Task<IEnumerable<Skin?>> 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<SkinDto> skins = await response.Content.ReadFromJsonAsync<IEnumerable<SkinDto>>();
IEnumerable<Skin> 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<IEnumerable<Skin?>> GetItemsByName(string substring, int index, int count, string? orderingPropertyName = null, bool descending = false)
{
throw new NotImplementedException();
}
public Task<int> GetNbItems()
{
throw new NotImplementedException();
}
public Task<int> GetNbItemsByChampion(Champion? champion)
{
throw new NotImplementedException();
}
public Task<int> GetNbItemsByName(string substring)
{
throw new NotImplementedException();
}
public Task<Skin?> UpdateItem(Skin? oldItem, Skin? newItem)
{
throw new NotImplementedException();
}
}
}
}

@ -51,11 +51,13 @@ namespace ApiMappeur
return new ChampionFullDTO() return new ChampionFullDTO()
{ {
Name = item.Name, Name = item.Name,
Characteristics = item.Characteristics,
Bio = item.Bio, Bio = item.Bio,
Skills = item.Skills, Skills = item.Skills,
Class = item.Class, Class = item.Class,
Skins = item.Skins.Select(i => i.ToDto()), 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); 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<Tuple<string, int>>());
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) public static Champion ToModel(this ChampionDTO dto)
{ {

@ -18,12 +18,20 @@ namespace ApiMappeur
return new SkinDto() return new SkinDto()
{ {
Name = item.Name, Name = item.Name,
LargeImage = item.Image.ToDTO(),
Description = item.Description, Description = item.Description,
Icon = item.Icon, 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 ?? "");
}
} }
} }

@ -8,10 +8,13 @@ namespace DTO
{ {
public class SkinDto public class SkinDto
{ {
public string Champion { get; set; }
public string Name { get; set; } public string Name { get; set; }
public string Description { get; set; } public string Description { get; set; }
public string Icon { get; set; } public string Icon { get; set; }
public float Price { get; set; } public float Price { get; set; }
public ImageDTO LargeImage { get; set; }
} }
} }

@ -63,7 +63,7 @@ public class Champion : IEquatable<Champion>
public ImmutableHashSet<Skill> Skills => skills.ToImmutableHashSet(); public ImmutableHashSet<Skill> Skills => skills.ToImmutableHashSet();
private HashSet<Skill> skills = new HashSet<Skill>(); private HashSet<Skill> skills = new HashSet<Skill>();
internal bool AddSkin(Skin skin) public bool AddSkin(Skin skin)
{ {
if (skins.Contains(skin)) if (skins.Contains(skin))
return false; return false;

@ -16,6 +16,7 @@ namespace StubLib
new Champion("Alistar", ChampionClass.Tank), new Champion("Alistar", ChampionClass.Tank),
}; };
public class ChampionsManager : IChampionsManager public class ChampionsManager : IChampionsManager
{ {
private readonly StubData parent; private readonly StubData parent;

@ -29,7 +29,5 @@ public partial class StubData : IDataManager
championsAndRunePages.Add(Tuple.Create(champions[0], runePages[0])); championsAndRunePages.Add(Tuple.Create(champions[0], runePages[0]));
} }
} }

@ -8,6 +8,7 @@ using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Logging.Abstractions;
using Model; using Model;
using Shared;
using StubLib; using StubLib;
using System.Net; using System.Net;
@ -27,11 +28,12 @@ namespace Test_Api
championCtrl = new ChampionsController(stubMgr, logger); championCtrl = new ChampionsController(stubMgr, logger);
} }
/* [TestMethod] [TestMethod]
public async Task TestGetChampions() public async Task TestGetChampions()
{ {
var totalcountTest = await stubMgr.ChampionsMgr.GetNbItems();
// Arrange
var request = new PageRequest var request = new PageRequest
{ {
index = 0, index = 0,
@ -40,43 +42,48 @@ namespace Test_Api
descending = false descending = false
}; };
var totalcountTest = await stubMgr.ChampionsMgr.GetNbItems(); // Create some test data
var champions = new List<Champion>
{
// Act 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); var getResult = await championCtrl.Get(request);
// Assert // Assert
Assert.IsInstanceOfType(getResult, typeof(OkObjectResult));
Assert.IsInstanceOfType(getResult.Result, typeof(OkObjectResult));
var objectRes = getResult.Result as OkObjectResult; var objectRes = getResult.Result as OkObjectResult;
Assert.AreEqual(200, objectRes.StatusCode); Assert.AreEqual(200, objectRes.StatusCode);
Assert.IsNotNull(objectRes); Assert.IsNotNull(objectRes);
var champions = objectRes?.Value as IEnumerable<ChampionDTO>;
Assert.IsNotNull(champions);
Assert.IsInstanceOfType(objectRes.Value, typeof(PageResponse<ChampionDTO>));
var pageResponse = objectRes.Value as PageResponse<ChampionDTO>; var pageResponse = objectRes.Value as PageResponse<ChampionDTO>;
Assert.AreEqual(totalcountTest, pageResponse.TotalCount); Assert.IsNotNull(pageResponse);
Assert.AreEqual(totalcountTest, pageResponse.Data.Count()); Assert.IsInstanceOfType(pageResponse, typeof(PageResponse<ChampionDTO>));
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] [TestMethod]
public async Task TestGetChampions_When_Count_Index_Too_High() public async Task TestGetChampions_When_Count_Index_Too_High()
@ -92,16 +99,12 @@ namespace Test_Api
orderingPropertyName = "Name", orderingPropertyName = "Name",
descending = false descending = false
}; };
// Act // Act
var getResult = await championCtrl.Get(request); var getResult = await championCtrl.Get(request);
// Assert // Assert
var badRequestResult = getResult.Result as BadRequestObjectResult; var badRequestResult = getResult.Result as BadRequestObjectResult;
Assert.IsNotNull(badRequestResult); Assert.IsNotNull(badRequestResult);
Assert.AreEqual("To many object is asked the max is : {totalcountTest}", badRequestResult.Value); Assert.AreEqual($"To many object is asked the max is : {totalcountTest}", badRequestResult.Value);
} }
@ -109,8 +112,21 @@ namespace Test_Api
public async Task TestGetBadRequest_WhenNoChampionsFound() public async Task TestGetBadRequest_WhenNoChampionsFound()
{ {
var totalcountTest = await stubMgr.ChampionsMgr.GetNbItems();
// need to be empty // need to be empty
List<Champion> 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);
}
var request = new PageRequest var request = new PageRequest
{ {
@ -128,10 +144,10 @@ namespace Test_Api
// Assert // Assert
var badRequestResult = getResult.Result as BadRequestObjectResult; var badRequestResult = getResult.Result as BadRequestObjectResult;
Assert.IsNotNull(badRequestResult); Assert.IsNotNull(badRequestResult);
Assert.AreEqual("No chamions found : totalcount is : 0", badRequestResult.Value); Assert.AreEqual("To many object is asked the max is : 0", badRequestResult.Value);
} }
*/
/* /*
@ -192,6 +208,17 @@ namespace Test_Api
} }
*/ */
} }

Loading…
Cancel
Save