Skip to content
3 changes: 1 addition & 2 deletions exercise.tests/IntegrationTests/PostTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,8 @@
using (Assert.EnterMultipleScope())
{
Assert.That(post?["id"]?.GetValue<int>(), Is.GreaterThan(0));
Assert.That(post["content"]?.GetValue<string>(), Is.Not.Null);
Assert.That(post?["content"]?.GetValue<string>(), Is.Not.Null);
Assert.That(post["numLikes"]?.GetValue<int>(), Is.Not.Null);

Check warning on line 48 in exercise.tests/IntegrationTests/PostTests.cs

View workflow job for this annotation

GitHub Actions / build-and-test

Dereference of a possibly null reference.
Assert.That(post["createdAt"], Is.Not.Null);
}

Expand Down Expand Up @@ -569,7 +569,6 @@
[Test]
public async Task GetCommentsByUser_Success()
{

//Assert get token
var token = await LoginAndGetToken("oyvind.perez1@example.com", "SuperHash!4");

Expand Down
128 changes: 50 additions & 78 deletions exercise.tests/IntegrationTests/UserTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,33 +6,16 @@
using System.Text.Json;
using System.Text.Json.Nodes;
using exercise.tests.Helpers;
using exercise.wwwapi.DTOs;

namespace exercise.tests.IntegrationTests
{
/// <summary>
/// Integration tests exercising the user management endpoints end-to-end via the API surface.
/// </summary>
[TestFixture]
public class UserTests
public class UserTests : BaseIntegrationTest
{
private WebApplicationFactory<Program> _factory;
private HttpClient _client;

[SetUp]
public void SetUp()
{
// Arrange
_factory = new WebApplicationFactory<Program>();
_client = _factory.CreateClient();
}

[TearDown]
public void TearDown()
{
_client.Dispose();
_factory.Dispose();
}

/// <summary>
/// Confirms that valid registration payloads yield an HTTP 201 Created response.
/// </summary>
Expand Down Expand Up @@ -193,19 +176,18 @@ public async Task Login_failure(string email, string password)
[Test]
public async Task UpdateUserSuccess()
{
var fieldsToUpdate = new Dictionary<string, object?>
var fieldsToUpdate = new UserPatchDTO()
{
{ "username", "roman-olsen13"},
{ "email", "roman.olsen13@example.com"},
{ "password", "aGoodPassword!200" },
{ "role", 0}
Username = "roman-olsen13",
Email = "roman.olsen13@example.com",
Password = "aGoodPassword!200" ,
Role = 0
};

var json = JsonSerializer.Serialize(fieldsToUpdate);
var content = new StringContent(json, Encoding.UTF8, "application/json");

string token = await LoginAndGetToken(TeacherEmail, TeacherPassword);
int userId = 13;
var response = await _client.PatchAsync($"/users/{userId}", content);
var response = await SendAuthenticatedPatchAsync($"/users/{userId}", token, fieldsToUpdate);


Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
}
Expand All @@ -216,14 +198,12 @@ public async Task UpdateUserSuccess()
[Test]
public async Task UpdateUserNullFieldsOnly()
{
var fieldsToUpdate = new Dictionary<string, object?> { };

var json = JsonSerializer.Serialize(fieldsToUpdate);
var content = new StringContent(json, Encoding.UTF8, "application/json");

var fieldsToUpdate = new UserPatchDTO();

string token = await LoginAndGetToken(TeacherEmail, TeacherPassword);
int userId = 1;
var response = await _client.PatchAsync($"/users/{userId}", content);


var response = await SendAuthenticatedPatchAsync($"/users/{userId}", token, fieldsToUpdate);
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}

Expand All @@ -233,17 +213,15 @@ public async Task UpdateUserNullFieldsOnly()
[Test]
public async Task UpdateUserInvalidUsername()
{
var fieldsToUpdate = new Dictionary<string, object?>
var fieldsToUpdate = new UserPatchDTO()
{
{ "username", "roman--olsen13"}
Username = "roman--olsen13"
};

var json = JsonSerializer.Serialize(fieldsToUpdate);
var content = new StringContent(json, Encoding.UTF8, "application/json");

int userId = 13;
var response = await _client.PatchAsync($"/users/{userId}", content);

string token = await LoginAndGetToken(TeacherEmail, TeacherPassword);

var response = await SendAuthenticatedPatchAsync($"/users/{userId}", token, fieldsToUpdate);
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}

Expand All @@ -253,17 +231,15 @@ public async Task UpdateUserInvalidUsername()
[Test]
public async Task UpdateUserInvalidGitHubUsername()
{
var fieldsToUpdate = new Dictionary<string, object?>
var fieldsToUpdate = new UserPatchDTO()
{
{ "gitHubUsername", "roman--olsen13"}
GithubUsername = "roman--olsen13"
};

var json = JsonSerializer.Serialize(fieldsToUpdate);
var content = new StringContent(json, Encoding.UTF8, "application/json");

int userId = 13;
var response = await _client.PatchAsync($"/users/{userId}", content);

string token = await LoginAndGetToken(TeacherEmail, TeacherPassword);

var response = await SendAuthenticatedPatchAsync($"/users/{userId}", token, fieldsToUpdate);
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}

Expand All @@ -273,16 +249,15 @@ public async Task UpdateUserInvalidGitHubUsername()
[Test]
public async Task UpdateUserInvalidEmail()
{
var fieldsToUpdate = new Dictionary<string, object?>
var fieldsToUpdate = new UserPatchDTO()
{
{ "email", "roman.olsen13@.e.com"}
Email = "roman.olsen13@.e.com"
};

var json = JsonSerializer.Serialize(fieldsToUpdate);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var token = await LoginAndGetToken(TeacherEmail, TeacherPassword);

int userId = 13;
var response = await _client.PatchAsync($"/users/{userId}", content);
var response = await SendAuthenticatedPatchAsync($"/users/{userId}", token, fieldsToUpdate);

Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
Expand All @@ -298,12 +273,11 @@ public async Task UpdateUserInvalidPassword()
{ "password", "nope!"}
};

var json = JsonSerializer.Serialize(fieldsToUpdate);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var token = await LoginAndGetToken(TeacherEmail, TeacherPassword);

int userId = 13;
var response = await _client.PatchAsync($"/users/{userId}", content);

var response = await SendAuthenticatedPatchAsync($"/users/{userId}", token, fieldsToUpdate);
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}

Expand All @@ -318,11 +292,10 @@ public async Task UpdateUserInvalidRole()
{ "role", 10}
};

var json = JsonSerializer.Serialize(fieldsToUpdate);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var token = await LoginAndGetToken(TeacherEmail, TeacherPassword);

int userId = 13;
var response = await _client.PatchAsync($"/users/{userId}", content);
var response = await SendAuthenticatedPatchAsync($"/users/{userId}", token, fieldsToUpdate);

Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
Expand All @@ -338,11 +311,10 @@ public async Task UpdateUserUsernameExists()
{ "username", "nigel-nowak2"}
};

var json = JsonSerializer.Serialize(fieldsToUpdate);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var token = await LoginAndGetToken(TeacherEmail, TeacherPassword);

int userId = 13;
var response = await _client.PatchAsync($"/users/{userId}", content);
var response = await SendAuthenticatedPatchAsync($"/users/{userId}", token, fieldsToUpdate);

Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
Expand All @@ -353,16 +325,15 @@ public async Task UpdateUserUsernameExists()
[Test]
public async Task UpdateUserGitHubUsernameExists()
{
var fieldsToUpdate = new Dictionary<string, object?>
var fieldsToUpdate = new UserPatchDTO()
{
{ "gitHubUsername", "nigel-nowak2"}
GithubUsername = "nigel-nowak2"
};

var json = JsonSerializer.Serialize(fieldsToUpdate);
var content = new StringContent(json, Encoding.UTF8, "application/json");

int userId = 13;
var response = await _client.PatchAsync($"/users/{userId}", content);
string token = await LoginAndGetToken(TeacherEmail, TeacherPassword);

var response = await SendAuthenticatedPatchAsync($"/users/{userId}", token, fieldsToUpdate);

Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
Expand All @@ -373,16 +344,15 @@ public async Task UpdateUserGitHubUsernameExists()
[Test]
public async Task UpdateUserEmailExists()
{
var fieldsToUpdate = new Dictionary<string, object?>
var fieldsToUpdate = new UserPatchDTO()
{
{ "email", "nigel.nowak2@example.com"}
Email="nigel.nowak2@example.com"
};

var json = JsonSerializer.Serialize(fieldsToUpdate);
var content = new StringContent(json, Encoding.UTF8, "application/json");


int userId = 13;
var response = await _client.PatchAsync($"/users/{userId}", content);
string token = await LoginAndGetToken(TeacherEmail, TeacherPassword);

var response = await SendAuthenticatedPatchAsync($"/users/{userId}", token, fieldsToUpdate);

Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
Expand All @@ -396,7 +366,9 @@ public async Task UpdateUserEmailExists()
[TestCase("10000000", HttpStatusCode.NotFound)]
public async Task GetUserByIdTest(string id, HttpStatusCode responseStatus)
{
var response = await _client.GetAsync($"/users/{id}");
string token = await LoginAndGetToken(TeacherEmail, TeacherPassword);

var response = await SendAuthenticatedGetAsync($"/users/{id}", token);
Assert.That(response.StatusCode, Is.EqualTo(responseStatus));

}
Expand Down
9 changes: 6 additions & 3 deletions exercise.wwwapi/Endpoints/LogEndpoints.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace exercise.wwwapi.Endpoints
{
Expand All @@ -10,10 +11,12 @@ public static void ConfigureLogEndpoints(this WebApplication app)
logs.MapPost("/", CreateDeliveryLog).WithSummary("Create a delivery log");
}

[Authorize]
[ProducesResponseType(StatusCodes.Status200OK)]
public static async Task<IResult> CreateDeliveryLog()
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
private static Task<IResult> CreateDeliveryLog()
{
return TypedResults.Ok();
return Task.FromResult<IResult>(TypedResults.Ok());
}
}
}
28 changes: 20 additions & 8 deletions exercise.wwwapi/Endpoints/PostEndpoints.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,10 @@ public static void ConfigurePostEndpoints(this WebApplication app)

[Authorize]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public static IResult CreatePost(
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
private static IResult CreatePost(
IRepository<User> userservice,
IRepository<Post> postservice,
IMapper mapper,
Expand Down Expand Up @@ -74,9 +75,11 @@ CreatePostDTO request

return Results.Created($"/posts/{post.Id}", response);
}

[Authorize]
[ProducesResponseType(StatusCodes.Status200OK)]
public static IResult GetAllPosts(IRepository<Post> service, IMapper mapper)
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
private static IResult GetAllPosts(IRepository<Post> service, IMapper mapper)
{
IEnumerable<Post> results = service.GetWithIncludes(q => q.Include(p => p.User).Include(p => p.Comments).ThenInclude(c => c.User));
IEnumerable<PostDTO> postDTOs = mapper.Map<IEnumerable<PostDTO>>(results);
Expand All @@ -91,9 +94,10 @@ public static IResult GetAllPosts(IRepository<Post> service, IMapper mapper)
[Authorize]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
[ProducesResponseType(StatusCodes.Status403Forbidden)]

public static IResult UpdatePost(IRepository<Post> service, IMapper mapper, ClaimsPrincipal user, int postid, UpdatePostDTO request)
private static IResult UpdatePost(IRepository<Post> service, IMapper mapper, ClaimsPrincipal user, int postid, UpdatePostDTO request)
{
if (string.IsNullOrWhiteSpace(request.Content)) return TypedResults.BadRequest(new ResponseDTO<object>{
Message = "Content cannot be empty"
Expand Down Expand Up @@ -128,8 +132,9 @@ public static IResult UpdatePost(IRepository<Post> service, IMapper mapper, Clai

[Authorize]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
[ProducesResponseType(StatusCodes.Status403Forbidden)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
private static IResult DeletePost(IRepository<Post> service, ClaimsPrincipal user, int postid)
{
Post? post = service.GetById(postid, q => q.Include(p => p.User).Include(p => p.Comments).ThenInclude(c => c.User));
Expand All @@ -151,8 +156,9 @@ private static IResult DeletePost(IRepository<Post> service, ClaimsPrincipal use

[Authorize]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
private static IResult AddCommentToPost(
IRepository<PostComment> commentService,
IRepository<Post> postService,
Expand Down Expand Up @@ -203,6 +209,7 @@ private static IResult AddCommentToPost(

[Authorize]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
private static IResult GetCommentsForPost(IRepository<Post> postservice, IMapper mapper, int postId)
{
Post? post = postservice.GetById(postId, q => q.Include(p => p.User).Include(p => p.Comments).ThenInclude(c => c.User));
Expand All @@ -211,10 +218,12 @@ private static IResult GetCommentsForPost(IRepository<Post> postservice, IMapper
List<PostCommentDTO> commentsDTO = mapper.Map<List<PostCommentDTO>>(comments);
return TypedResults.Ok(new ResponseDTO<List<PostCommentDTO>> { Message = "Success", Data = commentsDTO });
}


[Authorize]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
private static IResult UpdateComment(
IRepository<PostComment> service,
IMapper mapper,
Expand Down Expand Up @@ -252,6 +261,7 @@ private static IResult UpdateComment(

[Authorize]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
private static IResult DeleteCommentById(IRepository<PostComment> service, ClaimsPrincipal user, int commentId)
{
Expand All @@ -278,6 +288,7 @@ private static IResult DeleteCommentById(IRepository<PostComment> service, Claim

[Authorize]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
private static IResult GetPostsByUser(IRepository<Post> service, IMapper mapper, int userid)
{
Expand All @@ -295,6 +306,7 @@ private static IResult GetPostsByUser(IRepository<Post> service, IMapper mapper,

[Authorize]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
private static IResult GetCommentsByUser(IRepository<PostComment> service, IMapper mapper, int userid)
{
Expand Down
Loading
Loading