Compare commits

..

2 Commits

Author SHA1 Message Date
Svrnty
92231df745 test: add xUnit test project for Svrnty.CQRS core library
Add tests/Svrnty.CQRS.Tests with 61 tests covering:
- CommandMeta and QueryMeta metadata creation and naming conventions
- CommandDiscovery and QueryDiscovery lookup, existence, and enumeration
- DI service registration for commands (with/without result) and queries
- Full pipeline integration (register -> discover -> resolve)
- CqrsBuilder fluent API configuration
- CqrsConfiguration generic storage and mapping callbacks
- Handler execution via DI-resolved instances

Co-Authored-By: Svrnty Inc. <eng@svrnty.com>
2026-02-27 18:38:44 -05:00
Svrnty
5a35e23234 chore: add .editorconfig with standard C# conventions
Adds EditorConfig for consistent formatting across the solution:
- 4-space indentation, UTF-8 encoding, LF line endings
- Standard .NET naming conventions (_camelCase private fields, PascalCase types)
- File-scoped namespace preference matching existing code style
- Allman brace style, var preferences, expression-bodied member rules
- Appropriate indentation for XML/JSON/proto files

Co-Authored-By: Svrnty Inc. <eng@svrnty.com>
2026-02-27 18:37:51 -05:00
12 changed files with 1107 additions and 0 deletions

261
.editorconfig Normal file
View File

@ -0,0 +1,261 @@
# Top-most EditorConfig file
root = true
# All files
[*]
indent_style = space
indent_size = 4
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
# XML project files
[*.{csproj,vbproj,vcxproj,vcxproj.filters,proj,projitems,shproj}]
indent_size = 2
# XML config files
[*.{props,targets,ruleset,config,nuspec,resx,vsixmanifest,vsct}]
indent_size = 2
# JSON and YAML files
[*.{json,yml,yaml}]
indent_size = 2
# Markdown files
[*.md]
trim_trailing_whitespace = false
# Proto files
[*.proto]
indent_size = 2
# Solution files
[*.sln]
indent_style = tab
# C# files
[*.cs]
#### Core EditorConfig Options ####
# Indentation and spacing
indent_size = 4
indent_style = space
tab_width = 4
#### .NET Coding Conventions ####
# Organise usings
dotnet_sort_system_directives_first = true
dotnet_separate_import_directive_groups = false
# this. and Me. preferences
dotnet_style_qualification_for_field = false:suggestion
dotnet_style_qualification_for_property = false:suggestion
dotnet_style_qualification_for_method = false:suggestion
dotnet_style_qualification_for_event = false:suggestion
# Language keywords vs BCL types preferences
dotnet_style_predefined_type_for_locals_parameters_members = true:suggestion
dotnet_style_predefined_type_for_member_access = true:suggestion
# Parentheses preferences
dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:silent
dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:silent
dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:silent
dotnet_style_parentheses_in_other_operators = never_if_unnecessary:silent
# Modifier preferences
dotnet_style_require_accessibility_modifiers = for_non_interface_members:suggestion
# Expression-level preferences
dotnet_style_coalesce_expression = true:suggestion
dotnet_style_collection_initializer = true:suggestion
dotnet_style_explicit_tuple_names = true:suggestion
dotnet_style_null_propagation = true:suggestion
dotnet_style_object_initializer = true:suggestion
dotnet_style_prefer_auto_properties = true:suggestion
dotnet_style_prefer_conditional_expression_over_assignment = true:silent
dotnet_style_prefer_conditional_expression_over_return = true:silent
dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion
dotnet_style_prefer_inferred_tuple_names = true:suggestion
dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion
dotnet_style_prefer_simplified_boolean_expressions = true:suggestion
dotnet_style_prefer_simplified_interpolation = true:suggestion
# Field preferences
dotnet_style_readonly_field = true:suggestion
# Parameter preferences
dotnet_code_quality_unused_parameters = all:suggestion
#### C# Coding Conventions ####
# var preferences
csharp_style_var_for_built_in_types = true:suggestion
csharp_style_var_when_type_is_apparent = true:suggestion
csharp_style_var_elsewhere = true:suggestion
# Expression-bodied members
csharp_style_expression_bodied_methods = when_on_single_line:silent
csharp_style_expression_bodied_constructors = false:silent
csharp_style_expression_bodied_operators = when_on_single_line:silent
csharp_style_expression_bodied_properties = when_on_single_line:suggestion
csharp_style_expression_bodied_indexers = when_on_single_line:suggestion
csharp_style_expression_bodied_accessors = when_on_single_line:suggestion
csharp_style_expression_bodied_lambdas = when_on_single_line:silent
csharp_style_expression_bodied_local_functions = when_on_single_line:silent
# Pattern matching preferences
csharp_style_pattern_matching_over_as_with_null_check = true:suggestion
csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion
csharp_style_prefer_not_pattern = true:suggestion
csharp_style_prefer_pattern_matching = true:silent
csharp_style_prefer_switch_expression = true:suggestion
# Null-checking preferences
csharp_style_conditional_delegate_call = true:suggestion
csharp_style_prefer_null_check_over_type_check = true:suggestion
# Code-block preferences
csharp_prefer_braces = true:silent
csharp_prefer_simple_using_statement = true:suggestion
csharp_style_prefer_method_group_conversion = true:silent
# Expression-level preferences
csharp_prefer_simple_default_expression = true:suggestion
csharp_style_prefer_local_over_anonymous_function = true:suggestion
csharp_style_prefer_index_operator = true:suggestion
csharp_style_prefer_range_operator = true:suggestion
csharp_style_prefer_tuple_swap = true:suggestion
csharp_style_implicit_object_creation_when_type_is_apparent = true:suggestion
csharp_style_inlined_variable_declaration = true:suggestion
csharp_style_deconstructed_variable_declaration = true:suggestion
csharp_style_throw_expression = true:suggestion
# 'using' directive preferences
csharp_using_directive_placement = outside_namespace:suggestion
# Namespace preferences
csharp_style_namespace_declarations = file_scoped:suggestion
#### C# Formatting Rules ####
# New line preferences
csharp_new_line_before_open_brace = all
csharp_new_line_before_else = true
csharp_new_line_before_catch = true
csharp_new_line_before_finally = true
csharp_new_line_before_members_in_object_initializers = true
csharp_new_line_before_members_in_anonymous_types = true
csharp_new_line_between_query_expression_clauses = true
# Indentation preferences
csharp_indent_case_contents = true
csharp_indent_switch_labels = true
csharp_indent_labels = one_less_than_current
csharp_indent_block_contents = true
csharp_indent_braces = false
csharp_indent_case_contents_when_block = true
# Space preferences
csharp_space_after_cast = false
csharp_space_after_keywords_in_control_flow_statements = true
csharp_space_between_parentheses = false
csharp_space_before_colon_in_inheritance_clause = true
csharp_space_after_colon_in_inheritance_clause = true
csharp_space_around_binary_operators = before_and_after
csharp_space_between_method_declaration_parameter_list_parentheses = false
csharp_space_between_method_declaration_empty_parameter_list_parentheses = false
csharp_space_between_method_declaration_name_and_open_parenthesis = false
csharp_space_between_method_call_parameter_list_parentheses = false
csharp_space_between_method_call_empty_parameter_list_parentheses = false
csharp_space_between_method_call_name_and_opening_parenthesis = false
csharp_space_after_comma = true
csharp_space_before_comma = false
csharp_space_after_dot = false
csharp_space_before_dot = false
csharp_space_after_semicolon_in_for_statement = true
csharp_space_before_semicolon_in_for_statement = false
csharp_space_around_declaration_statements = false
csharp_space_before_open_square_brackets = false
csharp_space_between_empty_square_brackets = false
csharp_space_between_square_brackets = false
# Wrapping preferences
csharp_preserve_single_line_statements = false
csharp_preserve_single_line_blocks = true
#### Naming Conventions ####
# Naming rules
dotnet_naming_rule.interface_should_begin_with_i.severity = suggestion
dotnet_naming_rule.interface_should_begin_with_i.symbols = interface
dotnet_naming_rule.interface_should_begin_with_i.style = begins_with_i
dotnet_naming_rule.types_should_be_pascal_case.severity = suggestion
dotnet_naming_rule.types_should_be_pascal_case.symbols = types
dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case
dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = suggestion
dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members
dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case
dotnet_naming_rule.private_or_internal_field_should_be_camel_case_with_underscore.severity = suggestion
dotnet_naming_rule.private_or_internal_field_should_be_camel_case_with_underscore.symbols = private_or_internal_field
dotnet_naming_rule.private_or_internal_field_should_be_camel_case_with_underscore.style = camel_case_with_underscore
dotnet_naming_rule.constant_fields_should_be_pascal_case.severity = suggestion
dotnet_naming_rule.constant_fields_should_be_pascal_case.symbols = constant_fields
dotnet_naming_rule.constant_fields_should_be_pascal_case.style = pascal_case
dotnet_naming_rule.async_methods_should_end_with_async.severity = suggestion
dotnet_naming_rule.async_methods_should_end_with_async.symbols = async_methods
dotnet_naming_rule.async_methods_should_end_with_async.style = ends_with_async
dotnet_naming_rule.type_parameters_should_begin_with_t.severity = suggestion
dotnet_naming_rule.type_parameters_should_begin_with_t.symbols = type_parameters
dotnet_naming_rule.type_parameters_should_begin_with_t.style = begins_with_t
# Symbol specifications
dotnet_naming_symbols.interface.applicable_kinds = interface
dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum
dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method
dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.private_or_internal_field.applicable_kinds = field
dotnet_naming_symbols.private_or_internal_field.applicable_accessibilities = private, internal, private_protected
dotnet_naming_symbols.constant_fields.applicable_kinds = field
dotnet_naming_symbols.constant_fields.applicable_accessibilities = *
dotnet_naming_symbols.constant_fields.required_modifiers = const
dotnet_naming_symbols.async_methods.applicable_kinds = method
dotnet_naming_symbols.async_methods.applicable_accessibilities = *
dotnet_naming_symbols.async_methods.required_modifiers = async
dotnet_naming_symbols.type_parameters.applicable_kinds = type_parameter
dotnet_naming_symbols.type_parameters.applicable_accessibilities = *
# Naming styles
dotnet_naming_style.pascal_case.capitalization = pascal_case
dotnet_naming_style.begins_with_i.required_prefix = I
dotnet_naming_style.begins_with_i.capitalization = pascal_case
dotnet_naming_style.camel_case_with_underscore.required_prefix = _
dotnet_naming_style.camel_case_with_underscore.capitalization = camel_case
dotnet_naming_style.ends_with_async.required_suffix = Async
dotnet_naming_style.ends_with_async.capitalization = pascal_case
dotnet_naming_style.begins_with_t.required_prefix = T
dotnet_naming_style.begins_with_t.capitalization = pascal_case

View File

@ -43,6 +43,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Svrnty.CQRS.Events.Abstract
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Svrnty.CQRS.Events.RabbitMQ", "Svrnty.CQRS.Events.RabbitMQ\Svrnty.CQRS.Events.RabbitMQ.csproj", "{3C7412EF-13C2-41F3-9D4C-D2BEC4843C8C}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{0AB3BF05-4346-4AA6-1389-037BE0695223}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Svrnty.CQRS.Tests", "tests\Svrnty.CQRS.Tests\Svrnty.CQRS.Tests.csproj", "{BCB3DD95-DFDB-452C-A0AD-AA657AE0C049}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -257,10 +261,25 @@ Global
{3C7412EF-13C2-41F3-9D4C-D2BEC4843C8C}.Release|x64.Build.0 = Release|Any CPU
{3C7412EF-13C2-41F3-9D4C-D2BEC4843C8C}.Release|x86.ActiveCfg = Release|Any CPU
{3C7412EF-13C2-41F3-9D4C-D2BEC4843C8C}.Release|x86.Build.0 = Release|Any CPU
{BCB3DD95-DFDB-452C-A0AD-AA657AE0C049}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{BCB3DD95-DFDB-452C-A0AD-AA657AE0C049}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BCB3DD95-DFDB-452C-A0AD-AA657AE0C049}.Debug|x64.ActiveCfg = Debug|Any CPU
{BCB3DD95-DFDB-452C-A0AD-AA657AE0C049}.Debug|x64.Build.0 = Debug|Any CPU
{BCB3DD95-DFDB-452C-A0AD-AA657AE0C049}.Debug|x86.ActiveCfg = Debug|Any CPU
{BCB3DD95-DFDB-452C-A0AD-AA657AE0C049}.Debug|x86.Build.0 = Debug|Any CPU
{BCB3DD95-DFDB-452C-A0AD-AA657AE0C049}.Release|Any CPU.ActiveCfg = Release|Any CPU
{BCB3DD95-DFDB-452C-A0AD-AA657AE0C049}.Release|Any CPU.Build.0 = Release|Any CPU
{BCB3DD95-DFDB-452C-A0AD-AA657AE0C049}.Release|x64.ActiveCfg = Release|Any CPU
{BCB3DD95-DFDB-452C-A0AD-AA657AE0C049}.Release|x64.Build.0 = Release|Any CPU
{BCB3DD95-DFDB-452C-A0AD-AA657AE0C049}.Release|x86.ActiveCfg = Release|Any CPU
{BCB3DD95-DFDB-452C-A0AD-AA657AE0C049}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{BCB3DD95-DFDB-452C-A0AD-AA657AE0C049} = {0AB3BF05-4346-4AA6-1389-037BE0695223}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {D6D431EA-C04F-462B-8033-60F510FEB49E}
EndGlobalSection

View File

@ -0,0 +1,124 @@
using Svrnty.CQRS.Abstractions.Discovery;
using Svrnty.CQRS.Discovery;
namespace Svrnty.CQRS.Tests;
public class CommandDiscoveryTests
{
private static CommandDiscovery CreateDiscovery(params ICommandMeta[] metas)
{
return new CommandDiscovery(metas);
}
[Fact]
public void GetCommands_ReturnsAllRegistered()
{
var meta1 = new CommandMeta(typeof(CreatePersonCommand), typeof(object), typeof(CreatePersonResult));
var meta2 = new CommandMeta(typeof(DeletePersonCommand), typeof(object));
var discovery = CreateDiscovery(meta1, meta2);
var commands = discovery.GetCommands().ToList();
Assert.Equal(2, commands.Count);
}
[Fact]
public void GetCommands_ReturnsEmpty_WhenNoneRegistered()
{
var discovery = CreateDiscovery();
var commands = discovery.GetCommands().ToList();
Assert.Empty(commands);
}
[Fact]
public void FindCommand_ByName_ReturnsCorrectMeta()
{
var meta = new CommandMeta(typeof(CreatePersonCommand), typeof(object), typeof(CreatePersonResult));
var discovery = CreateDiscovery(meta);
var found = discovery.FindCommand("CreatePerson");
Assert.NotNull(found);
Assert.Equal(typeof(CreatePersonCommand), found.CommandType);
}
[Fact]
public void FindCommand_ByName_ReturnsNull_WhenNotFound()
{
var discovery = CreateDiscovery();
var found = discovery.FindCommand("NonExistent");
Assert.Null(found);
}
[Fact]
public void FindCommand_ByType_ReturnsCorrectMeta()
{
var meta = new CommandMeta(typeof(CreatePersonCommand), typeof(object), typeof(CreatePersonResult));
var discovery = CreateDiscovery(meta);
var found = discovery.FindCommand(typeof(CreatePersonCommand));
Assert.NotNull(found);
Assert.Equal("CreatePerson", found.Name);
}
[Fact]
public void FindCommand_ByType_ReturnsNull_WhenNotFound()
{
var discovery = CreateDiscovery();
var found = discovery.FindCommand(typeof(CreatePersonCommand));
Assert.Null(found);
}
[Fact]
public void CommandExists_ByName_ReturnsTrue_WhenFound()
{
var meta = new CommandMeta(typeof(CreatePersonCommand), typeof(object));
var discovery = CreateDiscovery(meta);
Assert.True(discovery.CommandExists("CreatePerson"));
}
[Fact]
public void CommandExists_ByName_ReturnsFalse_WhenNotFound()
{
var discovery = CreateDiscovery();
Assert.False(discovery.CommandExists("CreatePerson"));
}
[Fact]
public void CommandExists_ByType_ReturnsTrue_WhenFound()
{
var meta = new CommandMeta(typeof(CreatePersonCommand), typeof(object));
var discovery = CreateDiscovery(meta);
Assert.True(discovery.CommandExists(typeof(CreatePersonCommand)));
}
[Fact]
public void CommandExists_ByType_ReturnsFalse_WhenNotFound()
{
var discovery = CreateDiscovery();
Assert.False(discovery.CommandExists(typeof(CreatePersonCommand)));
}
[Fact]
public void FindCommand_WithCustomName_FindsByAttributeName()
{
var meta = new CommandMeta(typeof(CreateWidgetCommand), typeof(object));
var discovery = CreateDiscovery(meta);
var found = discovery.FindCommand("customCreate");
Assert.NotNull(found);
Assert.Equal(typeof(CreateWidgetCommand), found.CommandType);
}
}

View File

@ -0,0 +1,64 @@
using Svrnty.CQRS.Abstractions.Discovery;
namespace Svrnty.CQRS.Tests;
public class CommandMetaTests
{
[Fact]
public void Name_StripsCommandSuffix()
{
var meta = new CommandMeta(typeof(CreatePersonCommand), typeof(object));
Assert.Equal("CreatePerson", meta.Name);
}
[Fact]
public void Name_UsesCommandNameAttribute_WhenPresent()
{
var meta = new CommandMeta(typeof(CreateWidgetCommand), typeof(object));
Assert.Equal("customCreate", meta.Name);
}
[Fact]
public void LowerCamelCaseName_ConvertsFirstCharToLower()
{
var meta = new CommandMeta(typeof(CreatePersonCommand), typeof(object));
Assert.Equal("createPerson", meta.LowerCamelCaseName);
}
[Fact]
public void LowerCamelCaseName_PreservesAlreadyLowerCase()
{
var meta = new CommandMeta(typeof(CreateWidgetCommand), typeof(object));
// customCreate -> already lower first char
Assert.Equal("customCreate", meta.LowerCamelCaseName);
}
[Fact]
public void CommandType_IsSetCorrectly()
{
var meta = new CommandMeta(typeof(CreatePersonCommand), typeof(object));
Assert.Equal(typeof(CreatePersonCommand), meta.CommandType);
}
[Fact]
public void ServiceType_IsSetCorrectly()
{
var serviceType = typeof(object);
var meta = new CommandMeta(typeof(CreatePersonCommand), serviceType);
Assert.Equal(serviceType, meta.ServiceType);
}
[Fact]
public void CommandResultType_IsSetCorrectly_WithThreeArgConstructor()
{
var meta = new CommandMeta(typeof(CreatePersonCommand), typeof(object), typeof(CreatePersonResult));
Assert.Equal(typeof(CreatePersonResult), meta.CommandResultType);
}
[Fact]
public void CommandResultType_IsNull_WithTwoArgConstructor()
{
var meta = new CommandMeta(typeof(DeletePersonCommand), typeof(object));
Assert.Null(meta.CommandResultType);
}
}

View File

@ -0,0 +1,106 @@
using Svrnty.CQRS.Configuration;
namespace Svrnty.CQRS.Tests;
public class CqrsConfigurationTests
{
private class TestConfig
{
public string Value { get; set; } = string.Empty;
}
private class OtherConfig
{
public int Number { get; set; }
}
[Fact]
public void SetConfiguration_CanBeRetrieved()
{
var config = new CqrsConfiguration();
var testConfig = new TestConfig { Value = "hello" };
config.SetConfiguration(testConfig);
var retrieved = config.GetConfiguration<TestConfig>();
Assert.NotNull(retrieved);
Assert.Equal("hello", retrieved.Value);
}
[Fact]
public void GetConfiguration_ReturnsNull_WhenNotSet()
{
var config = new CqrsConfiguration();
var retrieved = config.GetConfiguration<TestConfig>();
Assert.Null(retrieved);
}
[Fact]
public void HasConfiguration_ReturnsTrue_WhenSet()
{
var config = new CqrsConfiguration();
config.SetConfiguration(new TestConfig());
Assert.True(config.HasConfiguration<TestConfig>());
}
[Fact]
public void HasConfiguration_ReturnsFalse_WhenNotSet()
{
var config = new CqrsConfiguration();
Assert.False(config.HasConfiguration<TestConfig>());
}
[Fact]
public void SetConfiguration_OverwritesPrevious()
{
var config = new CqrsConfiguration();
config.SetConfiguration(new TestConfig { Value = "first" });
config.SetConfiguration(new TestConfig { Value = "second" });
var retrieved = config.GetConfiguration<TestConfig>();
Assert.Equal("second", retrieved!.Value);
}
[Fact]
public void MultipleConfigTypes_AreIndependent()
{
var config = new CqrsConfiguration();
config.SetConfiguration(new TestConfig { Value = "test" });
config.SetConfiguration(new OtherConfig { Number = 42 });
Assert.Equal("test", config.GetConfiguration<TestConfig>()!.Value);
Assert.Equal(42, config.GetConfiguration<OtherConfig>()!.Number);
}
[Fact]
public void ExecuteMappingCallbacks_InvokesAllCallbacks()
{
var config = new CqrsConfiguration();
var callCount = 0;
config.AddMappingCallback(_ => callCount++);
config.AddMappingCallback(_ => callCount++);
config.ExecuteMappingCallbacks(new object());
Assert.Equal(2, callCount);
}
[Fact]
public void ExecuteMappingCallbacks_PassesAppObject()
{
var config = new CqrsConfiguration();
object? receivedApp = null;
config.AddMappingCallback(app => receivedApp = app);
var expected = new object();
config.ExecuteMappingCallbacks(expected);
Assert.Same(expected, receivedApp);
}
}

View File

@ -0,0 +1,81 @@
using Svrnty.CQRS.Abstractions;
using Svrnty.CQRS.Abstractions.Attributes;
namespace Svrnty.CQRS.Tests;
// Commands
public class CreatePersonCommand
{
public string FirstName { get; set; } = string.Empty;
public string LastName { get; set; } = string.Empty;
}
public class DeletePersonCommand
{
public int Id { get; set; }
}
[CommandName("customCreate")]
public class CreateWidgetCommand
{
public string Name { get; set; } = string.Empty;
}
// Command results
public class CreatePersonResult
{
public int Id { get; set; }
}
// Queries
public class PersonQuery
{
public string? NameFilter { get; set; }
}
[QueryName("customPersonLookup")]
public class PersonLookupQuery
{
public int Id { get; set; }
}
// Handlers
public class CreatePersonCommandHandler : ICommandHandler<CreatePersonCommand, CreatePersonResult>
{
public Task<CreatePersonResult> HandleAsync(CreatePersonCommand command, CancellationToken cancellationToken = default)
{
return Task.FromResult(new CreatePersonResult { Id = 1 });
}
}
public class DeletePersonCommandHandler : ICommandHandler<DeletePersonCommand>
{
public Task HandleAsync(DeletePersonCommand command, CancellationToken cancellationToken = default)
{
return Task.CompletedTask;
}
}
public class CreateWidgetCommandHandler : ICommandHandler<CreateWidgetCommand>
{
public Task HandleAsync(CreateWidgetCommand command, CancellationToken cancellationToken = default)
{
return Task.CompletedTask;
}
}
public class PersonQueryHandler : IQueryHandler<PersonQuery, IEnumerable<string>>
{
public Task<IEnumerable<string>> HandleAsync(PersonQuery query, CancellationToken cancellationToken = default)
{
return Task.FromResult<IEnumerable<string>>(["Alice", "Bob"]);
}
}
public class PersonLookupQueryHandler : IQueryHandler<PersonLookupQuery, string>
{
public Task<string> HandleAsync(PersonLookupQuery query, CancellationToken cancellationToken = default)
{
return Task.FromResult("Alice");
}
}

View File

@ -0,0 +1 @@
global using Xunit;

View File

@ -0,0 +1,64 @@
using Microsoft.Extensions.DependencyInjection;
using Svrnty.CQRS.Abstractions;
namespace Svrnty.CQRS.Tests;
public class HandlerTests
{
[Fact]
public async Task CommandHandler_WithResult_ExecutesCorrectly()
{
var services = new ServiceCollection();
services.AddCommand<CreatePersonCommand, CreatePersonResult, CreatePersonCommandHandler>();
var provider = services.BuildServiceProvider();
var handler = provider.GetRequiredService<ICommandHandler<CreatePersonCommand, CreatePersonResult>>();
var result = await handler.HandleAsync(new CreatePersonCommand
{
FirstName = "John",
LastName = "Doe"
});
Assert.Equal(1, result.Id);
}
[Fact]
public async Task CommandHandler_WithoutResult_ExecutesWithoutException()
{
var services = new ServiceCollection();
services.AddCommand<DeletePersonCommand, DeletePersonCommandHandler>();
var provider = services.BuildServiceProvider();
var handler = provider.GetRequiredService<ICommandHandler<DeletePersonCommand>>();
await handler.HandleAsync(new DeletePersonCommand { Id = 1 });
}
[Fact]
public async Task QueryHandler_ExecutesCorrectly()
{
var services = new ServiceCollection();
services.AddQuery<PersonQuery, IEnumerable<string>, PersonQueryHandler>();
var provider = services.BuildServiceProvider();
var handler = provider.GetRequiredService<IQueryHandler<PersonQuery, IEnumerable<string>>>();
var result = await handler.HandleAsync(new PersonQuery());
Assert.Equal(["Alice", "Bob"], result);
}
[Fact]
public async Task CommandHandler_SupportsCancellationToken()
{
var services = new ServiceCollection();
services.AddCommand<DeletePersonCommand, DeletePersonCommandHandler>();
var provider = services.BuildServiceProvider();
var handler = provider.GetRequiredService<ICommandHandler<DeletePersonCommand>>();
using var cts = new CancellationTokenSource();
await handler.HandleAsync(new DeletePersonCommand { Id = 1 }, cts.Token);
}
}

View File

@ -0,0 +1,124 @@
using Svrnty.CQRS.Abstractions.Discovery;
using Svrnty.CQRS.Discovery;
namespace Svrnty.CQRS.Tests;
public class QueryDiscoveryTests
{
private static QueryDiscovery CreateDiscovery(params IQueryMeta[] metas)
{
return new QueryDiscovery(metas);
}
[Fact]
public void GetQueries_ReturnsAllRegistered()
{
var meta1 = new QueryMeta(typeof(PersonQuery), typeof(object), typeof(IEnumerable<string>));
var meta2 = new QueryMeta(typeof(PersonLookupQuery), typeof(object), typeof(string));
var discovery = CreateDiscovery(meta1, meta2);
var queries = discovery.GetQueries().ToList();
Assert.Equal(2, queries.Count);
}
[Fact]
public void GetQueries_ReturnsEmpty_WhenNoneRegistered()
{
var discovery = CreateDiscovery();
var queries = discovery.GetQueries().ToList();
Assert.Empty(queries);
}
[Fact]
public void FindQuery_ByName_ReturnsCorrectMeta()
{
var meta = new QueryMeta(typeof(PersonQuery), typeof(object), typeof(IEnumerable<string>));
var discovery = CreateDiscovery(meta);
var found = discovery.FindQuery("Person");
Assert.NotNull(found);
Assert.Equal(typeof(PersonQuery), found.QueryType);
}
[Fact]
public void FindQuery_ByName_ReturnsNull_WhenNotFound()
{
var discovery = CreateDiscovery();
var found = discovery.FindQuery("NonExistent");
Assert.Null(found);
}
[Fact]
public void FindQuery_ByType_ReturnsCorrectMeta()
{
var meta = new QueryMeta(typeof(PersonQuery), typeof(object), typeof(IEnumerable<string>));
var discovery = CreateDiscovery(meta);
var found = discovery.FindQuery(typeof(PersonQuery));
Assert.NotNull(found);
Assert.Equal("Person", found.Name);
}
[Fact]
public void FindQuery_ByType_ReturnsNull_WhenNotFound()
{
var discovery = CreateDiscovery();
var found = discovery.FindQuery(typeof(PersonQuery));
Assert.Null(found);
}
[Fact]
public void QueryExists_ByName_ReturnsTrue_WhenFound()
{
var meta = new QueryMeta(typeof(PersonQuery), typeof(object), typeof(IEnumerable<string>));
var discovery = CreateDiscovery(meta);
Assert.True(discovery.QueryExists("Person"));
}
[Fact]
public void QueryExists_ByName_ReturnsFalse_WhenNotFound()
{
var discovery = CreateDiscovery();
Assert.False(discovery.QueryExists("Person"));
}
[Fact]
public void QueryExists_ByType_ReturnsTrue_WhenFound()
{
var meta = new QueryMeta(typeof(PersonQuery), typeof(object), typeof(IEnumerable<string>));
var discovery = CreateDiscovery(meta);
Assert.True(discovery.QueryExists(typeof(PersonQuery)));
}
[Fact]
public void QueryExists_ByType_ReturnsFalse_WhenNotFound()
{
var discovery = CreateDiscovery();
Assert.False(discovery.QueryExists(typeof(PersonQuery)));
}
[Fact]
public void FindQuery_WithCustomName_FindsByAttributeName()
{
var meta = new QueryMeta(typeof(PersonLookupQuery), typeof(object), typeof(string));
var discovery = CreateDiscovery(meta);
var found = discovery.FindQuery("customPersonLookup");
Assert.NotNull(found);
Assert.Equal(typeof(PersonLookupQuery), found.QueryType);
}
}

View File

@ -0,0 +1,57 @@
using Svrnty.CQRS.Abstractions.Discovery;
namespace Svrnty.CQRS.Tests;
public class QueryMetaTests
{
[Fact]
public void Name_StripsQuerySuffix()
{
var meta = new QueryMeta(typeof(PersonQuery), typeof(object), typeof(IEnumerable<string>));
Assert.Equal("Person", meta.Name);
}
[Fact]
public void Name_UsesQueryNameAttribute_WhenPresent()
{
var meta = new QueryMeta(typeof(PersonLookupQuery), typeof(object), typeof(string));
Assert.Equal("customPersonLookup", meta.Name);
}
[Fact]
public void LowerCamelCaseName_ConvertsFirstCharToLower()
{
var meta = new QueryMeta(typeof(PersonQuery), typeof(object), typeof(IEnumerable<string>));
Assert.Equal("person", meta.LowerCamelCaseName);
}
[Fact]
public void Category_DefaultsToBasicQuery()
{
var meta = new QueryMeta(typeof(PersonQuery), typeof(object), typeof(IEnumerable<string>));
Assert.Equal("BasicQuery", meta.Category);
}
[Fact]
public void QueryType_IsSetCorrectly()
{
var meta = new QueryMeta(typeof(PersonQuery), typeof(object), typeof(IEnumerable<string>));
Assert.Equal(typeof(PersonQuery), meta.QueryType);
}
[Fact]
public void ServiceType_IsSetCorrectly()
{
var serviceType = typeof(object);
var meta = new QueryMeta(typeof(PersonQuery), serviceType, typeof(IEnumerable<string>));
Assert.Equal(serviceType, meta.ServiceType);
}
[Fact]
public void QueryResultType_IsSetCorrectly()
{
var resultType = typeof(IEnumerable<string>);
var meta = new QueryMeta(typeof(PersonQuery), typeof(object), resultType);
Assert.Equal(resultType, meta.QueryResultType);
}
}

View File

@ -0,0 +1,180 @@
using Microsoft.Extensions.DependencyInjection;
using Svrnty.CQRS.Abstractions;
using Svrnty.CQRS.Abstractions.Discovery;
using Svrnty.CQRS.Discovery;
namespace Svrnty.CQRS.Tests;
public class ServiceRegistrationTests
{
[Fact]
public void AddCommand_WithResult_RegistersHandlerInDI()
{
var services = new ServiceCollection();
services.AddCommand<CreatePersonCommand, CreatePersonResult, CreatePersonCommandHandler>();
var provider = services.BuildServiceProvider();
var handler = provider.GetService<ICommandHandler<CreatePersonCommand, CreatePersonResult>>();
Assert.NotNull(handler);
Assert.IsType<CreatePersonCommandHandler>(handler);
}
[Fact]
public void AddCommand_WithResult_RegistersCommandMeta()
{
var services = new ServiceCollection();
services.AddCommand<CreatePersonCommand, CreatePersonResult, CreatePersonCommandHandler>();
var provider = services.BuildServiceProvider();
var metas = provider.GetServices<ICommandMeta>().ToList();
Assert.Single(metas);
Assert.Equal(typeof(CreatePersonCommand), metas[0].CommandType);
Assert.Equal(typeof(CreatePersonResult), metas[0].CommandResultType);
}
[Fact]
public void AddCommand_WithoutResult_RegistersHandlerInDI()
{
var services = new ServiceCollection();
services.AddCommand<DeletePersonCommand, DeletePersonCommandHandler>();
var provider = services.BuildServiceProvider();
var handler = provider.GetService<ICommandHandler<DeletePersonCommand>>();
Assert.NotNull(handler);
Assert.IsType<DeletePersonCommandHandler>(handler);
}
[Fact]
public void AddCommand_WithoutResult_RegistersCommandMeta()
{
var services = new ServiceCollection();
services.AddCommand<DeletePersonCommand, DeletePersonCommandHandler>();
var provider = services.BuildServiceProvider();
var metas = provider.GetServices<ICommandMeta>().ToList();
Assert.Single(metas);
Assert.Equal(typeof(DeletePersonCommand), metas[0].CommandType);
Assert.Null(metas[0].CommandResultType);
}
[Fact]
public void AddQuery_RegistersHandlerInDI()
{
var services = new ServiceCollection();
services.AddQuery<PersonQuery, IEnumerable<string>, PersonQueryHandler>();
var provider = services.BuildServiceProvider();
var handler = provider.GetService<IQueryHandler<PersonQuery, IEnumerable<string>>>();
Assert.NotNull(handler);
Assert.IsType<PersonQueryHandler>(handler);
}
[Fact]
public void AddQuery_RegistersQueryMeta()
{
var services = new ServiceCollection();
services.AddQuery<PersonQuery, IEnumerable<string>, PersonQueryHandler>();
var provider = services.BuildServiceProvider();
var metas = provider.GetServices<IQueryMeta>().ToList();
Assert.Single(metas);
Assert.Equal(typeof(PersonQuery), metas[0].QueryType);
Assert.Equal(typeof(IEnumerable<string>), metas[0].QueryResultType);
}
[Fact]
public void AddDefaultCommandDiscovery_RegistersCommandDiscovery()
{
var services = new ServiceCollection();
services.AddDefaultCommandDiscovery();
var provider = services.BuildServiceProvider();
var discovery = provider.GetService<ICommandDiscovery>();
Assert.NotNull(discovery);
Assert.IsType<CommandDiscovery>(discovery);
}
[Fact]
public void AddDefaultQueryDiscovery_RegistersQueryDiscovery()
{
var services = new ServiceCollection();
services.AddDefaultQueryDiscovery();
var provider = services.BuildServiceProvider();
var discovery = provider.GetService<IQueryDiscovery>();
Assert.NotNull(discovery);
Assert.IsType<QueryDiscovery>(discovery);
}
[Fact]
public void FullPipeline_DiscoveryFindsRegisteredCommands()
{
var services = new ServiceCollection();
services.AddCommand<CreatePersonCommand, CreatePersonResult, CreatePersonCommandHandler>();
services.AddCommand<DeletePersonCommand, DeletePersonCommandHandler>();
services.AddDefaultCommandDiscovery();
var provider = services.BuildServiceProvider();
var discovery = provider.GetRequiredService<ICommandDiscovery>();
Assert.Equal(2, discovery.GetCommands().Count());
Assert.True(discovery.CommandExists("CreatePerson"));
Assert.True(discovery.CommandExists("DeletePerson"));
}
[Fact]
public void FullPipeline_DiscoveryFindsRegisteredQueries()
{
var services = new ServiceCollection();
services.AddQuery<PersonQuery, IEnumerable<string>, PersonQueryHandler>();
services.AddQuery<PersonLookupQuery, string, PersonLookupQueryHandler>();
services.AddDefaultQueryDiscovery();
var provider = services.BuildServiceProvider();
var discovery = provider.GetRequiredService<IQueryDiscovery>();
Assert.Equal(2, discovery.GetQueries().Count());
Assert.True(discovery.QueryExists("Person"));
Assert.True(discovery.QueryExists("customPersonLookup"));
}
[Fact]
public void AddSvrntyCqrs_RegistersDiscoveryServices()
{
var services = new ServiceCollection();
services.AddSvrntyCqrs();
var provider = services.BuildServiceProvider();
Assert.NotNull(provider.GetService<ICommandDiscovery>());
Assert.NotNull(provider.GetService<IQueryDiscovery>());
}
[Fact]
public void AddSvrntyCqrs_WithFluentBuilder_RegistersCommandsAndQueries()
{
var services = new ServiceCollection();
services.AddSvrntyCqrs(builder =>
{
builder
.AddCommand<CreatePersonCommand, CreatePersonResult, CreatePersonCommandHandler>()
.AddCommand<DeletePersonCommand, DeletePersonCommandHandler>()
.AddQuery<PersonQuery, IEnumerable<string>, PersonQueryHandler>();
});
var provider = services.BuildServiceProvider();
var cmdDiscovery = provider.GetRequiredService<ICommandDiscovery>();
var qryDiscovery = provider.GetRequiredService<IQueryDiscovery>();
Assert.Equal(2, cmdDiscovery.GetCommands().Count());
Assert.Single(qryDiscovery.GetQueries());
}
}

View File

@ -0,0 +1,26 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<LangVersion>14</LangVersion>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.*" />
<PackageReference Include="xunit" Version="2.*" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.*">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="10.0.0-*" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Svrnty.CQRS\Svrnty.CQRS.csproj" />
<ProjectReference Include="..\..\Svrnty.CQRS.Abstractions\Svrnty.CQRS.Abstractions.csproj" />
</ItemGroup>
</Project>