Add comments API support and tests
Some checks failed
Dotnet build and test / build (push) Has been cancelled
Dotnet build and test / log-the-inputs (push) Has been cancelled

This commit is contained in:
Paul Schneider 2026-08-10 22:27:52 +01:00
commit eebc83cf7e
No known key found for this signature in database
GPG key ID: 1E66C65EE2B46F1B
6 changed files with 236 additions and 18 deletions

View file

@ -0,0 +1,92 @@
using System.Net;
using System.Net.Http.Json;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Yavsc.Models;
using Yavsc.Models.Blog;
using Yavsc.Tests.Shared;
namespace Yavsc.Org.Tests.Controllers;
public class CommentsApiIntegrationTests : IClassFixture<TestWebApplicationFactory>
{
private readonly TestWebApplicationFactory _factory;
public CommentsApiIntegrationTests(TestWebApplicationFactory factory)
{
_factory = factory;
}
[Fact]
public async Task Post_blogcomments_json_returns_201_and_persists_comment()
{
long postId;
using (var scope = _factory.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
if (!db.Users.Any(u => u.Id == TestUserMiddleware.UserId))
{
db.Users.Add(new ApplicationUser
{
Id = TestUserMiddleware.UserId,
UserName = "test-user",
NormalizedUserName = "TEST-USER",
Email = "test-user@example.com",
NormalizedEmail = "TEST-USER@EXAMPLE.COM",
EmailConfirmed = true,
SecurityStamp = Guid.NewGuid().ToString("N"),
ConcurrencyStamp = Guid.NewGuid().ToString("N")
});
}
var post = new BlogPost
{
Title = "Post for comment API test",
AuthorId = TestUserMiddleware.UserId,
DateCreated = DateTime.UtcNow,
DateModified = DateTime.UtcNow
};
db.BlogSpot.Add(post);
await db.SaveChangesAsync(TestContext.Current.CancellationToken);
postId = post.Id;
}
var http = _factory.CreateClient(new WebApplicationFactoryClientOptions
{
HandleCookies = true,
AllowAutoRedirect = false
});
http.DefaultRequestHeaders.Add(TestAuthPolicyProvider.HeaderName, TestAuthPolicyProvider.AdminRole);
var response = await http.PostAsJsonAsync(
"/api/v1/blogcomments",
new
{
Article = "Comment API integration test",
ReceiverId = postId
},
TestContext.Current.CancellationToken);
var responseBody = await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken);
Assert.True(
response.StatusCode != HttpStatusCode.InternalServerError,
$"Unexpected 500 on POST /api/v1/blogcomments. Body: {responseBody}");
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
Assert.Contains("\"id\"", responseBody, StringComparison.OrdinalIgnoreCase);
Assert.Contains("\"dateCreated\"", responseBody, StringComparison.OrdinalIgnoreCase);
using var verifyScope = _factory.Services.CreateScope();
var verifyDb = verifyScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
var stored = await verifyDb.Comment
.OrderByDescending(c => c.Id)
.FirstOrDefaultAsync(c => c.ReceiverId == postId, TestContext.Current.CancellationToken);
Assert.NotNull(stored);
Assert.Equal("Comment API integration test", stored!.Article);
Assert.Equal(TestUserMiddleware.UserId, stored.AuthorId);
}
}

View file

@ -0,0 +1,63 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Yavsc.Controllers;
using Yavsc.Models;
using Yavsc.Models.Blog;
namespace Yavsc.Org.Tests.Controllers;
public class CommentsControllerTests
{
[Fact]
public async Task Create_sets_author_and_persists_comment()
{
var dbName = $"comments-controller-{Guid.NewGuid():N}";
var options = new DbContextOptionsBuilder<ApplicationDbContext>()
.UseInMemoryDatabase(dbName)
.Options;
await using var db = new ApplicationDbContext(options);
var post = new BlogPost
{
Title = "Post de test",
AuthorId = "post-author",
DateCreated = DateTime.UtcNow,
DateModified = DateTime.UtcNow
};
db.BlogSpot.Add(post);
await db.SaveChangesAsync(TestContext.Current.CancellationToken);
var controller = new CommentsController(db)
{
ControllerContext = new ControllerContext
{
HttpContext = new DefaultHttpContext
{
User = new ClaimsPrincipal(new ClaimsIdentity(
[
new Claim(ClaimTypes.NameIdentifier, "comment-author")
], "TestAuth"))
}
}
};
var comment = new Comment
{
ReceiverId = post.Id,
Article = "Commentaire de test",
Visible = true
};
var result = await controller.Create(comment);
var redirect = Assert.IsType<RedirectToActionResult>(result);
Assert.Equal("Index", redirect.ActionName);
var stored = await db.Comment.SingleAsync(TestContext.Current.CancellationToken);
Assert.Equal("comment-author", stored.AuthorId);
Assert.Equal(post.Id, stored.ReceiverId);
Assert.Equal("Commentaire de test", stored.Article);
}
}

View file

@ -33,15 +33,11 @@ public class TestUserStartupFilter : IStartupFilter
{
return app =>
{
// Replay the production pipeline first (this is what
// Program.Main + ConfigurePipeline set up, including
// UseAuthentication and UseAuthorization).
next(app);
// Then add our middleware on top. UseMiddleware<T> wires
// it through the same IMiddlewareActivator the framework
// uses, so the dependency on TestUserMiddleware is
// resolved from the request scope.
app.UseMiddleware<TestUserMiddleware>();
// Replay the production pipeline after the test middleware,
// so downstream auth and controllers can see the injected
// principal when no real login flow is used.
next(app);
};
}
}