Skip to content

Commit 904b31c

Browse files
author
Oyvind Timian Dokk Husveg
committed
Adjusted tests a bit, also added new functions to the repository
1 parent 1258ffe commit 904b31c

File tree

4 files changed

+52
-62
lines changed

4 files changed

+52
-62
lines changed

exercise.tests/IntegrationTests/PostTests.cs

Lines changed: 27 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -176,78 +176,46 @@ public async Task FailedCreatePostMessage(int userid, string content, string exp
176176
Assert.That(message["timestamp"], Is.Not.Null);
177177
}
178178
[Test]
179-
public async Task GetAllPostsStatusAndMessage()
179+
public async Task DeletePostById_SuccessAndNotFound()
180180
{
181-
// Act
182-
var response = await _client.GetAsync("/posts");
183-
var contentString = await response.Content.ReadAsStringAsync();
184-
185-
JsonNode? message = null;
186-
if (!string.IsNullOrWhiteSpace(contentString))
181+
// Arrange, create a post first
182+
var newPost = new CreatePostDTO
187183
{
188-
message = JsonNode.Parse(contentString);
189-
}
184+
Userid = 1,
185+
Content = "Temp post to delete"
186+
};
187+
var json = JsonSerializer.Serialize(newPost);
188+
var requestBody = new StringContent(json, Encoding.UTF8, "application/json");
190189

191-
Console.WriteLine("Message: " + message);
190+
var createResponse = await _client.PostAsync("/posts", requestBody);
191+
var createContent = await createResponse.Content.ReadAsStringAsync();
192+
var createMessage = JsonNode.Parse(createContent);
192193

193-
// Assert status
194-
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
194+
int createdPostId = createMessage!["data"]!["id"]!.GetValue<int>();
195195

196-
// Assert JSON structure
197-
Assert.That(message, Is.Not.Null);
198-
Assert.That(message?["message"]?.GetValue<string>(), Is.EqualTo("success"));
196+
// Act, delete the post
197+
var deleteResponse = await _client.DeleteAsync($"/posts/{createdPostId}");
198+
var deleteContent = await deleteResponse.Content.ReadAsStringAsync();
199199

200-
var data = message["data"];
201-
Assert.That(data, Is.Not.Null);
202-
Assert.That(data.AsArray(), Has.Count.GreaterThanOrEqualTo(0));
200+
// Assert delete success
201+
Assert.That(deleteResponse.StatusCode, Is.EqualTo(HttpStatusCode.OK));
203202

204-
foreach (var post in data.AsArray())
205-
{
206-
Assert.That(post["id"]?.GetValue<int>(), Is.GreaterThan(0));
207-
Assert.That(post["content"]?.GetValue<string>(), Is.Not.Null);
208-
Assert.That(post["numLikes"]?.GetValue<int>(), Is.Not.Null);
209-
Assert.That(post["comments"]?.AsArray(), Is.Not.Null);
210-
211-
var user = post["user"];
212-
Assert.That(user, Is.Not.Null);
213-
Assert.That(user!["id"]?.GetValue<int>(), Is.GreaterThan(0));
214-
Assert.That(user["firstName"]?.GetValue<string>(), Is.Not.Null);
215-
Assert.That(user["lastName"]?.GetValue<string>(), Is.Not.Null);
216-
Assert.That(user["photo"]?.GetValue<string>(), Is.Not.Null);
217-
}
218-
}
203+
// Act again, try deleting same post (should now be gone)
204+
var deleteAgainResponse = await _client.DeleteAsync($"/posts/{createdPostId}");
205+
var deleteAgainContent = await deleteAgainResponse.Content.ReadAsStringAsync();
206+
var deleteAgainMessage = JsonNode.Parse(deleteAgainContent);
219207

220-
[TestCase(1, HttpStatusCode.NoContent)] // existing post
221-
[TestCase(9999999, HttpStatusCode.NotFound)] // non-existing post
222-
public async Task DeletePostById(int postId, HttpStatusCode expected)
223-
{
224-
// Act
225-
var response = await _client.DeleteAsync($"/posts/{postId}");
226-
var contentString = await response.Content.ReadAsStringAsync();
227-
228-
JsonNode? message = null;
229-
if (!string.IsNullOrWhiteSpace(contentString))
230-
{
231-
message = JsonNode.Parse(contentString);
232-
}
208+
// Assert not found
209+
Assert.That(deleteAgainResponse.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
210+
Assert.That(deleteAgainMessage?["message"]?.GetValue<string>(), Is.EqualTo("Post not found"));
211+
}
233212

234-
Console.WriteLine("Message: " + message);
235213

236-
// Assert status
237-
Assert.That(response.StatusCode, Is.EqualTo(expected));
238214

239-
if (expected == HttpStatusCode.NotFound)
240-
{
241-
Assert.That(message, Is.Not.Null);
242-
Assert.That(message?["message"]?.GetValue<string>(), Is.EqualTo("Post not found"));
243-
Assert.That(message["data"], Is.Null);
244-
Assert.That(message["timestamp"], Is.Not.Null);
245-
}
246-
}
247215

248-
[TestCase(1, "Updated content", HttpStatusCode.OK)]
216+
[TestCase(5, "Updated content", HttpStatusCode.OK)]
249217
[TestCase(9999999, "Updated content", HttpStatusCode.NotFound)]
250-
[TestCase(1, "", HttpStatusCode.BadRequest)]
218+
[TestCase(5, "", HttpStatusCode.BadRequest)]
251219
public async Task UpdatePostById(int postId, string newContent, HttpStatusCode expected)
252220
{
253221
// Arrange

exercise.wwwapi/Endpoints/PostEndpoints.cs

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
using AutoMapper;
2+
using exercise.wwwapi.Data;
23
using exercise.wwwapi.DTOs;
34
using exercise.wwwapi.DTOs.GetUsers;
45
using exercise.wwwapi.DTOs.Posts;
@@ -17,8 +18,9 @@ public static void ConfigurePostEndpoints(this WebApplication app)
1718
posts.MapPost("/", CreatePost).WithSummary("Create post");
1819
posts.MapGet("/", GetAllPosts).WithSummary("Get all posts");
1920
posts.MapPatch("/{id}", UpdatePost).WithSummary("Update a certain post");
20-
posts.MapDelete("/{id}", GetAllPosts).WithSummary("Remove a certain post");
21+
posts.MapDelete("/{id}", DeletePost).WithSummary("Remove a certain post");
2122
}
23+
2224
[ProducesResponseType(StatusCodes.Status200OK)]
2325
[ProducesResponseType(StatusCodes.Status404NotFound)]
2426
[ProducesResponseType(StatusCodes.Status400BadRequest)]
@@ -72,8 +74,7 @@ public static IResult UpdatePost(IRepository<Post> service, IMapper mapper, int
7274
Message = "Content cannot be empty"
7375
});
7476

75-
// TODO: Add new getbyid that uses includes
76-
var post = service.GetById(id);
77+
Post? post = service.GetById(id, q=>q.Include(p => p.User));
7778

7879
if (post == null) return TypedResults.NotFound(new ResponseDTO<Object> { Message = "Post not found" });
7980

@@ -88,5 +89,18 @@ public static IResult UpdatePost(IRepository<Post> service, IMapper mapper, int
8889

8990
return TypedResults.Ok(new ResponseDTO<PostDTO> { Message = "Success", Data = postDTO });
9091
}
92+
93+
[ProducesResponseType(StatusCodes.Status200OK)]
94+
[ProducesResponseType(StatusCodes.Status404NotFound)]
95+
private static IResult DeletePost(IRepository<Post> service, int id)
96+
{
97+
Post? post = service.GetById(id, q => q.Include(p => p.User));
98+
if (post == null) return TypedResults.NotFound(new ResponseDTO<Object> { Message = "Post not found" });
99+
100+
service.Delete(id);
101+
service.Save();
102+
103+
return TypedResults.Ok(new ResponseDTO<PostDTO> { Message = "Success" });
104+
}
91105
}
92106
}

exercise.wwwapi/Repository/IRepository.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ public interface IRepository<T> where T : class
1111

1212
IEnumerable<T> GetAllFiltered(Expression<Func<T, bool>> filter);
1313
IEnumerable<T> GetWithIncludes(Func<IQueryable<T>, IQueryable<T>> includeQuery);
14+
T? GetById(int id, Func<IQueryable<T>, IQueryable<T>> includeQuery);
1415
T GetById(object id);
1516
void Insert(T obj);
1617
void Update(T obj);

exercise.wwwapi/Repository/Repository.cs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,13 @@ public T GetById(object id)
5050
return _table.Find(id);
5151
}
5252

53+
public T? GetById(int id, Func<IQueryable<T>, IQueryable<T>> includeQuery)
54+
{
55+
IQueryable<T> query = _table.Where(e => EF.Property<int>(e, "Id") == id);
56+
query = includeQuery(query);
57+
return query.FirstOrDefault();
58+
}
59+
5360
public void Insert(T obj)
5461
{
5562
_table.Add(obj);

0 commit comments

Comments
 (0)