Skip to content

Commit

Permalink
added some sample unit tests in a different assembly
Browse files Browse the repository at this point in the history
  • Loading branch information
Radoslav Radev committed Mar 9, 2024
1 parent e5ee97c commit 7d9eb15
Show file tree
Hide file tree
Showing 10 changed files with 234 additions and 11 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/AccountPipeline.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ jobs:
- name: Build
run: dotnet build Backend/Account/Account.csproj --no-restore
- name: Test
run: dotnet test Backend/Account/Account.csproj --no-build --verbosity normal
run: dotnet test .\Backend\Tests\Account.Test\Account.Test.csproj --no-build --verbosity normal

- name: Log in to DockerHub
uses: docker/login-action@v1
Expand Down
13 changes: 7 additions & 6 deletions Backend/Account/Controllers/AccountController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,18 @@ public class AccountController(AccountService _accountService):ControllerBase


[HttpPost("register")]
public async Task<ActionResult<AccountDTO>> Register([FromBody] RegisterRequestDTO request)
public async Task<OkObjectResult> Register([FromBody] RegisterRequestDTO request)
{
var account = await _accountService.Register(request);
return Ok(account);
var accountNtoken = await _accountService.Register(request);

return Ok(accountNtoken);
}

[HttpPost("login")]
public async Task<ActionResult<AccountDTO>> Login([FromBody] LoginRequestDTO request)
public async Task<OkObjectResult> Login([FromBody] LoginRequestDTO request)
{
var account = await _accountService.Login(request);
return Ok(account);
var accountNtoken = await _accountService.Login(request);
return Ok(accountNtoken);
}

[HttpGet("balance")]
Expand Down
5 changes: 3 additions & 2 deletions Backend/Account/Services/AccountService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,12 @@ public class AccountService(DatabaseContext _accountDbContext, IConfiguration co
{
private readonly AsyncRetryPolicy _dbRetryPolicy = Policy.Handle<Exception>().WaitAndRetryAsync(3, i => TimeSpan.FromSeconds(10));

public async Task<AccountDTO?> Login(LoginRequestDTO request)
public async Task<Tuple<AccountDTO,string>?> Login(LoginRequestDTO request)
{
var account = await _accountDbContext.Accounts.FirstOrDefaultAsync(x => x.Email == request.email);
if (account is null) return null;
return AccountMapper.AccountToAccountDto(account);
var authToken = AuthTokenGenerator.GenerateOwnAuthToken(account.AccId.ToString(),configuration);
return new Tuple<AccountDTO, string>(AccountMapper.AccountToAccountDto(account), authToken);
}

public async Task<Tuple<AccountDTO,string>> Register(RegisterRequestDTO request)
Expand Down
Binary file modified Backend/OpenVidStreamer.ManagementNdiscovary/var/raft/raft.db
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -1 +1 @@
{"last_seen_unix":1709995809}
{"last_seen_unix":1709999409}
11 changes: 11 additions & 0 deletions Backend/OpenVidStreamer.sln
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VideoStreamer", "VideoStrea
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Render", "Render\Render.csproj", "{DBAEC32F-4430-487F-A421-D03842A9871C}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{43FDBBCE-75B2-4BC5-AEA8-F001FB3C67E2}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Account.Test", "Tests\Account.Test\Account.Test.csproj", "{919F0ADE-6541-4DCE-94D9-18C5A7C41ED4}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -57,8 +61,15 @@ Global
{DBAEC32F-4430-487F-A421-D03842A9871C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{DBAEC32F-4430-487F-A421-D03842A9871C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{DBAEC32F-4430-487F-A421-D03842A9871C}.Release|Any CPU.Build.0 = Release|Any CPU
{919F0ADE-6541-4DCE-94D9-18C5A7C41ED4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{919F0ADE-6541-4DCE-94D9-18C5A7C41ED4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{919F0ADE-6541-4DCE-94D9-18C5A7C41ED4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{919F0ADE-6541-4DCE-94D9-18C5A7C41ED4}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{919F0ADE-6541-4DCE-94D9-18C5A7C41ED4} = {43FDBBCE-75B2-4BC5-AEA8-F001FB3C67E2}
EndGlobalSection
EndGlobal
41 changes: 41 additions & 0 deletions Backend/Tests/Account.Test/Account.Test.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<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.EntityFrameworkCore.Design" Version="8.0.2">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="8.0.2" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0"/>
<PackageReference Include="Moq" Version="4.20.70" />
<PackageReference Include="xunit" Version="2.5.3"/>
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.3"/>
</ItemGroup>

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

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

<ItemGroup>
<Content Update="appsettings.json">
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</Content>
</ItemGroup>

</Project>
139 changes: 139 additions & 0 deletions Backend/Tests/Account.Test/AccountServiceTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
using Account.Model.DTO;
using Account.Repository.EFC;
using Account.Services;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace Account.Test;

public class AccountServiceTests
{
private readonly DatabaseContext _dbContext;
private readonly IConfiguration _configuration;
private readonly AccountService _accountService;

public AccountServiceTests()
{
var serviceProvider = new ServiceCollection()
.AddEntityFrameworkInMemoryDatabase()
.BuildServiceProvider();

var options = new DbContextOptionsBuilder<DatabaseContext>()
.UseInMemoryDatabase(databaseName: "TestDatabase")
.UseInternalServiceProvider(serviceProvider)
.Options;

_dbContext = new DatabaseContext(options);

// Build configuration from appsettings.json
_configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();

_accountService = new AccountService(_dbContext, _configuration);
}

[Fact]
public async Task Login_ReturnsAccountDto_WhenEmailExists()
{
// Arrange
var loginRequest = new LoginRequestDTO { email = "[email protected]" };
_dbContext.Accounts.Add(new Account.Repository.Entities.Account { Email = "[email protected]", PasswordHashed = "hashedPassword" });
await _dbContext.SaveChangesAsync();

// Act
var result = await _accountService.Login(loginRequest);

// Assert
Assert.NotNull(result);
Assert.Equal("[email protected]", result.Item1.Email);
}

[Fact]
public async Task Login_ReturnsNull_WhenEmailDoesNotExist()
{
// Arrange
var loginRequest = new LoginRequestDTO { email = "[email protected]" };

// Act
var result = await _accountService.Login(loginRequest);

// Assert
Assert.Null(result);
}

[Fact]
public async Task Register_ReturnsAccountDtoAndToken_WhenRegistrationIsSuccessful()
{
// Arrange
var registerRequest = new RegisterRequestDTO { email = "[email protected]", passwordUnhashed = "password" };

// Act
var result = await _accountService.Register(registerRequest);

// Assert
Assert.NotNull(result);
Assert.Equal("[email protected]", result.Item1.Email);
Assert.NotNull(result.Item2);
}

[Fact]
public async Task GetBalance_ReturnsBalance_WhenAccountExists()
{
// Arrange
var accountId = Guid.NewGuid();
_dbContext.Accounts.Add(new Account.Repository.Entities.Account { AccId = accountId, Balance = 100, Email = "[email protected]", PasswordHashed = "hashedPassword" });
await _dbContext.SaveChangesAsync();

// Act
var result = await _accountService.GetBalance(accountId);

// Assert
Assert.Equal(100, result);
}

[Fact]
public async Task GetBalance_ThrowsException_WhenAccountDoesNotExist()
{
// Arrange
var accountId = Guid.NewGuid();

// Act & Assert
await Assert.ThrowsAsync<Exception>(() => _accountService.GetBalance(accountId));
}

[Fact]
public async Task ActivateSubscription_ReturnsAccountDto_WhenAccountExistsAndHasSufficientBalance()
{
// Arrange
var accountId = Guid.NewGuid();
_dbContext.Accounts.Add(new Account.Repository.Entities.Account
{
AccId = accountId,
Balance = 100,
Email = "[email protected]",
PasswordHashed = "hashedPassword"
});
await _dbContext.SaveChangesAsync();

// Act
var result = await _accountService.ActivateSubscription(accountId);

// Assert
Assert.NotNull(result);
Assert.Equal(accountId, result.AccId);
Assert.Equal(85, result.Balance); // Assuming the monthly subscription price is 15 (it is set from the appsettings.json of the assembly)
}

[Fact]
public async Task ActivateSubscription_ThrowsException_WhenAccountDoesNotExist()
{
// Arrange
var accountId = Guid.NewGuid();

// Act & Assert
await Assert.ThrowsAsync<Exception>(() => _accountService.ActivateSubscription(accountId));
}
}
30 changes: 30 additions & 0 deletions Backend/Tests/Account.Test/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"ConnectionStrings": {
"DefaultConnection": "server=account-db-service;uid=admin;pwd=12345;database=accountDB;"
},
"AllowedHosts": "*",
"consulUri": "http://consul-service:8500",
"POD_IP": "localhost",
"servicePort": "8081",
"serviceName": "OpenVisStreamer.Account",

"CustomJWT": {
"Issuer": "OpenVidStreamerAccountService",
"Audience": "OpenVidStreamerFE",
"Secret": "rxio0SNqgU2yYEvOyZJ1greSMC75JBU0D6IxBZBxIXm+xzSr2ZZ+ZV/PHoV7sNYg7f9PCHulGu+QHG5qaSNpTQ==",
"ExpirationInHours": 72,
"SignalRsecret" : "qsMC75JBU0D6IxBZBxIXm+xzSr2ZZ+ZV/PHoV7sNYg7f9PCHulGu+QHG5qaSNpTQ=="
},
"monthlySubscriptionPrice": "15",
"RabbitMQ":{
"HostAddress": "amqp://rabbitmq-service:5672",
"UserName": "guest",
"Password": "guest"
}
}
2 changes: 1 addition & 1 deletion Backend/VideoStreamer/entrypoint.sh
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#!/bin/bash

# Mount the NFS share
mount -t nfs $NFS_SERVER:$NFS_PATH /app/data
mount -t nfs $NFS_SERVER:$NFS_PATH

# Check if mount was successful
if [ $? -ne 0 ]; then
Expand Down

0 comments on commit 7d9eb15

Please sign in to comment.