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

Development #5

Merged
merged 7 commits into from
Feb 2, 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
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -305,3 +305,6 @@ nuget.config
**/.stryker-tmp/*

launchSettings.json

**/mysql/*
**/docker-compose.yml
7 changes: 7 additions & 0 deletions RemindoBot.Test/Handlers/VoiceChannelStatusHandlerTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
namespace RemindoBot.Test.Handlers;

[TestClass]
public class VoiceChannelStatusHandlerTests
{

}
26 changes: 26 additions & 0 deletions RemindoBot.Test/RemindoBot.Test.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

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

<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="7.0.15" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.5.0"/>
<PackageReference Include="Moq" Version="4.20.70" />
<PackageReference Include="MSTest.TestAdapter" Version="2.2.10"/>
<PackageReference Include="MSTest.TestFramework" Version="2.2.10"/>
<PackageReference Include="coverlet.collector" Version="3.2.0"/>
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\DAL\DAL.csproj" />
<ProjectReference Include="..\RemindoBot\RemindoBot.csproj" />
</ItemGroup>

</Project>
162 changes: 162 additions & 0 deletions RemindoBot.Test/Repositories/RemindoRepositoryTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
using DAL;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using RemindoBot.Models;
using RemindoBot.Repositories;

namespace RemindoBot.Test.Repositories;

[TestClass]
public class RemindoRepositoryTests
{
private SqliteConnection _connection = null!;
private DbContextOptions<RemindoDbContext> _contextOptions = null!;

[TestInitialize]
public void BeforeEach()
{
_connection = new SqliteConnection("Filename=:memory:");
_connection.Open();
_contextOptions = new DbContextOptionsBuilder<RemindoDbContext>()
.UseSqlite(_connection)
.Options;
using var context = new RemindoDbContext(_contextOptions);
context.Database.EnsureDeleted();
context.Database.EnsureCreated();
}

[TestMethod]
public async Task CreateReminder_Creates_Reminder_Returns_Id()
{
// Arrange
var reminderDto = new ReminderDTO
{
Message = "Test",
RemindTime = DateTime.Now,
userId = 12345,
guildId = 12356,
channelId = 1234567
};
await using (var context = new RemindoDbContext(_contextOptions))
{
var repository = new RemindoRepository(context);

// Act
var result = repository.CreateReminder(reminderDto).Result;

// Assert
Assert.AreEqual(1L, result);
}

await using (var context = new RemindoDbContext(_contextOptions))
{
const ulong expectedUserId = 12345;
const ulong expectedGuildId = 12356;
const ulong expectedChannelId = 1234567;
var reminders = await context.Reminders.ToListAsync();
Assert.AreEqual(1, reminders.Count);
Assert.AreEqual(1L, reminders[0].Id);
Assert.AreEqual("Test", reminders[0].Message);
Assert.AreEqual(expectedUserId, reminders[0].userId);
Assert.AreEqual(expectedGuildId, reminders[0].guildId);
Assert.AreEqual(expectedChannelId, reminders[0].channelId);
}
}

[TestMethod]
public async Task GetReminders_Returns_Reminders()
{
// Arrange
await using (var context = new RemindoDbContext(_contextOptions))
{
context.Reminders.Add(new Reminder
{
Message = "Test",
RemindTime = DateTime.Now,
userId = 12345,
guildId = 12356,
channelId = 1234567
});
context.Reminders.Add(new Reminder
{
Message = "Test2",
RemindTime = DateTime.Now,
userId = 12345,
guildId = 12356,
channelId = 1234567
});
await context.SaveChangesAsync();
}

// Act
await using (var context = new RemindoDbContext(_contextOptions))
{
var repository = new RemindoRepository(context);
var result = repository.GetReminders().Result;

// Assert
Assert.AreEqual(2, result.Count());
}
}

[TestMethod]
public async Task SetReminderHandled_Removes_Reminder()
{
// Arrange
await using (var context = new RemindoDbContext(_contextOptions))
{
context.Reminders.Add(new Reminder
{
Message = "Test",
RemindTime = DateTime.Now,
userId = 12345,
guildId = 12356,
channelId = 1234567
});
await context.SaveChangesAsync();
}

// Act
await using (var context = new RemindoDbContext(_contextOptions))
{
var repository = new RemindoRepository(context);
await repository.SetReminderHandled(1L);
}

// Assert
await using (var context = new RemindoDbContext(_contextOptions))
{
var reminders = await context.Reminders.ToListAsync();
Assert.AreEqual(0, reminders.Count);
}
}

[TestMethod]
public async Task GetReminder_Returns_Reminder()
{
// Arrange
await using (var context = new RemindoDbContext(_contextOptions))
{
context.Reminders.Add(new Reminder
{
Message = "Test",
RemindTime = DateTime.Now,
userId = 12345,
guildId = 12356,
channelId = 1234567
});
await context.SaveChangesAsync();
}

// Act
await using (var context = new RemindoDbContext(_contextOptions))
{
var repository = new RemindoRepository(context);
var result = repository.GetReminder(1L);

// Assert
Assert.IsNotNull(result);
Assert.AreEqual(1L, result!.Id);
}
}
}
38 changes: 38 additions & 0 deletions RemindoBot.Test/Services/RemindoServiceTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
using DAL;
using Discord;
using Discord.WebSocket;
using Moq;
using RemindoBot.Models;
using RemindoBot.Repositories;
using RemindoBot.Services;

namespace RemindoBot.Test.Services;

[TestClass]
public class RemindoServiceTests
{
[TestMethod]
public async Task CreateReminder_Calls_CreateReminder_On_Repository()
{
// Arrange
var repositoryMock = new Mock<IRemindoRepository>(MockBehavior.Strict);
var clientMock = new Mock<DiscordSocketClient>();

repositoryMock.Setup(x => x.CreateReminder(It.IsAny<ReminderDTO>())).ReturnsAsync(1L);

var service = new RemindoService(repositoryMock.Object, clientMock.Object);
var reminder = new ReminderDTO
{
Message = "Test",
RemindTime = DateTime.Now.AddSeconds(10), // 10 seconds from now
userId = 1
};

// Act
await service.CreateReminder(reminder);

// Assert
repositoryMock.Verify(x => x.CreateReminder(reminder), Times.Once);
}

}
1 change: 1 addition & 0 deletions RemindoBot.Test/Usings.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
global using Microsoft.VisualStudio.TestTools.UnitTesting;
6 changes: 6 additions & 0 deletions RemindoBot.sln
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RemindoBot", "RemindoBot\Re
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DAL", "DAL\DAL.csproj", "{D46415E1-1384-45E7-88BA-8D1232A34619}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RemindoBot.Test", "RemindoBot.Test\RemindoBot.Test.csproj", "{4B83945F-3881-41A8-973B-B8634DCE1D9E}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -18,5 +20,9 @@ Global
{D46415E1-1384-45E7-88BA-8D1232A34619}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D46415E1-1384-45E7-88BA-8D1232A34619}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D46415E1-1384-45E7-88BA-8D1232A34619}.Release|Any CPU.Build.0 = Release|Any CPU
{4B83945F-3881-41A8-973B-B8634DCE1D9E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4B83945F-3881-41A8-973B-B8634DCE1D9E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4B83945F-3881-41A8-973B-B8634DCE1D9E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4B83945F-3881-41A8-973B-B8634DCE1D9E}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal
56 changes: 56 additions & 0 deletions RemindoBot/Commands/CommandManager.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
using System.Reflection;
using Discord.Net;
using Discord.WebSocket;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;

namespace RemindoBot.Commands;

public class CommandManager
{
private readonly DiscordSocketClient _client;
private readonly IServiceProvider _services;
private readonly ILogger<CommandManager> _logger;
private Dictionary<string, Type> _commands = new();

public CommandManager(DiscordSocketClient client, IServiceProvider services, ILogger<CommandManager> logger)
{
_client = client;
_services = services;
_logger = logger;
}

public void RegisterCommands()
{
_commands.Clear();
var commandTypes = Assembly.GetExecutingAssembly().GetTypes()
.Where(t => t.GetInterfaces().Contains(typeof(ICommand)));

foreach (var commandType in commandTypes)
{
var command = (ICommand) ActivatorUtilities.CreateInstance(_services, commandType);

try
{
_client.CreateGlobalApplicationCommandAsync(command.Command.Build());
_commands.Add(command.Command.Name, command.GetType());
_logger.LogInformation($"Registered command {command.Command.Name}");
}
catch (ApplicationCommandException exception)

Check warning on line 40 in RemindoBot/Commands/CommandManager.cs

View workflow job for this annotation

GitHub Actions / build

'ApplicationCommandException' is obsolete: 'Please use HttpException instead of this. Will be removed in next major version.'

Check warning on line 40 in RemindoBot/Commands/CommandManager.cs

View workflow job for this annotation

GitHub Actions / build

'ApplicationCommandException' is obsolete: 'Please use HttpException instead of this. Will be removed in next major version.'
{
var json = JsonConvert.SerializeObject(exception.Errors, Formatting.Indented);
_logger.LogError($"Unable to register command {command.Command.Name}: {json}");
}
}
}

public async Task SlashCommandHandler(SocketSlashCommand command)
{
if (_commands.TryGetValue(command.Data.Name, out var handler))
{
var commandHandler = (ICommand) ActivatorUtilities.CreateInstance(_services, handler);
await commandHandler.Handle(command);
}
}
}
12 changes: 12 additions & 0 deletions RemindoBot/Commands/ICommand.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
using Discord.Interactions.Builders;
using Discord.WebSocket;
using SlashCommandBuilder = Discord.SlashCommandBuilder;

namespace RemindoBot.Commands;

public interface ICommand
{
string Name { get; }
SlashCommandBuilder Command { get; }
Task Handle(SocketSlashCommand command);
}
Loading
Loading