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

Tester2 #24

Merged
merged 15 commits into from
Jun 19, 2024
Merged
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
18 changes: 9 additions & 9 deletions .github/workflows/angular.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,13 @@ jobs:
working-directory: TaskmanClient

steps:
- uses: actions/checkout@v4
- name: Setup
uses: actions/setup-node@v4
with:
node-version: 20.12.2
- name: Restore dependencies
run: npm install
- name: Build
run: npm run build --prod
- uses: actions/checkout@v4
- name: Setup
uses: actions/setup-node@v4
with:
node-version: 20.12.2
- name: Restore dependencies
run: npm install
- name: Build
run: npm run build --prod
# TODO: tests?
22 changes: 11 additions & 11 deletions .github/workflows/dotnet.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,14 @@ jobs:
working-directory: TaskmanAPI

steps:
- uses: actions/checkout@v4
- name: Setup .NET
uses: actions/setup-dotnet@v4
with:
dotnet-version: 8.0.x
- name: Restore dependencies
run: dotnet restore
- name: Build
run: dotnet build --no-restore
- name: Test
run: dotnet test --no-build --verbosity normal
- uses: actions/checkout@v4
- name: Setup .NET
uses: actions/setup-dotnet@v4
with:
dotnet-version: 8.0.x
- name: Restore dependencies
run: dotnet restore
- name: Build
run: dotnet build --no-restore
- name: Test
run: dotnet test --no-build --verbosity normal
16 changes: 16 additions & 0 deletions Taskman.Tests/DbSetMockHelper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using Microsoft.EntityFrameworkCore;
using Moq;

public static class DbSetMockHelper
{
public static DbSet<T> CreateMockDbSet<T>(List<T> elements) where T : class
{
var queryable = elements.AsQueryable();
var mockSet = new Mock<DbSet<T>>();
mockSet.As<IQueryable<T>>().Setup(m => m.Provider).Returns(queryable.Provider);
mockSet.As<IQueryable<T>>().Setup(m => m.Expression).Returns(queryable.Expression);
mockSet.As<IQueryable<T>>().Setup(m => m.ElementType).Returns(queryable.ElementType);
mockSet.As<IQueryable<T>>().Setup(m => m.GetEnumerator()).Returns(queryable.GetEnumerator());
return mockSet.Object;
}
}
161 changes: 161 additions & 0 deletions Taskman.Tests/NotificationsControllerTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using TaskmanAPI.Contexts;
using TaskmanAPI.Controllers;
using TaskmanAPI.Model;

public class NotificationsControllerTests
{
private DefaultContext _context;
private NotificationsController _controller;

public NotificationsControllerTests()
{
Setup();
}

private void Setup()
{
var options = new DbContextOptionsBuilder<DefaultContext>()
.UseInMemoryDatabase($"TestDatabase_{Guid.NewGuid()}")
.Options;
_context = new DefaultContext(options);

// Seed the in-memory database
SeedDatabase();

// Create controller
_controller = new NotificationsController(_context);
}

private void SeedDatabase()
{
var notifications = new List<Notification>
{
new() { Id = 1, UserId = "1", Title = "Titlu1", Content = "Test1" },
new() { Id = 2, UserId = "2", Title = "Titlu2", Content = "Test2" }
};

_context.Notifications.AddRange(notifications);
_context.SaveChanges();
}

//Test for GetNotifications method
[Fact]
public async Task GetNotifications_ReturnsAllNotifications()
{
// Act
var result = await _controller.GetNotifications();

// Assert
var okResult = Assert.IsType<ActionResult<IEnumerable<Notification>>>(result);
var returnValue = Assert.IsType<List<Notification>>(okResult.Value);
Assert.Equal(2, returnValue.Count);
}

//Tests for GetNotification method
[Fact]
public async Task GetNotification_ReturnsNotification_WhenNotificationExists()
{
// Act
var result = await _controller.GetNotification(1);

// Assert
var okResult = Assert.IsType<ActionResult<Notification>>(result);
Assert.Equal(1, okResult.Value.Id);
}

[Fact]
public async Task GetNotification_ReturnsNotFound_WhenNotificationDoesNotExist()
{
// Act
var result = await _controller.GetNotification(99);

// Assert
Assert.IsType<NotFoundResult>(result.Result);
}

//Tester for PutNotification method
[Fact]
public async Task PutNotification_ReturnsNoContent_WhenUpdateIsSuccessful()
{
// Arrange
var existingNotification = await _context.Notifications.FindAsync(1);
existingNotification.Content = "Updated";

// Act
var result = await _controller.PutNotification(1, existingNotification);

// Assert
Assert.IsType<NoContentResult>(result);

// Verify the update
var updatedNotification = await _context.Notifications.FindAsync(1);
Assert.Equal("Updated", updatedNotification.Content);
}

[Fact]
public async Task PutNotification_ReturnsBadRequest_WhenIdMismatch()
{
// Arrange
var notification = new Notification { Id = 1, Content = "Updated" };

// Act
var result = await _controller.PutNotification(2, notification);

// Assert
Assert.IsType<BadRequestResult>(result);
}

[Fact]
public async Task PutNotification_ReturnsNotFound_WhenNotificationDoesNotExist()
{
// Arrange
var notification = new Notification { Id = 10, UserId = "99", Title = "Titlu99", Content = "Updated" };

// Act
var result = await _controller.PutNotification(10, notification);

// Assert
Assert.IsType<NotFoundResult>(result);
}


//Test for PostNotification method
[Fact]
public async Task PostNotification_ReturnsCreatedAtAction_WhenPostIsSuccessful()
{
// Arrange
var notification = new Notification { Id = 3, UserId = "3", Title = "Title3", Content = "New" };

// Act
var result = await _controller.PostNotification(notification);

// Assert
var actionResult = Assert.IsType<ActionResult<Notification>>(result);
var createdAtActionResult = Assert.IsType<CreatedAtActionResult>(actionResult.Result);
Assert.Equal("GetNotification", createdAtActionResult.ActionName);
Assert.Equal(notification.Id, ((Notification)createdAtActionResult.Value).Id);
}

//Test for DeleteNotification
[Fact]
public async Task DeleteNotification_ReturnsNoContent_WhenDeleteIsSuccessful()
{
// Act
var result = await _controller.DeleteNotification(1);

// Assert
Assert.IsType<NoContentResult>(result);
}

[Fact]
public async Task DeleteNotification_ReturnsNotFound_WhenNotificationDoesNotExist()
{
// Act
var result = await _controller.DeleteNotification(99);

// Assert
Assert.IsType<NotFoundResult>(result);
}
}
134 changes: 134 additions & 0 deletions Taskman.Tests/PrivilegeCheckerTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
// MyProject.Tests/PrivilegeCheckerTests.cs

using System.Security.Claims;
using Microsoft.EntityFrameworkCore;
using TaskmanAPI.Contexts;
using TaskmanAPI.Enums;
using TaskmanAPI.Models;
using TaskmanAPI.Services;

namespace MyProject.Tests;

public class PrivilegeCheckerTests : IDisposable
{
private readonly DefaultContext _context;
private readonly ClaimsPrincipal _mockUser;
private readonly PrivilegeChecker _privilegeChecker;

public PrivilegeCheckerTests()
{
// Configurăm opțiunile pentru DbContextOptions
var options = new DbContextOptionsBuilder<DefaultContext>()
.UseInMemoryDatabase(Guid.NewGuid().ToString())
.Options;

// Inițializăm contextul cu opțiunile definite
_context = new DefaultContext(options);

// Populăm contextul cu datele de test
SeedDatabase();

// Configurăm un mock pentru utilizator
var claims = new List<Claim>
{
new(ClaimTypes.NameIdentifier, "user1")
};
var identity = new ClaimsIdentity(claims, "TestAuthType");
_mockUser = new ClaimsPrincipal(identity);

// Inițializăm PrivilegeChecker cu contextul și utilizatorul simulat
_privilegeChecker = new PrivilegeChecker(_context, _mockUser);
}

public void Dispose()
{
_context.Dispose();
}

// Metodă pentru popularea bazei de date cu date de test
private void SeedDatabase()
{
var rolePerProjects = new List<RolePerProject>
{
new() { ProjectId = 1, UserId = "user1", RoleName = "User" }
};
_context.RolePerProjects.AddRange(rolePerProjects);
_context.SaveChanges();
}

[Fact]
public void HasAccessToProject_ReturnsTrue_WhenUserHasAccess()
{
// Act
var result = _privilegeChecker.HasAccessToProject(1);

// Assert
Assert.True(result);
}

[Fact]
public void HasAccessToProject_ReturnsFalse_WhenUserDoesNotHaveAccess()
{
// Arrange
var rolePerProjects = new List<RolePerProject>();
var mockDbSet = DbSetMockHelper.CreateMockDbSet(rolePerProjects);
_context.RolePerProjects = mockDbSet;

// Act
var result = _privilegeChecker.HasAccessToProject(1);

// Assert
Assert.False(result);
}

[Fact]
public void HasPrivilege_ReturnsTrue_WhenUserHasSufficientRole()
{
// Arrange
var rolePerProjects = new List<RolePerProject>
{
new() { ProjectId = 1, UserId = "user1", RoleName = "Admin" }
};
var mockDbSet = DbSetMockHelper.CreateMockDbSet(rolePerProjects);
_context.RolePerProjects = mockDbSet;

// Act
var result = _privilegeChecker.HasPrivilege(1, Role.Admin);

// Assert
Assert.True(result);
}

[Fact]
public void HasPrivilege_ReturnsFalse_WhenUserHasInsufficientRole()
{
// Arrange
var rolePerProjects = new List<RolePerProject>
{
new() { ProjectId = 1, UserId = "user1", RoleName = "User" }
};
var mockDbSet = DbSetMockHelper.CreateMockDbSet(rolePerProjects);
_context.RolePerProjects = mockDbSet;

// Act
var result = _privilegeChecker.HasPrivilege(1, Role.Admin);

// Assert
Assert.False(result);
}

[Fact]
public void HasPrivilege_ReturnsFalse_WhenUserHasNoRole()
{
// Arrange
var rolePerProjects = new List<RolePerProject>();
var mockDbSet = DbSetMockHelper.CreateMockDbSet(rolePerProjects);
_context.RolePerProjects = mockDbSet;

// Act
var result = _privilegeChecker.HasPrivilege(1, Role.User);

// Assert
Assert.False(result);
}
}
31 changes: 31 additions & 0 deletions Taskman.Tests/Taskman.Tests.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<BaseOutputPath>$(SolutionDir)\bin\$(MSBuildProjectName)\</BaseOutputPath>
<BaseIntermediateOutputPath>$(SolutionDir)\obj\$(MSBuildProjectName)\</BaseIntermediateOutputPath>

<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.0"/>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.10.0"/>
<PackageReference Include="Moq" Version="4.20.70"/>
<PackageReference Include="xunit" Version="2.8.1"/>
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.1"/>
</ItemGroup>

<ItemGroup>
<Using Include="Xunit"/>
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\TaskmanAPI.csproj"/>
</ItemGroup>

</Project>
Loading
Loading