Skip to content

Commit

Permalink
created and run unit Tests - all green
Browse files Browse the repository at this point in the history
  • Loading branch information
jas20202 committed Feb 24, 2024
1 parent 4395213 commit def6b82
Show file tree
Hide file tree
Showing 4 changed files with 197 additions and 22 deletions.
50 changes: 30 additions & 20 deletions PWManager.CLI/Controllers/LoginController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using PWManager.CLI.Enums;
using PWManager.CLI.Interfaces;
using Sharprompt;
using System.IO;

namespace PWManager.CLI.Controllers {
public class LoginController : IController {
Expand All @@ -19,22 +20,42 @@ public ExitCondition Handle(string[] args) {
throw new UserFeedbackException("Command not available in a session!");
}

(var username, var path) = ParseArgs(args);

var lastUser = ConfigFileHandler.ReadDefaultFile();
if (String.IsNullOrWhiteSpace(username)) {
username = lastUser.Split('\n')[0];
}
if (String.IsNullOrWhiteSpace(path)) {
path = lastUser.Split('\n')[1];
}

var pass = Prompt.Password("Enter your password");
_loginService.Login(username, pass, path);

ConfigFileHandler.WriteDefaultFile(username, path);
Console.WriteLine($"Welcome {username} :)");

_env.RunningSession = true;
return ExitCondition.CONTINUE;
}

public (string, string) ParseArgs(string[] args) {
string username = "";
string path = "";

int basepointer = 0;
while(basepointer < args.Length) {
while (basepointer < args.Length) {
if ((args[basepointer].Equals("-u") || args[basepointer].Equals("--username"))) {
if ((args.Length - basepointer <= 1) || args[basepointer + 1].StartsWith('-')) {
username = Prompt.Input<string>("Please enter your username");
username = AskForInput("Please enter your username");
} else {
username = args[basepointer + 1];
basepointer++;
}
}
else if ((args[basepointer].Equals("-d") || args[basepointer].Equals("--directory"))) {
} else if ((args[basepointer].Equals("-d") || args[basepointer].Equals("--directory"))) {
if ((args.Length - basepointer <= 1) || args[basepointer + 1].StartsWith('-')) {
path = Prompt.Input<string>("Please enter the location of your databasefile");
path = AskForInput("Please enter the location of your databasefile");
} else {
path = args[basepointer + 1];
basepointer++;
Expand All @@ -43,22 +64,11 @@ public ExitCondition Handle(string[] args) {
basepointer++;
}

var lastUser = ConfigFileHandler.ReadDefaultFile();
if (String.IsNullOrWhiteSpace(username)) {
username = lastUser.Split('\n')[0];
}
if (String.IsNullOrWhiteSpace(path)) {
path = lastUser.Split('\n')[1];
}

var pass = Prompt.Password("Enter your password");
_loginService.Login(username, pass, path);

ConfigFileHandler.WriteDefaultFile(username, path);
Console.WriteLine($"Welcome {username} :)");
return (username, path);
}

_env.RunningSession = true;
return ExitCondition.CONTINUE;
public virtual string AskForInput(string prompt) {
return Prompt.Input<string>(prompt);
}
}
}
12 changes: 10 additions & 2 deletions PWManager.Data/Services/LoginService.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using PWManager.Application.Context;
using PWManager.Application.Exceptions;
using PWManager.Application.Services.Interfaces;
using PWManager.Data.Abstraction;
using PWManager.Domain.Exceptions;
using PWManager.Domain.Repositories;
using PWManager.Domain.Services.Interfaces;
Expand All @@ -14,19 +15,26 @@ public class LoginService : ILoginService {
private readonly ICryptService _cryptService;
private readonly IApplicationEnvironment _env;

private readonly DataContextWrapper _dataContext;

internal LoginService(DataContextWrapper wrapper, IUserRepository userRepository, IGroupRepository groupRepository, ICryptService cryptService, ISettingsRepository settingsRepository, IApplicationEnvironment env) : this(
userRepository, groupRepository, cryptService, settingsRepository, env) {
_dataContext = wrapper;
}
public LoginService(IUserRepository userRepository, IGroupRepository groupRepository, ICryptService cryptService, ISettingsRepository settingsRepository, IApplicationEnvironment env) {
_userRepository = userRepository;
_groupRepository = groupRepository;
_settingsRepository = settingsRepository;
_cryptService = cryptService;
_env = env;
_dataContext = new DataContextWrapper();
}
public void Login(string username, string password, string dbPath) {
if(!DataContext.DatabaseExists(dbPath)) {
if(!_dataContext.DatabaseExists(dbPath)) {
throw new UserFeedbackException("Database not found.");
}

DataContext.InitDataContext(dbPath);
_dataContext.InitDataContext(dbPath);

var user = _userRepository.CheckPasswordAttempt(username, password);
if(user is null) {
Expand Down
88 changes: 88 additions & 0 deletions PWManager.UnitTests/Cli/LoginControllerTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
using NSubstitute;
using PWManager.Application.Context;
using PWManager.Application.Services.Interfaces;
using PWManager.CLI.Controllers;
using PWManager.Data.Repositories;
using PWManager.Data.Services;
using PWManager.Domain.Entities;
using PWManager.Domain.Repositories;
using PWManager.Domain.ValueObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PWManager.UnitTests.Cli {
public class LoginControllerTest {

private LoginController _sut;

public LoginControllerTest()
{
_sut = Substitute.ForPartsOf<LoginController>(null, null);
_sut.AskForInput(Arg.Any<string>()).Returns("Test");
}

[Fact]
public void Arguments_ShouldBe_Empty_WithoutArgs() {
string[] args = { };

(var username, var path) = _sut.ParseArgs(args);

Assert.Equal(0, username.Length);
Assert.Equal(0, path.Length);
}

[Fact]
public void Arguments_Should_Return_Path() {
string[] args = { "-d", "TestPath" };

(var username, var path) = _sut.ParseArgs(args);

Assert.Equal(0, username.Length);
Assert.Equal("TestPath", path);
}

[Fact]
public void Arguments_Should_Return_Username() {
string[] args = { "-u", "TestUserName" };

(var username, var path) = _sut.ParseArgs(args);

Assert.Equal("TestUserName", username);
Assert.Equal(0, path.Length);
}


[Fact]
public void Arguments_Should_Return_Path_And_PromptName() {
string[] args = { "-d", "TestPath", "-u" };

(var username, var path) = _sut.ParseArgs(args);

Assert.Equal("Test", username);
Assert.Equal("TestPath", path);
}

[Fact]
public void Arguments_Should_Return_Username_And_PromptPath() {
string[] args = { "-d", "-u", "TestUserName" };

(var username, var path) = _sut.ParseArgs(args);

Assert.Equal("TestUserName", username);
Assert.Equal("Test", path);
}

[Fact]
public void Arguments_Should_Return_From_Prompts() {
string[] args = { "-d", "-u" };

(var username, var path) = _sut.ParseArgs(args);

Assert.Equal("Test", username);
Assert.Equal("Test", path);
}
}
}
69 changes: 69 additions & 0 deletions PWManager.UnitTests/Services/LoginServiceTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
using NSubstitute;
using NSubstitute.ReturnsExtensions;
using PWManager.Application.Context;
using PWManager.Application.Exceptions;
using PWManager.Data.Abstraction;
using PWManager.Data.Services;
using PWManager.Domain.Entities;
using PWManager.Domain.Repositories;
using PWManager.Domain.Services.Interfaces;
using PWManager.Domain.ValueObjects;

namespace PWManager.UnitTests.Services {
public class LoginServiceTest {

private LoginService _sut;
private IGroupRepository _groupRepo = Substitute.For<IGroupRepository>();
private ICryptService _cryptService = Substitute.For<ICryptService>();
private ISettingsRepository _settingsRepository = Substitute.For<ISettingsRepository>();
private DataContextWrapper _wrapper = Substitute.For<DataContextWrapper>();
private IApplicationEnvironment _env = Substitute.For<IApplicationEnvironment>();
private IUserRepository _userRepo = Substitute.For<IUserRepository>();

[Fact]
public void Login_Should_SetEnviroment() {
_wrapper.DatabaseExists(Arg.Any<string>()).Returns(true);
var user = new User(Guid.NewGuid().ToString(), DateTimeOffset.Now, DateTimeOffset.Now, "TestUserName");
_userRepo.CheckPasswordAttempt(Arg.Any<string>(), Arg.Any<string>()).Returns(user);
var group = new Group("TestGroup", user.Id);
_settingsRepository.GetSettings().Returns(
new Settings(user.Id, null, null, new MainGroupSetting(group.Identifier))
);
_groupRepo.GetGroup(Arg.Any<string>()).Returns(group);

_sut = new LoginService(_wrapper, _userRepo, _groupRepo, _cryptService, _settingsRepository, _env);
_sut.Login("TestUserName", "WhatAPasswort", ".");

Assert.Equal(user, _env.CurrentUser);
Assert.NotNull(_env.EncryptionKey);
Assert.NotNull(_env.CurrentGroup);
}

[Fact]
public void Login_ShouldNot_IfDatabaseDoesntExists() {
_wrapper.DatabaseExists(Arg.Any<string>()).Returns(false);
var user = new User(Guid.NewGuid().ToString(), DateTimeOffset.Now, DateTimeOffset.Now, "TestUserName");
_userRepo.CheckPasswordAttempt(Arg.Any<string>(), Arg.Any<string>()).Returns(user);


_sut = new LoginService(_wrapper, _userRepo, _groupRepo, _cryptService, _settingsRepository, _env);

var ex = Assert.Throws<UserFeedbackException>(() => _sut.Login("TestUserName", "WhatAPassword", "."));
Assert.Equal("Database not found.", ex.Message);
}

[Fact]
public void Login_ShouldNot_IfUserNotFound() {
_wrapper.DatabaseExists(Arg.Any<string>()).Returns(true);
var user = new User(Guid.NewGuid().ToString(), DateTimeOffset.Now, DateTimeOffset.Now, "TestUserName");
_userRepo.CheckPasswordAttempt(Arg.Any<string>(), Arg.Any<string>()).ReturnsNull();


_sut = new LoginService(_wrapper, _userRepo, _groupRepo, _cryptService, _settingsRepository, _env);

var ex = Assert.Throws<UserFeedbackException>(() => _sut.Login("TestUserName", "WhatAPassword", "."));
Assert.Equal("No such user found.", ex.Message);
}

}
}

0 comments on commit def6b82

Please sign in to comment.