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

Reviewed-on: #8
ApiManager
Emre KARTAL 2 years ago
commit f0d1451095

Binary file not shown.

@ -22,17 +22,37 @@
<img src="doc/Images/Title-Répartition.png" width="400">
La racine de mon GitLab contient deux dossiers essentiels pour le projet :
La racine de mon GitLab contient deux dossiers :open_file_folder: essentiels pour le projet :
[**src**](src) : **Toute la partie codage de l'application**
[**doc**](doc) : **Documentation de l'application** (Images + Schéma et description de l'architecture globale de l'application)
[**doc**](doc) : **Documentation de l'application** (Images + Schéma de l'architecture globale de l'application)
👉 [**Solution de l'application**](src/EntityFramework_LoL/Sources/LeagueOfLegends.sln)
<img src="doc/Images/Title-Fonctionnement.png" width="460" >
- ### :building_construction: Comment est structurée l'architecture globale de l'application ?
Voici un **schéma** pour mieux représenter mon architecture :
<img src="doc/Schémas/Architecture_Global.png" width="1000" >
</br>
</br>
:information_source: Tout d'abord, il y a la partie client, qui correspond à tous les appareils :computer: qui vont effectuer des requêtes à mon API et recevoir, sous format *.json*:envelope: (JavaScript Object Notation), des informations sur des champions, des skins, etc.
La web API est chargée de transformer les classes métiers du modèle en DTO (Data Transfer Object), afin de filtrer et renvoyer seulement les données essentielles aux utilisateurs. Pour obtenir les données qu'elle va transmettre, elle utilise d'abord l'IDataManager du modèle, qui est hérité par le stub (:pushpin:un regroupement de fausses données qui permet de s'assurer que tout fonctionne et d'éviter de bloquer le développement), puis le DbManager, qui contactera la base de données et assurera la persistance des données.
Grâce à l'injection de dépendances dans le projet, la Web API n'a pas besoin d'être modifiée lorsqu'on veut passer du StubLib au DbManager (si vous ne savez pas ce que c'est, je vous invite à voir cette vidéo qui explique très clairement l'[Injection de dépendances](https://www.youtube.com/watch?v=OeWgBNR1BLU&t=10s&ab_channel=BaptisteMobileDev)).
La partie **bases de données** est gérée par le DbManager, qui utilise l'ORM Entity Framework (plus précisément le DbContext) pour récupérer les données dans la base de données. De plus, grâce à une factory :factory: (oui, comme celle de la web API), elle transforme les données en tables (appelées "Entities") en classes du modèle.
- ### Comment récupérer le projet ?
Tout d'abord, si ce n'est pas déjà fait, clonez le dépôt de la branche **master/main**. Pour ce faire, copiez le lien URL du dépôt git :
@ -53,7 +73,7 @@ Vous pouvez le cloner via un terminal dans le répertoire de votre choix en util
:information_source: *Si vous ne disposez pas de Visual Studio, allez sur le site [Microsoft Visual Studio](https://visualstudio.microsoft.com/fr/downloads/) pour pouvoir le télécharger !!!*
- ### Comment lancer l'API dotnet ?
- ### Comment lancer l'API dotnet :question:
Pour pouvoir utiliser toutes les requêtes de l'API, il est nécessaire de récupérer le projet si cela n'a pas été fait, puis de le lancer à partir de Visual Studio. Vous pouvez directement cliquer sur la solution du projet. Ensuite, dans les projets de démarrage, choisissez "Api-Lol" :
@ -71,7 +91,7 @@ Normalement, tout est bon et vous serez redirigé vers Swagger, qui est l'interf
</div>
Vous pouvez aussi utiliser l'API via cette url: https://codefirst.iut.uca.fr/containers/emrekartal-lolApi/Api/v3/champions
:paperclip: Vous pouvez aussi utiliser l'API via cette url: https://codefirst.iut.uca.fr/containers/emrekartal-lolApi/Api/v3/champions
- ### Comment lancer Le projet Entity Framework ?
@ -114,6 +134,55 @@ réalisez à nouveau la migration (ou mettez à jour celle actuelle), puis suppr
:information_source: *Notez qu'il est également possible, grâce à SQLLite, d'ajouter, modifier ou supprimer des données dans les tables.*
- ### Avancement du projet :construction_worker:
Où en suis-je:grey_question::grey_exclamation: (:white_check_mark: réalisé, :warning: presque abouti, :x: non commencé )
Côté API :
- :warning: [**Partie 1**](src/EntityFramework_Lol/Sources/ApiLol/Controllers) : **Mise en place de toutes les opérations CRUD**
- :white_check_mark: [**Partie 2**](src/EntityFramework_Lol/Sources/ApiLol/Controllers) : **Respect des règles de routage, utilisation des bons status code**
- :white_check_mark: [**Partie 3**](src/EntityFramework_Lol/Sources/ApiLol/Controllers) : **Versionnage de l'api**
- :warning: [**Partie 4**](src/EntityFramework_Lol/Sources/Tests/ApiTests) : **Tests unitaires**
- :white_check_mark: [**Partie 5**](.drone.yml) : **Dockerisation et Hébergement de l'API**
- :white_check_mark: [**Partie 6**](src/EntityFramework_Lol/Sources/ApiLol/Controllers) : **Logs **
- :white_check_mark: [**Partie 7**](src/EntityFramework_Lol/Sources/ApiLol/Controllers) : **Filtrage + Pagination des données **
- :x: [**Partie 8**](src/EntityFramework_Lol/Sources/ApiLol/) : **Utilisation des fichiers configurations **
- :x: [**Partie 9**](src/EntityFramework_Lol/Sources/) : **Réalisation du client MAUI et liaison avec l'api **
- :x: [**Partie 10**](src/EntityFramework_Lol/Sources/ApiLol/) : **Liaison avec la base de données **
Côté Entity_Framework :
- :warning: [**Partie 1**](src/EntityFramework_Lol/Sources/MyFlib/Entities) : **Réalisation des Entities**
- :white_check_mark: [**Partie 2**](src/EntityFramework_Lol/Sources/MyFlib/DataSeeder.cs) : **Data seeder**
- :warning: [**Partie 3**](src/EntityFramework_Lol/Sources/Tests/UT_EF) : **Tests unitaires**
- :x: [**Partie 4**](src/EntityFramework_Lol/Sources/MyFlib) : **Many to many**
- :x: [**Partie 5**](src/EntityFramework_Lol/Sources/) : **DbManager**
- :x: [**Partie 6**](src/EntityFramework_Lol/Sources/) : **Mapping**
Autre :
- :white_check_mark: [**Partie 1**](.drone.yml) : **Mise en place de SonarQube**
- :white_check_mark: [**Partie 2**](.drone.yml) : **Schéma et description de l'architecture globale de l'application**
<br>
<img src="doc/Images/Title-Environnement.png" width="400" >
Mon environnement de travail est basé sur un outil et un langage en particulier : 👇
@ -133,9 +202,14 @@ Mon environnement de travail est basé sur un outil et un langage en particulier
<img src="doc/Images/Title-Technicien.png" width="400" >
⚙️ Emre KARTAL
:mortar_board: Emre KARTAL
<br>
<div align = center>
<a href = "https://codefirst.iut.uca.fr/git/emre.kartal">
<img src="https://codefirst.iut.uca.fr/git/avatars/402cf312e853192f42c0135a888725c2?size=870" width="50" >
</br>
</a>
© PM2
</div>

@ -0,0 +1,181 @@
using ApiLol.Mapper;
using DTO;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using Model;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace ApiLol.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class RunePagesController : ControllerBase
{
private readonly IDataManager _manager;
private readonly ILogger<RunePagesController> _logger;
public RunePagesController(IDataManager dataManager, ILogger<RunePagesController> logger)
{
_manager = dataManager;
_logger = logger;
}
// GET: api/<RunePagesController>
[HttpGet]
public async Task<IActionResult> Get([FromQuery] PageRequest pageRequest)
{
_logger.LogInformation("Executing {Action} - RUNEPAGE with parameters: {Parameters}", nameof(Get), pageRequest);
try
{
int nbTotal = await _manager.RunePagesMgr.GetNbItems();
if (pageRequest.count == 0)
{
pageRequest = new PageRequest() { index = 0, count = nbTotal, orderingPropertyName = pageRequest.orderingPropertyName, descending = pageRequest.descending, name = pageRequest.name };
}
else if (pageRequest.count * pageRequest.index >= nbTotal || pageRequest.count > nbTotal)
{
_logger.LogWarning("too many, maximum {number}", nbTotal);
return BadRequest($"RunePage limit exceed, max {nbTotal}");
}
IEnumerable<RunePageDto> dtos;
if (pageRequest.name == null)
{
dtos = (await _manager.RunePagesMgr.GetItems(pageRequest.index, pageRequest.count, pageRequest.orderingPropertyName, pageRequest.descending))
.Select(x => x.ToDto());
}
else
{
dtos = (await _manager.RunePagesMgr.GetItemsByName(pageRequest.name, pageRequest.index, pageRequest.count, pageRequest.orderingPropertyName, pageRequest.descending))
.Select(x => x.ToDto());
}
return Ok(new PageResponse<RunePageDto> { Data = dtos, index = pageRequest.index, count = pageRequest.count, total = nbTotal });
}
catch (Exception error)
{
_logger.LogError(error.Message);
return BadRequest(error.Message);
}
}
// GET api/<RunePagesController>/5
[HttpGet("{name}")]
public async Task<IActionResult> Get(string name)
{
_logger.LogInformation("method {Action} - RUNEPAGE call with {name}", nameof(Get), name);
try
{
var dtos = (await _manager.RunePagesMgr.GetItemByName(name, 0, await _manager.RunePagesMgr.GetNbItems()))
.Select(x => x.ToDto());
if (dtos.IsNullOrEmpty())
{
_logger.LogWarning($"{name} was not found");
return NotFound($"{name} was not found");
}
return Ok(dtos.First());
}
catch (Exception error)
{
_logger.LogError(error.Message);
return BadRequest(error.Message);
}
}
// POST api/<RunePagesController>
[HttpPost]
public async Task<IActionResult> Post([FromBody] RunePageDto runePage)
{
_logger.LogInformation("method {Action} - RUNEPAGE call with {item}", nameof(Post), runePage);
try
{
if (await _manager.RunePagesMgr.GetNbItemsByName(runePage.Name) == 0)
{
return CreatedAtAction(nameof(Get),
(await _manager.RunePagesMgr.AddItem(runePage.ToModel())).ToDto());
}
_logger.LogWarning($"Name : {runePage.Name} is already exist");
return BadRequest($"Name : {runePage.Name} is already exist");
}
catch (Exception error)
{
_logger.LogError(error.Message);
return BadRequest(error.Message);
}
}
// PUT api/<RunePagesController>/5
[HttpPut("{name}")]
public async Task<IActionResult> Put(string name, [FromBody] RunePageDto runePage)
{
_logger.LogInformation("method {Action} - RUNEPAGE call with {name} and {item}", nameof(Put), name, runePage);
try
{
var dtos = (await _manager.RunePagesMgr.GetItemByName(name, 0, await _manager.RunePagesMgr.GetNbItems()));
if (dtos.IsNullOrEmpty())
{
return NotFound($"Name {name} not exist");
}
// Checks if the new name exists
if (name != runePage.Name)
{
var dtos2 = (await _manager.RunesMgr.GetItemByName(runePage.Name, 0, await _manager.RunePagesMgr.GetNbItems()));
if (!dtos2.IsNullOrEmpty() || dtos2.Count() > 0)
{
return BadRequest($"New Name {runePage.Name} is already exist");
}
}
return Ok((await _manager.RunePagesMgr.UpdateItem(dtos.First(), runePage.ToModel())).ToDto());
}
catch (Exception error)
{
_logger.LogError(error.Message);
return BadRequest(error.Message);
}
}
// DELETE api/<RunePagesController>/5
[HttpDelete("{name}")]
public async Task<IActionResult> Delete(string name)
{
_logger.LogInformation("method {Action} - RUNEPAGE call with {name}", nameof(Delete), name);
try
{
var dtos = (await _manager.RunePagesMgr.GetItemByName(name, 0, await _manager.RunePagesMgr.GetNbItems()));
if (dtos.IsNullOrEmpty())
{
_logger.LogWarning("{name} was not found", name);
return NotFound($"{name} was not found");
}
await _manager.RunePagesMgr.DeleteItem(dtos.First());
return NoContent();
}
catch (Exception error)
{
_logger.LogError(error.Message);
return BadRequest(error.Message);
}
}
[HttpGet("/countRunePages")]
public async Task<ActionResult> GetCountRunePages()
{
_logger.LogInformation("method {Action} - RUNEPAGE call", nameof(GetCountRunePages));
try
{
return Ok(await _manager.RunePagesMgr.GetNbItems());
}
catch (Exception error)
{
_logger.LogError(error.Message);
return BadRequest(error.Message);
}
}
}
}

@ -44,14 +44,14 @@ namespace ApiLol.Controllers
if (pageRequest.name == null)
{
dtos = (await _manager.RunesMgr.GetItems(pageRequest.index, pageRequest.count, pageRequest.orderingPropertyName, pageRequest.descending))
.Select(x => x.ToDto());
.Select(x => x.ToDto());
}
else
{
dtos = (await _manager.RunesMgr.GetItemsByName(pageRequest.name, pageRequest.index, pageRequest.count, pageRequest.orderingPropertyName, pageRequest.descending))
.Select(x => x.ToDto());
}
return Ok(new { Data = dtos, index = pageRequest.index, count = pageRequest.count, total = nbTotal });
return Ok(new PageResponse<RuneDto> { Data = dtos, index = pageRequest.index, count = pageRequest.count, total = nbTotal });
}
catch (Exception error)
@ -94,7 +94,7 @@ namespace ApiLol.Controllers
if (await _manager.RunesMgr.GetNbItemsByName(rune.Name) == 0)
{
return CreatedAtAction(nameof(Get),
(await _manager.RunesMgr.AddItem(rune.ToModel())));
(await _manager.RunesMgr.AddItem(rune.ToModel())).ToDto());
}
_logger.LogWarning($"Name : {rune.Name} is already exist");
return BadRequest($"Name : {rune.Name} is already exist");
@ -122,12 +122,12 @@ namespace ApiLol.Controllers
if (name != rune.Name)
{
var dtos2 = (await _manager.RunesMgr.GetItemByName(rune.Name, 0, await _manager.RunesMgr.GetNbItems()));
if (dtos2.IsNullOrEmpty() || dtos2.Count() > 0)
if (!dtos2.IsNullOrEmpty() || dtos2.Count() > 0)
{
return BadRequest($"New Name {rune.Name} is already exist");
}
}
return Ok(await _manager.RunesMgr.UpdateItem(dtos.First(),rune.ToModel()));
return Ok((await _manager.RunesMgr.UpdateItem(dtos.First(), rune.ToModel())).ToDto());
}
catch (Exception error)
@ -148,9 +148,10 @@ namespace ApiLol.Controllers
if (dtos.IsNullOrEmpty())
{
_logger.LogWarning("{name} was not found", name);
return BadRequest();
return NotFound($"{name} was not found");
}
return Ok(await _manager.RunesMgr.DeleteItem(dtos.First()));
await _manager.RunesMgr.DeleteItem(dtos.First());
return NoContent();
}
catch (Exception error)
{
@ -160,8 +161,9 @@ namespace ApiLol.Controllers
}
[HttpGet("/countRunes")]
public async Task<ActionResult<int>> GetCountSkins()
public async Task<ActionResult> GetCountRunes()
{
_logger.LogInformation("method {Action} - RUNE call", nameof(GetCountRunes));
try
{
return Ok(await _manager.RunesMgr.GetNbItems());

@ -50,7 +50,7 @@ namespace ApiLol.Controllers
dtos = (await _manager.SkinsMgr.GetItemsByName(pageRequest.name, pageRequest.index, pageRequest.count, pageRequest.orderingPropertyName, pageRequest.descending))
.Select(x => x.ToDtoC());
}
return Ok(new { Data = dtos, index = pageRequest.index, count = pageRequest.count, total = nbTotal });
return Ok(new PageResponse<SkinDtoC> { Data = dtos, index = pageRequest.index, count = pageRequest.count, total = nbTotal });
}
catch (Exception error)
@ -67,7 +67,7 @@ namespace ApiLol.Controllers
_logger.LogInformation("method {Action} - SKIN call with {name}", nameof(Get), name);
try
{
var dtos = (await _manager.SkinsMgr.GetItemByName(name, 0, await _manager.ChampionsMgr.GetNbItems()))
var dtos = (await _manager.SkinsMgr.GetItemByName(name, 0, await _manager.SkinsMgr.GetNbItems()))
.Select(x => x.ToDtoC());
if (dtos.IsNullOrEmpty())
{
@ -137,7 +137,7 @@ namespace ApiLol.Controllers
if (name != skin.Name)
{
var dtos2 = (await _manager.SkinsMgr.GetItemByName(skin.Name, 0, await _manager.SkinsMgr.GetNbItems()));
if (dtos2.IsNullOrEmpty() || dtos2.Count() > 0)
if (!dtos2.IsNullOrEmpty() || dtos2.Count() > 0)
{
return BadRequest($"New Name {skin.Name} is already exist");
}
@ -183,8 +183,9 @@ namespace ApiLol.Controllers
[HttpGet("/countSkins")]
public async Task<ActionResult<int>> GetCountSkins()
public async Task<ActionResult> GetCountSkins()
{
_logger.LogInformation("method {Action} - SKIN call", nameof(GetCountSkins));
try
{
return Ok(await _manager.SkinsMgr.GetNbItems());
@ -207,9 +208,10 @@ namespace ApiLol.Controllers
if (dtos.IsNullOrEmpty())
{
_logger.LogWarning("{name} was not found", name);
return BadRequest();
return NotFound($"{name} was not found");
}
return Ok(await _manager.SkinsMgr.DeleteItem(dtos.First()));
await _manager.SkinsMgr.DeleteItem(dtos.First());
return NoContent();
}
catch (Exception error)
{

@ -68,7 +68,7 @@ namespace ApiLol.Controllers.v1
}
[HttpGet("/countChampions")]
public async Task<ActionResult<int>> GetCountChampions()
public async Task<ActionResult> GetCountChampions()
{
try
{
@ -89,7 +89,8 @@ namespace ApiLol.Controllers.v1
_logger.LogInformation("method {Action} - CHAMPION - V1.0 call with {name}", nameof(Delete), name);
var dtos = (await _manager.ChampionsMgr.GetItemByName(name, 0, await _manager.ChampionsMgr.GetNbItems()));
return Ok(await _manager.ChampionsMgr.DeleteItem(dtos.First()));
await _manager.ChampionsMgr.DeleteItem(dtos.First());
return NoContent();
}
}

@ -81,7 +81,7 @@ namespace ApiLol.Controllers.v2
dtos = (await _manager.ChampionsMgr.GetItemsByName(pageRequest.name, pageRequest.index, pageRequest.count, pageRequest.orderingPropertyName, pageRequest.descending))
.Select(x => x.ToDto());
}
return Ok(new { Data = dtos, index = pageRequest.index, count = pageRequest.count, total = nbTotal });
return Ok(new PageResponse<ChampionDto>{ Data = dtos, index = pageRequest.index, count = pageRequest.count, total = nbTotal });
}
catch (Exception error)
{
@ -151,7 +151,7 @@ namespace ApiLol.Controllers.v2
if (name != champion.Name)
{
var dtos2 = (await _manager.ChampionsMgr.GetItemByName(champion.Name, 0, await _manager.ChampionsMgr.GetNbItems()));
if (dtos2.IsNullOrEmpty() || dtos2.Count() > 0)
if (!dtos2.IsNullOrEmpty() || dtos2.Count() > 0)
{
return BadRequest($"New Name {champion.Name} is already exist");
}
@ -204,8 +204,9 @@ namespace ApiLol.Controllers.v2
}
[HttpGet("/countChampions")]
public async Task<ActionResult<int>> GetCountChampions()
public async Task<ActionResult> GetCountChampions()
{
_logger.LogInformation("method {Action} - CHAMPION - V2.0 call", nameof(GetCountChampions));
try
{
return Ok(await _manager.ChampionsMgr.GetNbItems());
@ -228,9 +229,10 @@ namespace ApiLol.Controllers.v2
if (dtos.IsNullOrEmpty())
{
_logger.LogWarning("{name} was not found", name);
return BadRequest();
return NotFound($"{name} was not found");
}
return Ok(await _manager.ChampionsMgr.DeleteItem(dtos.First()));
await _manager.ChampionsMgr.DeleteItem(dtos.First());
return NoContent();
}
catch (Exception error)
{

@ -15,7 +15,9 @@ namespace ApiLol.Mapper
Icon = champion.Icon,
Image = champion.Image.ToDto(),
Skins = champion.Skins.Select(e => e.ToDto()),
Skills = champion.Skills.Select(e => e.ToDto())
Skills = champion.Skills.Select(e => e.ToDto()),
Characteristics = champion.Characteristics.ToDictionary(c => c.Key, c => c.Value)
};
}
@ -26,6 +28,12 @@ namespace ApiLol.Mapper
{
champ.AddSkin(skin.ToModel(champ));
}
foreach (var skill in championDto.Skills)
{
champ.AddSkill(skill.ToModel());
}
if (championDto.Characteristics != null)
champ.AddCharacteristics(championDto.Characteristics.Select(c => Tuple.Create(c.Key, c.Value)).ToArray());
return champ;
}

@ -0,0 +1,41 @@
using ApiLol.Mapper.enums;
using DTO;
using Model;
using static Model.RunePage;
namespace ApiLol.Mapper
{
public static class RunePageMapper
{
public static RunePageDto ToDto(this RunePage runePage)
{
return new RunePageDto()
{
Name = runePage.Name,
Runes = runePage.Runes.ToDictionary(c => c.Key.ToString(), r => r.Value.ToDto())
};
}
public static RunePage ToModel(this RunePageDto runePageDto)
{
Category category;
Dictionary<Category, Rune> runDico = runePageDto.Runes.ToDictionary(
r => (RunePage.Category)Enum.Parse(typeof(RunePage.Category), r.Key),
r => r.Value.ToModel()
);
var runePage = new RunePage(runePageDto.Name);
foreach (var rune in runePageDto.Runes)
{
if (!Enum.TryParse<Category>(rune.Key, true, out category))
{
continue;
}
runePage[category] = rune.Value.ToModel();
}
return runePage;
}
}
}

@ -0,0 +1,50 @@
using DTO;
using Model;
namespace ApiLol.Mapper.enums
{
public static class CategoryMapper
{
public static RunePageDto.CategoryDto ToDto(this RunePage.Category category)
{
switch (category)
{
case RunePage.Category.Major:
return RunePageDto.CategoryDto.Major;
case RunePage.Category.Minor1:
return RunePageDto.CategoryDto.Minor1;
case RunePage.Category.Minor2:
return RunePageDto.CategoryDto.Minor2;
case RunePage.Category.Minor3:
return RunePageDto.CategoryDto.Minor3;
case RunePage.Category.OtherMinor1:
return RunePageDto.CategoryDto.OtherMinor1;
case RunePage.Category.OtherMinor2:
return RunePageDto.CategoryDto.OtherMinor2;
default:
return RunePageDto.CategoryDto.Major;
}
}
public static RunePage.Category ToModel(this RunePageDto.CategoryDto category)
{
switch (category)
{
case RunePageDto.CategoryDto.Major:
return RunePage.Category.Major;
case RunePageDto.CategoryDto.Minor1:
return RunePage.Category.Minor1;
case RunePageDto.CategoryDto.Minor2:
return RunePage.Category.Minor2;
case RunePageDto.CategoryDto.Minor3:
return RunePage.Category.Minor3;
case RunePageDto.CategoryDto.OtherMinor1:
return RunePage.Category.OtherMinor1;
case RunePageDto.CategoryDto.OtherMinor2:
return RunePage.Category.OtherMinor2;
default:
return RunePage.Category.Major;
}
}
}
}

@ -7,8 +7,9 @@
public ChampionClassDto Class { get; set; }
public string Icon { get; set; }
public LargeImageDto Image { get; set; }
public IEnumerable<SkinDto> Skins { get; set; }
public IEnumerable<SkillDto> Skills { get; set; }
public IEnumerable<SkinDto>? Skins { get; set; }
public IEnumerable<SkillDto>? Skills { get; set; }
public Dictionary<string, int>? Characteristics { get; set; }
}
}

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DTO
{
public class PageResponse<T>
{
public IEnumerable<T> Data { get; set; }
public int index { get; set; }
public int count { get; set; }
public int total { get; set; }
}
}

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DTO
{
public partial class RunePageDto
{
public string Name { get; set; }
public Dictionary<string, RuneDto> Runes { get; set; }
}
}

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DTO
{
public partial class RunePageDto
{
public enum CategoryDto
{
Major,
Minor1,
Minor2,
Minor3,
OtherMinor1,
OtherMinor2
}
}
}

@ -11,7 +11,7 @@ public class Champion : IEquatable<Champion>
get => name;
private init
{
if(string.IsNullOrWhiteSpace(value))
if (string.IsNullOrWhiteSpace(value))
{
name = "Unknown";
return;
@ -26,7 +26,7 @@ public class Champion : IEquatable<Champion>
get => bio;
set
{
if(value == null)
if (value == null)
{
bio = "";
return;
@ -54,7 +54,7 @@ public class Champion : IEquatable<Champion>
}
public ReadOnlyCollection<Skin> Skins { get; private set; }
private List<Skin> skins = new ();
private List<Skin> skins = new();
public ReadOnlyDictionary<string, int> Characteristics { get; private set; }
private readonly Dictionary<string, int> characteristics = new Dictionary<string, int>();
@ -81,7 +81,7 @@ public class Champion : IEquatable<Champion>
public void AddCharacteristics(params Tuple<string, int>[] someCharacteristics)
{
foreach(var c in someCharacteristics)
foreach (var c in someCharacteristics)
{
characteristics[c.Item1] = c.Item2;
}
@ -94,12 +94,12 @@ public class Champion : IEquatable<Champion>
{
get
{
if(!characteristics.TryGetValue(label, out int value)) return null;
if (!characteristics.TryGetValue(label, out int value)) return null;
else return value;
}
set
{
if(!value.HasValue)
if (!value.HasValue)
{
RemoveCharacteristics(label);
return;
@ -110,9 +110,9 @@ public class Champion : IEquatable<Champion>
public override bool Equals(object? obj)
{
if(ReferenceEquals(obj, null)) return false;
if(ReferenceEquals(obj, this)) return true;
if(GetType() != obj.GetType()) return false;
if (ReferenceEquals(obj, null)) return false;
if (ReferenceEquals(obj, this)) return true;
if (GetType() != obj.GetType()) return false;
return Equals(obj as Champion);
}
@ -125,22 +125,22 @@ public class Champion : IEquatable<Champion>
public override string ToString()
{
StringBuilder sb = new StringBuilder($"{Name} ({Class})");
if(!string.IsNullOrWhiteSpace(bio))
if (!string.IsNullOrWhiteSpace(bio))
{
sb.AppendLine($"\t{bio}");
}
if(characteristics.Any())
if (characteristics.Any())
{
sb.AppendLine("\tCharacteristics:");
foreach(var characteristic in characteristics)
foreach (var characteristic in characteristics)
{
sb.AppendLine($"\t\t{characteristic.Key} - {characteristic.Value}");
}
}
if(skills.Any())
if (skills.Any())
{
sb.AppendLine("\tSkills:");
foreach(var skill in Skills)
foreach (var skill in Skills)
{
sb.AppendLine($"\t\t{skill.Name} - {skill.Description}");
}

@ -3,93 +3,94 @@ using System.Collections.ObjectModel;
namespace Model
{
public partial class RunePage
{
public string Name
{
get => name;
private init
{
if(string.IsNullOrWhiteSpace(value))
{
throw new ArgumentException("a Rune Page must have a name");
}
name = value;
}
}
private readonly string name = null!;
public partial class RunePage
{
public string Name
{
get => name;
private init
{
if (string.IsNullOrWhiteSpace(value))
{
throw new ArgumentException("a Rune Page must have a name");
}
name = value;
}
}
private readonly string name = null!;
public ReadOnlyDictionary<Category, Rune> Runes { get; private set; }
private Dictionary<Category, Rune> runes = new Dictionary<Category, Rune>();
public ReadOnlyDictionary<Category, Rune> Runes { get; private set; }
private Dictionary<Category, Rune> runes = new Dictionary<Category, Rune>();
public RunePage(string name)
{
Name = name;
Runes = new ReadOnlyDictionary<Category, Rune>(runes);
}
public RunePage(string name)
{
Name = name;
Runes = new ReadOnlyDictionary<Category, Rune>(runes);
}
public Rune? this[Category category]
{
get
{
if(runes.TryGetValue(category, out Rune? rune))
{
return rune;
}
return null;
}
set
{
if(value == null)
{
runes.Remove(category);
}
runes[category] = value!;
CheckRunes(category);
}
}
public Rune? this[Category category]
{
get
{
if (runes.TryGetValue(category, out Rune? rune))
{
return rune;
}
return null;
}
set
{
if (value == null)
{
runes.Remove(category);
return;
}
runes[category] = value!;
CheckRunes(category);
}
}
private void CheckRunes(Category newRuneCategory)
{
switch(newRuneCategory)
{
case Category.Major:
UpdateMajorFamily(Category.Minor1, true);
UpdateMajorFamily(Category.Minor2, true);
UpdateMajorFamily(Category.Minor3, true);
UpdateMajorFamily(Category.OtherMinor1, false);
UpdateMajorFamily(Category.OtherMinor2, false);
break;
case Category.Minor1:
case Category.Minor2:
case Category.Minor3:
UpdateMajorFamily(newRuneCategory, true);
break;
case Category.OtherMinor1:
case Category.OtherMinor2:
UpdateMajorFamily(newRuneCategory, false);
break;
}
}
private void CheckRunes(Category newRuneCategory)
{
switch (newRuneCategory)
{
case Category.Major:
UpdateMajorFamily(Category.Minor1, true);
UpdateMajorFamily(Category.Minor2, true);
UpdateMajorFamily(Category.Minor3, true);
UpdateMajorFamily(Category.OtherMinor1, false);
UpdateMajorFamily(Category.OtherMinor2, false);
break;
case Category.Minor1:
case Category.Minor2:
case Category.Minor3:
UpdateMajorFamily(newRuneCategory, true);
break;
case Category.OtherMinor1:
case Category.OtherMinor2:
UpdateMajorFamily(newRuneCategory, false);
break;
}
}
private bool? CheckFamilies(Category cat1, Category cat2)
{
runes.TryGetValue(cat1, out Rune? rune1);
runes.TryGetValue(cat2, out Rune? rune2);
if(rune1 == null || rune2 == null)
{
return null;
}
return rune1.Family == rune2.Family;
}
private bool? CheckFamilies(Category cat1, Category cat2)
{
runes.TryGetValue(cat1, out Rune? rune1);
runes.TryGetValue(cat2, out Rune? rune2);
if (rune1 == null || rune2 == null)
{
return null;
}
return rune1.Family == rune2.Family;
}
private void UpdateMajorFamily(Category minor, bool expectedValue)
{
if(CheckFamilies(Category.Major, minor).GetValueOrDefault(expectedValue) == expectedValue)
{
runes.Remove(minor);
}
}
}
private void UpdateMajorFamily(Category cat, bool expectedValue)
{
if (CheckFamilies(Category.Major, cat).GetValueOrDefault(expectedValue) != expectedValue)
{
runes.Remove(cat);
}
}
}
}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

@ -1,127 +0,0 @@
using ApiLol.Controllers;
using ApiLol.Controllers.v2;
using DTO;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using StubLib;
namespace ApiTests
{
[TestClass]
public class ChampionsControllerTest
{
private readonly StubData stub;
private readonly ChampionsController champs;
public ChampionsControllerTest()
{
stub = new StubData();
champs = new ChampionsController(stub, new NullLogger<ChampionsController>());
}
[TestMethod]
public async Task TestGetChampions()
{
//Arrange
//Act
var total = await stub.ChampionsMgr.GetNbItems();
var champion = await champs.Get(new PageRequest());
//Assert
var objectResult = champion as OkObjectResult;
Assert.IsNotNull(objectResult);
var champions = objectResult?.Value as IEnumerable<ChampionDto>;
Assert.IsNotNull(champions);
Assert.AreEqual(champions.Count(), total);
}
[TestMethod]
public async Task TestPostChampion()
{
//Arange
var ChampionDto = new ChampionDto
{
Name = "Sylas",
Bio = "Good",
Class = ChampionClassDto.Tank,
Icon = "",
Image = new LargeImageDto() { Base64 = "" },
Skins = new List<SkinDto>()
};
//Act
var championsResult = await champs.Post(ChampionDto);
//Assert
var objectResult = championsResult as CreatedAtActionResult;
Assert.IsNotNull(objectResult);
var champions = objectResult?.Value as ChampionDto;
Assert.IsNotNull(champions);
}
[TestMethod]
public async Task TestPutChampion()
{
//Arange
var ChampionDto = new ChampionDto
{
Name = "Sylas",
Bio = "Good",
Class = ChampionClassDto.Tank,
Icon = "",
Image = new LargeImageDto() { Base64 = "" },
Skins = new List<SkinDto>()
};
var ChampionDtoPut = new ChampionDto
{
Name = "Sylas",
Bio = "Bad",
Class = ChampionClassDto.Tank,
Icon = "",
Image = new LargeImageDto() { Base64 = "" },
Skins = new List<SkinDto>()
};
//Act
await champs.Post(ChampionDto);
var championsResult = await champs.Put(ChampionDto.Name, ChampionDtoPut);
//Assert
var objectResult = championsResult as OkObjectResult;
Assert.IsNotNull(objectResult);
var champions = objectResult?.Value as ChampionDto;
Assert.IsNotNull(champions);
Assert.AreNotEqual(ChampionDto.Bio, champions.Bio);
Assert.AreEqual(ChampionDtoPut.Bio, champions.Bio);
}
[TestMethod]
public async Task TestDeleteChampion()
{
//Arange
//Act
var total = await stub.ChampionsMgr.GetNbItems();
var championsResult = await champs.Delete("Akali");
//Assert
var objectResult = championsResult as OkObjectResult;
Assert.IsNotNull(objectResult);
Assert.AreEqual(objectResult.Value, true);
Assert.AreNotEqual(await stub.ChampionsMgr.GetNbItems(), total);
}
}
}

@ -0,0 +1,199 @@
using ApiLol.Controllers.v1;
using DTO;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging.Abstractions;
using StubLib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.PortableExecutable;
using System.Text;
using System.Threading.Tasks;
namespace ApiTests
{
[TestClass]
public class ChampionsControllerTestV1
{
private readonly StubData stub;
private readonly ChampionsController champs;
public ChampionsControllerTestV1()
{
stub = new StubData();
champs = new ChampionsController(stub, new NullLogger<ChampionsController>());
}
[TestMethod]
public async Task TestGetChampions()
{
//Arrange
//Act
var total = await stub.ChampionsMgr.GetNbItems();
var champion = await champs.Get(new PageRequest() { index = 0, count = total });
//Assert
var objectResult = champion as OkObjectResult;
Assert.IsNotNull(objectResult);
var champions = objectResult?.Value as IEnumerable<ChampionDto>;
Assert.IsNotNull(champions);
Assert.AreEqual(champions.Count(), total);
}
[TestMethod]
public async Task TestPostChampion()
{
//Arange
var ChampionDto = new ChampionDto
{
Name = "Sylas",
Bio = "Good",
Class = ChampionClassDto.Tank,
Icon = "",
Image = new LargeImageDto() { Base64 = "" },
Skins = new List<SkinDto>()
{
new SkinDto() {Name = "Project", Description = "Test", Icon = "",Image = new LargeImageDto(),Price = 900 }
},
Skills = new List<SkillDto>()
{
new SkillDto() {Name = "Test skill", Description="Empty", Type = SkillTypeDto.Unknown}
},
Characteristics = {}
};
//Act
var championsResult = await champs.Post(ChampionDto);
//Assert
var objectResult = championsResult as CreatedAtActionResult;
Assert.IsNotNull(objectResult);
var champions = objectResult?.Value as ChampionDto;
Assert.IsNotNull(champions);
Assert.AreEqual("Sylas", champions.Name);
Assert.AreEqual("Project", champions.Skins.First().Name);
Assert.AreEqual("Test", champions.Skins.First().Description);
Assert.AreEqual("Test skill", champions.Skills.First().Name);
Assert.AreEqual("Empty", champions.Skills.First().Description);
}
[TestMethod]
public async Task TestCountChampion()
{
//Arange
var ChampionDto = new ChampionDto
{
Name = "Sylas",
Bio = "Good",
Class = ChampionClassDto.Tank,
Icon = "",
Image = new LargeImageDto() { Base64 = "" },
Skins = new List<SkinDto>()
{
new SkinDto() {Name = "Project", Description = "Test", Icon = "",Image = new LargeImageDto(),Price = 900 }
},
Skills = new List<SkillDto>()
{
new SkillDto() {Name = "Test skill", Description="Empty", Type = SkillTypeDto.Unknown}
}
};
//Act
var oldTotal = await stub.ChampionsMgr.GetNbItems();
var oldResult = await champs.GetCountChampions();
await champs.Post(ChampionDto);
var newTotal = await stub.ChampionsMgr.GetNbItems();
var newResult = await champs.GetCountChampions();
//Assert
var objectResultOld = oldResult as OkObjectResult;
Assert.IsNotNull(objectResultOld);
var objectResultNew = newResult as OkObjectResult;
Assert.IsNotNull(objectResultNew);
Assert.AreEqual(objectResultOld.Value, oldTotal);
Assert.AreNotEqual(objectResultOld.Value, newTotal);
Assert.AreEqual(objectResultNew.Value, newTotal);
Assert.AreNotEqual(objectResultNew.Value, oldTotal);
}
[TestMethod]
public async Task TestPutChampion()
{
//Arange
var ChampionDto = new ChampionDto
{
Name = "Sylas",
Bio = "Good",
Class = ChampionClassDto.Tank,
Icon = "",
Image = new LargeImageDto() { Base64 = "" },
Skins = new List<SkinDto>()
{
new SkinDto() {Name = "Project", Description = "Test", Icon = "",Image = new LargeImageDto(),Price = 900 }
},
Skills = new List<SkillDto>()
{
new SkillDto() {Name = "Test skill", Description="Empty", Type = SkillTypeDto.Unknown}
}
};
var ChampionDtoPut = new ChampionDto
{
Name = "Sylas",
Bio = "Bad",
Class = ChampionClassDto.Tank,
Icon = "",
Image = new LargeImageDto() { Base64 = "" },
Skins = new List<SkinDto>(),
Skills = new List<SkillDto>()
};
//Act
await champs.Post(ChampionDto);
var championsResult = await champs.Put(ChampionDto.Name, ChampionDtoPut);
//Assert
var objectResult = championsResult as OkObjectResult;
Assert.IsNotNull(objectResult);
var champions = objectResult?.Value as ChampionDto;
Assert.IsNotNull(champions);
Assert.AreNotEqual(ChampionDto.Bio, champions.Bio);
Assert.AreEqual(ChampionDtoPut.Bio, champions.Bio);
}
[TestMethod]
public async Task TestDeleteChampion()
{
//Arange
//Act
var total = await stub.ChampionsMgr.GetNbItems();
var championsResult = await champs.Delete("Renekton");
//Assert
var objectResult = championsResult as NoContentResult;
Assert.IsNotNull(objectResult);
Assert.AreNotEqual(await stub.ChampionsMgr.GetNbItems(), total);
}
}
}

@ -0,0 +1,219 @@
using ApiLol.Controllers;
using ApiLol.Controllers.v2;
using DTO;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using StubLib;
namespace ApiTests
{
[TestClass]
public class ChampionsControllerTestV2
{
private readonly StubData stub;
private readonly ChampionsController champs;
public ChampionsControllerTestV2()
{
stub = new StubData();
champs = new ChampionsController(stub, new NullLogger<ChampionsController>());
}
[TestMethod]
public async Task TestGetChampions()
{
//Arrange
//Act
var total = await stub.ChampionsMgr.GetNbItems();
var champion = await champs.Get(new PageRequest());
//Assert
var objectResult = champion as OkObjectResult;
Assert.IsNotNull(objectResult);
var champions = objectResult?.Value as IEnumerable<ChampionDto>;
Assert.IsNotNull(champions);
Assert.AreEqual(champions.Count(), total);
}
[TestMethod]
public async Task TestGetV3Champions()
{
//Arrange
//Act
var total = await stub.ChampionsMgr.GetNbItems();
var champion = await champs.GetV3(new PageRequest());
//Assert
var objectResult = champion as OkObjectResult;
Assert.IsNotNull(objectResult);
var skinsResult = objectResult?.Value as PageResponse<ChampionDto>;
Assert.IsNotNull(skinsResult);
var result = skinsResult?.Data as IEnumerable<ChampionDto>;
Assert.IsNotNull(result);
Assert.AreEqual(result.Count(), total);
}
[TestMethod]
public async Task TestCountChampion()
{
//Arange
var ChampionDto = new ChampionDto
{
Name = "Sylas",
Bio = "Good",
Class = ChampionClassDto.Tank,
Icon = "",
Image = new LargeImageDto() { Base64 = "" },
Skins = new List<SkinDto>()
{
new SkinDto() {Name = "Project", Description = "Test", Icon = "",Image = new LargeImageDto(),Price = 900 }
},
Skills = new List<SkillDto>()
{
new SkillDto() {Name = "Test skill", Description="Empty", Type = SkillTypeDto.Unknown}
}
};
//Act
var oldTotal = await stub.ChampionsMgr.GetNbItems();
var oldResult = await champs.GetCountChampions();
await champs.Post(ChampionDto);
var newTotal = await stub.ChampionsMgr.GetNbItems();
var newResult = await champs.GetCountChampions();
//Assert
var objectResultOld = oldResult as OkObjectResult;
Assert.IsNotNull(objectResultOld);
var objectResultNew = newResult as OkObjectResult;
Assert.IsNotNull(objectResultNew);
Assert.AreEqual(objectResultOld.Value, oldTotal);
Assert.AreNotEqual(objectResultOld.Value, newTotal);
Assert.AreEqual(objectResultNew.Value, newTotal);
Assert.AreNotEqual(objectResultNew.Value, oldTotal);
}
[TestMethod]
public async Task TestPostChampion()
{
//Arange
var ChampionDto = new ChampionDto
{
Name = "Sylas",
Bio = "Good",
Class = ChampionClassDto.Tank,
Icon = "",
Image = new LargeImageDto() { Base64 = "" },
Skins = new List<SkinDto>()
{
new SkinDto() {Name = "Project", Description = "Test", Icon = "",Image = new LargeImageDto(),Price = 900 }
},
Skills = new List<SkillDto>()
{
new SkillDto() {Name = "Test skill", Description="Empty", Type = SkillTypeDto.Unknown}
}
};
//Act
var championsResult = await champs.Post(ChampionDto);
//Assert
var objectResult = championsResult as CreatedAtActionResult;
Assert.IsNotNull(objectResult);
var champions = objectResult?.Value as ChampionDto;
Assert.IsNotNull(champions);
Assert.AreEqual("Sylas", champions.Name);
Assert.AreEqual("Project", champions.Skins.First().Name);
Assert.AreEqual("Test", champions.Skins.First().Description);
Assert.AreEqual("Test skill", champions.Skills.First().Name);
Assert.AreEqual("Empty", champions.Skills.First().Description);
}
[TestMethod]
public async Task TestPutChampion()
{
//Arange
var ChampionDto = new ChampionDto
{
Name = "Sylas",
Bio = "Good",
Class = ChampionClassDto.Tank,
Icon = "",
Image = new LargeImageDto() { Base64 = "" },
Skins = new List<SkinDto>()
{
new SkinDto() {Name = "Project", Description = "Test", Icon = "",Image = new LargeImageDto(),Price = 900 }
},
Skills = new List<SkillDto>()
{
new SkillDto() {Name = "Test skill", Description="Empty", Type = SkillTypeDto.Unknown}
}
};
var ChampionDtoPut = new ChampionDto
{
Name = "new Sylas",
Bio = "Bad",
Class = ChampionClassDto.Tank,
Icon = "",
Image = new LargeImageDto() { Base64 = "" },
Skins = new List<SkinDto>(),
Skills = new List<SkillDto>()
};
//Act
await champs.Post(ChampionDto);
var championsResult = await champs.Put(ChampionDto.Name, ChampionDtoPut);
//Assert
var objectResult = championsResult as OkObjectResult;
Assert.IsNotNull(objectResult);
var champions = objectResult?.Value as ChampionDto;
Assert.IsNotNull(champions);
Assert.AreNotEqual(ChampionDto.Bio, champions.Bio);
Assert.AreNotEqual(ChampionDto.Name, champions.Name);
Assert.AreEqual(ChampionDtoPut.Bio, champions.Bio);
Assert.AreEqual(ChampionDtoPut.Name, champions.Name);
}
[TestMethod]
public async Task TestDeleteChampion()
{
//Arange
//Act
var total = await stub.ChampionsMgr.GetNbItems();
var championsResult = await champs.Delete("Renekton");
//Assert
var objectResult = championsResult as NoContentResult;
Assert.IsNotNull(objectResult);
Assert.AreNotEqual(await stub.ChampionsMgr.GetNbItems(), total);
}
}
}

@ -0,0 +1,162 @@
using ApiLol.Controllers;
using DTO;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging.Abstractions;
using StubLib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ApiTests
{
[TestClass]
public class RunePagesControllerTest
{
private readonly StubData stub;
private readonly RunePagesController runePages;
public RunePagesControllerTest()
{
stub = new StubData();
runePages = new RunePagesController(stub, new NullLogger<RunePagesController>());
}
[TestMethod]
public async Task TestGetRunePage()
{
//Arrange
//Act
var total = await stub.RunePagesMgr.GetNbItems();
var runePage = await runePages.Get(new PageRequest());
//Assert
var objectResult = runePage as OkObjectResult;
Assert.IsNotNull(objectResult);
var runePResult = objectResult.Value as PageResponse<RunePageDto>;
Assert.IsNotNull(runePResult);
var runePagesResult = runePResult.Data as IEnumerable<RunePageDto>;
Assert.IsNotNull(runePagesResult);
Assert.AreEqual(runePagesResult.Count(), total);
}
[TestMethod]
public async Task TestCountRunePage()
{
//Arange
var runePageDto = new RunePageDto
{
Name = "rune page 2",
Runes = new Dictionary<string, RuneDto>()
};
//Act
var oldTotal = await stub.RunePagesMgr.GetNbItems();
var oldResult = await runePages.GetCountRunePages();
await runePages.Post(runePageDto);
var newTotal = await stub.RunePagesMgr.GetNbItems();
var newResult = await runePages.GetCountRunePages();
//Assert
var objectResultOld = oldResult as OkObjectResult;
Assert.IsNotNull(objectResultOld);
var objectResultNew = newResult as OkObjectResult;
Assert.IsNotNull(objectResultNew);
Assert.AreEqual(objectResultOld.Value, oldTotal);
Assert.AreNotEqual(objectResultOld.Value, newTotal);
Assert.AreEqual(objectResultNew.Value, newTotal);
Assert.AreNotEqual(objectResultNew.Value, oldTotal);
}
[TestMethod]
public async Task TestPostRunePage()
{
//Arange
var runePageDto = new RunePageDto
{
Name = "rune page 2",
Runes = new Dictionary<string, RuneDto>()
};
//Act
var total = await stub.RunePagesMgr.GetNbItems();
var runePageResult = await runePages.Post(runePageDto);
//Assert
var objectResult = runePageResult as CreatedAtActionResult;
Assert.IsNotNull(objectResult);
var rp = objectResult?.Value as RunePageDto;
Assert.IsNotNull(rp);
Assert.AreEqual("rune page 2", rp.Name);
Assert.AreNotEqual(total, await stub.RunePagesMgr.GetNbItems());
}
[TestMethod]
public async Task TestPutRunePage()
{
//Arange
var runePageDto = new RunePageDto
{
Name = "rune page 2",
Runes = new Dictionary<string, RuneDto>()
};
var runePageDtoPut = new RunePageDto
{
Name = "rune page 3",
Runes = new Dictionary<string, RuneDto>()
};
//Act
await runePages.Post(runePageDto);
var runePagesResult = await runePages.Put(runePageDto.Name, runePageDtoPut);
//Assert
var objectResult = runePagesResult as OkObjectResult;
Assert.IsNotNull(objectResult);
var rpResult = objectResult?.Value as RunePageDto;
Assert.IsNotNull(rpResult);
Assert.AreNotEqual(runePageDto.Name, rpResult.Name);
Assert.AreEqual(runePageDtoPut.Name, rpResult.Name);
}
[TestMethod]
public async Task TestDeleteRunePage()
{
//Arange
//Act
var total = await stub.RunePagesMgr.GetNbItems();
var runePagesResult = await runePages.Delete("rune page 1");
//Assert
var objectResult = runePagesResult as NoContentResult;
Assert.IsNotNull(objectResult);
Assert.AreNotEqual(await stub.RunePagesMgr.GetNbItems(), total);
}
}
}

@ -0,0 +1,174 @@
using ApiLol.Controllers;
using DTO;
using DTO.enums;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging.Abstractions;
using StubLib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ApiTests
{
[TestClass]
public class RunesControllerTest
{
private readonly StubData stub;
private readonly RunesController runes;
public RunesControllerTest()
{
stub = new StubData();
runes = new RunesController(stub, new NullLogger<RunesController>());
}
[TestMethod]
public async Task TestGetRunes()
{
//Arrange
//Act
var total = await stub.RunesMgr.GetNbItems();
var rune = await runes.Get(new PageRequest());
//Assert
var objectResult = rune as OkObjectResult;
Assert.IsNotNull(objectResult);
var runesResult = objectResult.Value as PageResponse<RuneDto>;
Assert.IsNotNull(runesResult);
var result = runesResult.Data as IEnumerable<RuneDto>;
Assert.IsNotNull(result);
Assert.AreEqual(result.Count(), total);
Assert.AreEqual(total, runesResult.total);
}
[TestMethod]
public async Task TestPostRune()
{
//Arange
var runeDto = new RuneDto
{
Name = "Project",
Description = "Test",
Icon = "",
Image = new LargeImageDto(),
Family = RuneFamilyDto.Precision
};
//Act
var total = await stub.RunesMgr.GetNbItems();
var runesResult = await runes.Post(runeDto);
//Assert
var objectResult = runesResult as CreatedAtActionResult;
Assert.IsNotNull(objectResult);
var isRuneDto = objectResult?.Value as RuneDto;
Assert.IsNotNull(isRuneDto);
Assert.AreNotEqual(total, await stub.RunesMgr.GetNbItems());
}
[TestMethod]
public async Task TestCountRunes()
{
//Arange
var runeDto = new RuneDto
{
Name = "Project",
Description = "Test",
Icon = "",
Image = new LargeImageDto(),
Family = RuneFamilyDto.Domination
};
//Act
var oldTotal = await stub.RunesMgr.GetNbItems();
var oldResult = await runes.GetCountRunes();
await runes.Post(runeDto);
var newTotal = await stub.RunesMgr.GetNbItems();
var newResult = await runes.GetCountRunes();
//Assert
var objectResultOld = oldResult as OkObjectResult;
Assert.IsNotNull(objectResultOld);
var objectResultNew = newResult as OkObjectResult;
Assert.IsNotNull(objectResultNew);
Assert.AreEqual(objectResultOld.Value, oldTotal);
Assert.AreNotEqual(objectResultOld.Value, newTotal);
Assert.AreEqual(objectResultNew.Value, newTotal);
Assert.AreNotEqual(objectResultNew.Value, oldTotal);
}
[TestMethod]
public async Task TestPutRune()
{
//Arange
var runeDto = new RuneDto
{
Name = "Project",
Description = "Test",
Icon = "",
Image = new LargeImageDto(),
Family = RuneFamilyDto.Precision
};
var runeDtoPut = new RuneDto
{
Name = "New Project",
Description = "new Test",
Icon = "",
Image = new LargeImageDto(),
Family = RuneFamilyDto.Unknown
};
//Act
await runes.Post(runeDto);
var runesResult = await runes.Put(runeDto.Name, runeDtoPut);
//Assert
var objectResult = runesResult as OkObjectResult;
Assert.IsNotNull(objectResult);
var rune = objectResult?.Value as RuneDto;
Assert.IsNotNull(rune);
Assert.AreNotEqual(runeDto.Description, rune.Description);
Assert.AreNotEqual(runeDto.Family, rune.Family);
Assert.AreEqual(runeDtoPut.Description, rune.Description);
Assert.AreEqual(runeDtoPut.Family, rune.Family);
}
[TestMethod]
public async Task TestDeleteRune()
{
//Arange
//Act
var total = await stub.RunesMgr.GetNbItems();
var result = await runes.Delete("Conqueror");
//Assert
var objectResult = result as NoContentResult;
Assert.IsNotNull(objectResult);
Assert.AreNotEqual(await stub.RunesMgr.GetNbItems(), total);
}
}
}

@ -22,7 +22,7 @@ namespace ApiTests
skins = new SkinsController(stub, new NullLogger<SkinsController>());
}
/* [TestMethod]
[TestMethod]
public async Task TestGetSkins()
{
//Arrange
@ -35,92 +35,145 @@ namespace ApiTests
var objectResult = skin as OkObjectResult;
Assert.IsNotNull(objectResult);
var skinsResult = objectResult?.Value as IEnumerable<SkinDtoC>;
var skinsResult = objectResult.Value as PageResponse<SkinDtoC>;
Assert.IsNotNull(skinsResult);
Assert.AreEqual(skinsResult.Count(), total);
var result = skinsResult.Data as IEnumerable<SkinDtoC>;
Assert.IsNotNull(result);
Assert.AreEqual(result.Count(), total);
Assert.AreEqual(total, skinsResult.total);
}*/
}
/* [TestMethod]
[TestMethod]
public async Task TestPostSkin()
{
//Arange
var SkinDto = new SkinDtoC
{
Name = "Project",
ChampionName = "Aatrox"
Name = "Project Pyke",
Description = "Test",
Icon = "",
Image = new LargeImageDto(),
Price = 900,
ChampionName = "Volibear"
};
//Act
var total = await stub.SkinsMgr.GetNbItems();
var skinsResult = await skins.Post(SkinDto);
//Assert
var objectResult = skinsResult as CreatedAtActionResult;
Assert.IsNotNull(objectResult);
var champions = objectResult?.Value as Ski;
Assert.IsNotNull(champions);
var isSkinDto = objectResult?.Value as SkinDtoC;
Assert.IsNotNull(isSkinDto);
Assert.AreEqual(total + 1, await stub.SkinsMgr.GetNbItems());
}
[TestMethod]
public async Task TestCountSkins()
{
//Arange
var SkinDto = new SkinDtoC
{
Name = "Project Pyke",
Description = "Test",
Icon = "",
Image = new LargeImageDto(),
Price = 900,
ChampionName = "Volibear"
};
//Act
var oldTotal = await stub.SkinsMgr.GetNbItems();
var oldResult = await skins.GetCountSkins();
await skins.Post(SkinDto);
var newTotal = await stub.SkinsMgr.GetNbItems();
var newResult = await skins.GetCountSkins();
//Assert
var objectResultOld = oldResult as OkObjectResult;
Assert.IsNotNull(objectResultOld);
var objectResultNew = newResult as OkObjectResult;
Assert.IsNotNull(objectResultNew);
Assert.AreEqual(objectResultOld.Value, oldTotal);
Assert.AreNotEqual(objectResultOld.Value, newTotal);
Assert.AreEqual(objectResultNew.Value, newTotal);
Assert.AreNotEqual(objectResultNew.Value, oldTotal);
}*/
/* [TestMethod]
}
[TestMethod]
public async Task TestPutSkin()
{
//Arange
var ChampionDto = new ChampionDto
var SkinDto = new SkinDtoC
{
Name = "Sylas",
Bio = "Good",
Class = ChampionClassDto.Tank,
Name = "Project",
Description = "Test",
Icon = "",
Image = new LargeImageDto() { Base64 = "" },
Skins = new List<SkinDto>()
Image = new LargeImageDto(),
Price = 900,
ChampionName = "Volibear"
};
var ChampionDtoPut = new ChampionDto
var SkinDtoPut = new SkinDtoC
{
Name = "Sylas",
Bio = "Bad",
Class = ChampionClassDto.Tank,
Name = "new Project",
Description = "ForTestTest",
Icon = "",
Image = new LargeImageDto() { Base64 = "" },
Skins = new List<SkinDto>()
Image = new LargeImageDto(),
Price = 850,
ChampionName = "Volibear"
};
//Act
await champs.Post(ChampionDto);
var championsResult = await champs.Put(ChampionDto.Name, ChampionDtoPut);
await skins.Post(SkinDto);
var skinsResult = await skins.Put(SkinDto.Name, SkinDtoPut);
//Assert
var objectResult = championsResult as OkObjectResult;
var objectResult = skinsResult as OkObjectResult;
Assert.IsNotNull(objectResult);
var champions = objectResult?.Value as ChampionDto;
Assert.IsNotNull(champions);
var skin = objectResult?.Value as SkinDtoC;
Assert.IsNotNull(skin);
Assert.AreNotEqual(SkinDto.Name, skin.Name);
Assert.AreNotEqual(SkinDto.Description, skin.Description);
Assert.AreNotEqual(SkinDto.Price, skin.Price);
Assert.AreNotEqual(ChampionDto.Bio, champions.Bio);
Assert.AreEqual(ChampionDtoPut.Bio, champions.Bio);
Assert.AreEqual(SkinDtoPut.Name, skin.Name);
Assert.AreEqual(SkinDtoPut.Description, skin.Description);
Assert.AreEqual(SkinDtoPut.Price, skin.Price);
}
[TestMethod]
public async Task TestDeleteChampion()
public async Task TestDeleteSkin()
{
//Arange
//Act
var total = await stub.ChampionsMgr.GetNbItems();
var championsResult = await champs.Delete("Akali");
var total = await stub.SkinsMgr.GetNbItems();
var skinsResult = await skins.Delete("Project");
//Assert
var objectResult = championsResult as OkObjectResult;
var objectResult = skinsResult as NoContentResult;
Assert.IsNotNull(objectResult);
Assert.AreEqual(objectResult.Value, true);
Assert.AreNotEqual(await stub.ChampionsMgr.GetNbItems(), total);
Assert.AreNotEqual(await stub.SkinsMgr.GetNbItems(), total);
}*/
}
}
}

@ -124,5 +124,26 @@ namespace UT_EF
}
}
[Fact]
public void Test_DataSeeder()
{
var options = new DbContextOptionsBuilder<LolDbContext>()
.UseInMemoryDatabase(databaseName: "DataSeeder_Test_Champion_database")
.Options;
using (var context = new LolDbContext(options))
{
DataSeeder.SeedData(context);
string nameToFind = "hecarim";
ChampionClassEntity type = ChampionClassEntity.Assassin;
Assert.Equal(1, context.Champions.Where(c => c.Name.ToLower().Contains(nameToFind)).Count());
Assert.Equal(1, context.Champions.Where(c => c.Class == type).Count());
Assert.Equal(3, context.Champions.Count());
}
}
}
}
Loading…
Cancel
Save