Skip to content

Commit

Permalink
Refactor(*): services and tests (#54)
Browse files Browse the repository at this point in the history
* Folders & Reformat!

* Add MessageResponseCreator class.

* Add CRUD classes.

* add tests and refactor graph dto creator

* fixed messages functions for create node categories

* fix response messages and create an interface

* add tests for nodes addition services and refactor

* fix response messages in EdgesAdditionService.cs

* add ContextEdgesAdditionService.cs

* add EdgeValueAdditionService.cs

* add ContextEdgesAdditionService.cs

* fix tests for edges addition classes

* Refactor & DI.

* Merge Graph refactor.

* Fix namespace

* Fix refactor

* fix bugs and refactor

---------

Co-authored-by: Mohammad Saleh Mahdinejad <[email protected]>
  • Loading branch information
SwimmingRieux and msmahdinejad authored Aug 28, 2024
1 parent 861bdad commit ff8b1a4
Show file tree
Hide file tree
Showing 216 changed files with 3,588 additions and 2,944 deletions.
24 changes: 12 additions & 12 deletions RelationAnalysis.Migrations/InitialRecordsCreator.cs
Original file line number Diff line number Diff line change
@@ -1,65 +1,65 @@
using Microsoft.Extensions.Configuration;
using RelationshipAnalysis.Context;
using RelationshipAnalysis.Models.Auth;
using RelationshipAnalysis.Services.UserPanelServices.Abstraction.AuthServices;
using RelationshipAnalysis.Services.AuthServices;

namespace RelationAnalysis.Migrations;

public class InitialRecordsCreator(ApplicationDbContext context, IConfiguration configuration)
{
public async Task AddInitialRecords()
{
var roles = new List<Role>()
var roles = new List<Role>
{
new Role()
new()
{
Name = "Admin",
Permissions =
"[\"/api/Admin\",\"/api/Auth\", \"/api/User\", \"/api/Edge\", \"/api/Graph\", \"/api/Node\"]",
Id = 1
},
new Role()
new()
{
Name = "DataAdmin",
Permissions = "[\"/api/Auth\", \"/api/User\", \"/api/Edge\", \"/api/Graph\", \"/api/Node\"]",
Id = 2
},
new Role()
new()
{
Name = "DataAnalyst",
Permissions = "[\"/api/Auth\", \"/api/User\", \"/api/Edge\", \"/api/Graph\", \"/api/Node\"]",
Id = 3
}
};
var userRoles = new List<UserRole>()
var userRoles = new List<UserRole>
{
new UserRole()
new()
{
UserId = 1,
RoleId = 1
},
new UserRole()
new()
{
UserId = 1,
RoleId = 2
},
new UserRole()
new()
{
UserId = 1,
RoleId = 3
}
};
var users = new List<User>()
var users = new List<User>
{
new User()
new()
{
Username = "admin",
PasswordHash = new CustomPasswordHasher()
.HashPassword(configuration.GetValue<string>("DefaultPassword")),
FirstName = "FirstName",
LastName = "LastName",
Email = "[email protected]",
Id = 1,
Id = 1
}
};
try
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,9 @@
using System.Net.Http.Json;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using RelationshipAnalysis.Context;
using System.Net;
using System.Net.Http.Json;
using RelationshipAnalysis.Dto;
using RelationshipAnalysis.Models;
using RelationshipAnalysis.Dto.Auth;


namespace RelationshipAnalysis.Integration.Test.Controllers;
namespace RelationshipAnalysis.Integration.Test.Controllers.Auth;

public class HomeControllerTests : IClassFixture<CustomWebApplicationFactory<Program>>
{
Expand Down Expand Up @@ -53,7 +48,7 @@ public async Task Login_ShouldReturnUnauthorized_WhenCredentialsAreInvalid()
var response = await _client.PostAsJsonAsync("/api/auth/login", loginModel);

// Assert
Assert.Equal(System.Net.HttpStatusCode.Unauthorized, response.StatusCode);
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}

[Fact]
Expand All @@ -64,6 +59,6 @@ public async Task Login_ShouldReturnBadRequest_WhenNoCredentialsAreProvided()
var response = await _client.PostAsJsonAsync("/api/auth/login", loginModel);

// Assert
Assert.Equal(System.Net.HttpStatusCode.BadRequest, response.StatusCode);
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.DependencyInjection;
using RelationshipAnalysis.Context;
using RelationshipAnalysis.Models;
using RelationshipAnalysis.Models.Auth;
using RelationshipAnalysis.Models.Graph;
using RelationshipAnalysis.Models.Graph.Edge;
using RelationshipAnalysis.Models.Graph.Node;

namespace RelationshipAnalysis.Integration.Test.Controllers;

Expand All @@ -20,15 +20,15 @@ protected override void ConfigureWebHost(IWebHostBuilder builder)
{
var descriptor =
services.SingleOrDefault(d => d.ServiceType == typeof(DbContextOptions<ApplicationDbContext>));
if (descriptor != null)
{
services.Remove(descriptor);
}
if (descriptor != null) services.Remove(descriptor);


services.AddDbContext<ApplicationDbContext>(options => { options.UseInMemoryDatabase(_databaseName)
.ConfigureWarnings(w => w.Ignore(InMemoryEventId.TransactionIgnoredWarning))
.UseLazyLoadingProxies(); });
services.AddDbContext<ApplicationDbContext>(options =>
{
options.UseInMemoryDatabase(_databaseName)
.ConfigureWarnings(w => w.Ignore(InMemoryEventId.TransactionIgnoredWarning))
.UseLazyLoadingProxies();
});


var serviceProvider = services.BuildServiceProvider();
Expand Down Expand Up @@ -59,7 +59,7 @@ private void SeedDatabase(ApplicationDbContext dbContext)
{
Id = 1,
Name = "admin",
Permissions = "[\"AdminPermissions\"]",
Permissions = "[\"AdminPermissions\"]"
};
var userRole = new UserRole
{
Expand All @@ -75,7 +75,7 @@ private void SeedDatabase(ApplicationDbContext dbContext)
dbContext.Users.Add(user);
dbContext.Roles.Add(role);
dbContext.SaveChanges();

var nodeCategory1 = new NodeCategory
{
NodeCategoryId = 1,
Expand All @@ -86,7 +86,7 @@ private void SeedDatabase(ApplicationDbContext dbContext)
NodeCategoryId = 2,
NodeCategoryName = "Person"
};

var node1 = new Node
{
NodeId = 1,
Expand Down Expand Up @@ -115,8 +115,8 @@ private void SeedDatabase(ApplicationDbContext dbContext)
dbContext.Nodes.Add(node1);
dbContext.Nodes.Add(node2);
dbContext.EdgeCategories.Add(edgeCategory);


var edge = new Edge
{
EdgeId = 1,
Expand All @@ -128,8 +128,7 @@ private void SeedDatabase(ApplicationDbContext dbContext)
};

dbContext.Edges.Add(edge);

dbContext.SaveChangesAsync();

dbContext.SaveChangesAsync();
}
}
Original file line number Diff line number Diff line change
@@ -1,18 +1,16 @@
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text;
using Microsoft.Extensions.Options;
using Moq;
using Newtonsoft.Json;
using RelationshipAnalysis.Dto;
using RelationshipAnalysis.Dto.Category;
using RelationshipAnalysis.Dto.Graph.Edge;
using RelationshipAnalysis.Models.Auth;
using RelationshipAnalysis.Services.UserPanelServices.Abstraction.AuthServices;
using RelationshipAnalysis.Services.AuthServices;
using RelationshipAnalysis.Settings.JWT;
using JsonSerializer = System.Text.Json.JsonSerializer;

namespace RelationshipAnalysis.Integration.Test.Controllers;
namespace RelationshipAnalysis.Integration.Test.Controllers.Graph;

public class EdgeControllerTests : IClassFixture<CustomWebApplicationFactory<Program>>
{
Expand All @@ -36,10 +34,10 @@ public async Task GetAllEdgeCategories_ShouldReturnCorrectList_Whenever()
};
Mock<IOptions<JwtSettings>> mockJwtSettings = new();
mockJwtSettings.Setup(m => m.Value).Returns(jwtSettings);
var user = new User()
var user = new User
{
Username = "Test",
UserRoles = new List<UserRole>() { new UserRole() { Role = new Role() { Name = "Admin" } } }
UserRoles = new List<UserRole> { new() { Role = new Role { Name = "Admin" } } }
};
var token = new JwtTokenGenerator(mockJwtSettings.Object).GenerateJwtToken(user);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
Expand All @@ -53,8 +51,8 @@ public async Task GetAllEdgeCategories_ShouldReturnCorrectList_Whenever()
Assert.NotNull(responseData);
Assert.Contains(expectedResult1, responseData);
}


[Fact]
public async Task CreateEdgeCategory_ShouldReturnCorrectList_Whenever()
{
Expand All @@ -67,20 +65,20 @@ public async Task CreateEdgeCategory_ShouldReturnCorrectList_Whenever()
};
Mock<IOptions<JwtSettings>> mockJwtSettings = new();
mockJwtSettings.Setup(m => m.Value).Returns(jwtSettings);
var user = new User()
var user = new User
{
Username = "Test",
UserRoles = new List<UserRole>() { new UserRole() { Role = new Role() { Name = "Admin" } } }
UserRoles = new List<UserRole> { new() { Role = new Role { Name = "Admin" } } }
};
var token = new JwtTokenGenerator(mockJwtSettings.Object).GenerateJwtToken(user);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);

var dto = new CreateEdgeCategoryDto()
var dto = new CreateEdgeCategoryDto
{
EdgeCategoryName = "NotExist"
};
request.Content = new StringContent(
JsonSerializer.Serialize<CreateEdgeCategoryDto>(dto),
JsonSerializer.Serialize(dto),
Encoding.UTF8,
"application/json"
);
Expand All @@ -93,5 +91,4 @@ public async Task CreateEdgeCategory_ShouldReturnCorrectList_Whenever()
var responseData = await response.Content.ReadFromJsonAsync<MessageDto>();
Assert.NotNull(responseData);
}

}
Original file line number Diff line number Diff line change
@@ -1,25 +1,20 @@
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using Moq;
using Newtonsoft.Json;
using NSubstitute;
using RelationshipAnalysis.Dto;
using RelationshipAnalysis.Dto.Graph;
using RelationshipAnalysis.Dto.Graph.Edge;
using RelationshipAnalysis.Dto.Graph.Node;
using RelationshipAnalysis.Models.Auth;
using RelationshipAnalysis.Models.Graph;
using RelationshipAnalysis.Services.UserPanelServices.Abstraction.AuthServices;
using RelationshipAnalysis.Models.Graph.Edge;
using RelationshipAnalysis.Models.Graph.Node;
using RelationshipAnalysis.Services.AuthServices;
using RelationshipAnalysis.Settings.JWT;
using JsonSerializer = System.Text.Json.JsonSerializer;

namespace RelationshipAnalysis.Integration.Test.Controllers;
namespace RelationshipAnalysis.Integration.Test.Controllers.Graph;

public class GraphControllerTests : IClassFixture<CustomWebApplicationFactory<Program>>
{

private readonly HttpClient _client;
private readonly JwtSettings _jwtSettings;

Expand Down Expand Up @@ -48,14 +43,13 @@ public async Task GetGraph_ShouldReturnGraph_WhenUserIsAuthorized()
FirstName = "Admin",
LastName = "User",
Email = "[email protected]",
UserRoles = new List<UserRole>() { new UserRole() { Role = new Role() { Name = "admin" } } }

UserRoles = new List<UserRole> { new() { Role = new Role { Name = "admin" } } }
};

var token = new JwtTokenGenerator(mockJwtSettings.Object).GenerateJwtToken(user);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);


var nodeCategory1 = new NodeCategory
{
NodeCategoryId = 1,
Expand All @@ -66,8 +60,8 @@ public async Task GetGraph_ShouldReturnGraph_WhenUserIsAuthorized()
NodeCategoryId = 2,
NodeCategoryName = "Person"
};
var node1 = new Node

var node1 = new Node
{
NodeId = 1,
NodeUniqueString = "Node1",
Expand All @@ -90,21 +84,20 @@ public async Task GetGraph_ShouldReturnGraph_WhenUserIsAuthorized()
};



var expectedNodes = new List<NodeDto>()
var expectedNodes = new List<NodeDto>
{
new NodeDto()
new()
{
id = node1.NodeId.ToString(),
label = $"{node1.NodeCategory.NodeCategoryName}/{node1.NodeUniqueString}"
},
new NodeDto()
new()
{
id = node2.NodeId.ToString(),
label = $"{node2.NodeCategory.NodeCategoryName}/{node2.NodeUniqueString}"
}
};

var edge = new Edge
{
EdgeId = 1,
Expand All @@ -116,25 +109,24 @@ public async Task GetGraph_ShouldReturnGraph_WhenUserIsAuthorized()
};


var expectedEdges = new List<EdgeDto>()
var expectedEdges = new List<EdgeDto>
{
new EdgeDto()
new()
{
id = edge.EdgeId.ToString(),
source = node1.NodeId.ToString(),
target = node2.NodeId.ToString()
}
};


// Act
var response = await _client.SendAsync(request);

// Assert
response.EnsureSuccessStatusCode();
var responseData = await response.Content.ReadFromJsonAsync<GraphDto>();
Assert.Equivalent(responseData.nodes, expectedNodes);
Assert.Equivalent(responseData.edges, expectedEdges);

Assert.Equivalent(responseData.Nodes, expectedNodes);
Assert.Equivalent(responseData.Edges, expectedEdges);
}
}
Loading

0 comments on commit ff8b1a4

Please sign in to comment.