Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Storyteller - Technical Exercise by MingFei #8

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 80 additions & 0 deletions Todo.Tests/ApiControllers/TodoItemApiControllerTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Threading.Tasks;
using Todo.Controllers;
using Todo.Data;
using Todo.Data.Entities;
using Xunit;

namespace Todo.Tests.Controllers
{
public class TodoItemApiControllerTests
{
private readonly ApplicationDbContext _context;
private readonly TodoItemApiController _controller;

public TodoItemApiControllerTests()
{
var options = new DbContextOptionsBuilder<ApplicationDbContext>()
.UseInMemoryDatabase(databaseName: "TodoDatabase")
.Options;

_context = new ApplicationDbContext(options);
_controller = new TodoItemApiController(_context);
}

[Fact]
public async Task Create_ValidRequest_ReturnsOkResult()
{
// Arrange
var request = new TodoItemRequest
{
TodoListId = 1,
Title = "Test Title",
ResponsiblePartyId = "user1",
Importance = Importance.Medium,
Rank = 1
};

// Act
var result = await _controller.Create(request) as ActionResult;

// Assert
Assert.NotNull(result);
var okResult = result as OkObjectResult;
Assert.NotNull(okResult);
Assert.Equal(200, okResult.StatusCode);

var createdItem = okResult.Value as TodoItem;
Assert.NotNull(createdItem);
Assert.Equal(request.Title, createdItem.Title);
Assert.Equal(request.ResponsiblePartyId, createdItem.ResponsiblePartyId);
Assert.Equal(request.Importance, createdItem.Importance);
Assert.Equal(request.Rank, createdItem.Rank);
}

[Fact]
public async Task Create_InvalidRequest_ReturnsBadRequest()
{
// Arrange
var request = new TodoItemRequest
{
TodoListId = 1,
Title = "", // Invalid title
ResponsiblePartyId = "user1",
Importance = Importance.Medium,
Rank = 1
};

// Act
var result = await _controller.Create(request) as ActionResult;

// Assert
Assert.NotNull(result);
var badRequestResult = result as BadRequestObjectResult;
Assert.NotNull(badRequestResult);
Assert.Equal(400, badRequestResult.StatusCode);
Assert.Equal("Invalid data.", badRequestResult.Value);
}
}
}
71 changes: 71 additions & 0 deletions Todo.Tests/Services/TestGravatar.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
using System;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace Todo.Tests.Services
{
public static class Gravatar
{
private static HttpClient _httpClient = new HttpClient();

// Property to allow setting HttpClient for testing
public static HttpClient HttpClientInstance
{
get => _httpClient;
set => _httpClient = value;
}

public static async Task<string> GetGravatarProfileNameAsync(string email)
{
try
{
var emailHash = GetHash(email.Trim().ToLower());
var requestUrl = $"https://en.gravatar.com/{emailHash}.json";

var response = await _httpClient.GetAsync(requestUrl);
if (response.IsSuccessStatusCode)
{
var jsonResponse = await response.Content.ReadAsStringAsync();
var gravatarProfile = JsonSerializer.Deserialize<GravatarProfile>(jsonResponse);
return gravatarProfile?.entry?[0]?.displayName ?? email;
}
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}

return email; // Fallback to email if something goes wrong
}

public static string GetHash(string emailAddress)
{
using (var md5 = MD5.Create())
{
var inputBytes = Encoding.Default.GetBytes(emailAddress.Trim().ToLowerInvariant());
var hashBytes = md5.ComputeHash(inputBytes);

var builder = new StringBuilder();
foreach (var b in hashBytes)
{
builder.Append(b.ToString("X2"));
}
return builder.ToString().ToLowerInvariant();
}
}

private class GravatarProfile
{
public GravatarEntry[] entry { get; set; }
}

private class GravatarEntry
{
public string displayName { get; set; }
}
}
}

8 changes: 4 additions & 4 deletions Todo.Tests/TestTodoListBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,24 +12,24 @@ public class TestTodoListBuilder
{
private readonly string title;
private readonly IdentityUser owner;
private readonly List<(string, Importance)> items = new List<(string, Importance)>();
private readonly List<(string, Importance, int)> items = new List<(string, Importance, int)>();

public TestTodoListBuilder(IdentityUser owner, string title)
{
this.title = title;
this.owner = owner;
}

public TestTodoListBuilder WithItem(string itemTitle, Importance importance)
public TestTodoListBuilder WithItem(string itemTitle, Importance importance, int rank)
{
items.Add((itemTitle, importance));
items.Add((itemTitle, importance, rank));
return this;
}

public TodoList Build()
{
var todoList = new TodoList(owner, title);
var todoItems = items.Select(itm => new TodoItem(todoList.TodoListId, owner.Id, itm.Item1, itm.Item2));
var todoItems = items.Select(itm => new TodoItem(todoList.TodoListId, owner.Id, itm.Item1, itm.Item2, itm.Item3));
todoItems.ToList().ForEach(tlItm =>
{
todoList.Items.Add(tlItm);
Expand Down
2 changes: 2 additions & 0 deletions Todo.Tests/Todo.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,10 @@
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="3.1.13" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="3.1.13" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.13" />
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="3.1.13" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="3.1.13" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.8.0" />
<PackageReference Include="Moq" Version="4.20.70" />
<PackageReference Include="xunit" Version="2.3.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.3.1" />
</ItemGroup>
Expand Down
2 changes: 1 addition & 1 deletion Todo.Tests/WhenTodoItemIsConvertedToEditFields.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public class WhenTodoItemIsConvertedToEditFields
public WhenTodoItemIsConvertedToEditFields()
{
var todoList = new TestTodoListBuilder(new IdentityUser("[email protected]"), "shopping")
.WithItem("bread", Importance.High)
.WithItem("bread", Importance.High, 10)
.Build()
;

Expand Down
59 changes: 59 additions & 0 deletions Todo/ApiControllers/TodoItemApiController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;
using Todo.Data;
using Todo.Data.Entities;

namespace Todo.Controllers
{
[ApiController]
[Route("api/[controller]")]

public class TodoItemApiController : ControllerBase
{
private readonly ApplicationDbContext _context;

public TodoItemApiController(ApplicationDbContext context)
{
_context = context;
}

[HttpPost]
public async Task<ActionResult> Create(TodoItemRequest request)
{
try
{
if (request == null || string.IsNullOrEmpty(request.Title))
{
return BadRequest("Invalid data.");
}

var todoItem = new TodoItem(request.TodoListId, request.ResponsiblePartyId, request.Title, request.Importance, request.Rank)
{
Rank = request.Rank,
IsDone = false
};

_context.TodoItems.Add(todoItem);
await _context.SaveChangesAsync();

return Ok(todoItem);
}
catch (Exception ex)
{

return NotFound();
throw ex;
}
}
}
}

public class TodoItemRequest
{
public int TodoListId { get; set; }
public string Title { get; set; }
public string ResponsiblePartyId { get; set; }
public Importance Importance { get; set; }
public int Rank { get; set; }
}
6 changes: 3 additions & 3 deletions Todo/Controllers/TodoItemController.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using Todo.Data;
using Todo.Data.Entities;
using Todo.EntityModelMappers.TodoItems;
Expand Down Expand Up @@ -33,7 +33,7 @@ public async Task<IActionResult> Create(TodoItemCreateFields fields)
{
if (!ModelState.IsValid) { return View(fields); }

var item = new TodoItem(fields.TodoListId, fields.ResponsiblePartyId, fields.Title, fields.Importance);
var item = new TodoItem(fields.TodoListId, fields.ResponsiblePartyId, fields.Title, fields.Importance, fields.Rank);

await dbContext.AddAsync(item);
await dbContext.SaveChangesAsync();
Expand Down
20 changes: 16 additions & 4 deletions Todo/Controllers/TodoListController.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System.Threading;
using System.Threading.Tasks;
using Todo.Data;
using Todo.Data.Entities;
using Todo.EntityModelMappers.TodoLists;
Expand Down Expand Up @@ -31,10 +31,22 @@ public IActionResult Index()
return View(viewmodel);
}

public IActionResult Detail(int todoListId)
public async Task<IActionResult> Detail(int todoListId, string sortOrder = "Importance")
{
var todoList = dbContext.SingleTodoList(todoListId);

var viewmodel = TodoListDetailViewmodelFactory.Create(todoList);

viewmodel.CurrentSort = sortOrder;

foreach (var item in viewmodel.Items)
{
var gravatarName = await Gravatar.GetGravatarProfileNameAsync(item.ResponsibleParty.Email);

item.ResponsibleParty.GravatarName = ((gravatarName == null) || (gravatarName == item.ResponsibleParty.Email))
? item.ResponsibleParty.Email : gravatarName;
}

return View(viewmodel);
}

Expand Down
6 changes: 3 additions & 3 deletions Todo/Data/Entities/Importance.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
namespace Todo.Data.Entities {
public enum Importance
{
High,
Medium,
Low,
High = 0,
Medium = 1,
Low = 2,
}
}
4 changes: 3 additions & 1 deletion Todo/Data/Entities/TodoItem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,21 @@ public class TodoItem
public string ResponsiblePartyId { get; set; }
public IdentityUser ResponsibleParty { get; set; }
public bool IsDone { get; set; }
public int Rank { get; set; }
public Importance Importance { get; set; }

public int TodoListId { get; set; }
public TodoList TodoList { get; set; }

protected TodoItem() { }

public TodoItem(int todoListId, string responsiblePartyId, string title, Importance importance)
public TodoItem(int todoListId, string responsiblePartyId, string title, Importance importance, int rank)
{
TodoListId = todoListId;
ResponsiblePartyId = responsiblePartyId;
Title = title;
Importance = importance;
Rank = rank;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ public static TodoItemEditFields Create(TodoItem todoItem)
{
var todoList = todoItem.TodoList;
return new TodoItemEditFields(todoList.TodoListId, todoList.Title, todoItem.TodoItemId, todoItem.Title,
todoItem.IsDone, todoItem.ResponsiblePartyId, todoItem.Importance);
todoItem.IsDone, todoItem.ResponsiblePartyId, todoItem.Importance, todoItem.Rank);
}

public static void Update(TodoItemEditFields src, TodoItem dest)
Expand All @@ -18,6 +18,7 @@ public static void Update(TodoItemEditFields src, TodoItem dest)
dest.IsDone = src.IsDone;
dest.ResponsiblePartyId = src.ResponsiblePartyId;
dest.Importance = src.Importance;
dest.Rank = src.Rank;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ public static class TodoItemSummaryViewmodelFactory
{
public static TodoItemSummaryViewmodel Create(TodoItem ti)
{
return new TodoItemSummaryViewmodel(ti.TodoItemId, ti.Title, ti.IsDone, UserSummaryViewmodelFactory.Create(ti.ResponsibleParty), ti.Importance);
return new TodoItemSummaryViewmodel(ti.TodoItemId, ti.Title, ti.IsDone, UserSummaryViewmodelFactory.Create(ti.ResponsibleParty), ti.Importance, ti.Rank);
}
}
}
Loading