Skip to content

Commit

Permalink
feat(Category ): Add Category Controller. (#27)
Browse files Browse the repository at this point in the history
* first attempt to singletonize the scoped classes

* add context lazy loading

* add context container

* converted all the scoped classes to singleton classes

* resolved tests errors.

* add get_graph endpoint to graphcontroller

* add getgraph endpoint integration test

* fix integration test bug

* Make Db methods async.

* create Categories class.

* Add Failed CreateEdgeCategory Unit Tests.

* complete CreateEdgeCategory class.

* Pass CreateEdgeCategory Tests.

* fix integration test bug.

* Add failed CreateNodeCategory Unit Tests.

* Complete CreateNodeCategory class & pass its unit tests.

* Edit unit tests name.

* Fix some bugs.

* Add failed EdgeCategoryReceiver unit tests.

* Complete EdgeCategoryReceiver class &

* Add NodeCategoryReceiver unit tests.

* Complete NodeCategoryReceiver class & pass its unit tests.

* Add DI.

* Add Integration Tests.

---------

Co-authored-by: sadq <[email protected]>
  • Loading branch information
msmahdinejad and SwimmingRieux authored Aug 20, 2024
1 parent 20ffa2e commit fb31045
Show file tree
Hide file tree
Showing 40 changed files with 1,389 additions and 80 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
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.Models.Auth;
using RelationshipAnalysis.Services.UserPanelServices.Abstraction.AuthServices;
using RelationshipAnalysis.Settings.JWT;
using JsonSerializer = System.Text.Json.JsonSerializer;

namespace RelationshipAnalysis.Integration.Test.Controllers;

public class CategoryControllerTests : IClassFixture<CustomWebApplicationFactory<Program>>
{
private readonly HttpClient _client;

public CategoryControllerTests(CustomWebApplicationFactory<Program> factory)
{
_client = factory.CreateClient();
}

[Fact]
public async Task GetAllNodeCategories_ShouldReturnCorrectList_Whenever()
{
// Arrange
var expectedResult1 = "Person";
var expectedResult2 = "Account";
var request = new HttpRequestMessage(HttpMethod.Get, "/api/category/GetAllNodeCategories");
var jwtSettings = new JwtSettings
{
Key = "kajbdiuhdqhpjQE89HBSDJIABFCIWSGF89GW3EJFBWEIUBCZNMXCJNLZDKNJKSNJKFBIGW3EASHHDUIASZGCUI",
ExpireMinutes = 60
};
Mock<IOptions<JwtSettings>> mockJwtSettings = new();
mockJwtSettings.Setup(m => m.Value).Returns(jwtSettings);
var user = new User()
{
Username = "Test",
UserRoles = new List<UserRole>() { new UserRole() { Role = new Role() { Name = "Admin" } } }
};
var token = new JwtTokenGenerator(mockJwtSettings.Object).GenerateJwtToken(user);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);

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

// Assert
response.EnsureSuccessStatusCode();
var responseData = await response.Content.ReadFromJsonAsync<List<string>>();
Assert.NotNull(responseData);
Assert.Contains(expectedResult1, responseData);
Assert.Contains(expectedResult2, responseData);
}

[Fact]
public async Task GetAllEdgeCategories_ShouldReturnCorrectList_Whenever()
{
// Arrange
var expectedResult1 = "Transaction";
var request = new HttpRequestMessage(HttpMethod.Get, "/api/category/GetAllEdgeCategories");
var jwtSettings = new JwtSettings
{
Key = "kajbdiuhdqhpjQE89HBSDJIABFCIWSGF89GW3EJFBWEIUBCZNMXCJNLZDKNJKSNJKFBIGW3EASHHDUIASZGCUI",
ExpireMinutes = 60
};
Mock<IOptions<JwtSettings>> mockJwtSettings = new();
mockJwtSettings.Setup(m => m.Value).Returns(jwtSettings);
var user = new User()
{
Username = "Test",
UserRoles = new List<UserRole>() { new UserRole() { Role = new Role() { Name = "Admin" } } }
};
var token = new JwtTokenGenerator(mockJwtSettings.Object).GenerateJwtToken(user);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);

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

// Assert
response.EnsureSuccessStatusCode();
var responseData = await response.Content.ReadFromJsonAsync<List<string>>();
Assert.NotNull(responseData);
Assert.Contains(expectedResult1, responseData);
}

[Fact]
public async Task CreateNodeCategory_ShouldReturnCorrectList_Whenever()
{
// Arrange
var request = new HttpRequestMessage(HttpMethod.Post, "/api/category/CreateNodeCategory");
var jwtSettings = new JwtSettings
{
Key = "kajbdiuhdqhpjQE89HBSDJIABFCIWSGF89GW3EJFBWEIUBCZNMXCJNLZDKNJKSNJKFBIGW3EASHHDUIASZGCUI",
ExpireMinutes = 60
};
Mock<IOptions<JwtSettings>> mockJwtSettings = new();
mockJwtSettings.Setup(m => m.Value).Returns(jwtSettings);
var user = new User()
{
Username = "Test",
UserRoles = new List<UserRole>() { new UserRole() { Role = new Role() { Name = "Admin" } } }
};
var token = new JwtTokenGenerator(mockJwtSettings.Object).GenerateJwtToken(user);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);

var dto = new CreateNodeCategoryDto()
{
NodeCategoryName = "NotExist"
};
request.Content = new StringContent(
JsonSerializer.Serialize<CreateNodeCategoryDto>(dto),
Encoding.UTF8,
"application/json"
);

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

// Assert
response.EnsureSuccessStatusCode();
var responseData = await response.Content.ReadFromJsonAsync<MessageDto>();
Assert.NotNull(responseData);
}

[Fact]
public async Task CreateEdgeCategory_ShouldReturnCorrectList_Whenever()
{
// Arrange
var request = new HttpRequestMessage(HttpMethod.Post, "/api/category/CreateEdgeCategory");
var jwtSettings = new JwtSettings
{
Key = "kajbdiuhdqhpjQE89HBSDJIABFCIWSGF89GW3EJFBWEIUBCZNMXCJNLZDKNJKSNJKFBIGW3EASHHDUIASZGCUI",
ExpireMinutes = 60
};
Mock<IOptions<JwtSettings>> mockJwtSettings = new();
mockJwtSettings.Setup(m => m.Value).Returns(jwtSettings);
var user = new User()
{
Username = "Test",
UserRoles = new List<UserRole>() { new UserRole() { Role = new Role() { Name = "Admin" } } }
};
var token = new JwtTokenGenerator(mockJwtSettings.Object).GenerateJwtToken(user);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);

var dto = new CreateEdgeCategoryDto()
{
EdgeCategoryName = "NotExist"
};
request.Content = new StringContent(
JsonSerializer.Serialize<CreateEdgeCategoryDto>(dto),
Encoding.UTF8,
"application/json"
);

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

// Assert
response.EnsureSuccessStatusCode();
var responseData = await response.Content.ReadFromJsonAsync<MessageDto>();
Assert.NotNull(responseData);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using RelationshipAnalysis.Context;
using RelationshipAnalysis.Models;
using RelationshipAnalysis.Models.Auth;
using RelationshipAnalysis.Models.Graph;

namespace RelationshipAnalysis.Integration.Test.Controllers;

Expand Down Expand Up @@ -71,5 +72,46 @@ private void SeedDatabase(ApplicationDbContext dbContext)
dbContext.Users.Add(user);
dbContext.Roles.Add(role);
dbContext.SaveChanges();

var nodeCategory1 = new NodeCategory { NodeCategoryName = "Account" };
var nodeCategory2 = new NodeCategory { NodeCategoryName = "Person" };

var node1 = new Node
{
NodeUniqueString = "Node1",
NodeCategory = nodeCategory1,
NodeCategoryId = nodeCategory1.NodeCategoryId
};

var node2 = new Node
{
NodeUniqueString = "Node2",
NodeCategory = nodeCategory2,
NodeCategoryId = nodeCategory2.NodeCategoryId
};

var edgeCategory = new EdgeCategory { EdgeCategoryName = "Transaction"};


dbContext.NodeCategories.Add(nodeCategory1);
dbContext.NodeCategories.Add(nodeCategory2);
dbContext.Nodes.Add(node1);
dbContext.Nodes.Add(node2);
dbContext.EdgeCategories.Add(edgeCategory);


var edge = new Edge
{
EdgeSourceNodeId = node1.NodeId,
EdgeDestinationNodeId = node2.NodeId,
EdgeCategory = edgeCategory,
EdgeCategoryId = edgeCategory.EdgeCategoryId,
EdgeUniqueString = "Edge1"
};

dbContext.Edges.Add(edge);

dbContext.SaveChangesAsync();

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
using System.Net.Http.Headers;
using System.Net.Http.Json;
using Microsoft.Extensions.Options;
using Moq;
using RelationshipAnalysis.Dto.Graph;
using RelationshipAnalysis.Models.Auth;
using RelationshipAnalysis.Models.Graph;
using RelationshipAnalysis.Services.UserPanelServices.Abstraction.AuthServices;
using RelationshipAnalysis.Settings.JWT;

namespace RelationshipAnalysis.Integration.Test.Controllers;

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

private readonly HttpClient _client;
private readonly JwtSettings _jwtSettings;

public GraphControllerTests(CustomWebApplicationFactory<Program> factory)
{
_client = factory.CreateClient();
_jwtSettings = new JwtSettings
{
Key = "kajbdiuhdqhpjQE89HBSDJIABFCIWSGF89GW3EJFBWEIUBCZNMXCJNLZDKNJKSNJKFBIGW3EASHHDUIASZGCUI",
ExpireMinutes = 60
};
}

[Fact]
public async Task GetGraph_ShouldReturnGraph_WhenUserIsAuthorized()
{
// Arrange
var request = new HttpRequestMessage(HttpMethod.Get, "/api/graph/getgraph");
Mock<IOptions<JwtSettings>> mockJwtSettings = new();
mockJwtSettings.Setup(m => m.Value).Returns(_jwtSettings);
var user = new User
{
Id = 1,
Username = "admin",
PasswordHash = "74b2c5bd3a8de69c8c7c643e8b5c49d6552dc636aeb0995aff6f01a1f661a979",
FirstName = "Admin",
LastName = "User",
Email = "[email protected]",
UserRoles = new List<UserRole>() { new UserRole() { Role = new Role() { Name = "admin" } } }

};

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


var nodeCategory1 = new NodeCategory { NodeCategoryName = "Account" };
var nodeCategory2 = new NodeCategory { NodeCategoryName = "Person" };

var node1 = new Node
{
NodeId = 1,
NodeUniqueString = "Node1",
NodeCategory = nodeCategory1,
NodeCategoryId = nodeCategory1.NodeCategoryId
};

var node2 = new Node
{
NodeId = 2,
NodeUniqueString = "Node2",
NodeCategory = nodeCategory2,
NodeCategoryId = nodeCategory2.NodeCategoryId
};

var edgeCategory = new EdgeCategory { EdgeCategoryName = "Transaction"};



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

var edge = new Edge
{
EdgeId = 1,
EdgeSourceNodeId = node1.NodeId,
EdgeDestinationNodeId = node2.NodeId,
EdgeCategory = edgeCategory,
EdgeCategoryId = edgeCategory.EdgeCategoryId,
EdgeUniqueString = "Edge1"
};


var expectedEdges = new List<EdgeDto>()
{
new EdgeDto()
{
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);

}
}
Loading

0 comments on commit fb31045

Please sign in to comment.