Merge branch 'Merge_API_EF' of https://codefirst.iut.uca.fr/git/WhatTheFantasy/WF-PmAPI into Merge_API_EF
continuous-integration/drone/push Build is passing Details

pull/6/head
kekentin 3 weeks ago
commit c13a864252

@ -13,19 +13,19 @@ steps:
- name: retore & build
image: mcr.microsoft.com/dotnet/sdk:8.0
commands:
- dotnet build --configuration Release
- dotnet build WF_EF_Api/WF_EF_Api.sln --configuration Release
depend_on: [clone]
- name: test
image: mcr.microsoft.com/dotnet/sdk:8.0
commands:
- dotnet test
- dotnet test WF_EF_Api/XUnitTest/XUnitTest.csproj
depends_on: [retore & build]
- name: publish
image: mcr.microsoft.com/dotnet/sdk:8.0
commands:
- dotnet publish -c Release -o out
- dotnet publish WF_EF_Api/WfApi/WfApi.csproj -c Release -o out
depends_on: [retore & build, test]
---

@ -38,20 +38,28 @@ namespace Contextlib
.Include(q => q.Commentarys) // collection des commentaires est chargée
.FirstOrDefaultAsync(q => q.Id == idQuote);
var dbU = new DbUsersManager(_context);
var User = await dbU.GetUserByUsername(comment.User.UserName);
if (User == null)
{
throw new ArgumentException("Quote not exist", nameof(comment.User.UserName));
}
if (quote == null)
{
throw new ArgumentException("Quote not exist", nameof(idQuote));
}
comment.User = User;
comment.IdUser = User.Id;
// Lien entre le commentaire et la citation
comment.Quote = quote;
comment.IdQuote = idQuote;
// Ajout commentaire à la collection des commentaires de la citation
quote.Commentarys.Add(comment);
_repo.Insert(comment);
//_repo.Insert(comment);
_context.Add(comment);
await _context.SaveChangesAsync();
}
@ -163,7 +171,13 @@ namespace Contextlib
public async Task RemoveCommentary(int id)
{
_repo.Delete(id);
Commentary? commentary = await GetCommentaryById(id);
if (commentary == null)
{
throw new KeyNotFoundException($"Error : No comment found with the ID: {id}.");
}
_repo.Delete(commentary);
await _context.SaveChangesAsync();
}

@ -5,6 +5,7 @@ using System.Text;
using System.Threading.Tasks;
using Entity;
using Shared;
using static System.Runtime.InteropServices.JavaScript.JSType;
namespace Contextlib
{
@ -40,6 +41,12 @@ namespace Contextlib
throw new NotImplementedException();
}
public async Task<PaginationResult<Source>> GetSomesSource(int page, int count)
{
var srcLst = _repo.GetItems(page, count, []).ToList();
return new PaginationResult<Source>(srcLst.Count, 0, srcLst.Count, srcLst);
}
public async Task<PaginationResult<Source>> GetSourceByDate(int date)
{

@ -53,7 +53,7 @@ namespace Contextlib
.HasMany<Quote>()
.WithMany()
.UsingEntity<Commentary>(
i => i.HasKey(e => new { e.IdUser, e.IdQuote })
i => i.HasKey(e => e.Id)
);
modelBuilder.Entity<Commentary>()

@ -282,7 +282,9 @@ namespace Dto2Entities
commentary.Id = item.Id;
commentary.DateCommentary = item.Date;
commentary.Comment = item.Comment;
commentary.User = new Users();
commentary.User.UserName = item.User;
commentary.User.Images = new Images();
commentary.User.Images.ImgPath = item.ImagePath;
return commentary;
}

@ -42,7 +42,14 @@ namespace ServicesApi
public async Task<CommentaryDTO> GetCommentaryById(int id)
{
return commentaryService.GetCommentaryById(id).Result.ToDto();
try
{
return (await commentaryService.GetCommentaryById(id)).ToDto();
}
catch(KeyNotFoundException)
{
throw new KeyNotFoundException($"No comments found with the given ID: {id}.");
}
}
public async Task<PaginationResult<CommentaryDTO>> GetCommentaryByQuote(int quoteId, int index, int pageSize)

@ -36,16 +36,21 @@ namespace ServicesApi
return await srcService.GetLastSourceId();
}
public async Task<PaginationResult<SourceDTO>> GetSomesSource(int page, int count)
{
var sources = (await srcService.GetSomesSource(page, count)).items;
return new PaginationResult<SourceDTO>(sources.Count(), page, count, sources.ToDto());
}
public async Task<PaginationResult<SourceDTO>> GetSourceByDate(int date)
{
var sources = (await srcService.GetSourceByDate(date)).items;
return new PaginationResult<SourceDTO>(sources.Count(), 0, 10, sources.ToDto());
}
public async Task<SourceDTO> GetSourceById(int id)
{
return srcService.GetSourceById(id).Result.ToDto();
return (await srcService.GetSourceById(id)).ToDto();
}
public async Task<SourceDTO> GetSourceByTitle(string title)

@ -42,5 +42,7 @@ namespace Shared
// Retrieves the unique identifier of the last added source.
Task<int> GetLastSourceId();
Task<PaginationResult<TSource>> GetSomesSource(int page, int count);
}
}

File diff suppressed because it is too large Load Diff

@ -1,22 +0,0 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace StubbedContextLib.Migrations
{
/// <inheritdoc />
public partial class migr1 : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
}

File diff suppressed because it is too large Load Diff

@ -1,126 +0,0 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace StubbedContextLib.Migrations
{
/// <inheritdoc />
public partial class migr5 : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<bool>(
name: "IsValid",
table: "question",
type: "bit",
nullable: false,
defaultValue: false);
migrationBuilder.CreateTable(
name: "admins",
columns: table => new
{
IdUsers = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
UserId = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_admins", x => x.IdUsers);
table.ForeignKey(
name: "FK_admins_users_UserId",
column: x => x.UserId,
principalTable: "users",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.UpdateData(
table: "question",
keyColumn: "Id",
keyValue: 1,
column: "IsValid",
value: true);
migrationBuilder.UpdateData(
table: "question",
keyColumn: "Id",
keyValue: 2,
column: "IsValid",
value: false);
migrationBuilder.UpdateData(
table: "question",
keyColumn: "Id",
keyValue: 3,
column: "IsValid",
value: true);
migrationBuilder.UpdateData(
table: "question",
keyColumn: "Id",
keyValue: 4,
column: "IsValid",
value: true);
migrationBuilder.UpdateData(
table: "question",
keyColumn: "Id",
keyValue: 5,
column: "IsValid",
value: true);
migrationBuilder.UpdateData(
table: "question",
keyColumn: "Id",
keyValue: 6,
column: "IsValid",
value: true);
migrationBuilder.UpdateData(
table: "question",
keyColumn: "Id",
keyValue: 7,
column: "IsValid",
value: true);
migrationBuilder.UpdateData(
table: "question",
keyColumn: "Id",
keyValue: 8,
column: "IsValid",
value: true);
migrationBuilder.UpdateData(
table: "question",
keyColumn: "Id",
keyValue: 9,
column: "IsValid",
value: true);
migrationBuilder.UpdateData(
table: "question",
keyColumn: "Id",
keyValue: 10,
column: "IsValid",
value: true);
migrationBuilder.CreateIndex(
name: "IX_admins_UserId",
table: "admins",
column: "UserId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "admins");
migrationBuilder.DropColumn(
name: "IsValid",
table: "question");
}
}
}

@ -1,61 +0,0 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace StubbedContextLib.Migrations
{
/// <inheritdoc />
public partial class suprDailyQuote : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "dailyquotes");
migrationBuilder.UpdateData(
table: "quotes",
keyColumn: "Id",
keyValue: 10,
column: "IsValid",
value: false);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "dailyquotes",
columns: table => new
{
IdQuote = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_dailyquotes", x => x.IdQuote);
table.ForeignKey(
name: "FK_dailyquotes_quotes_IdQuote",
column: x => x.IdQuote,
principalTable: "quotes",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.InsertData(
table: "dailyquotes",
column: "IdQuote",
values: new object[]
{
1,
5
});
migrationBuilder.UpdateData(
table: "quotes",
keyColumn: "Id",
keyValue: 10,
column: "IsValid",
value: true);
}
}
}

@ -1,32 +0,0 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace StubbedContextLib.Migrations
{
/// <inheritdoc />
public partial class myFirstMigration : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.UpdateData(
table: "quotes",
keyColumn: "Id",
keyValue: 10,
column: "IsValid",
value: false);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.UpdateData(
table: "quotes",
keyColumn: "Id",
keyValue: 10,
column: "IsValid",
value: true);
}
}
}

@ -1,22 +0,0 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace StubbedContextLib.Migrations
{
/// <inheritdoc />
public partial class migration204 : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
}

@ -1,22 +0,0 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace StubbedContextLib.Migrations
{
/// <inheritdoc />
public partial class migration1 : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
}

@ -12,8 +12,8 @@ using StubbedContextLib;
namespace StubbedContextLib.Migrations
{
[DbContext(typeof(StubWTFContext))]
[Migration("20250402105029_migration1")]
partial class migration1
[Migration("20250402113707_pm_api")]
partial class pm_api
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)

@ -8,7 +8,7 @@ using Microsoft.EntityFrameworkCore.Migrations;
namespace StubbedContextLib.Migrations
{
/// <inheritdoc />
public partial class migrationTest1 : Migration
public partial class pm_api : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
@ -37,7 +37,8 @@ namespace StubbedContextLib.Migrations
AnswerB = table.Column<string>(type: "nvarchar(50)", maxLength: 50, nullable: false),
AnswerC = table.Column<string>(type: "nvarchar(50)", maxLength: 50, nullable: false),
AnswerD = table.Column<string>(type: "nvarchar(50)", maxLength: 50, nullable: false),
CorrectAnswer = table.Column<string>(type: "nvarchar(1)", maxLength: 1, nullable: false)
CorrectAnswer = table.Column<string>(type: "nvarchar(1)", maxLength: 1, nullable: false),
IsValid = table.Column<bool>(type: "bit", nullable: false)
},
constraints: table =>
{
@ -147,6 +148,25 @@ namespace StubbedContextLib.Migrations
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "admins",
columns: table => new
{
IdUsers = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
UserId = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_admins", x => x.IdUsers);
table.ForeignKey(
name: "FK_admins_users_UserId",
column: x => x.UserId,
principalTable: "users",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "quotes",
columns: table => new
@ -210,23 +230,6 @@ namespace StubbedContextLib.Migrations
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "dailyquotes",
columns: table => new
{
IdQuote = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_dailyquotes", x => x.IdQuote);
table.ForeignKey(
name: "FK_dailyquotes_quotes_IdQuote",
column: x => x.IdQuote,
principalTable: "quotes",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "favorites",
columns: table => new
@ -268,19 +271,19 @@ namespace StubbedContextLib.Migrations
migrationBuilder.InsertData(
table: "question",
columns: new[] { "Id", "AnswerA", "AnswerB", "AnswerC", "AnswerD", "CorrectAnswer", "Text" },
columns: new[] { "Id", "AnswerA", "AnswerB", "AnswerC", "AnswerD", "CorrectAnswer", "IsValid", "Text" },
values: new object[,]
{
{ 1, "Gimli", "Aragorn", "Frodon", "Gandalf", "B", "Qui est le leader de la Communauté de l'Anneau ?" },
{ 2, "Serdaigle", "Gryffondor", "Serpentard", "Poufsouffle", "B", "Dans quelle maison Harry Potter est-il ?" },
{ 3, "Saroumane", "Sauron", "Gollum", "Gothmog", "B", "Qui est le Seigneur des Ténèbres dans la saga Le Seigneur des Anneaux ?" },
{ 4, "Han Solo", "Princesse Leia", "Chewbacca", "R2-D2", "A", "Dans le film Star Wars : Episode IV, qui sauve Luke Skywalker de l'Étoile de la Mort ?" },
{ 5, "Reine Jadis", "Aslan", "Edmund", "Lucy", "B", "Qui est le souverain de Narnia dans Le Lion, la Sorcière Blanche et l'Armoire Magique ?" },
{ 6, "Smaug", "Falkor", "Norbert", "Shenron", "A", "Quel est le nom du dragon dans Le Hobbit ?" },
{ 7, "Bella Swan", "Edward Cullen", "Jacob Black", "Victoria", "A", "Qui est la première personne à être mordue par un vampire dans Twilight ?" },
{ 8, "Obi-Wan Kenobi", "Yoda", "Han Solo", "Luke Skywalker", "A", "Quel personnage dit Que la Force soit avec toi dans Star Wars ?" },
{ 9, "Dr. Ellie Sattler", "Alan Grant", "John Hammond", "Dennis Nedry", "B", "Dans Jurassic Park, quel est le nom du paléontologue sur l'île ?" },
{ 10, "Cersei Lannister", "Arya Stark", "Daenerys Targaryen", "Sansa Stark", "C", "Dans Game of Thrones, qui est surnommée la Mère des Dragons ?" }
{ 1, "Gimli", "Aragorn", "Frodon", "Gandalf", "B", true, "Qui est le leader de la Communauté de l'Anneau ?" },
{ 2, "Serdaigle", "Gryffondor", "Serpentard", "Poufsouffle", "B", false, "Dans quelle maison Harry Potter est-il ?" },
{ 3, "Saroumane", "Sauron", "Gollum", "Gothmog", "B", true, "Qui est le Seigneur des Ténèbres dans la saga Le Seigneur des Anneaux ?" },
{ 4, "Han Solo", "Princesse Leia", "Chewbacca", "R2-D2", "A", true, "Dans le film Star Wars : Episode IV, qui sauve Luke Skywalker de l'Étoile de la Mort ?" },
{ 5, "Reine Jadis", "Aslan", "Edmund", "Lucy", "B", true, "Qui est le souverain de Narnia dans Le Lion, la Sorcière Blanche et l'Armoire Magique ?" },
{ 6, "Smaug", "Falkor", "Norbert", "Shenron", "A", true, "Quel est le nom du dragon dans Le Hobbit ?" },
{ 7, "Bella Swan", "Edward Cullen", "Jacob Black", "Victoria", "A", true, "Qui est la première personne à être mordue par un vampire dans Twilight ?" },
{ 8, "Obi-Wan Kenobi", "Yoda", "Han Solo", "Luke Skywalker", "A", true, "Quel personnage dit Que la Force soit avec toi dans Star Wars ?" },
{ 9, "Dr. Ellie Sattler", "Alan Grant", "John Hammond", "Dennis Nedry", "B", true, "Dans Jurassic Park, quel est le nom du paléontologue sur l'île ?" },
{ 10, "Cersei Lannister", "Arya Stark", "Daenerys Targaryen", "Sansa Stark", "C", true, "Dans Game of Thrones, qui est surnommée la Mère des Dragons ?" }
});
migrationBuilder.InsertData(
@ -369,7 +372,7 @@ namespace StubbedContextLib.Migrations
{ 7, "Je suis la dernière Targaryen. Je suis la reine des dragons", 7, 3, 1, true, 1, 11025 },
{ 8, "Je ne suis pas prêt à affronter ça. C'est trop pour moi.", 8, 5, 1, true, 1, 11025 },
{ 9, "Aidez-moi, Obi-Wan Kenobi, vous êtes mon seul espoir.", 9, 5, 1, true, 1, 11025 },
{ 10, "La quoi ?", 10, 4, 1, true, 1, 11025 }
{ 10, "La quoi ?", 10, 4, 1, false, 1, 11025 }
});
migrationBuilder.InsertData(
@ -381,15 +384,6 @@ namespace StubbedContextLib.Migrations
{ 1, 3, "Very good", new DateTime(2025, 3, 11, 0, 0, 0, 0, DateTimeKind.Unspecified), 2 }
});
migrationBuilder.InsertData(
table: "dailyquotes",
column: "IdQuote",
values: new object[]
{
1,
5
});
migrationBuilder.InsertData(
table: "favorites",
columns: new[] { "IdQuote", "IdUsers" },
@ -406,6 +400,11 @@ namespace StubbedContextLib.Migrations
{ 10, 5 }
});
migrationBuilder.CreateIndex(
name: "IX_admins_UserId",
table: "admins",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_characters_IdImage",
table: "characters",
@ -456,10 +455,10 @@ namespace StubbedContextLib.Migrations
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "comments");
name: "admins");
migrationBuilder.DropTable(
name: "dailyquotes");
name: "comments");
migrationBuilder.DropTable(
name: "favorites");

@ -12,8 +12,8 @@ using StubbedContextLib;
namespace StubbedContextLib.Migrations
{
[DbContext(typeof(StubWTFContext))]
[Migration("20250401141906_suprDailyQuote")]
partial class suprDailyQuote
[Migration("20250402134601_pm_apiV2")]
partial class pm_apiV2
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
@ -130,11 +130,11 @@ namespace StubbedContextLib.Migrations
modelBuilder.Entity("Entity.Commentary", b =>
{
b.Property<int>("IdUser")
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<int>("IdQuote")
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("Comment")
.IsRequired()
@ -145,34 +145,36 @@ namespace StubbedContextLib.Migrations
.HasColumnType("date")
.HasColumnName("DateCommentary");
b.Property<int>("Id")
.ValueGeneratedOnAdd()
b.Property<int>("IdQuote")
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("IdUser")
.HasColumnType("int");
b.HasKey("IdUser", "IdQuote");
b.HasKey("Id");
b.HasIndex("IdQuote");
b.HasIndex("IdUser");
b.ToTable("comments");
b.HasData(
new
{
IdUser = 2,
IdQuote = 1,
Id = 1,
Comment = "Ce film est le meilleur",
DateCommentary = new DateTime(2025, 2, 3, 0, 0, 0, 0, DateTimeKind.Unspecified),
Id = 1
IdQuote = 1,
IdUser = 2
},
new
{
IdUser = 3,
IdQuote = 1,
Id = 2,
Comment = "Very good",
DateCommentary = new DateTime(2025, 3, 11, 0, 0, 0, 0, DateTimeKind.Unspecified),
Id = 2
IdQuote = 1,
IdUser = 3
});
});

@ -0,0 +1,86 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
#pragma warning disable CA1814 // Prefer jagged arrays over multidimensional
namespace StubbedContextLib.Migrations
{
/// <inheritdoc />
public partial class pm_apiV2 : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropPrimaryKey(
name: "PK_comments",
table: "comments");
migrationBuilder.DeleteData(
table: "comments",
keyColumns: new[] { "IdQuote", "IdUser" },
keyValues: new object[] { 1, 2 });
migrationBuilder.DeleteData(
table: "comments",
keyColumns: new[] { "IdQuote", "IdUser" },
keyValues: new object[] { 1, 3 });
migrationBuilder.AddPrimaryKey(
name: "PK_comments",
table: "comments",
column: "Id");
migrationBuilder.InsertData(
table: "comments",
columns: new[] { "Id", "Comment", "DateCommentary", "IdQuote", "IdUser" },
values: new object[,]
{
{ 1, "Ce film est le meilleur", new DateTime(2025, 2, 3, 0, 0, 0, 0, DateTimeKind.Unspecified), 1, 2 },
{ 2, "Very good", new DateTime(2025, 3, 11, 0, 0, 0, 0, DateTimeKind.Unspecified), 1, 3 }
});
migrationBuilder.CreateIndex(
name: "IX_comments_IdUser",
table: "comments",
column: "IdUser");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropPrimaryKey(
name: "PK_comments",
table: "comments");
migrationBuilder.DropIndex(
name: "IX_comments_IdUser",
table: "comments");
migrationBuilder.DeleteData(
table: "comments",
keyColumn: "Id",
keyValue: 1);
migrationBuilder.DeleteData(
table: "comments",
keyColumn: "Id",
keyValue: 2);
migrationBuilder.AddPrimaryKey(
name: "PK_comments",
table: "comments",
columns: new[] { "IdUser", "IdQuote" });
migrationBuilder.InsertData(
table: "comments",
columns: new[] { "IdQuote", "IdUser", "Comment", "DateCommentary", "Id" },
values: new object[,]
{
{ 1, 2, "Ce film est le meilleur", new DateTime(2025, 2, 3, 0, 0, 0, 0, DateTimeKind.Unspecified), 1 },
{ 1, 3, "Very good", new DateTime(2025, 3, 11, 0, 0, 0, 0, DateTimeKind.Unspecified), 2 }
});
}
}
}

@ -18,4 +18,8 @@
<ProjectReference Include="..\Entity\Entity.csproj" />
</ItemGroup>
<ItemGroup>
<Folder Include="Migrations\" />
</ItemGroup>
</Project>

@ -57,16 +57,18 @@ namespace WfApi.Controllers
return BadRequest(new { message = "Comment data is required." });
}
var existingCommentary = _commentary.GetCommentaryById(newCommentary.Id).Result;
if (existingCommentary != null)
try
{
var existingCommentary = await _commentary.GetCommentaryById(newCommentary.Id);
return Conflict(new { message = "A comment with this ID already exists." });
}
catch (KeyNotFoundException e)
{
await _commentary.AddComment(newCommentary, idQuote);
return CreatedAtAction(nameof(GetCommentary), new { id = newCommentary.Id }, newCommentary);
}
}
catch (Exception)
{
return StatusCode((int)HttpStatusCode.InternalServerError, new { message = "Erreur interne du serveur." });
@ -89,7 +91,7 @@ namespace WfApi.Controllers
return NotFound(new { message = "Commentary not found." });
}
_commentary.RemoveCommentary(existingCommentary.Id);
await _commentary.RemoveCommentary(existingCommentary.Id);
return Ok(new { message = $"Commentary {id} deleted successfully." });
}

@ -33,13 +33,9 @@ namespace WfApi.Controllers
try
{
var result = await _quote.GetQuoteById(id);
if (result == null)
{
throw new KeyNotFoundException($"Error : No quotes found with the ID: {id}.");
}
if (result!=null)
{
return await Task.FromResult<IActionResult>(Ok(result));
return Ok(result);
}
else
{

@ -0,0 +1,125 @@
using System.Net;
using DTO;
using Entity;
using Microsoft.AspNetCore.Mvc;
using Shared;
namespace WfApi.Controllers
{
[Route("api/v1/source")]
[ApiController]
public class SourceController : ControllerBase
{
private readonly ISourceService<SourceDTO> _source;
private readonly ILogger<SourceController> _logger;
public SourceController(ISourceService<SourceDTO> sourceService, ILogger<SourceController> logger)
{
_source = sourceService;
_logger = logger;
}
[HttpGet("{id}")] // Indiquer que l'id est dans l'URL
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> GetSource(int id)
{
try
{
var source = await _source.GetSourceById(id);
if(source != null)
{
return Ok(source);
}
else
{
return NoContent();
}
}
catch(Exception e)
{
return StatusCode((int)HttpStatusCode.InternalServerError, new { message = "Internal Server Error (" + e + ")" });
}
}
[HttpGet("all")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> GetAllSource(int index = 0, int count = 10)
{
try
{
var result = await _source.GetSomesSource(index, count);
if (result != null)
{
return await Task.FromResult<IActionResult>(Ok(result));
}
else
{
return NoContent();
}
}
catch (Exception e)
{
return StatusCode((int)HttpStatusCode.InternalServerError, new { message = "Internal Server Error (" + e + ")" });
}
}
[HttpPost]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> CreateSource([FromBody] SourceDTO newSource)
{
try
{
if(newSource == null)
{
return BadRequest(new { message = "Source data is required." });
}
try
{
var existingSource = await _source.GetSourceById(newSource.Id);
return Conflict(new { message = "A source with this ID already exists." });
}
catch(KeyNotFoundException e)
{
await _source.AddSource(newSource);
return CreatedAtAction(nameof(GetAllSource), new { id = newSource.Id }, newSource);
}
}
catch (Exception e)
{
return StatusCode((int)HttpStatusCode.InternalServerError, new { message = "Internal Server Error (" + e + ")" });
}
}
[HttpPut()]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> UpdateSource([FromQuery] int id, [FromBody] SourceDTO updatedSource)
{
try
{
if (updatedSource == null)
{
return BadRequest(new { message = "new source data is required." });
}
var result = _source.UpdateSource(id, updatedSource);
return Ok(result);
}
catch (Exception e)
{
return StatusCode((int)HttpStatusCode.InternalServerError, new { message = "Internal Server Error (" + e + ")" });
}
}
}
}

@ -11,272 +11,272 @@ namespace XUnitTest
{
public class UnitTest1
{
private readonly Mock<IUserService<UserDTO>> _mockUserService;
private readonly Mock<ILogger<UsersController>> _mockLogger;
private readonly UsersController _userController;
public UnitTest1()
{
// Initialisation des mocks
_mockUserService = new Mock<IUserService<UserDTO>>();
_mockLogger = new Mock<ILogger<UsersController>>();
_userController = new UsersController(_mockUserService.Object, _mockLogger.Object);
}
[Fact]
public async Task Get_ReturnsOk_WhenUserExists()
{
// Arrange
var userId = 1;
var userDTO = new UserDTO
{
Id = userId,
Pseudo = "test",
Email = "test@unitaire.fr",
ImageProfil = "http://test",
Password = "1234"
};
_mockUserService.Setup(service => service.GetUserById(userId)).ReturnsAsync(userDTO);
// Act
var result = await _userController.Get(userId);
// Assert
Assert.IsType<OkObjectResult>(result);
}
[Fact]
public async Task GetAllUsers_ReturnsOk()
{
// Arrange
var userDTO = new UserDTO
{
Id = 1,
Pseudo = "test",
Email = "test@unitaire.fr",
ImageProfil = "http://test",
Password = "1234"
};
var userDTO2 = new UserDTO
{
Id = 2,
Pseudo = "test",
Email = "test@unitaire.fr",
ImageProfil = "http://test",
Password = "1234"
};
_mockUserService.Setup(service => service.GetUserById(1)).ReturnsAsync(userDTO);
_mockUserService.Setup(service => service.GetUserById(2)).ReturnsAsync(userDTO);
// Act
var result = await _userController.GetAllUsers();
// Assert
Assert.IsType<OkObjectResult>(result);
}
//private readonly Mock<IUserService<UserDTO>> _mockUserService;
//private readonly Mock<ILogger<UsersController>> _mockLogger;
//private readonly UsersController _userController;
//public UnitTest1()
//{
// // Initialisation des mocks
// _mockUserService = new Mock<IUserService<UserDTO>>();
// _mockLogger = new Mock<ILogger<UsersController>>();
// _userController = new UsersController(_mockUserService.Object, _mockLogger.Object);
//}
//[Fact]
//public async Task Get_ReturnsOk_WhenUserExists()
//{
// // Arrange
// var userId = 1;
// var userDTO = new UserDTO
// {
// Id = userId,
// Pseudo = "test",
// Email = "test@unitaire.fr",
// ImageProfil = "http://test",
// Password = "1234"
// };
// _mockUserService.Setup(service => service.GetUserById(userId)).ReturnsAsync(userDTO);
// // Act
// var result = await _userController.Get(userId);
// // Assert
// Assert.IsType<OkObjectResult>(result);
//}
//[Fact]
//public async Task GetAllUsers_ReturnsOk()
//{
// // Arrange
// var userDTO = new UserDTO
// {
// Id = 1,
// Pseudo = "test",
// Email = "test@unitaire.fr",
// ImageProfil = "http://test",
// Password = "1234"
// };
// var userDTO2 = new UserDTO
// {
// Id = 2,
// Pseudo = "test",
// Email = "test@unitaire.fr",
// ImageProfil = "http://test",
// Password = "1234"
// };
// _mockUserService.Setup(service => service.GetUserById(1)).ReturnsAsync(userDTO);
// _mockUserService.Setup(service => service.GetUserById(2)).ReturnsAsync(userDTO);
// // Act
// var result = await _userController.GetAllUsers();
// // Assert
// Assert.IsType<OkObjectResult>(result);
//}
//[Fact]
//public async Task GetHashPassword_ReturnsOk_WhenPasswordHashIsFound()
//{
// // Arrange
// var username = "testUser";
// var expectedHash = "hashedPassword";
// var taskResult = Task.FromResult(expectedHash);
// _mockUserService.Setup(service => service.GetHashPassword(username)).Returns(taskResult);
// // Act
// var result = await _userController.GetHashPassword(username);
// // Assert
// Assert.IsType<OkObjectResult>(result);
//}
//[Fact]
//public async Task GetUserByUsername_ReturnsOk_WhenPasswordHashIsFound()
//{
// // Arrange
// var username = "testUser";
// var userDTO = new UserDTO
// {
// Id = 1,
// Pseudo = "testUser",
// Email = "test@unitaire.fr",
// ImageProfil = "http://test",
// Password = "1234"
// };
// var taskResult = Task.FromResult(userDTO);
// _mockUserService.Setup(service => service.GetUserByUsername(username)).Returns(taskResult);
// // Act
// var result = await _userController.GetUserByUsername(username);
// // Assert
// Assert.IsType<OkObjectResult>(result);
//}
//[Fact]
//public async Task GetUserByEmail_ReturnsOk_WhenUserExists()
//{
// // Arrange
// var email = "test@unitaire.fr";
// var userDTO = new UserDTO
// {
// Id = 1,
// Pseudo = "testUser",
// Email = email,
// ImageProfil = "http://test",
// Password = "1234"
// };
// var taskResult = Task.FromResult(userDTO);
// _mockUserService.Setup(service => service.GetUserByEmail(email)).Returns(taskResult);
// // Act
// var result = await _userController.GetUserByEmail(email);
// // Assert
// Assert.IsType<OkObjectResult>(result);
//}
//[Fact]
//public async Task GetCountUser_ReturnsOk_WhenCountIsSuccessful()
//{
// // Arrange
// var expectedCount = 5;
// var taskResult = Task.FromResult(expectedCount);
// _mockUserService.Setup(service => service.CountUser()).Returns(taskResult);
// // Act
// var result = await _userController.GetCountUser();
// // Assert
// Assert.IsType<OkObjectResult>(result);
//}
//[Fact]
//public async Task GetExistUsername_ReturnsOk_WhenUserExists()
//{
// // Arrange
// var username = "testUser";
// var taskResult = Task.FromResult(true);
// _mockUserService.Setup(service => service.ExistUsername(username)).Returns(taskResult);
// // Act
// var result = await _userController.GetExistUsername(username);
// // Assert
// Assert.IsType<OkObjectResult>(result);
//}
//[Fact]
//public async Task GetExistEmail_ReturnsOk_WhenEmailExists()
//{
// // Arrange
// var email = "test@unitaire.fr";
// var taskResult = Task.FromResult(true);
// _mockUserService.Setup(service => service.ExistEmail(email)).Returns(taskResult);
// // Act
// var result = await _userController.GetExistEmail(email);
// // Assert
// Assert.IsType<OkObjectResult>(result);
//}
//[Fact]
//public async Task UpdateUser_ReturnsOk_WhenUserDataIsValid()
//{
// // Arrange
// var id = 1;
// var updatedUser = new UserDTO
// {
// Id = id,
// Pseudo = "UpdatedUser",
// Email = "updated@unitaire.fr",
// ImageProfil = "http://updatedImage.com",
// Password = "newPassword123"
// };
// var taskResult = Task.FromResult(updatedUser);
// _mockUserService.Setup(service => service.UpdateUser(id, updatedUser)).Returns(taskResult);
// // Act
// var result = await _userController.UpdateUser(id, updatedUser);
// // Assert
// var okResult = Assert.IsType<OkObjectResult>(result);
// Assert.IsType<OkObjectResult>(result);
//}
//[Fact]
//public async Task CreateUser_ReturnsCreatedAtAction_WhenUserIsValid()
//{
// // Arrange
// var newUser = new UserDTO
// {
// Id = 2,
// Pseudo = "NewUser",
// Email = "newuser@unitaire.fr",
// ImageProfil = "http://newuserimage.com",
// Password = "newPassword123"
// };
// _mockUserService.Setup(service => service.GetUserById(newUser.Id)).ReturnsAsync((UserDTO)null);
// _mockUserService.Setup(service => service.AddUser(newUser)).Verifiable();
// // Act
// var result = await _userController.CreateUser(newUser);
// // Assert
// var createdResult = Assert.IsType<CreatedAtActionResult>(result);
// Assert.Equal(newUser.Id, createdResult.RouteValues["id"]);
//}
//[Fact]
//public async Task DeletePlayer_ReturnsOk_WhenPlayerExists()
//{
// // Arrange
// var id = 1;
// var existingPlayer = new UserDTO
// {
// Id = id,
// Pseudo = "ExistingUser",
// Email = "existing@unitaire.fr",
// ImageProfil = "http://existingimage.com",
// Password = "existingPassword123"
// };
// _mockUserService.Setup(service => service.GetUserById(id)).ReturnsAsync(existingPlayer);
// _mockUserService.Setup(service => service.RemoveUser(existingPlayer.Id)).Verifiable();
// // Act
// var result = await _userController.DeletePlayer(id);
[Fact]
public async Task GetHashPassword_ReturnsOk_WhenPasswordHashIsFound()
{
// Arrange
var username = "testUser";
var expectedHash = "hashedPassword";
var taskResult = Task.FromResult(expectedHash);
_mockUserService.Setup(service => service.GetHashPassword(username)).Returns(taskResult);
// Act
var result = await _userController.GetHashPassword(username);
// Assert
Assert.IsType<OkObjectResult>(result);
}
[Fact]
public async Task GetUserByUsername_ReturnsOk_WhenPasswordHashIsFound()
{
// Arrange
var username = "testUser";
var userDTO = new UserDTO
{
Id = 1,
Pseudo = "testUser",
Email = "test@unitaire.fr",
ImageProfil = "http://test",
Password = "1234"
};
var taskResult = Task.FromResult(userDTO);
_mockUserService.Setup(service => service.GetUserByUsername(username)).Returns(taskResult);
// Act
var result = await _userController.GetUserByUsername(username);
// Assert
Assert.IsType<OkObjectResult>(result);
}
[Fact]
public async Task GetUserByEmail_ReturnsOk_WhenUserExists()
{
// Arrange
var email = "test@unitaire.fr";
var userDTO = new UserDTO
{
Id = 1,
Pseudo = "testUser",
Email = email,
ImageProfil = "http://test",
Password = "1234"
};
var taskResult = Task.FromResult(userDTO);
_mockUserService.Setup(service => service.GetUserByEmail(email)).Returns(taskResult);
// Act
var result = await _userController.GetUserByEmail(email);
// Assert
Assert.IsType<OkObjectResult>(result);
}
[Fact]
public async Task GetCountUser_ReturnsOk_WhenCountIsSuccessful()
{
// Arrange
var expectedCount = 5;
var taskResult = Task.FromResult(expectedCount);
_mockUserService.Setup(service => service.CountUser()).Returns(taskResult);
// Act
var result = await _userController.GetCountUser();
// Assert
Assert.IsType<OkObjectResult>(result);
}
[Fact]
public async Task GetExistUsername_ReturnsOk_WhenUserExists()
{
// Arrange
var username = "testUser";
var taskResult = Task.FromResult(true);
_mockUserService.Setup(service => service.ExistUsername(username)).Returns(taskResult);
// Act
var result = await _userController.GetExistUsername(username);
// Assert
Assert.IsType<OkObjectResult>(result);
}
[Fact]
public async Task GetExistEmail_ReturnsOk_WhenEmailExists()
{
// Arrange
var email = "test@unitaire.fr";
var taskResult = Task.FromResult(true);
_mockUserService.Setup(service => service.ExistEmail(email)).Returns(taskResult);
// Act
var result = await _userController.GetExistEmail(email);
// Assert
Assert.IsType<OkObjectResult>(result);
}
[Fact]
public async Task UpdateUser_ReturnsOk_WhenUserDataIsValid()
{
// Arrange
var id = 1;
var updatedUser = new UserDTO
{
Id = id,
Pseudo = "UpdatedUser",
Email = "updated@unitaire.fr",
ImageProfil = "http://updatedImage.com",
Password = "newPassword123"
};
var taskResult = Task.FromResult(updatedUser);
_mockUserService.Setup(service => service.UpdateUser(id, updatedUser)).Returns(taskResult);
// Act
var result = await _userController.UpdateUser(id, updatedUser);
// Assert
var okResult = Assert.IsType<OkObjectResult>(result);
Assert.IsType<OkObjectResult>(result);
}
[Fact]
public async Task CreateUser_ReturnsCreatedAtAction_WhenUserIsValid()
{
// Arrange
var newUser = new UserDTO
{
Id = 2,
Pseudo = "NewUser",
Email = "newuser@unitaire.fr",
ImageProfil = "http://newuserimage.com",
Password = "newPassword123"
};
_mockUserService.Setup(service => service.GetUserById(newUser.Id)).ReturnsAsync((UserDTO)null);
_mockUserService.Setup(service => service.AddUser(newUser)).Verifiable();
// Act
var result = await _userController.CreateUser(newUser);
// Assert
var createdResult = Assert.IsType<CreatedAtActionResult>(result);
Assert.Equal(newUser.Id, createdResult.RouteValues["id"]);
}
[Fact]
public async Task DeletePlayer_ReturnsOk_WhenPlayerExists()
{
// Arrange
var id = 1;
var existingPlayer = new UserDTO
{
Id = id,
Pseudo = "ExistingUser",
Email = "existing@unitaire.fr",
ImageProfil = "http://existingimage.com",
Password = "existingPassword123"
};
_mockUserService.Setup(service => service.GetUserById(id)).ReturnsAsync(existingPlayer);
_mockUserService.Setup(service => service.RemoveUser(existingPlayer.Id)).Verifiable();
// Act
var result = await _userController.DeletePlayer(id);
// Assert
Assert.IsType<OkObjectResult>(result);
}
// // Assert
// Assert.IsType<OkObjectResult>(result);
//}
}

Loading…
Cancel
Save