Merge pull request 'Dave_more' (#9) from Dave_more into master
continuous-integration/drone/push Build is passing Details

Reviewed-on: #9
pull/11/head
Arthur VALIN 2 years ago
commit 991d29d53c

@ -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;
}

@ -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<ChampionDTO> res = champions.Select(c => c.ToDTO());
if (res.Count() <= 0 || res == null)
{
@ -140,7 +142,7 @@ namespace API_LoL_Project.Controllers.version2
// GET api/champions/name
[HttpGet("{name}")]
public async Task<ActionResult<LolResponse<ChampionFullDTO>>> GetChampionsByName(string name)
public async Task<ActionResult<IEnumerable<LolResponse<ChampionFullDTO>>>> GetChampionsByName(string name)
{
if (name == null || name == "")
{
@ -155,10 +157,10 @@ namespace API_LoL_Project.Controllers.version2
if (totalcount <= 0)
{
_logger.LogError("No chamions found with this name {name} in the dataContext", name); ;
return BadRequest("No chamions found with this name: " + name + "in the dataContext");
return NotFound("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>
{
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);
}
@ -266,6 +282,7 @@ namespace API_LoL_Project.Controllers.version2
// should change for id cause model implementation use filteringbyName to getItemByNAme and it use substring
// PUT api/<ChampionController>/5
[HttpPut("{name}")]
// should be champions full Dto
public async Task<IActionResult> Put(string name, [FromBody] ChampionDTO value)
{
try
@ -279,8 +296,15 @@ namespace API_LoL_Project.Controllers.version2
return NotFound();
}
await dataManager.UpdateItem(champion.First(), value.ToModel());
return Ok();
var savedUpdatedChampions = await dataManager.UpdateItem(champion.First(), value.ToModel());
if(savedUpdatedChampions == null)
{
_logger.LogWarning("The updated champions not returned {name}", name); ;
return BadRequest();
}
return Ok(savedUpdatedChampions);
}
catch (Exception e)
{
@ -303,7 +327,12 @@ namespace API_LoL_Project.Controllers.version2
_logger.LogWarning(message + nameof(ChampionsController)); ;
return BadRequest(message);
}
var totalcount = await dataManager.GetNbItemsByName(name);
if (totalcount <= 0)
{
_logger.LogError("No chamions found with this name {name} in the dataContext cannot delete", name);
return NotFound($"No chamions found with {name} cannot delete");
}
var champion = await dataManager
.GetItemsByName(name, 0, await dataManager.GetNbItems());
@ -390,6 +419,83 @@ namespace API_LoL_Project.Controllers.version2
var nbChampions = await dataManager.GetNbItems();
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)
{
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; }

@ -25,12 +25,15 @@ namespace ApiLib
public ChampionsManager(ApiManager parent)
=> this.parent = parent;
private const string urlChampion = "/champions";
public async Task<Champion?> AddItem(Champion? item)
{
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(urlChampion, item.toFullDTO());
if (response.IsSuccessStatusCode || response.StatusCode == HttpStatusCode.Created)// mayby changer to check the status code is more secure i think
{
@ -72,11 +75,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 +120,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($"{urlChampion}{queryString}");
if (response.IsSuccessStatusCode)
{
@ -152,13 +157,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($"{urlChampion}/characteristic/{charName}?index={index}&count={count}&orderingPropertyName={orderingPropertyName}&descending={descending}");
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}");
return champions;
IEnumerable<Champion> res = champions.Select(c => c.ToModel());
return res;
}
else
{
@ -186,7 +194,7 @@ namespace ApiLib
public async Task<IEnumerable<Champion?>> 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 +204,7 @@ namespace ApiLib
queryString.Append($"&Descending={descending}");
}
var uri = new UriBuilder("https://localhost:7234/api/Crafting")
var uri = new UriBuilder(urlChampion)
{
Query = queryString.ToString()
}.Uri;
@ -207,8 +215,10 @@ namespace ApiLib
var response = await parent.HttpClient.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
var champions = await response.Content.ReadFromJsonAsync<IEnumerable<Champion?>>();
return champions;
var champions = await response.Content.ReadFromJsonAsync<IEnumerable<ChampionDTO?>>();
IEnumerable<Champion> res = champions.Select(c => c.ToModel());
return res;
}
else
{
@ -249,7 +259,7 @@ namespace ApiLib
}
}*/
Uri uri = new Uri($"https://codefirst.iut.uca.fr/containers/arthurvalin-lolcontainer/api/champions/{substring}");
Uri uri = new Uri($"{urlChampion}/{substring}");
var response = await parent.HttpClient.GetAsync(uri);
if (response.IsSuccessStatusCode)
@ -314,7 +324,7 @@ namespace ApiLib
queryString += $"&{runePageQueryString}";
}
}
Uri uri = new Uri($"https://localhost:7234/api/Crafting{queryString}");
Uri uri = new Uri($"{urlChampion}/runePage{queryString}");
var response = await parent.HttpClient.GetAsync(uri);
@ -363,7 +373,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($"{urlChampion}/count");
if (response.IsSuccessStatusCode)
{
@ -388,7 +398,7 @@ namespace ApiLib
try
{
var response = await parent.HttpClient.GetAsync($"https://localhost:7234/api/Champion/CountByCharacteristic/{charName}");
var response = await parent.HttpClient.GetAsync($"{urlChampion}/count/characteristic/{charName}");
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
@ -420,7 +430,7 @@ namespace ApiLib
try
{
var response = await parent.HttpClient.GetAsync($"https://localhost:7234/api/Champion/CountByClass/{championClass}");
var response = await parent.HttpClient.GetAsync($"{urlChampion}/count/class/{championClass}");
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
@ -452,7 +462,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 +495,7 @@ namespace ApiLib
try
{
string requestUri = "https://localhost:7234/api/Champion/CountByRunePage";
string requestUri = $"{urlChampion}/count/runePage";
if (runePage != null)
{
@ -547,7 +557,7 @@ namespace ApiLib
}
try
{
var response = await parent.HttpClient.PutAsJsonAsync($"https://localhost:7234/api/Champion/{oldItem.Name}", newItem);
var response = await parent.HttpClient.PutAsJsonAsync($"{urlChampion}/{oldItem.Name}", newItem);
if (response.IsSuccessStatusCode)
{
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,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<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)
{

@ -18,12 +18,19 @@ namespace ApiMappeur
return new SkinDto()
{
Name = item.Name,
LargeImage = item.Image.ToDTO(),
Description = item.Description,
Icon = item.Icon,
Price = item.Price
Price = item.Price,
};
}
public static Skin ToModel(this SkinDto item)
{
var image = item?.LargeImage?.base64 ?? "";
return new(item?.Name ?? "", null, item?.Price ?? -1, image, item?.Description ?? "");
}
}
}

@ -8,7 +8,9 @@ namespace DTO
{
public class SkillDto
{
public string Name { get; set; }
/* public SkillDtoType type { get; set; }
*/ public string Name { get; set; }
public string Description { get; set; }
}
}

@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DTO
{
public class SkillDtoType
{
}
}

@ -8,10 +8,13 @@ namespace DTO
{
public class SkinDto
{
public string Name { get; set; }
/* 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; }
}
}

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

@ -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;

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

@ -2,14 +2,19 @@ using API_LoL_Project.Controllers;
using API_LoL_Project.Controllers.Request;
using API_LoL_Project.Controllers.Response;
using API_LoL_Project.Controllers.version2;
using API_LoL_Project.Middleware;
using DTO;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Model;
using Shared;
using StubLib;
using System.Collections.ObjectModel;
using System.Net;
using System.Xml.Linq;
namespace Test_Api
{
@ -27,11 +32,12 @@ namespace Test_Api
championCtrl = new ChampionsController(stubMgr, logger);
}
/* [TestMethod]
public async Task TestGetChampions()
[TestMethod]
public async Task TestGetSuccesChampions()
{
var totalcountTest = await stubMgr.ChampionsMgr.GetNbItems();
// Arrange
var request = new PageRequest
{
index = 0,
@ -40,159 +46,354 @@ namespace Test_Api
descending = false
};
var totalcountTest = await stubMgr.ChampionsMgr.GetNbItems();
// Create some test data
var champions = new List<Champion>
{
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<ChampionDTO>;
var pageResponse = objectRes.Value as PageResponse<ChampionDTO>;
Assert.IsNotNull(pageResponse);
Assert.IsInstanceOfType(pageResponse, typeof(PageResponse<ChampionDTO>));
Assert.AreEqual(totalcountTest + champions.Count, pageResponse.TotalCount);
Assert.AreEqual(totalcountTest + champions.Count, pageResponse.Data.Count());
Assert.IsNotNull(champions);
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]/")));
}
Assert.IsInstanceOfType(objectRes.Value, typeof(PageResponse<ChampionDTO>));
var pageResponse = objectRes.Value as PageResponse<ChampionDTO>;
Assert.AreEqual(totalcountTest, pageResponse.TotalCount);
Assert.AreEqual(totalcountTest, pageResponse.Data.Count());
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()
{
*//* 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 totalcountTest = await stubMgr.ChampionsMgr.GetNbItems();
}
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);
}
[TestMethod]
public async Task TestGetChampions_When_Count_Index_Too_High()
[TestMethod]
public async Task TestGetBadRequest_WhenNoChampionsFound()
{
// 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 totalcountTest = await stubMgr.ChampionsMgr.GetNbItems();
var request = new PageRequest
{
index = 0,
count = 10,
orderingPropertyName = "Name",
descending = false
};
var request = new PageRequest
{
index = 999,
count = 9,
orderingPropertyName = "Name",
descending = false
};
// Act
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);
}
// Act
[TestMethod]
public async Task TestGetChampionByName_ExistingName()
{
// Arrange
var getResult = await championCtrl.Get(request);
var championName = "lopalinda";
var champion = new Champion(championName, ChampionClass.Assassin);
await stubMgr.ChampionsMgr.AddItem(champion);
// Act
var getResult = await championCtrl.GetChampionsByName(championName);
// Assert
var badRequestResult = getResult.Result as BadRequestObjectResult;
Assert.IsNotNull(badRequestResult);
Assert.AreEqual("To many object is asked the max is : {totalcountTest}", badRequestResult.Value);
}
/* Assert.IsInstanceOfType(getResult, typeof(OkObjectResult));
var objectRes = getResult.Result as OkObjectResult;
Assert.AreEqual(200, objectRes.StatusCode);
Assert.IsInstanceOfType(okResult.Value, typeof(IEnumerable<LolResponse<ChampionFullDTO>>));
Assert.IsNotNull(objectRes);*/
Assert.IsInstanceOfType(getResult.Result, typeof(OkObjectResult));
var okResult = getResult.Result as OkObjectResult;
Assert.IsInstanceOfType(okResult.Value, typeof(IEnumerable<LolResponse<ChampionFullDTO>>));
var responseList = okResult.Value as IEnumerable<LolResponse<ChampionFullDTO>>;
Assert.AreEqual(1, responseList.Count());
var response = responseList.First();
Assert.AreEqual(champion.Name, response.Data.Name);
}
[TestMethod]
public async Task TestGetBadRequest_WhenNoChampionsFound()
public async Task TestGetChampionsByName_ReturnsBadRequest_WhenNameIsEmpty()
{
// Arrange
var name = "";
var totalcountTest = await stubMgr.ChampionsMgr.GetNbItems();
// need to be empty
var request = new PageRequest
{
index = 0,
count = 10,
orderingPropertyName = "Name",
descending = false
};
// Act
var result = await championCtrl.GetChampionsByName(name);
// Assert
Assert.IsInstanceOfType(result.Result, typeof(BadRequestObjectResult));
var badRequestResult = result.Result as BadRequestObjectResult;
Assert.AreEqual("Can not get champions without the name (is empty)", badRequestResult.Value);
}
[TestMethod]
public async Task TestGetChampionsByName_ReturnsBadRequest_WhenNoChampionsFound()
{
// Arrange
var name = "NonExistentChampionName";
// Act
var result = await championCtrl.GetChampionsByName(name);
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);
Assert.IsInstanceOfType(result.Result, typeof(NotFoundObjectResult));
var badRequestResult = result.Result as NotFoundObjectResult;
Assert.AreEqual("No chamions found with this name: NonExistentChampionNamein the dataContext", badRequestResult.Value);
}
*/
/*[TestMethod]
public async Task TestPostChampionsSucess()
{
var championName = "bhbhb";
var expectedChampion = new ChampionFullDTO()
{
Characteristics = new ReadOnlyDictionary<string, int>(new Dictionary<string, int>() {
{ "health", 500 },
{ "attack damage", 60 },
{ "ability power", 0 }
}),
Name = championName,
Bio = "Garen is a strong and noble warrior, the pride of Demacia.",
Class = ChampionClass.Fighter,
Icon = "https://example.com/garen-icon.png",
LargeImage = new ImageDTO() { base64 = "xyz" },
Skins = new List<SkinDto>() {
new SkinDto() {
Name = "Classic Garen",
Description = "The default skin for Garen.",
Icon = "https://example.com/garen-classic-icon.png",
Price = 1350,
LargeImage = new ImageDTO() { base64 = "xyz" }
},
new SkinDto() {
Name = "God-King Garen",
Description = "Garen as a divine being.",
Icon = "https://example.com/garen-god-king-icon.png",
Price = 1820,
LargeImage = new ImageDTO() { base64 = "xyz" }
}
},
Skills = new List<Skill>() {
new Skill("Decisive Strike", SkillType.Basic, "Garen's next attack strikes a vital area of his foe, dealing bonus damage and silencing them."),
new Skill("Courage", SkillType.Basic, "Garen passively increases his armor and magic resistance by killing enemies. He may also activate this ability to gain additional defensive statistics."),
new Skill("Judgment", SkillType.Basic, "Garen rapidly spins his sword around his body, dealing physical damage to nearby enemies and reducing the duration of all incoming crowd control effects."),
new Skill("Demacian Justice", SkillType.Ultimate, "Garen calls upon the might of Demacia to deal a finishing blow to an enemy champion, dealing massive damage based on their missing health.")
}
};
var rep = await championCtrl.Post(expectedChampion);
/*
[TestMethod]
public async Task TestPostChampions()
{
var getResult = await championCtrl.Get();
Console.WriteLine(getResult);
var objectRes = getResult 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>;
var champions = objectRes?.Value as IEnumerable<ChampionDTO>;
Assert.IsNotNull(champions);
Assert.IsNotNull(champions);
}
*/
[TestMethod]
public async Task TestPost_ReturnsCreatedAndSavedChampion()
{
// Arrange
var expectedChampion = new ChampionFullDTO()
{
Characteristics = new ReadOnlyDictionary<string, int>(new Dictionary<string, int>() {
{ "health", 500 },
{ "attack damage", 60 },
{ "ability power", 0 }
}),
Name = "iuhbbhs",
Bio = "Garen is a strong and noble warrior, the pride of Demacia.",
Class = ChampionClass.Fighter,
Icon = "https://example.com/garen-icon.png",
LargeImage = new ImageDTO() { base64 = "xyz" },
Skins = new List<SkinDto>() {
new SkinDto() {
Name = "Classic Garen",
Description = "The default skin for Garen.",
Icon = "https://example.com/garen-classic-icon.png",
Price = 1350,
LargeImage = new ImageDTO() { base64 = "xyz" }
},
new SkinDto() {
Name = "God-King Garen",
Description = "Garen as a divine being.",
Icon = "https://example.com/garen-god-king-icon.png",
Price = 1820,
LargeImage = new ImageDTO() { base64 = "xyz" }
}
},
Skills = new List<Skill>() {
new Skill("Decisive Strike", SkillType.Basic, "Garen's next attack strikes a vital area of his foe, dealing bonus damage and silencing them."),
new Skill("Courage", SkillType.Basic, "Garen passively increases his armor and magic resistance by killing enemies. He may also activate this ability to gain additional defensive statistics."),
new Skill("Judgment", SkillType.Basic, "Garen rapidly spins his sword around his body, dealing physical damage to nearby enemies and reducing the duration of all incoming crowd control effects."),
new Skill("Demacian Justice", SkillType.Ultimate, "Garen calls upon the might of Demacia to deal a finishing blow to an enemy champion, dealing massive damage based on their missing health.")
}
};
}
// Act
var postResult = await championCtrl.Post(expectedChampion);
[TestMethod]
public async Task TestUpdateChampions()
{
// Assert
Assert.IsInstanceOfType(postResult, typeof(CreatedAtActionResult));
var objectRes = postResult as CreatedAtActionResult;
Assert.AreEqual(201, objectRes.StatusCode);
Assert.IsNotNull(objectRes);
Assert.AreEqual(nameof(championCtrl.Get), objectRes.ActionName);
var createdChampion = objectRes.Value as ChampionDTO;
Assert.IsNotNull(createdChampion);
Assert.AreEqual(expectedChampion.Name, createdChampion.Name);
Assert.AreEqual(expectedChampion.Class, createdChampion.Class);
}
var getResult = await championCtrl.Get();
Console.WriteLine(getResult);
var objectRes = getResult as OkObjectResult;
[TestMethod]
public async Task TestPutChampion()
{
// Arrange
var championName = "kakarot";
var updatedChampion = new ChampionDTO
{
Name = championName,
Class = ChampionClass.Mage,
Icon = "dsodm",
Bio = "totto",
};
Assert.AreEqual(200, objectRes.StatusCode);
await stubMgr.ChampionsMgr.AddItem(new Champion(championName, ChampionClass.Assassin));
// Act
var result = await championCtrl.Put(championName, updatedChampion);
Assert.IsNotNull(objectRes);
// Assert
Assert.IsInstanceOfType(result, typeof(OkObjectResult));
var champion = await stubMgr.ChampionsMgr.GetItemsByName(championName, 0, 1);
Assert.AreEqual(updatedChampion.Name, champion.First().Name);
Assert.AreEqual(updatedChampion.Class, champion.First().Class);
Assert.AreEqual(updatedChampion.Bio, champion.First().Bio);
}
var champions = objectRes?.Value as IEnumerable<ChampionDTO>;
[TestMethod]
public async Task TestDeleteChampion()
{
// Arrange
var championToDelete = new Champion("Yasuo", ChampionClass.Fighter);
await stubMgr.ChampionsMgr.AddItem(championToDelete);
Assert.IsNotNull(champions);
// Act
var result = await championCtrl.Delete(championToDelete.Name);
// Assert
Assert.IsInstanceOfType(result, typeof(OkResult));
Assert.AreEqual(200, (result as OkResult).StatusCode);
}
var championsAfterDelete = await stubMgr.ChampionsMgr.GetItems(0, await stubMgr.ChampionsMgr.GetNbItems());
Assert.IsFalse(championsAfterDelete.Any(c => c.Name == championToDelete.Name));
}
[TestMethod]
public async Task TestDeleteChampions()
{
[TestMethod]
public async Task TestDeleteChampionWithInvalidName()
{
// Arrange
var invalidName = "Invalid Name";
var getResult = await championCtrl.Get();
Console.WriteLine(getResult);
var objectRes = getResult as OkObjectResult;
// Act
var result = await championCtrl.Delete(invalidName);
Assert.AreEqual(200, objectRes.StatusCode);
// Assert
Assert.IsInstanceOfType(result, typeof(NotFoundObjectResult));
Assert.AreEqual(404, (result as NotFoundObjectResult).StatusCode);
Assert.AreEqual($"No chamions found with {invalidName} cannot delete", (result as NotFoundObjectResult).Value);
}
Assert.IsNotNull(objectRes);
[TestMethod]
public async Task TestDeleteChampionWithEmptyName()
{
// Arrange
var emptyName = string.Empty;
var champions = objectRes?.Value as IEnumerable<ChampionDTO>;
// Act
var result = await championCtrl.Delete(emptyName);
Assert.IsNotNull(champions);
// Assert
Assert.IsInstanceOfType(result, typeof(BadRequestObjectResult));
Assert.AreEqual(400, (result as BadRequestObjectResult).StatusCode);
Assert.AreEqual("Can not delelte champions without the name (is empty)", (result as BadRequestObjectResult).Value);
}
}
*/
}
}
Loading…
Cancel
Save