From e39d52dc36e7af124ac2d101e44cb33dda3e99a8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Se=CC=81rgio=20Silveira?= Date: Tue, 24 Oct 2023 18:40:46 +0200 Subject: [PATCH] * no more IClassFixture * code reformat where possible for better readability --- .editorconfig | 294 +++++++++--------- Directory.Build.props | 32 +- Directory.Build.targets | 6 +- EventStore.Client.sln.DotSettings | 36 ++- .../MsBuildContextSourceGenerator.cs | 27 +- samples/Directory.Build.props | 13 +- src/Directory.Build.props | 3 + src/EventStore.Client/EventStoreClientBase.cs | 15 +- test/Directory.Build.props | 83 +++-- .../AuthenticationTests.cs | 21 +- .../EventStore.Client.Operations.Tests.csproj | 5 +- .../admin.cs | 18 +- .../admin_resign_node.cs | 7 +- .../admin_shutdown_node.cs | 7 +- .../scavenge.cs | 11 +- .../AssemblyInfo.cs | 2 +- .../Bugs/Issue_1125.cs | 106 ++++--- ...lient.PersistentSubscriptions.Tests.csproj | 9 +- .../EventStoreClientFixture.cs | 38 +-- .../FilterTestCase.cs | 33 +- .../PersistentSubscriptionSettingsTests.cs | 10 +- .../ReadOnlyMemoryExtensions.cs | 25 +- ...ate_duplicate_name_on_different_streams.cs | 29 +- ...connect_to_existing_with_max_one_client.cs | 39 ++- .../connect_to_existing_with_permissions.cs | 26 +- ...t_to_existing_with_start_from_beginning.cs | 75 ++--- ...ect_to_existing_with_start_from_not_set.cs | 85 ++--- ...h_start_from_not_set_then_event_written.cs | 70 +++-- ...ing_with_start_from_set_to_end_position.cs | 83 ++--- ..._set_to_end_position_then_event_written.cs | 74 ++--- ...art_from_set_to_invalid_middle_position.cs | 48 ++- ...start_from_set_to_valid_middle_position.cs | 68 ++-- ...connect_to_existing_without_permissions.cs | 29 +- ...o_existing_without_read_all_permissions.cs | 30 +- ...onnect_to_non_existing_with_permissions.cs | 28 +- .../SubscriptionToAll/connect_with_retries.cs | 69 ++-- .../create_after_deleting_the_same.cs | 37 ++- .../SubscriptionToAll/create_duplicate.cs | 39 +-- .../SubscriptionToAll/create_filtered.cs | 23 +- .../SubscriptionToAll/create_on_all_stream.cs | 30 +- ...rsistent_subscription_with_dont_timeout.cs | 21 +- ...position_equal_to_last_indexed_position.cs | 38 ++- ...ition_larger_than_last_indexed_position.cs | 44 +-- ...re_position_larger_than_commit_position.cs | 26 +- .../create_without_permissions.cs | 28 +- .../deleting_existing_with_permissions.cs | 27 +- .../deleting_existing_with_subscriber.cs | 78 ++--- .../SubscriptionToAll/deleting_filtered.cs | 23 +- .../SubscriptionToAll/deleting_nonexistent.cs | 16 +- .../deleting_without_permissions.cs | 21 +- .../SubscriptionToAll/get_info.cs | 161 +++++----- ...atching_up_to_link_to_events_manual_ack.cs | 91 +++--- ...catching_up_to_normal_events_manual_ack.cs | 78 +++-- .../SubscriptionToAll/happy_case_filtered.cs | 80 +++-- ...happy_case_filtered_with_start_from_set.cs | 90 +++--- ...subscribing_to_normal_events_manual_ack.cs | 75 +++-- .../list_with_persistent_subscriptions.cs | 87 +++--- .../list_without_persistent_subscriptions.cs | 25 +- .../SubscriptionToAll/replay_parked.cs | 111 +++---- .../SubscriptionToAll/update_existing.cs | 31 +- .../update_existing_filtered.cs | 27 +- .../update_existing_with_check_point.cs | 154 ++++----- ...date_existing_with_check_point_filtered.cs | 163 +++++----- ...position_equal_to_last_indexed_position.cs | 45 +-- ...ition_larger_than_last_indexed_position.cs | 54 ++-- .../update_existing_with_subscribers.cs | 48 +-- .../update_existing_without_permissions.cs | 36 +-- .../SubscriptionToAll/update_non_existent.cs | 22 +- ...re_position_larger_than_commit_position.cs | 28 +- .../when_writing_and_filtering_out_events.cs | 135 ++++---- ...ubscribing_to_normal_events_manual_nack.cs | 78 ++--- ...ate_duplicate_name_on_different_streams.cs | 34 +- ...connect_to_existing_with_max_one_client.cs | 41 ++- .../connect_to_existing_with_permissions.cs | 26 +- ...h_start_from_beginning_and_events_in_it.cs | 58 ++-- ...with_start_from_beginning_and_no_stream.cs | 61 ++-- ...ith_start_from_not_set_and_events_in_it.cs | 62 ++-- ...set_and_events_in_it_then_event_written.cs | 71 +++-- ...om_set_to_end_position_and_events_in_it.cs | 62 ++-- ...ion_and_events_in_it_then_event_written.cs | 60 ++-- ...sting_with_start_from_two_and_no_stream.cs | 62 ++-- ..._with_start_from_x_set_and_events_in_it.cs | 60 ++-- ...set_and_events_in_it_then_event_written.cs | 60 ++-- ...n_x_and_events_in_it_then_event_written.cs | 59 ++-- ...connect_to_existing_without_permissions.cs | 31 +- ...onnect_to_non_existing_with_permissions.cs | 31 +- .../connect_with_retries.cs | 80 +++-- ...connecting_to_a_persistent_subscription.cs | 59 ++-- .../create_after_deleting_the_same.cs | 41 ++- .../SubscriptionToStream/create_duplicate.cs | 41 ++- .../create_on_existing_stream.cs | 27 +- .../create_on_non_existing_stream.cs | 26 +- ...rsistent_subscription_with_dont_timeout.cs | 25 +- .../create_without_permissions.cs | 32 +- .../deleting_existing_with_permissions.cs | 32 +- .../deleting_existing_with_subscriber.cs | 78 ++--- .../deleting_nonexistent.cs | 21 +- .../deleting_without_permissions.cs | 25 +- .../SubscriptionToStream/get_info.cs | 176 ++++++----- ...atching_up_to_link_to_events_manual_ack.cs | 92 +++--- ...catching_up_to_normal_events_manual_ack.cs | 79 ++--- ...subscribing_to_normal_events_manual_ack.cs | 76 ++--- .../list_with_persistent_subscriptions.cs | 84 ++--- .../list_without_persistent_subscriptions.cs | 69 ++-- .../SubscriptionToStream/replay_parked.cs | 99 +++--- .../SubscriptionToStream/update_existing.cs | 31 +- .../update_existing_with_check_point.cs | 149 +++++---- .../update_existing_with_subscribers.cs | 51 +-- .../update_existing_without_permissions.cs | 45 +-- .../update_non_existent.cs | 24 +- ...ubscribing_to_normal_events_manual_nack.cs | 79 ++--- .../SupportsPSToAllFact.cs | 13 +- .../restart_subsystem.cs | 46 ++- .../AssertEx.cs | 30 +- ...e.Client.ProjectionManagement.Tests.csproj | 5 +- .../EventStoreClientFixture.cs | 28 +- .../StandardProjections.cs | 25 +- .../create.cs | 15 +- .../disable.cs | 11 +- .../enable.cs | 10 +- .../get_result.cs | 29 +- .../get_state.cs | 38 ++- .../get_status.cs | 8 +- .../list_all_projections.cs | 8 +- .../list_continuous_projections.cs | 18 +- .../list_one_time_projections.cs | 11 +- .../reset.cs | 10 +- .../restart_subsystem.cs | 21 +- .../update.cs | 18 +- .../EventStore.Client.Streams.Tests.csproj | 4 +- .../EventStore.Client.Tests.Common.csproj | 16 +- .../Extensions/EventStoreClientExtensions.cs | 100 +----- .../EventStoreClientWarmupExtensions.cs | 85 +++++ .../Extensions/OperatingSystemExtensions.cs | 4 +- .../Base/EventStoreClientFixtureBase.cs | 206 ++++++------ .../Fixtures/Base/EventStoreTestServer.cs | 240 +++++++------- .../Base/EventStoreTestServerCluster.cs | 136 ++++---- .../Base/EventStoreTestServerExternal.cs | 16 +- .../Fixtures/Base/IEventStoreTestServer.cs | 12 +- .../Fixtures/CertificatesCommander.cs | 76 +++++ .../Fixtures/DatabaseWarmup.cs | 69 ++++ .../Fixtures/EventStoreClientsFixture.cs | 93 ------ .../Fixtures/EventStoreFixture.Helpers.cs | 47 +++ .../Fixtures/EventStoreFixture.cs | 194 ++++++++++++ .../Fixtures/EventStoreIntegrationFixture.cs | 282 ----------------- .../Fixtures/EventStoreTestCluster.cs | 14 +- .../Fixtures/EventStoreTestNode.cs | 76 +++-- .../Fixtures/EventStoreTestServiceOptions.cs | 7 - .../Fixtures/EventStoreTestVoid.cs | 8 - .../Fixtures/Logging.cs | 86 +++++ .../FluentDockerBuilderExtensions.cs | 80 ----- .../FluentDockerServiceExtensions.cs | 44 +++ .../FluentDocker/TestBypassService.cs | 61 ++++ .../FluentDocker/TestCompositeService.cs | 6 + .../FluentDocker/TestContainerService.cs | 6 + .../FluentDocker/TestService.cs | 155 ++++----- .../GlobalEnvironment.cs | 7 +- .../TestCredentials.cs | 2 +- .../docker-compose.single.yml | 82 +++++ .../docker-compose.yml | 13 +- .../EventStore.Client.Tests.Common/shared.env | 12 +- .../Assertions/ComparableAssertion.cs | 140 +++++---- .../Assertions/EqualityAssertion.cs | 61 ++-- .../Assertions/NullArgumentAssertion.cs | 66 ++-- .../Assertions/StringConversionAssertion.cs | 27 +- .../Assertions/ValueObjectAssertion.cs | 6 +- .../AutoScenarioDataAttribute.cs | 12 +- .../ConnectionStringTests.cs | 89 ++++-- .../EventStore.Client.Tests.csproj | 8 +- .../EventStoreClientOperationOptionsTests.cs | 8 +- test/EventStore.Client.Tests/FromAllTests.cs | 14 +- .../FromStreamTests.cs | 43 ++- .../GossipChannelSelectorTests.cs | 62 +++- .../GrpcServerCapabilitiesClientTests.cs | 65 ++-- .../ReportLeaderInterceptorTests.cs | 217 ++++++++----- .../NodePreferenceComparerTests.cs | 47 +-- .../NodeSelectorTests.cs | 26 +- test/EventStore.Client.Tests/PositionTests.cs | 54 ++-- .../PrefixFilterExpressionTests.cs | 10 +- .../RegularFilterExpressionTests.cs | 8 +- .../SharingProviderTests.cs | 107 ++++--- .../StreamPositionTests.cs | 76 ++--- .../StreamRevisionTests.cs | 71 +++-- .../StreamStateTests.cs | 44 +-- .../EventStore.Client.Tests/TypeExtensions.cs | 6 +- test/EventStore.Client.Tests/UuidTests.cs | 6 +- .../ValueObjectTests.cs | 2 +- ...ntStore.Client.UserManagement.Tests.csproj | 4 +- .../InvalidCredentialsCases.cs | 4 +- .../changing_user_password.cs | 79 +---- .../creating_a_user.cs | 7 +- .../deleting_a_user.cs | 8 +- .../disabling_a_user.cs | 7 +- .../enabling_a_user.cs | 7 +- .../getting_current_user.cs | 7 +- .../listing_users.cs | 7 +- ...password.cs => resetting_user_password.cs} | 7 +- 197 files changed, 5261 insertions(+), 4677 deletions(-) create mode 100644 test/EventStore.Client.Tests.Common/Extensions/EventStoreClientWarmupExtensions.cs create mode 100644 test/EventStore.Client.Tests.Common/Fixtures/CertificatesCommander.cs create mode 100644 test/EventStore.Client.Tests.Common/Fixtures/DatabaseWarmup.cs delete mode 100644 test/EventStore.Client.Tests.Common/Fixtures/EventStoreClientsFixture.cs create mode 100644 test/EventStore.Client.Tests.Common/Fixtures/EventStoreFixture.Helpers.cs create mode 100644 test/EventStore.Client.Tests.Common/Fixtures/EventStoreFixture.cs delete mode 100644 test/EventStore.Client.Tests.Common/Fixtures/EventStoreIntegrationFixture.cs delete mode 100644 test/EventStore.Client.Tests.Common/Fixtures/EventStoreTestServiceOptions.cs delete mode 100644 test/EventStore.Client.Tests.Common/Fixtures/EventStoreTestVoid.cs create mode 100644 test/EventStore.Client.Tests.Common/Fixtures/Logging.cs create mode 100644 test/EventStore.Client.Tests.Common/FluentDocker/FluentDockerServiceExtensions.cs create mode 100644 test/EventStore.Client.Tests.Common/FluentDocker/TestBypassService.cs create mode 100644 test/EventStore.Client.Tests.Common/FluentDocker/TestCompositeService.cs create mode 100644 test/EventStore.Client.Tests.Common/FluentDocker/TestContainerService.cs create mode 100644 test/EventStore.Client.Tests.Common/docker-compose.single.yml rename test/EventStore.Client.UserManagement.Tests/{reset_user_password.cs => resetting_user_password.cs} (89%) diff --git a/.editorconfig b/.editorconfig index 4aabf60ae..2b9661849 100644 --- a/.editorconfig +++ b/.editorconfig @@ -1,153 +1,153 @@ # EditorConfig is awesome: http://EditorConfig.org -# top-most EditorConfig file -root = true - -[*] -insert_final_newline = true -indent_style = tab -indent_size = 4 - -# ReSharper properties -resharper_csharp_empty_block_style = together -resharper_csharp_space_before_empty_method_parentheses = true - -# Microsoft .NET properties -dotnet_separate_import_directive_groups = false - -# C# files -[*.cs] -# New line preferences -csharp_new_line_before_open_brace = none -csharp_new_line_before_catch = false -csharp_new_line_before_else = false -csharp_new_line_before_finally = false -csharp_new_line_before_members_in_anonymous_types = false -csharp_new_line_before_members_in_object_initializers = false -csharp_new_line_within_query_expression_clauses = true - -# Indentation preferences -csharp_indent_block_contents = true -csharp_indent_braces = false -csharp_indent_case_contents = true -csharp_indent_switch_labels = true -csharp_indent_labels = flush_left - -# avoid this. unless absolutely necessary -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 - -# only use var when it's obvious what the variable type is -csharp_style_var_for_built_in_types = true:none -csharp_style_var_when_type_is_apparent = true:none -csharp_style_var_elsewhere = true:suggestion - -# use language keywords instead of BCL types -dotnet_style_predefined_type_for_locals_parameters_members = true:suggestion -dotnet_style_predefined_type_for_member_access = true:suggestion - -# name all constant fields using PascalCase -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_style - -dotnet_naming_symbols.constant_fields.applicable_kinds = field -dotnet_naming_symbols.constant_fields.required_modifiers = const - -dotnet_naming_style.pascal_case_style.capitalization = pascal_case - -# static fields should have s_ prefix -dotnet_naming_rule.static_fields_should_have_prefix.severity = suggestion -dotnet_naming_rule.static_fields_should_have_prefix.symbols = static_fields - -dotnet_naming_symbols.static_fields.applicable_kinds = field -dotnet_naming_symbols.static_fields.required_modifiers = static - -dotnet_naming_style.static_prefix_style.capitalization = pascal_case - -# internal and private fields should be _camelCase -dotnet_naming_rule.camel_case_for_private_internal_fields.severity = suggestion -dotnet_naming_rule.camel_case_for_private_internal_fields.symbols = private_internal_fields -dotnet_naming_rule.camel_case_for_private_internal_fields.style = camel_case_underscore_style - -dotnet_naming_symbols.private_internal_fields.applicable_kinds = field -dotnet_naming_symbols.private_internal_fields.applicable_accessibilities = private, internal - -dotnet_naming_style.camel_case_underscore_style.required_prefix = _ -dotnet_naming_style.camel_case_underscore_style.capitalization = camel_case - -# Code style defaults -dotnet_sort_system_directives_first = true -csharp_preserve_single_line_blocks = true -csharp_preserve_single_line_statements = false - -# Expression-level preferences -dotnet_style_object_initializer = true:suggestion -dotnet_style_collection_initializer = true:suggestion -dotnet_style_explicit_tuple_names = true:suggestion -dotnet_style_coalesce_expression = true:suggestion -dotnet_style_null_propagation = true:suggestion - -# Expression-bodied members -csharp_style_expression_bodied_methods = false:none -csharp_style_expression_bodied_constructors = false:none -csharp_style_expression_bodied_operators = false:none -csharp_style_expression_bodied_properties = true:none -csharp_style_expression_bodied_indexers = true:none -csharp_style_expression_bodied_accessors = true:none - -# Pattern matching -csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion -csharp_style_pattern_matching_over_as_with_null_check = true:suggestion -csharp_style_inlined_variable_declaration = true:suggestion - -# Null checking preferences -csharp_style_throw_expression = true:suggestion -csharp_style_conditional_delegate_call = true:suggestion - -# Space preferences -csharp_space_after_cast = false -csharp_space_after_colon_in_inheritance_clause = true -csharp_space_after_comma = true -csharp_space_after_dot = false -csharp_space_after_keywords_in_control_flow_statements = true -csharp_space_after_semicolon_in_for_statement = true -csharp_space_around_binary_operators = before_and_after -csharp_space_around_declaration_statements = do_not_ignore -csharp_space_before_colon_in_inheritance_clause = true -csharp_space_before_comma = false -csharp_space_before_dot = false -csharp_space_before_open_square_brackets = false -csharp_space_before_semicolon_in_for_statement = false -csharp_space_between_empty_square_brackets = false -csharp_space_between_method_call_empty_parameter_list_parentheses = false -csharp_space_between_method_call_name_and_opening_parenthesis = false -csharp_space_between_method_call_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_declaration_parameter_list_parentheses = false -csharp_space_between_parentheses = false -csharp_space_between_square_brackets = false - -[*.{asm,inc}] + # top-most EditorConfig file + root = true + + [*] + insert_final_newline = true + indent_style = tab + indent_size = 4 + + # ReSharper properties + resharper_csharp_empty_block_style = together + resharper_csharp_space_before_empty_method_parentheses = true + + # Microsoft .NET properties + dotnet_separate_import_directive_groups = false + + # C# files + [*.cs] + # New line preferences + csharp_new_line_before_open_brace = none + csharp_new_line_before_catch = false + csharp_new_line_before_else = false + csharp_new_line_before_finally = false + csharp_new_line_before_members_in_anonymous_types = false + csharp_new_line_before_members_in_object_initializers = false + csharp_new_line_within_query_expression_clauses = true + + # Indentation preferences + csharp_indent_block_contents = true + csharp_indent_braces = false + csharp_indent_case_contents = true + csharp_indent_switch_labels = true + csharp_indent_labels = flush_left + + # avoid this. unless absolutely necessary + 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 + + # only use var when it's obvious what the variable type is + csharp_style_var_for_built_in_types = true:none + csharp_style_var_when_type_is_apparent = true:none + csharp_style_var_elsewhere = true:suggestion + + # use language keywords instead of BCL types + dotnet_style_predefined_type_for_locals_parameters_members = true:suggestion + dotnet_style_predefined_type_for_member_access = true:suggestion + + # name all constant fields using PascalCase + 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_style + + dotnet_naming_symbols.constant_fields.applicable_kinds = field + dotnet_naming_symbols.constant_fields.required_modifiers = const + + dotnet_naming_style.pascal_case_style.capitalization = pascal_case + + # static fields should have s_ prefix + dotnet_naming_rule.static_fields_should_have_prefix.severity = suggestion + dotnet_naming_rule.static_fields_should_have_prefix.symbols = static_fields + + dotnet_naming_symbols.static_fields.applicable_kinds = field + dotnet_naming_symbols.static_fields.required_modifiers = static + + dotnet_naming_style.static_prefix_style.capitalization = pascal_case + + # internal and private fields should be _camelCase + dotnet_naming_rule.camel_case_for_private_internal_fields.severity = suggestion + dotnet_naming_rule.camel_case_for_private_internal_fields.symbols = private_internal_fields + dotnet_naming_rule.camel_case_for_private_internal_fields.style = camel_case_underscore_style + + dotnet_naming_symbols.private_internal_fields.applicable_kinds = field + dotnet_naming_symbols.private_internal_fields.applicable_accessibilities = private, internal + + dotnet_naming_style.camel_case_underscore_style.required_prefix = _ + dotnet_naming_style.camel_case_underscore_style.capitalization = camel_case + + # Code style defaults + dotnet_sort_system_directives_first = true + csharp_preserve_single_line_blocks = true + csharp_preserve_single_line_statements = false + + # Expression-level preferences + dotnet_style_object_initializer = true:suggestion + dotnet_style_collection_initializer = true:suggestion + dotnet_style_explicit_tuple_names = true:suggestion + dotnet_style_coalesce_expression = true:suggestion + dotnet_style_null_propagation = true:suggestion + + # Expression-bodied members + csharp_style_expression_bodied_methods = false:none + csharp_style_expression_bodied_constructors = false:none + csharp_style_expression_bodied_operators = false:none + csharp_style_expression_bodied_properties = true:none + csharp_style_expression_bodied_indexers = true:none + csharp_style_expression_bodied_accessors = true:none + + # Pattern matching + csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion + csharp_style_pattern_matching_over_as_with_null_check = true:suggestion + csharp_style_inlined_variable_declaration = true:suggestion + + # Null checking preferences + csharp_style_throw_expression = true:suggestion + csharp_style_conditional_delegate_call = true:suggestion + + # Space preferences + csharp_space_after_cast = false + csharp_space_after_colon_in_inheritance_clause = true + csharp_space_after_comma = true + csharp_space_after_dot = false + csharp_space_after_keywords_in_control_flow_statements = true + csharp_space_after_semicolon_in_for_statement = true + csharp_space_around_binary_operators = before_and_after + csharp_space_around_declaration_statements = do_not_ignore + csharp_space_before_colon_in_inheritance_clause = true + csharp_space_before_comma = false + csharp_space_before_dot = false + csharp_space_before_open_square_brackets = false + csharp_space_before_semicolon_in_for_statement = false + csharp_space_between_empty_square_brackets = false + csharp_space_between_method_call_empty_parameter_list_parentheses = false + csharp_space_between_method_call_name_and_opening_parenthesis = false + csharp_space_between_method_call_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_declaration_parameter_list_parentheses = false + csharp_space_between_parentheses = false + csharp_space_between_square_brackets = false + + [*.{asm, inc}] + indent_size = 8 + + # Xml project files + [*.{csproj, vcxproj, vcxproj.filters, proj, nativeproj, locproj}] + indent_size = 2 + + # Xml config files + [*.{props, targets, config, nuspec}] + indent_size = 2 + + [CMakeLists.txt] + indent_size = 2 + + [*.{cmd, ps1}] indent_size = 8 -# Xml project files -[*.{csproj,vcxproj,vcxproj.filters,proj,nativeproj,locproj}] -indent_size = 2 - -# Xml config files -[*.{props,targets,config,nuspec}] -indent_size = 2 - -[CMakeLists.txt] -indent_size = 2 - -[*.{cmd,ps1}] -indent_size = 8 - -[*.{yaml, yml}] +[*.{yaml, yml}] indent_size = 2 diff --git a/Directory.Build.props b/Directory.Build.props index fd751cf2c..4234ae27a 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,20 +1,22 @@ - - net6.0;net7.0;net8.0; - x64 - true - enable - enable + + net6.0;net7.0; + x64 + true + enable + enable true - true - 11 - - - - - - true + true + 11 + + Debug + full + pdbonly + + + + true 2.49.0 2.50.0 - + diff --git a/Directory.Build.targets b/Directory.Build.targets index 80ae31a5f..75a7fa9c1 100644 --- a/Directory.Build.targets +++ b/Directory.Build.targets @@ -1,5 +1,5 @@ - - true - + + true + diff --git a/EventStore.Client.sln.DotSettings b/EventStore.Client.sln.DotSettings index fc66848ad..9ebd69176 100644 --- a/EventStore.Client.sln.DotSettings +++ b/EventStore.Client.sln.DotSettings @@ -79,20 +79,23 @@ ExpressionBody ExpressionBody ExpressionBody + BaseClass + 0 1 0 False + True False False True END_OF_LINE END_OF_LINE True - True + False True True True - True + False True True END_OF_LINE @@ -116,6 +119,7 @@ 1 1 False + 10 3 EXPANDED END_OF_LINE @@ -127,10 +131,13 @@ True True True - CHOP_ALWAYS + CHOP_IF_LONG + WRAP_IF_LONG True True True + False + WRAP_IF_LONG CHOP_ALWAYS <Patterns xmlns="urn:schemas-jetbrains-com:member-reordering-patterns"> <TypePattern DisplayName="Non-reorderable types"> @@ -282,24 +289,23 @@ </Entry.SortBy> </Entry> - <Entry DisplayName="Static Fields and Constants"> + <Entry DisplayName="Constants" Priority="90"> <Entry.Match> - <Or> - <Kind Is="Constant" /> - <And> + <Kind Is="Constant" /> + </Entry.Match> + </Entry> + + <Entry DisplayName="Static Fields" Priority="85"> + <Entry.Match> + <And> <Kind Is="Field" /> <Static /> - </And> - </Or> + </And> </Entry.Match> <Entry.SortBy> - <Kind> - <Kind.Order> - <DeclarationKind>Constant</DeclarationKind> - <DeclarationKind>Field</DeclarationKind> - </Kind.Order> - </Kind> + <Readonly /> + <Name /> </Entry.SortBy> </Entry> diff --git a/generators/EventStore.Tests.SourceGenerators/MsBuildContextSourceGenerator.cs b/generators/EventStore.Tests.SourceGenerators/MsBuildContextSourceGenerator.cs index 63bcd1f6a..495a51d8f 100644 --- a/generators/EventStore.Tests.SourceGenerators/MsBuildContextSourceGenerator.cs +++ b/generators/EventStore.Tests.SourceGenerators/MsBuildContextSourceGenerator.cs @@ -2,19 +2,17 @@ using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; -namespace EventStore.Client { - [Generator] - public class MsBuildContextSourceGenerator : ISourceGenerator { - public void Initialize(GeneratorInitializationContext context) { - } +namespace EventStore.Client.Tests; - public void Execute(GeneratorExecutionContext context) { - context.AnalyzerConfigOptions.GlobalOptions.TryGetValue("build_property.RootNamespace", - out var rootNamespace); - context.AnalyzerConfigOptions.GlobalOptions.TryGetValue("build_property.ProjectDir", - out var projectDir); +[Generator] +public class MsBuildContextSourceGenerator : ISourceGenerator { + public void Initialize(GeneratorInitializationContext context) { } - var sourceText = SourceText.From(@$" + public void Execute(GeneratorExecutionContext context) { + context.AnalyzerConfigOptions.GlobalOptions.TryGetValue("build_property.RootNamespace", out var rootNamespace); + context.AnalyzerConfigOptions.GlobalOptions.TryGetValue("build_property.ProjectDir", out var projectDir); + + var sourceText = SourceText.From(@$" namespace {rootNamespace} {{ public static class ProjectDir {{ public static readonly string Current = @""{projectDir}""; @@ -22,7 +20,6 @@ public static class ProjectDir {{ }} ", Encoding.UTF8); - context.AddSource("ProjectDir.cs", sourceText); ; - } - } -} + context.AddSource("ProjectDir.cs", sourceText); ; + } +} \ No newline at end of file diff --git a/samples/Directory.Build.props b/samples/Directory.Build.props index 4b318ded2..de3078b18 100644 --- a/samples/Directory.Build.props +++ b/samples/Directory.Build.props @@ -1,8 +1,9 @@ - - enable - enable - Exe - net6.0;net7.0 - + + net6.0;net7.0 + enable + enable + true + Exe + diff --git a/src/Directory.Build.props b/src/Directory.Build.props index ca76f1376..2a404554d 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -57,5 +57,8 @@ <_Parameter1>$(ProjectName).Tests.Common + + <_Parameter1>EventStore.Client + diff --git a/src/EventStore.Client/EventStoreClientBase.cs b/src/EventStore.Client/EventStoreClientBase.cs index 5c180faef..d3252a330 100644 --- a/src/EventStore.Client/EventStoreClientBase.cs +++ b/src/EventStore.Client/EventStoreClientBase.cs @@ -82,22 +82,11 @@ private async Task GetChannelInfoExpensive( /// Gets the current channel info. protected async ValueTask GetChannelInfo(CancellationToken cancellationToken) => await _channelInfoProvider.CurrentAsync.WithCancellation(cancellationToken).ConfigureAwait(false); - - - /// - /// only exists so that we can manually trigger rediscovery in the tests (by reflection) - /// in cases where the server doesn't yet let the client know that it needs to. - /// see EventStoreClientExtensions.WarmUpWith. - /// note if rediscovery is already in progress it will continue, not restart. - /// - internal void Rediscover() { - _channelInfoProvider.Reset(); - } + /// - /// only exists so that we can manually trigger rediscovery in the tests (by reflection) + /// Only exists so that we can manually trigger rediscovery in the tests /// in cases where the server doesn't yet let the client know that it needs to. - /// see EventStoreClientExtensions.WarmUpWith. /// note if rediscovery is already in progress it will continue, not restart. /// internal Task RediscoverAsync() { diff --git a/test/Directory.Build.props b/test/Directory.Build.props index 7bc4510f3..c84046098 100644 --- a/test/Directory.Build.props +++ b/test/Directory.Build.props @@ -1,50 +1,41 @@ - - - true - - - - - - - - - - - - - - - - - - all - runtime; build; native; contentfiles; analyzers - - - - - - - - - - - - - - - - - - - - - - - + + + + true + + + + + + + + + + + + all + runtime; build; native; contentfiles; analyzers + + + + + + + + + + + certs\%(RecursiveDir)/%(FileName)%(Extension) + Always + + + + + + + - + diff --git a/test/EventStore.Client.Operations.Tests/AuthenticationTests.cs b/test/EventStore.Client.Operations.Tests/AuthenticationTests.cs index 19ac4e7ac..187f1a511 100644 --- a/test/EventStore.Client.Operations.Tests/AuthenticationTests.cs +++ b/test/EventStore.Client.Operations.Tests/AuthenticationTests.cs @@ -1,10 +1,7 @@ namespace EventStore.Client; -public class AuthenticationTests : IClassFixture { - public AuthenticationTests(EventStoreClientsFixture fixture, ITestOutputHelper output) => - Fixture = fixture.With(f => f.CaptureLogs(output)); - - EventStoreClientsFixture Fixture { get; } +public class AuthenticationTests : EventStoreFixture { + public AuthenticationTests(ITestOutputHelper output) : base(output) { } public enum CredentialsCase { None, TestUser, RootUser } @@ -39,19 +36,7 @@ async Task ExecuteTest(int caseNr, CredentialsCase defaultCredentials, Credentia var defaultUserCredentials = GetCredentials(defaultCredentials); var actualUserCredentials = GetCredentials(actualCredentials); - var settings = Fixture.GetOptions().ClientSettings; - - // var settings = new EventStoreClientSettings { - // Interceptors = ogSettings.Interceptors, - // ConnectionName = $"Authentication case #{caseNr} {defaultCredentials}", - // CreateHttpMessageHandler = ogSettings.CreateHttpMessageHandler, - // LoggerFactory = ogSettings.LoggerFactory, - // ChannelCredentials = ogSettings.ChannelCredentials, - // OperationOptions = ogSettings.OperationOptions, - // ConnectivitySettings = ogSettings.ConnectivitySettings, - // DefaultCredentials = defaultUserCredentials, - // DefaultDeadline = ogSettings.DefaultDeadline - // }; + var settings = Fixture.ClientSettings; settings.DefaultCredentials = defaultUserCredentials; settings.ConnectionName = $"Authentication case #{caseNr} {defaultCredentials}"; diff --git a/test/EventStore.Client.Operations.Tests/EventStore.Client.Operations.Tests.csproj b/test/EventStore.Client.Operations.Tests/EventStore.Client.Operations.Tests.csproj index 0601af8dc..62cdb17ed 100644 --- a/test/EventStore.Client.Operations.Tests/EventStore.Client.Operations.Tests.csproj +++ b/test/EventStore.Client.Operations.Tests/EventStore.Client.Operations.Tests.csproj @@ -1,9 +1,6 @@ - - - - + diff --git a/test/EventStore.Client.Operations.Tests/admin.cs b/test/EventStore.Client.Operations.Tests/admin.cs index 270f223b1..39a2311e1 100644 --- a/test/EventStore.Client.Operations.Tests/admin.cs +++ b/test/EventStore.Client.Operations.Tests/admin.cs @@ -1,24 +1,19 @@ -namespace EventStore.Client; +namespace EventStore.Client; -public class @admin : IClassFixture { - public admin(EventStoreClientsFixture fixture, ITestOutputHelper output) => - Fixture = fixture.With(f => f.CaptureLogs(output)); - - EventStoreClientsFixture Fixture { get; } +public class @admin : EventStoreFixture { + public admin(ITestOutputHelper output) : base(output, x => x.WithoutDefaultCredentials()) { } [Fact] - public async Task merge_indexes_does_not_throw() { + public async Task merge_indexes_does_not_throw() => await Fixture.Operations .MergeIndexesAsync(userCredentials: TestCredentials.Root) .ShouldNotThrowAsync(); - } [Fact] - public async Task merge_indexes_without_credentials_throws() { + public async Task merge_indexes_without_credentials_throws() => await Fixture.Operations .MergeIndexesAsync() .ShouldThrowAsync(); - } [Fact] public async Task restart_persistent_subscriptions_does_not_throw() => @@ -27,9 +22,8 @@ await Fixture.Operations .ShouldNotThrowAsync(); [Fact] - public async Task restart_persistent_subscriptions_without_credentials_throws() { + public async Task restart_persistent_subscriptions_without_credentials_throws() => await Fixture.Operations .RestartPersistentSubscriptions() .ShouldThrowAsync(); - } } \ No newline at end of file diff --git a/test/EventStore.Client.Operations.Tests/admin_resign_node.cs b/test/EventStore.Client.Operations.Tests/admin_resign_node.cs index 50ebe040a..33e6219c8 100644 --- a/test/EventStore.Client.Operations.Tests/admin_resign_node.cs +++ b/test/EventStore.Client.Operations.Tests/admin_resign_node.cs @@ -1,10 +1,7 @@ namespace EventStore.Client; -public class admin_resign_node : IClassFixture { - public admin_resign_node(EventStoreClientsFixture fixture, ITestOutputHelper output) => - Fixture = fixture.With(f => f.CaptureLogs(output)); - - EventStoreClientsFixture Fixture { get; } +public class admin_resign_node : EventStoreFixture { + public admin_resign_node(ITestOutputHelper output) : base(output) { } [Fact] public async Task resign_node_does_not_throw() { diff --git a/test/EventStore.Client.Operations.Tests/admin_shutdown_node.cs b/test/EventStore.Client.Operations.Tests/admin_shutdown_node.cs index c901c455e..a85f02816 100644 --- a/test/EventStore.Client.Operations.Tests/admin_shutdown_node.cs +++ b/test/EventStore.Client.Operations.Tests/admin_shutdown_node.cs @@ -1,10 +1,7 @@ namespace EventStore.Client; -public class admin_shutdown_node : IClassFixture { - public admin_shutdown_node(EventStoreClientsFixture fixture, ITestOutputHelper output) => - Fixture = fixture.With(f => f.CaptureLogs(output)); - - EventStoreClientsFixture Fixture { get; } +public class admin_shutdown_node : EventStoreFixture { + public admin_shutdown_node(ITestOutputHelper output) : base(output) { } [Fact] public async Task shutdown_does_not_throw() => await Fixture.Operations.ShutdownAsync(userCredentials: TestCredentials.Root); diff --git a/test/EventStore.Client.Operations.Tests/scavenge.cs b/test/EventStore.Client.Operations.Tests/scavenge.cs index b81335f58..2bf431faf 100644 --- a/test/EventStore.Client.Operations.Tests/scavenge.cs +++ b/test/EventStore.Client.Operations.Tests/scavenge.cs @@ -1,13 +1,8 @@ namespace EventStore.Client; -public class @scavenge : IClassFixture { - public scavenge(EventStoreClientsFixture fixture, ITestOutputHelper output) { - Fixture = fixture.With(f => f.CaptureLogs(output)); - // runInMemory: false - } - - EventStoreClientsFixture Fixture { get; } - +public class @scavenge : EventStoreFixture { + public scavenge(ITestOutputHelper output) : base(output, x => x.RunInMemory(false)) { } + [Fact] public async Task start() { var result = await Fixture.Operations.StartScavengeAsync(userCredentials: TestCredentials.Root); diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/AssemblyInfo.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/AssemblyInfo.cs index e5cc5d402..b0b47aa73 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/AssemblyInfo.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/AssemblyInfo.cs @@ -1 +1 @@ -[assembly: CollectionBehavior(DisableTestParallelization = true)] +[assembly: CollectionBehavior(DisableTestParallelization = true)] \ No newline at end of file diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/Bugs/Issue_1125.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/Bugs/Issue_1125.cs index de5b28449..c27c0a350 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/Bugs/Issue_1125.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/Bugs/Issue_1125.cs @@ -1,66 +1,80 @@ -namespace EventStore.Client.Bugs; +namespace EventStore.Client.Bugs; public class Issue_1125 : IClassFixture { - private readonly Fixture _fixture; + readonly Fixture _fixture; - public Issue_1125(Fixture fixture) { - _fixture = fixture; - } + public Issue_1125(Fixture fixture) => _fixture = fixture; - public static IEnumerable TestCases() => Enumerable.Range(0, 50) - .Select(i => new object[] {i}); + public static IEnumerable TestCases() => + Enumerable.Range(0, 50).Select(i => new object[] { i }); - [Theory, MemberData(nameof(TestCases))] + [Theory] + [MemberData(nameof(TestCases))] public async Task persistent_subscription_delivers_all_events(int iteration) { - if (Environment.OSVersion.IsWindows()) { + if (Environment.OSVersion.IsWindows()) { } - } const int eventCount = 250; const int totalEvents = eventCount * 2; var completed = new TaskCompletionSource(); - int hitCount = 0; + var hitCount = 0; var userCredentials = new UserCredentials("admin", "changeit"); var streamName = $"stream_{iteration}"; var subscriptionName = $"subscription_{iteration}"; - for (var i = 0; i < eventCount; i++) { - await _fixture.StreamsClient.AppendToStreamAsync(streamName, StreamState.Any, - _fixture.CreateTestEvents()); - } - - await _fixture.Client.CreateToStreamAsync(streamName, subscriptionName, - new PersistentSubscriptionSettings( - resolveLinkTos: true, startFrom: StreamPosition.Start, readBatchSize: 10, historyBufferSize: 20), - userCredentials: userCredentials); - - using (await _fixture.Client.SubscribeToStreamAsync(streamName, subscriptionName, - async (subscription, @event, retryCount, arg4) => { - int result; - if (retryCount == 0 || retryCount is null) { - result = Interlocked.Increment(ref hitCount); - - await subscription.Ack(@event); - - if (totalEvents == result) { - completed.TrySetResult(true); - } - } else { - // This is a retry - await subscription.Ack(@event); - } - }, (s, dr, e) => { - if (e != null) - completed.TrySetException(e); - else - completed.TrySetException(new Exception($"{dr}")); - }, userCredentials)) { - for (var i = 0; i < eventCount; i++) { - await _fixture.StreamsClient.AppendToStreamAsync(streamName, StreamState.Any, - _fixture.CreateTestEvents()); - } + for (var i = 0; i < eventCount; i++) + await _fixture.StreamsClient.AppendToStreamAsync( + streamName, + StreamState.Any, + _fixture.CreateTestEvents() + ); + + await _fixture.Client.CreateToStreamAsync( + streamName, + subscriptionName, + new( + true, + StreamPosition.Start, + readBatchSize: 10, + historyBufferSize: 20 + ), + userCredentials: userCredentials + ); + + using (await _fixture.Client.SubscribeToStreamAsync( + streamName, + subscriptionName, + async (subscription, @event, retryCount, arg4) => { + int result; + if (retryCount == 0 || retryCount is null) { + result = Interlocked.Increment(ref hitCount); + + await subscription.Ack(@event); + + if (totalEvents == result) + completed.TrySetResult(true); + } + else { + // This is a retry + await subscription.Ack(@event); + } + }, + (s, dr, e) => { + if (e != null) + completed.TrySetException(e); + else + completed.TrySetException(new Exception($"{dr}")); + }, + userCredentials + )) { + for (var i = 0; i < eventCount; i++) + await _fixture.StreamsClient.AppendToStreamAsync( + streamName, + StreamState.Any, + _fixture.CreateTestEvents() + ); await completed.Task.WithTimeout(TimeSpan.FromSeconds(30)); } diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/EventStore.Client.PersistentSubscriptions.Tests.csproj b/test/EventStore.Client.PersistentSubscriptions.Tests/EventStore.Client.PersistentSubscriptions.Tests.csproj index 1981ecc73..ee7d48512 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/EventStore.Client.PersistentSubscriptions.Tests.csproj +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/EventStore.Client.PersistentSubscriptions.Tests.csproj @@ -1,9 +1,6 @@  - - - - - - + + + diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/EventStoreClientFixture.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/EventStoreClientFixture.cs index 45f685867..7482ae415 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/EventStoreClientFixture.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/EventStoreClientFixture.cs @@ -1,33 +1,35 @@ -namespace EventStore.Client; +namespace EventStore.Client; public abstract class EventStoreClientFixture : EventStoreClientFixtureBase { - private readonly bool _skipPsWarmUp; + readonly bool _skipPsWarmUp; + + protected EventStoreClientFixture(EventStoreClientSettings? settings = null, bool skipPSWarmUp = false, bool noDefaultCredentials = false) + : base(settings, noDefaultCredentials: noDefaultCredentials) { + _skipPsWarmUp = skipPSWarmUp; + + Client = new(Settings); + StreamsClient = new(Settings); + UserManagementClient = new(Settings); + } public EventStorePersistentSubscriptionsClient Client { get; } public EventStoreClient StreamsClient { get; } public EventStoreUserManagementClient UserManagementClient { get; } - protected EventStoreClientFixture(EventStoreClientSettings? settings = null, bool skipPSWarmUp=false, bool noDefaultCredentials=false) - : base(settings, noDefaultCredentials: noDefaultCredentials){ - - _skipPsWarmUp = skipPSWarmUp; - - Client = new EventStorePersistentSubscriptionsClient(Settings); - StreamsClient = new EventStoreClient(Settings); - UserManagementClient = new EventStoreUserManagementClient(Settings); - } - protected override async Task OnServerUpAsync() { await StreamsClient.WarmUp(); await UserManagementClient.WarmUp(); - - if (!_skipPsWarmUp) { + + if (!_skipPsWarmUp) await Client.WarmUp(); - } - await UserManagementClient.CreateUserWithRetry(TestCredentials.TestUser1.Username!, - TestCredentials.TestUser1.Username!, Array.Empty(), TestCredentials.TestUser1.Password!, - TestCredentials.Root); + await UserManagementClient.CreateUserWithRetry( + TestCredentials.TestUser1.Username!, + TestCredentials.TestUser1.Username!, + Array.Empty(), + TestCredentials.TestUser1.Password!, + TestCredentials.Root + ); } public override async Task DisposeAsync() { diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/FilterTestCase.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/FilterTestCase.cs index 02944cb17..5f9304fe4 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/FilterTestCase.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/FilterTestCase.cs @@ -1,22 +1,32 @@ using System.Reflection; -namespace EventStore.Client; +namespace EventStore.Client; public static class Filters { - private const string StreamNamePrefix = nameof(StreamNamePrefix); - private const string StreamNameRegex = nameof(StreamNameRegex); - private const string EventTypePrefix = nameof(EventTypePrefix); - private const string EventTypeRegex = nameof(EventTypeRegex); + const string StreamNamePrefix = nameof(StreamNamePrefix); + const string StreamNameRegex = nameof(StreamNameRegex); + const string EventTypePrefix = nameof(EventTypePrefix); + const string EventTypeRegex = nameof(EventTypeRegex); - private static readonly IDictionary, Func)> + static readonly IDictionary, Func)> s_filters = new Dictionary, Func)> { [StreamNamePrefix] = (StreamFilter.Prefix, (_, e) => e), [StreamNameRegex] = (f => StreamFilter.RegularExpression(f), (_, e) => e), - [EventTypePrefix] = (EventTypeFilter.Prefix, - (term, e) => new EventData(e.EventId, term, e.Data, e.Metadata, e.ContentType)), - [EventTypeRegex] = (f => EventTypeFilter.RegularExpression(f), - (term, e) => new EventData(e.EventId, term, e.Data, e.Metadata, e.ContentType)) + [EventTypePrefix] = (EventTypeFilter.Prefix, (term, e) => new( + e.EventId, + term, + e.Data, + e.Metadata, + e.ContentType + )), + [EventTypeRegex] = (f => EventTypeFilter.RegularExpression(f), (term, e) => new( + e.EventId, + term, + e.Data, + e.Metadata, + e.ContentType + )) }; public static readonly IEnumerable All = typeof(Filters) @@ -25,5 +35,6 @@ public static class Filters { .Select(fi => (string)fi.GetRawConstantValue()!); public static (Func getFilter, Func prepareEvent) - GetFilter(string name) => s_filters[name]; + GetFilter(string name) => + s_filters[name]; } \ No newline at end of file diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/PersistentSubscriptionSettingsTests.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/PersistentSubscriptionSettingsTests.cs index 0449a6e47..72dbc6537 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/PersistentSubscriptionSettingsTests.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/PersistentSubscriptionSettingsTests.cs @@ -1,11 +1,11 @@ -namespace EventStore.Client; +namespace EventStore.Client; public class PersistentSubscriptionSettingsTests { [Fact] - public void LargeCheckpointAfterThrows() => Assert.Throws( - () => new PersistentSubscriptionSettings(checkPointAfter: TimeSpan.FromDays(25 * 365))); + public void LargeCheckpointAfterThrows() => + Assert.Throws(() => new PersistentSubscriptionSettings(checkPointAfter: TimeSpan.FromDays(25 * 365))); [Fact] - public void LargeMessageTimeoutThrows() => Assert.Throws( - () => new PersistentSubscriptionSettings(messageTimeout: TimeSpan.FromDays(25 * 365))); + public void LargeMessageTimeoutThrows() => + Assert.Throws(() => new PersistentSubscriptionSettings(messageTimeout: TimeSpan.FromDays(25 * 365))); } \ No newline at end of file diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/ReadOnlyMemoryExtensions.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/ReadOnlyMemoryExtensions.cs index 10001c30e..4a99c3762 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/ReadOnlyMemoryExtensions.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/ReadOnlyMemoryExtensions.cs @@ -1,30 +1,27 @@ using System.Text.Json; -namespace EventStore.Client; +namespace EventStore.Client; public static class ReadOnlyMemoryExtensions { public static Position ParsePosition(this ReadOnlyMemory json) { using var doc = JsonDocument.Parse(json); - + var checkPoint = doc.RootElement.GetString(); - if (checkPoint is null) { - throw new Exception("Unable to parse Position, data is missing!"); - } - - if (Position.TryParse(checkPoint, out var position) && position.HasValue) { + if (checkPoint is null) + throw new("Unable to parse Position, data is missing!"); + + if (Position.TryParse(checkPoint, out var position) && position.HasValue) return position.Value; - } - - throw new Exception("Unable to parse Position, invalid data!"); + + throw new("Unable to parse Position, invalid data!"); } public static StreamPosition ParseStreamPosition(this ReadOnlyMemory json) { using var doc = JsonDocument.Parse(json); - + var checkPoint = doc.RootElement.GetString(); - if (checkPoint is null) { - throw new Exception("Unable to parse Position, data is missing!"); - } + if (checkPoint is null) + throw new("Unable to parse Position, data is missing!"); return StreamPosition.FromInt64(int.Parse(checkPoint)); } diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/can_create_duplicate_name_on_different_streams.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/can_create_duplicate_name_on_different_streams.cs index 2f988a3ea..fd33a3b97 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/can_create_duplicate_name_on_different_streams.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/can_create_duplicate_name_on_different_streams.cs @@ -1,25 +1,28 @@ -namespace EventStore.Client.SubscriptionToAll; +namespace EventStore.Client.SubscriptionToAll; public class can_create_duplicate_name_on_different_streams : IClassFixture { - public can_create_duplicate_name_on_different_streams(Fixture fixture) { - _fixture = fixture; - } - + readonly Fixture _fixture; + public can_create_duplicate_name_on_different_streams(Fixture fixture) => _fixture = fixture; - private readonly Fixture _fixture; + [SupportsPSToAll.Fact] + public Task the_completion_succeeds() => + _fixture.Client.CreateToStreamAsync( + "someother", + "group3211", + new(), + userCredentials: TestCredentials.Root + ); public class Fixture : EventStoreClientFixture { protected override Task Given() => Task.CompletedTask; protected override Task When() => - Client.CreateToAllAsync("group3211", - new PersistentSubscriptionSettings(), userCredentials: TestCredentials.Root); + Client.CreateToAllAsync( + "group3211", + new(), + userCredentials: TestCredentials.Root + ); } - - [SupportsPSToAll.Fact] - public Task the_completion_succeeds() => - _fixture.Client.CreateToStreamAsync("someother", - "group3211", new PersistentSubscriptionSettings(), userCredentials: TestCredentials.Root); } \ No newline at end of file diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/connect_to_existing_with_max_one_client.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/connect_to_existing_with_max_one_client.cs index fc8e2b72b..0939f047b 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/connect_to_existing_with_max_one_client.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/connect_to_existing_with_max_one_client.cs @@ -1,26 +1,30 @@ -namespace EventStore.Client.SubscriptionToAll; +namespace EventStore.Client.SubscriptionToAll; public class connect_to_existing_with_max_one_client : IClassFixture { - private const string Group = "maxoneclient"; + const string Group = "maxoneclient"; - private readonly Fixture _fixture; + readonly Fixture _fixture; - public connect_to_existing_with_max_one_client(Fixture fixture) { - _fixture = fixture; - } + public connect_to_existing_with_max_one_client(Fixture fixture) => _fixture = fixture; [SupportsPSToAll.Fact] public async Task the_second_subscription_fails_to_connect() { - using var first = await _fixture.Client.SubscribeToAllAsync(Group, - delegate { return Task.CompletedTask; }, - userCredentials: TestCredentials.Root).WithTimeout(); - - var ex = await Assert.ThrowsAsync(async () => { - using var _ = await _fixture.Client.SubscribeToAllAsync(Group, - delegate { return Task.CompletedTask; }, - userCredentials: TestCredentials.Root); - }).WithTimeout(); + using var first = await _fixture.Client.SubscribeToAllAsync( + Group, + delegate { return Task.CompletedTask; }, + userCredentials: TestCredentials.Root + ).WithTimeout(); + + var ex = await Assert.ThrowsAsync( + async () => { + using var _ = await _fixture.Client.SubscribeToAllAsync( + Group, + delegate { return Task.CompletedTask; }, + userCredentials: TestCredentials.Root + ); + } + ).WithTimeout(); Assert.Equal(SystemStreams.AllStream, ex.StreamName); Assert.Equal(Group, ex.GroupName); @@ -30,8 +34,9 @@ public class Fixture : EventStoreClientFixture { protected override Task Given() => Client.CreateToAllAsync( Group, - new PersistentSubscriptionSettings(maxSubscriberCount: 1), - userCredentials: TestCredentials.Root); + new(maxSubscriberCount: 1), + userCredentials: TestCredentials.Root + ); protected override Task When() => Task.CompletedTask; } diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/connect_to_existing_with_permissions.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/connect_to_existing_with_permissions.cs index 618cefc32..061a2011f 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/connect_to_existing_with_permissions.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/connect_to_existing_with_permissions.cs @@ -1,22 +1,23 @@ -namespace EventStore.Client.SubscriptionToAll; +namespace EventStore.Client.SubscriptionToAll; public class connect_to_existing_with_permissions : IClassFixture { - private const string Group = "connectwithpermissions"; + const string Group = "connectwithpermissions"; + readonly Fixture _fixture; - private readonly Fixture _fixture; - - public connect_to_existing_with_permissions(Fixture fixture) { - _fixture = fixture; - } + public connect_to_existing_with_permissions(Fixture fixture) => _fixture = fixture; [SupportsPSToAll.Fact] public async Task the_subscription_succeeds() { var dropped = new TaskCompletionSource<(SubscriptionDroppedReason, Exception?)>(); - using var subscription = await _fixture.Client.SubscribeToAllAsync(Group, - delegate { return Task.CompletedTask; }, (s, reason, ex) => dropped.TrySetResult((reason, ex)), - userCredentials: TestCredentials.Root).WithTimeout(); + using var subscription = await _fixture.Client.SubscribeToAllAsync( + Group, + delegate { return Task.CompletedTask; }, + (s, reason, ex) => dropped.TrySetResult((reason, ex)), + TestCredentials.Root + ).WithTimeout(); + Assert.NotNull(subscription); await Assert.ThrowsAsync(() => dropped.Task.WithTimeout()); @@ -26,8 +27,9 @@ public class Fixture : EventStoreClientFixture { protected override Task Given() => Client.CreateToAllAsync( Group, - new PersistentSubscriptionSettings(), - userCredentials: TestCredentials.Root); + new(), + userCredentials: TestCredentials.Root + ); protected override Task When() => Task.CompletedTask; } diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/connect_to_existing_with_start_from_beginning.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/connect_to_existing_with_start_from_beginning.cs index 7038cc307..4102b3db0 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/connect_to_existing_with_start_from_beginning.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/connect_to_existing_with_start_from_beginning.cs @@ -1,17 +1,11 @@ -namespace EventStore.Client.SubscriptionToAll; +namespace EventStore.Client.SubscriptionToAll; -public class connect_to_existing_with_start_from_beginning - : IClassFixture { - private readonly Fixture _fixture; +public class connect_to_existing_with_start_from_beginning : IClassFixture { + const string Group = "startfrombeginning"; - private const string Group = "startfrombeginning"; + readonly Fixture _fixture; - - - public connect_to_existing_with_start_from_beginning(Fixture fixture) { - _fixture = fixture; - } + public connect_to_existing_with_start_from_beginning(Fixture fixture) => _fixture = fixture; [SupportsPSToAll.Fact] public async Task the_subscription_gets_event_zero_as_its_first_event() { @@ -20,38 +14,49 @@ public async Task the_subscription_gets_event_zero_as_its_first_event() { } public class Fixture : EventStoreClientFixture { - private readonly TaskCompletionSource _firstEventSource; - public Task FirstEvent => _firstEventSource.Task; - public ResolvedEvent[]? Events; - private PersistentSubscription? _subscription; + readonly TaskCompletionSource _firstEventSource; - public Fixture() { - _firstEventSource = new TaskCompletionSource(); - } + PersistentSubscription? _subscription; + + public Fixture() => _firstEventSource = new(); + + public ResolvedEvent[]? Events { get; set; } + + public Task FirstEvent => _firstEventSource.Task; protected override async Task Given() { //append 10 events to random streams to make sure we have at least 10 events in the transaction file - foreach (var @event in CreateTestEvents(10)) { - await StreamsClient.AppendToStreamAsync(Guid.NewGuid().ToString(), StreamState.NoStream, new []{ @event }); - } - Events = await StreamsClient.ReadAllAsync(Direction.Forwards, Position.Start, 10, userCredentials: TestCredentials.Root).ToArrayAsync(); + foreach (var @event in CreateTestEvents(10)) + await StreamsClient.AppendToStreamAsync(Guid.NewGuid().ToString(), StreamState.NoStream, new[] { @event }); - await Client.CreateToAllAsync(Group, - new PersistentSubscriptionSettings(startFrom: Position.Start), userCredentials: TestCredentials.Root); - } + Events = await StreamsClient.ReadAllAsync( + Direction.Forwards, + Position.Start, + 10, + userCredentials: TestCredentials.Root + ).ToArrayAsync(); - protected override async Task When() { - _subscription = await Client.SubscribeToAllAsync(Group, - async (subscription, e, r, ct) => { - _firstEventSource.TrySetResult(e); - await subscription.Ack(e); - }, (subscription, reason, ex) => { - if (reason != SubscriptionDroppedReason.Disposed) { - _firstEventSource.TrySetException(ex!); - } - }, userCredentials: TestCredentials.Root); + await Client.CreateToAllAsync( + Group, + new(startFrom: Position.Start), + userCredentials: TestCredentials.Root + ); } + protected override async Task When() => + _subscription = await Client.SubscribeToAllAsync( + Group, + async (subscription, e, r, ct) => { + _firstEventSource.TrySetResult(e); + await subscription.Ack(e); + }, + (subscription, reason, ex) => { + if (reason != SubscriptionDroppedReason.Disposed) + _firstEventSource.TrySetException(ex!); + }, + TestCredentials.Root + ); + public override Task DisposeAsync() { _subscription?.Dispose(); return base.DisposeAsync(); diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/connect_to_existing_with_start_from_not_set.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/connect_to_existing_with_start_from_not_set.cs index abe72e103..8cedce62b 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/connect_to_existing_with_start_from_not_set.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/connect_to_existing_with_start_from_not_set.cs @@ -1,57 +1,58 @@ -namespace EventStore.Client.SubscriptionToAll; +namespace EventStore.Client.SubscriptionToAll; -public class connect_to_existing_with_start_from_not_set - : IClassFixture { - private readonly Fixture _fixture; - private const string Group = "startfromend1"; +public class connect_to_existing_with_start_from_not_set : IClassFixture { + const string Group = "startfromend1"; + readonly Fixture _fixture; - - - public connect_to_existing_with_start_from_not_set( - Fixture fixture) { - _fixture = fixture; - } + public connect_to_existing_with_start_from_not_set(Fixture fixture) => _fixture = fixture; [SupportsPSToAll.Fact] - public async Task the_subscription_gets_no_non_system_events() { + public async Task the_subscription_gets_no_non_system_events() => await Assert.ThrowsAsync(() => _fixture.FirstNonSystemEvent.WithTimeout()); - } public class Fixture : EventStoreClientFixture { - private readonly TaskCompletionSource _firstNonSystemEventSource; - public Task FirstNonSystemEvent => _firstNonSystemEventSource.Task; - private PersistentSubscription? _subscription; + readonly TaskCompletionSource _firstNonSystemEventSource; + PersistentSubscription? _subscription; - public Fixture() { - _firstNonSystemEventSource = new TaskCompletionSource(); - } + public Fixture() => _firstNonSystemEventSource = new(); - protected override async Task Given() { - foreach (var @event in CreateTestEvents(10)) { - await StreamsClient.AppendToStreamAsync("non-system-stream-" + Guid.NewGuid(), - StreamState.Any, new[] {@event}); - } + public Task FirstNonSystemEvent => _firstNonSystemEventSource.Task; - await Client.CreateToAllAsync(Group, - new PersistentSubscriptionSettings(), userCredentials: TestCredentials.Root); + protected override async Task Given() { + foreach (var @event in CreateTestEvents(10)) + await StreamsClient.AppendToStreamAsync( + "non-system-stream-" + Guid.NewGuid(), + StreamState.Any, + new[] { + @event + } + ); + + await Client.CreateToAllAsync( + Group, + new(), + userCredentials: TestCredentials.Root + ); } - protected override async Task When() { - _subscription = await Client.SubscribeToAllAsync(Group, - async (subscription, e, r, ct) => { - if (SystemStreams.IsSystemStream(e.OriginalStreamId)) { - await subscription.Ack(e); - return; - } - _firstNonSystemEventSource.TrySetResult(e); - await subscription.Ack(e); - }, (subscription, reason, ex) => { - if (reason != SubscriptionDroppedReason.Disposed) { - _firstNonSystemEventSource.TrySetException(ex!); - } - }, userCredentials: TestCredentials.Root); - } + protected override async Task When() => + _subscription = await Client.SubscribeToAllAsync( + Group, + async (subscription, e, r, ct) => { + if (SystemStreams.IsSystemStream(e.OriginalStreamId)) { + await subscription.Ack(e); + return; + } + + _firstNonSystemEventSource.TrySetResult(e); + await subscription.Ack(e); + }, + (subscription, reason, ex) => { + if (reason != SubscriptionDroppedReason.Disposed) + _firstNonSystemEventSource.TrySetException(ex!); + }, + TestCredentials.Root + ); public override Task DisposeAsync() { _subscription?.Dispose(); diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/connect_to_existing_with_start_from_not_set_then_event_written.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/connect_to_existing_with_start_from_not_set_then_event_written.cs index 96a4ef4a1..f363fe571 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/connect_to_existing_with_start_from_not_set_then_event_written.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/connect_to_existing_with_start_from_not_set_then_event_written.cs @@ -1,19 +1,16 @@ -namespace EventStore.Client.SubscriptionToAll; +namespace EventStore.Client.SubscriptionToAll; public class connect_to_existing_with_start_from_not_set_then_event_written : IClassFixture< connect_to_existing_with_start_from_not_set_then_event_written .Fixture> { - private readonly Fixture _fixture; - private const string Group = "startfromnotset2"; - + const string Group = "startfromnotset2"; + readonly Fixture _fixture; public - connect_to_existing_with_start_from_not_set_then_event_written( - Fixture fixture) { + connect_to_existing_with_start_from_not_set_then_event_written(Fixture fixture) => _fixture = fixture; - } [SupportsPSToAll.Fact] public async Task the_subscription_gets_the_written_event_as_its_first_non_system_event() { @@ -23,44 +20,49 @@ public async Task the_subscription_gets_the_written_event_as_its_first_non_syste } public class Fixture : EventStoreClientFixture { - private readonly TaskCompletionSource _firstNonSystemEventSource; - public Task FirstNonSystemEvent => _firstNonSystemEventSource.Task; - private PersistentSubscription? _subscription; - public readonly EventData? ExpectedEvent; - public readonly string ExpectedStreamId; + readonly TaskCompletionSource _firstNonSystemEventSource; + public readonly EventData? ExpectedEvent; + public readonly string ExpectedStreamId; + PersistentSubscription? _subscription; public Fixture() { - _firstNonSystemEventSource = new TaskCompletionSource(); + _firstNonSystemEventSource = new(); ExpectedEvent = CreateTestEvents(1).First(); ExpectedStreamId = Guid.NewGuid().ToString(); } + public Task FirstNonSystemEvent => _firstNonSystemEventSource.Task; + protected override async Task Given() { - foreach (var @event in CreateTestEvents(10)) { - await StreamsClient.AppendToStreamAsync("non-system-stream-" + Guid.NewGuid(), - StreamState.Any, new[] {@event}); - } + foreach (var @event in CreateTestEvents(10)) + await StreamsClient.AppendToStreamAsync( + "non-system-stream-" + Guid.NewGuid(), + StreamState.Any, + new[] { @event } + ); - await Client.CreateToAllAsync(Group, new PersistentSubscriptionSettings(), userCredentials: TestCredentials.Root); - _subscription = await Client.SubscribeToAllAsync(Group, - async (subscription, e, r, ct) => { - if (SystemStreams.IsSystemStream(e.OriginalStreamId)) { - await subscription.Ack(e); - return; - } - _firstNonSystemEventSource.TrySetResult(e); - await subscription.Ack(e); - }, (subscription, reason, ex) => { - if (reason != SubscriptionDroppedReason.Disposed) { - _firstNonSystemEventSource.TrySetException(ex!); - } - }, userCredentials: TestCredentials.Root); - } + await Client.CreateToAllAsync(Group, new(), userCredentials: TestCredentials.Root); + _subscription = await Client.SubscribeToAllAsync( + Group, + async (subscription, e, r, ct) => { + if (SystemStreams.IsSystemStream(e.OriginalStreamId)) { + await subscription.Ack(e); + return; + } - protected override async Task When() { - await StreamsClient.AppendToStreamAsync(ExpectedStreamId, StreamState.NoStream, new []{ ExpectedEvent! }); + _firstNonSystemEventSource.TrySetResult(e); + await subscription.Ack(e); + }, + (subscription, reason, ex) => { + if (reason != SubscriptionDroppedReason.Disposed) + _firstNonSystemEventSource.TrySetException(ex!); + }, + TestCredentials.Root + ); } + protected override async Task When() => await StreamsClient.AppendToStreamAsync(ExpectedStreamId, StreamState.NoStream, new[] { ExpectedEvent! }); + public override Task DisposeAsync() { _subscription?.Dispose(); return base.DisposeAsync(); diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/connect_to_existing_with_start_from_set_to_end_position.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/connect_to_existing_with_start_from_set_to_end_position.cs index 4817f0267..e22d091c6 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/connect_to_existing_with_start_from_set_to_end_position.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/connect_to_existing_with_start_from_set_to_end_position.cs @@ -1,58 +1,59 @@ -namespace EventStore.Client.SubscriptionToAll; +namespace EventStore.Client.SubscriptionToAll; -public class connect_to_existing_with_start_from_set_to_end_position - : IClassFixture { - private readonly Fixture _fixture; - private const string Group = "startfromend1"; +public class connect_to_existing_with_start_from_set_to_end_position : IClassFixture { + const string Group = "startfromend1"; + readonly Fixture _fixture; - - public connect_to_existing_with_start_from_set_to_end_position( - Fixture fixture) { - _fixture = fixture; - } + public connect_to_existing_with_start_from_set_to_end_position(Fixture fixture) => _fixture = fixture; [SupportsPSToAll.Fact] - public async Task the_subscription_gets_no_non_system_events() { + public async Task the_subscription_gets_no_non_system_events() => await Assert.ThrowsAsync(() => _fixture.FirstNonSystemEvent.WithTimeout()); - } public class Fixture : EventStoreClientFixture { - private readonly TaskCompletionSource _firstNonSystemEventSource; - public Task FirstNonSystemEvent => _firstNonSystemEventSource.Task; - private PersistentSubscription? _subscription; + readonly TaskCompletionSource _firstNonSystemEventSource; - public Fixture() { - _firstNonSystemEventSource = new TaskCompletionSource(); - } + PersistentSubscription? _subscription; - protected override async Task Given() { - foreach (var @event in CreateTestEvents(10)) { - await StreamsClient.AppendToStreamAsync("non-system-stream-" + Guid.NewGuid(), - StreamState.Any, new[] {@event}); - } + public Fixture() => _firstNonSystemEventSource = new(); - await Client.CreateToAllAsync(Group, - new PersistentSubscriptionSettings(startFrom: Position.End), userCredentials: TestCredentials.Root); - } + public Task FirstNonSystemEvent => _firstNonSystemEventSource.Task; - protected override async Task When() { - _subscription = await Client.SubscribeToAllAsync(Group, - async (subscription, e, r, ct) => { - if (SystemStreams.IsSystemStream(e.OriginalStreamId)) { - await subscription.Ack(e); - return; - } - _firstNonSystemEventSource.TrySetResult(e); - await subscription.Ack(e); - }, (subscription, reason, ex) => { - if (reason != SubscriptionDroppedReason.Disposed) { - _firstNonSystemEventSource.TrySetException(ex!); - } - }, userCredentials: TestCredentials.Root); + protected override async Task Given() { + foreach (var @event in CreateTestEvents(10)) + await StreamsClient.AppendToStreamAsync( + "non-system-stream-" + Guid.NewGuid(), + StreamState.Any, + new[] { @event } + ); + + await Client.CreateToAllAsync( + Group, + new(startFrom: Position.End), + userCredentials: TestCredentials.Root + ); } + protected override async Task When() => + _subscription = await Client.SubscribeToAllAsync( + Group, + async (subscription, e, r, ct) => { + if (SystemStreams.IsSystemStream(e.OriginalStreamId)) { + await subscription.Ack(e); + return; + } + + _firstNonSystemEventSource.TrySetResult(e); + await subscription.Ack(e); + }, + (subscription, reason, ex) => { + if (reason != SubscriptionDroppedReason.Disposed) + _firstNonSystemEventSource.TrySetException(ex!); + }, + TestCredentials.Root + ); + public override Task DisposeAsync() { _subscription?.Dispose(); return base.DisposeAsync(); diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/connect_to_existing_with_start_from_set_to_end_position_then_event_written.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/connect_to_existing_with_start_from_set_to_end_position_then_event_written.cs index aa7b20998..b8f5e80fa 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/connect_to_existing_with_start_from_set_to_end_position_then_event_written.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/connect_to_existing_with_start_from_set_to_end_position_then_event_written.cs @@ -1,19 +1,14 @@ -namespace EventStore.Client.SubscriptionToAll; +namespace EventStore.Client.SubscriptionToAll; public class connect_to_existing_with_start_from_set_to_end_position_then_event_written - : IClassFixture< - connect_to_existing_with_start_from_set_to_end_position_then_event_written - .Fixture> { - private readonly Fixture _fixture; - private const string Group = "startfromnotset2"; + : IClassFixture { + const string Group = "startfromnotset2"; + readonly Fixture _fixture; - public - connect_to_existing_with_start_from_set_to_end_position_then_event_written( - Fixture fixture) { + public connect_to_existing_with_start_from_set_to_end_position_then_event_written(Fixture fixture) => _fixture = fixture; - } [SupportsPSToAll.Fact] public async Task the_subscription_gets_the_written_event_as_its_first_non_system_event() { @@ -23,44 +18,49 @@ public async Task the_subscription_gets_the_written_event_as_its_first_non_syste } public class Fixture : EventStoreClientFixture { - private readonly TaskCompletionSource _firstNonSystemEventSource; - public Task FirstNonSystemEvent => _firstNonSystemEventSource.Task; - private PersistentSubscription? _subscription; - public readonly EventData ExpectedEvent; - public readonly string ExpectedStreamId; + readonly TaskCompletionSource _firstNonSystemEventSource; + public readonly EventData ExpectedEvent; + public readonly string ExpectedStreamId; + PersistentSubscription? _subscription; public Fixture() { - _firstNonSystemEventSource = new TaskCompletionSource(); + _firstNonSystemEventSource = new(); ExpectedEvent = CreateTestEvents(1).First(); ExpectedStreamId = Guid.NewGuid().ToString(); } + public Task FirstNonSystemEvent => _firstNonSystemEventSource.Task; + protected override async Task Given() { - foreach (var @event in CreateTestEvents(10)) { - await StreamsClient.AppendToStreamAsync("non-system-stream-" + Guid.NewGuid(), - StreamState.Any, new[] {@event}); - } + foreach (var @event in CreateTestEvents(10)) + await StreamsClient.AppendToStreamAsync( + "non-system-stream-" + Guid.NewGuid(), + StreamState.Any, + new[] { @event } + ); - await Client.CreateToAllAsync(Group, new PersistentSubscriptionSettings(startFrom: Position.End), userCredentials: TestCredentials.Root); - _subscription = await Client.SubscribeToAllAsync(Group, - async (subscription, e, r, ct) => { - if (SystemStreams.IsSystemStream(e.OriginalStreamId)) { - await subscription.Ack(e); - return; - } - _firstNonSystemEventSource.TrySetResult(e); - await subscription.Ack(e); - }, (subscription, reason, ex) => { - if (reason != SubscriptionDroppedReason.Disposed) { - _firstNonSystemEventSource.TrySetException(ex!); - } - }, userCredentials: TestCredentials.Root); - } + await Client.CreateToAllAsync(Group, new(startFrom: Position.End), userCredentials: TestCredentials.Root); + _subscription = await Client.SubscribeToAllAsync( + Group, + async (subscription, e, r, ct) => { + if (SystemStreams.IsSystemStream(e.OriginalStreamId)) { + await subscription.Ack(e); + return; + } - protected override async Task When() { - await StreamsClient.AppendToStreamAsync(ExpectedStreamId, StreamState.NoStream, new []{ ExpectedEvent }); + _firstNonSystemEventSource.TrySetResult(e); + await subscription.Ack(e); + }, + (subscription, reason, ex) => { + if (reason != SubscriptionDroppedReason.Disposed) + _firstNonSystemEventSource.TrySetException(ex!); + }, + TestCredentials.Root + ); } + protected override async Task When() => await StreamsClient.AppendToStreamAsync(ExpectedStreamId, StreamState.NoStream, new[] { ExpectedEvent }); + public override Task DisposeAsync() { _subscription?.Dispose(); return base.DisposeAsync(); diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/connect_to_existing_with_start_from_set_to_invalid_middle_position.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/connect_to_existing_with_start_from_set_to_invalid_middle_position.cs index 1f47cc549..a12a6d9bd 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/connect_to_existing_with_start_from_set_to_invalid_middle_position.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/connect_to_existing_with_start_from_set_to_invalid_middle_position.cs @@ -1,17 +1,11 @@ -namespace EventStore.Client.SubscriptionToAll; +namespace EventStore.Client.SubscriptionToAll; public class connect_to_existing_with_start_from_set_to_invalid_middle_position - : IClassFixture { - private readonly Fixture _fixture; - private const string Group = "startfrominvalid1"; + : IClassFixture { + const string Group = "startfrominvalid1"; + readonly Fixture _fixture; - - - public connect_to_existing_with_start_from_set_to_invalid_middle_position( - Fixture fixture) { - _fixture = fixture; - } + public connect_to_existing_with_start_from_set_to_invalid_middle_position(Fixture fixture) => _fixture = fixture; [SupportsPSToAll.Fact] public async Task the_subscription_is_dropped() { @@ -21,28 +15,30 @@ public async Task the_subscription_is_dropped() { } public class Fixture : EventStoreClientFixture { - private readonly TaskCompletionSource<(SubscriptionDroppedReason, Exception?)> _dropped; - public Task<(SubscriptionDroppedReason, Exception?)> Dropped => _dropped.Task; + readonly TaskCompletionSource<(SubscriptionDroppedReason, Exception?)> _dropped; - private PersistentSubscription? _subscription; + PersistentSubscription? _subscription; - public Fixture() { - _dropped = new TaskCompletionSource<(SubscriptionDroppedReason, Exception?)>(); - } + public Fixture() => _dropped = new(); + + public Task<(SubscriptionDroppedReason, Exception?)> Dropped => _dropped.Task; protected override async Task Given() { var invalidPosition = new Position(1L, 1L); - await Client.CreateToAllAsync(Group, - new PersistentSubscriptionSettings(startFrom: invalidPosition), userCredentials: TestCredentials.Root); + await Client.CreateToAllAsync( + Group, + new(startFrom: invalidPosition), + userCredentials: TestCredentials.Root + ); } - protected override async Task When() { - _subscription = await Client.SubscribeToAllAsync(Group, - async (subscription, e, r, ct) => await subscription.Ack(e), - (subscription, reason, ex) => { - _dropped.TrySetResult((reason, ex)); - }, userCredentials: TestCredentials.Root); - } + protected override async Task When() => + _subscription = await Client.SubscribeToAllAsync( + Group, + async (subscription, e, r, ct) => await subscription.Ack(e), + (subscription, reason, ex) => { _dropped.TrySetResult((reason, ex)); }, + TestCredentials.Root + ); public override Task DisposeAsync() { _subscription?.Dispose(); diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/connect_to_existing_with_start_from_set_to_valid_middle_position.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/connect_to_existing_with_start_from_set_to_valid_middle_position.cs index 0ed539c22..9bd759eb0 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/connect_to_existing_with_start_from_set_to_valid_middle_position.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/connect_to_existing_with_start_from_set_to_valid_middle_position.cs @@ -1,17 +1,12 @@ -namespace EventStore.Client.SubscriptionToAll; +namespace EventStore.Client.SubscriptionToAll; public class connect_to_existing_with_start_from_set_to_valid_middle_position - : IClassFixture { - private readonly Fixture _fixture; - private const string Group = "startfromvalid"; + : IClassFixture { + const string Group = "startfromvalid"; + readonly Fixture _fixture; - - public connect_to_existing_with_start_from_set_to_valid_middle_position( - Fixture fixture) { - _fixture = fixture; - } + public connect_to_existing_with_start_from_set_to_valid_middle_position(Fixture fixture) => _fixture = fixture; [SupportsPSToAll.Fact] public async Task the_subscription_gets_the_event_at_the_specified_start_position_as_its_first_event() { @@ -22,35 +17,44 @@ public async Task the_subscription_gets_the_event_at_the_specified_start_positio } public class Fixture : EventStoreClientFixture { - private readonly TaskCompletionSource _firstEventSource; - public Task FirstEvent => _firstEventSource.Task; - private PersistentSubscription? _subscription; - public ResolvedEvent ExpectedEvent { get; private set; } + readonly TaskCompletionSource _firstEventSource; + PersistentSubscription? _subscription; - public Fixture() { - _firstEventSource = new TaskCompletionSource(); - } + public Fixture() => _firstEventSource = new(); + + public Task FirstEvent => _firstEventSource.Task; + public ResolvedEvent ExpectedEvent { get; private set; } protected override async Task Given() { - var events = await StreamsClient.ReadAllAsync(Direction.Forwards, Position.Start, 10, - userCredentials: TestCredentials.Root).ToArrayAsync(); + var events = await StreamsClient.ReadAllAsync( + Direction.Forwards, + Position.Start, + 10, + userCredentials: TestCredentials.Root + ).ToArrayAsync(); + ExpectedEvent = events[events.Length / 2]; //just a random event in the middle of the results - await Client.CreateToAllAsync(Group, - new PersistentSubscriptionSettings(startFrom: ExpectedEvent.OriginalPosition), userCredentials: TestCredentials.Root); + await Client.CreateToAllAsync( + Group, + new(startFrom: ExpectedEvent.OriginalPosition), + userCredentials: TestCredentials.Root + ); } - protected override async Task When() { - _subscription = await Client.SubscribeToAllAsync(Group, - async (subscription, e, r, ct) => { - _firstEventSource.TrySetResult(e); - await subscription.Ack(e); - }, (subscription, reason, ex) => { - if (reason != SubscriptionDroppedReason.Disposed) { - _firstEventSource.TrySetException(ex!); - } - }, userCredentials: TestCredentials.Root); - } + protected override async Task When() => + _subscription = await Client.SubscribeToAllAsync( + Group, + async (subscription, e, r, ct) => { + _firstEventSource.TrySetResult(e); + await subscription.Ack(e); + }, + (subscription, reason, ex) => { + if (reason != SubscriptionDroppedReason.Disposed) + _firstEventSource.TrySetException(ex!); + }, + TestCredentials.Root + ); public override Task DisposeAsync() { _subscription?.Dispose(); diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/connect_to_existing_without_permissions.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/connect_to_existing_without_permissions.cs index abcebe909..72c556bf6 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/connect_to_existing_without_permissions.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/connect_to_existing_without_permissions.cs @@ -1,27 +1,30 @@ -namespace EventStore.Client.SubscriptionToAll; +namespace EventStore.Client.SubscriptionToAll; public class connect_to_existing_without_permissions : IClassFixture { - - private readonly Fixture _fixture; - public connect_to_existing_without_permissions(Fixture fixture) { _fixture = fixture; } + readonly Fixture _fixture; + public connect_to_existing_without_permissions(Fixture fixture) => _fixture = fixture; [SupportsPSToAll.Fact] public Task throws_access_denied() => - Assert.ThrowsAsync(async () => { - using var _ = await _fixture.Client.SubscribeToAllAsync("agroupname55", - delegate { return Task.CompletedTask; }); - }).WithTimeout(); + Assert.ThrowsAsync( + async () => { + using var _ = await _fixture.Client.SubscribeToAllAsync( + "agroupname55", + delegate { return Task.CompletedTask; } + ); + } + ).WithTimeout(); public class Fixture : EventStoreClientFixture { - public Fixture () : base(noDefaultCredentials: true){ - } - + public Fixture() : base(noDefaultCredentials: true) { } + protected override Task Given() => Client.CreateToAllAsync( "agroupname55", - new PersistentSubscriptionSettings(), - userCredentials: TestCredentials.Root); + new(), + userCredentials: TestCredentials.Root + ); protected override Task When() => Task.CompletedTask; } diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/connect_to_existing_without_read_all_permissions.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/connect_to_existing_without_read_all_permissions.cs index 5f6446c59..bad4e7443 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/connect_to_existing_without_read_all_permissions.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/connect_to_existing_without_read_all_permissions.cs @@ -1,27 +1,31 @@ -namespace EventStore.Client.SubscriptionToAll; +namespace EventStore.Client.SubscriptionToAll; public class connect_to_existing_without_read_all_permissions : IClassFixture { - - private readonly Fixture _fixture; - public connect_to_existing_without_read_all_permissions(Fixture fixture) { _fixture = fixture; } + readonly Fixture _fixture; + public connect_to_existing_without_read_all_permissions(Fixture fixture) => _fixture = fixture; [SupportsPSToAll.Fact] public Task throws_access_denied() => - Assert.ThrowsAsync(async () => { - using var _ = await _fixture.Client.SubscribeToAllAsync("agroupname55", - delegate { return Task.CompletedTask; }, userCredentials: TestCredentials.TestUser1); - }).WithTimeout(); + Assert.ThrowsAsync( + async () => { + using var _ = await _fixture.Client.SubscribeToAllAsync( + "agroupname55", + delegate { return Task.CompletedTask; }, + userCredentials: TestCredentials.TestUser1 + ); + } + ).WithTimeout(); public class Fixture : EventStoreClientFixture { - public Fixture () : base(noDefaultCredentials: true){ - } - + public Fixture() : base(noDefaultCredentials: true) { } + protected override Task Given() => Client.CreateToAllAsync( "agroupname55", - new PersistentSubscriptionSettings(), - userCredentials: TestCredentials.Root); + new(), + userCredentials: TestCredentials.Root + ); protected override Task When() => Task.CompletedTask; } diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/connect_to_non_existing_with_permissions.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/connect_to_non_existing_with_permissions.cs index 20adb1194..eb2cde2ec 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/connect_to_non_existing_with_permissions.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/connect_to_non_existing_with_permissions.cs @@ -1,26 +1,24 @@ -namespace EventStore.Client.SubscriptionToAll; +namespace EventStore.Client.SubscriptionToAll; public class connect_to_non_existing_with_permissions : IClassFixture { + const string Group = "foo"; - private const string Group = "foo"; + readonly Fixture _fixture; - private readonly Fixture _fixture; - - public connect_to_non_existing_with_permissions(Fixture fixture) { - _fixture = fixture; - } + public connect_to_non_existing_with_permissions(Fixture fixture) => _fixture = fixture; [SupportsPSToAll.Fact] public async Task throws_persistent_subscription_not_found() { - var ex = await Assert.ThrowsAsync(async () => { - using var _ = await _fixture.Client.SubscribeToAllAsync( - Group, - delegate { - return Task.CompletedTask; - }, - userCredentials: TestCredentials.Root); - }).WithTimeout(); + var ex = await Assert.ThrowsAsync( + async () => { + using var _ = await _fixture.Client.SubscribeToAllAsync( + Group, + delegate { return Task.CompletedTask; }, + userCredentials: TestCredentials.Root + ); + } + ).WithTimeout(); Assert.Equal(SystemStreams.AllStream, ex.StreamName); Assert.Equal(Group, ex.GroupName); diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/connect_with_retries.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/connect_with_retries.cs index 73f1885ca..19bef49cd 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/connect_with_retries.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/connect_with_retries.cs @@ -1,46 +1,51 @@ -namespace EventStore.Client.SubscriptionToAll; +namespace EventStore.Client.SubscriptionToAll; public class connect_with_retries : IClassFixture { - private readonly Fixture _fixture; - private const string Group = "retries"; + const string Group = "retries"; + readonly Fixture _fixture; - - public connect_with_retries(Fixture fixture) { - _fixture = fixture; - } + public connect_with_retries(Fixture fixture) => _fixture = fixture; [SupportsPSToAll.Fact] - public async Task events_are_retried_until_success() { - Assert.Equal(5, await _fixture.RetryCount.WithTimeout()); - } + public async Task events_are_retried_until_success() => Assert.Equal(5, await _fixture.RetryCount.WithTimeout()); public class Fixture : EventStoreClientFixture { - private readonly TaskCompletionSource _retryCountSource; - public Task RetryCount => _retryCountSource.Task; - private PersistentSubscription? _subscription; + readonly TaskCompletionSource _retryCountSource; + PersistentSubscription? _subscription; - public Fixture() { - _retryCountSource = new TaskCompletionSource(); - } + public Fixture() => _retryCountSource = new(); + + public Task RetryCount => _retryCountSource.Task; protected override async Task Given() { - await Client.CreateToAllAsync(Group, - new PersistentSubscriptionSettings(startFrom: Position.Start), userCredentials: TestCredentials.Root); - _subscription = await Client.SubscribeToAllAsync(Group, - async (subscription, e, r, ct) => { - if (r > 4) { - _retryCountSource.TrySetResult(r.Value); - await subscription.Ack(e.Event.EventId); - } else { - await subscription.Nack(PersistentSubscriptionNakEventAction.Retry, - "Not yet tried enough times", e); - } - }, subscriptionDropped: (subscription, reason, ex) => { - if (reason != SubscriptionDroppedReason.Disposed) { - _retryCountSource.TrySetException(ex!); - } - }, userCredentials:TestCredentials.Root); + await Client.CreateToAllAsync( + Group, + new(startFrom: Position.Start), + userCredentials: TestCredentials.Root + ); + + _subscription = await Client.SubscribeToAllAsync( + Group, + async (subscription, e, r, ct) => { + if (r > 4) { + _retryCountSource.TrySetResult(r.Value); + await subscription.Ack(e.Event.EventId); + } + else { + await subscription.Nack( + PersistentSubscriptionNakEventAction.Retry, + "Not yet tried enough times", + e + ); + } + }, + (subscription, reason, ex) => { + if (reason != SubscriptionDroppedReason.Disposed) + _retryCountSource.TrySetException(ex!); + }, + TestCredentials.Root + ); } protected override Task When() => Task.CompletedTask; diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/create_after_deleting_the_same.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/create_after_deleting_the_same.cs index 823cadaea..040ca67c2 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/create_after_deleting_the_same.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/create_after_deleting_the_same.cs @@ -1,27 +1,32 @@ -namespace EventStore.Client.SubscriptionToAll; +namespace EventStore.Client.SubscriptionToAll; -public class create_after_deleting_the_same - : IClassFixture { - public create_after_deleting_the_same(Fixture fixture) { - _fixture = fixture; - } +public class create_after_deleting_the_same : IClassFixture { + readonly Fixture _fixture; + public create_after_deleting_the_same(Fixture fixture) => _fixture = fixture; - private readonly Fixture _fixture; + [SupportsPSToAll.Fact] + public async Task the_completion_succeeds() => + await _fixture.Client.CreateToAllAsync( + "existing", + new(), + userCredentials: TestCredentials.Root + ); public class Fixture : EventStoreClientFixture { protected override Task Given() => Task.CompletedTask; protected override async Task When() { - await Client.CreateToAllAsync("existing", - new PersistentSubscriptionSettings(), userCredentials: TestCredentials.Root); - await Client.DeleteToAllAsync("existing", - userCredentials: TestCredentials.Root); + await Client.CreateToAllAsync( + "existing", + new(), + userCredentials: TestCredentials.Root + ); + + await Client.DeleteToAllAsync( + "existing", + userCredentials: TestCredentials.Root + ); } } - - [SupportsPSToAll.Fact] - public async Task the_completion_succeeds() => - await _fixture.Client.CreateToAllAsync("existing", - new PersistentSubscriptionSettings(), userCredentials: TestCredentials.Root); } \ No newline at end of file diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/create_duplicate.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/create_duplicate.cs index 89a05bc09..e0aafd338 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/create_duplicate.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/create_duplicate.cs @@ -1,30 +1,33 @@ using Grpc.Core; -namespace EventStore.Client.SubscriptionToAll; +namespace EventStore.Client.SubscriptionToAll; -public class create_duplicate - : IClassFixture { - public create_duplicate(Fixture fixture) { - _fixture = fixture; - } +public class create_duplicate : IClassFixture { + readonly Fixture _fixture; + public create_duplicate(Fixture fixture) => _fixture = fixture; - private readonly Fixture _fixture; + [SupportsPSToAll.Fact] + public async Task the_completion_fails() { + var ex = await Assert.ThrowsAsync( + () => _fixture.Client.CreateToAllAsync( + "group32", + new(), + userCredentials: TestCredentials.Root + ) + ); + + Assert.Equal(StatusCode.AlreadyExists, ex.StatusCode); + } public class Fixture : EventStoreClientFixture { protected override Task Given() => Task.CompletedTask; protected override Task When() => - Client.CreateToAllAsync("group32", - new PersistentSubscriptionSettings(), userCredentials: TestCredentials.Root); - } - - [SupportsPSToAll.Fact] - public async Task the_completion_fails() { - var ex = await Assert.ThrowsAsync( - () => _fixture.Client.CreateToAllAsync("group32", - new PersistentSubscriptionSettings(), - userCredentials: TestCredentials.Root)); - Assert.Equal(StatusCode.AlreadyExists, ex.StatusCode); + Client.CreateToAllAsync( + "group32", + new(), + userCredentials: TestCredentials.Root + ); } } \ No newline at end of file diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/create_filtered.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/create_filtered.cs index 309089ea1..815023ca1 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/create_filtered.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/create_filtered.cs @@ -1,26 +1,27 @@ -namespace EventStore.Client.SubscriptionToAll; +namespace EventStore.Client.SubscriptionToAll; public class create_filtered : IClassFixture { - public create_filtered(Fixture fixture) { - _fixture = fixture; - } + readonly Fixture _fixture; + + public create_filtered(Fixture fixture) => _fixture = fixture; - private readonly Fixture _fixture; - public static IEnumerable FilterCases() => Filters.All.Select(filter => new object[] {filter}); + public static IEnumerable FilterCases() => Filters.All.Select(filter => new object[] { filter }); - [SupportsPSToAll.Theory, MemberData(nameof(FilterCases))] + [SupportsPSToAll.Theory] + [MemberData(nameof(FilterCases))] public async Task the_completion_succeeds(string filterName) { var streamPrefix = _fixture.GetStreamName(); var (getFilter, _) = Filters.GetFilter(filterName); var filter = getFilter(streamPrefix); - + await _fixture.Client.CreateToAllAsync( filterName, filter, - new PersistentSubscriptionSettings(), - userCredentials: TestCredentials.Root); + new(), + userCredentials: TestCredentials.Root + ); } - + public class Fixture : EventStoreClientFixture { protected override Task Given() => Task.CompletedTask; protected override Task When() => Task.CompletedTask; diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/create_on_all_stream.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/create_on_all_stream.cs index 365b6f742..48cb92377 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/create_on_all_stream.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/create_on_all_stream.cs @@ -1,25 +1,21 @@ -namespace EventStore.Client.SubscriptionToAll; +namespace EventStore.Client.SubscriptionToAll; -public class create_on_all_stream - : IClassFixture { - public create_on_all_stream(Fixture fixture) { - _fixture = fixture; - } +public class create_on_all_stream : IClassFixture { + readonly Fixture _fixture; + + public create_on_all_stream(Fixture fixture) => _fixture = fixture; - private readonly Fixture _fixture; + [SupportsPSToAll.Fact] + public Task the_completion_succeeds() => _fixture.Client.CreateToAllAsync("existing", new(), userCredentials: TestCredentials.Root); + + [SupportsPSToAll.Fact] + public Task throws_argument_exception_if_wrong_start_from_type_passed() => + Assert.ThrowsAsync( + () => _fixture.Client.CreateToAllAsync("existing", new(startFrom: StreamPosition.End), userCredentials: TestCredentials.Root) + ); public class Fixture : EventStoreClientFixture { protected override Task Given() => Task.CompletedTask; protected override Task When() => Task.CompletedTask; } - - [SupportsPSToAll.Fact] - public Task the_completion_succeeds() - => _fixture.Client.CreateToAllAsync( - "existing", new PersistentSubscriptionSettings(), userCredentials: TestCredentials.Root); - - [SupportsPSToAll.Fact] - public Task throws_argument_exception_if_wrong_start_from_type_passed() - => Assert.ThrowsAsync(() => _fixture.Client.CreateToAllAsync( - "existing", new PersistentSubscriptionSettings(startFrom: StreamPosition.End), userCredentials: TestCredentials.Root)); } \ No newline at end of file diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/create_persistent_subscription_with_dont_timeout.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/create_persistent_subscription_with_dont_timeout.cs index d73d3e78f..23a2a562e 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/create_persistent_subscription_with_dont_timeout.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/create_persistent_subscription_with_dont_timeout.cs @@ -1,22 +1,21 @@ -namespace EventStore.Client.SubscriptionToAll; +namespace EventStore.Client.SubscriptionToAll; public class create_with_dont_timeout : IClassFixture { - public create_with_dont_timeout(Fixture fixture) { - _fixture = fixture; - } + readonly Fixture _fixture; + public create_with_dont_timeout(Fixture fixture) => _fixture = fixture; - private readonly Fixture _fixture; + [SupportsPSToAll.Fact] + public Task the_subscription_is_created_without_error() => + _fixture.Client.CreateToAllAsync( + "dont-timeout", + new(messageTimeout: TimeSpan.Zero), + userCredentials: TestCredentials.Root + ); public class Fixture : EventStoreClientFixture { protected override Task Given() => Task.CompletedTask; protected override Task When() => Task.CompletedTask; } - - [SupportsPSToAll.Fact] - public Task the_subscription_is_created_without_error() => - _fixture.Client.CreateToAllAsync("dont-timeout", - new PersistentSubscriptionSettings(messageTimeout: TimeSpan.Zero), - userCredentials: TestCredentials.Root); } \ No newline at end of file diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/create_with_commit_position_equal_to_last_indexed_position.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/create_with_commit_position_equal_to_last_indexed_position.cs index fdaf9370c..4db5332bb 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/create_with_commit_position_equal_to_last_indexed_position.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/create_with_commit_position_equal_to_last_indexed_position.cs @@ -1,28 +1,32 @@ -namespace EventStore.Client.SubscriptionToAll; +namespace EventStore.Client.SubscriptionToAll; -public class create_with_commit_position_equal_to_last_indexed_position - : IClassFixture { - public create_with_commit_position_equal_to_last_indexed_position(Fixture fixture) { - _fixture = fixture; - } +public class create_with_commit_position_equal_to_last_indexed_position : IClassFixture { + readonly Fixture _fixture; + public create_with_commit_position_equal_to_last_indexed_position(Fixture fixture) => _fixture = fixture; - private readonly Fixture _fixture; + [SupportsPSToAll.Fact] + public async Task the_completion_succeeds() => + await _fixture.Client.CreateToAllAsync( + "group57", + new(startFrom: new Position(_fixture.LastCommitPosition, _fixture.LastCommitPosition)), + userCredentials: TestCredentials.Root + ); public class Fixture : EventStoreClientFixture { public ulong LastCommitPosition; + protected override async Task Given() { - var lastEvent = await StreamsClient.ReadAllAsync(Direction.Backwards, Position.End, 1, - userCredentials: TestCredentials.Root).FirstAsync(); - LastCommitPosition = lastEvent.OriginalPosition?.CommitPosition ?? throw new Exception(); + var lastEvent = await StreamsClient.ReadAllAsync( + Direction.Backwards, + Position.End, + 1, + userCredentials: TestCredentials.Root + ).FirstAsync(); + + LastCommitPosition = lastEvent.OriginalPosition?.CommitPosition ?? throw new(); } + protected override Task When() => Task.CompletedTask; } - - [SupportsPSToAll.Fact] - public async Task the_completion_succeeds() => - await _fixture.Client.CreateToAllAsync("group57", - new PersistentSubscriptionSettings( - startFrom: new Position(_fixture.LastCommitPosition, _fixture.LastCommitPosition)), - userCredentials: TestCredentials.Root); } \ No newline at end of file diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/create_with_commit_position_larger_than_last_indexed_position.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/create_with_commit_position_larger_than_last_indexed_position.cs index a49c4796a..d012ce754 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/create_with_commit_position_larger_than_last_indexed_position.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/create_with_commit_position_larger_than_last_indexed_position.cs @@ -1,33 +1,41 @@ using Grpc.Core; -namespace EventStore.Client.SubscriptionToAll; +namespace EventStore.Client.SubscriptionToAll; public class create_with_commit_position_larger_than_last_indexed_position : IClassFixture { - public create_with_commit_position_larger_than_last_indexed_position(Fixture fixture) { - _fixture = fixture; - } + readonly Fixture _fixture; + public create_with_commit_position_larger_than_last_indexed_position(Fixture fixture) => _fixture = fixture; - private readonly Fixture _fixture; + [SupportsPSToAll.Fact] + public async Task fails() { + var ex = await Assert.ThrowsAsync( + () => + _fixture.Client.CreateToAllAsync( + "group57", + new(startFrom: new Position(_fixture.LastCommitPosition + 1, _fixture.LastCommitPosition)), + userCredentials: TestCredentials.Root + ) + ); + + Assert.Equal(StatusCode.Internal, ex.StatusCode); + } public class Fixture : EventStoreClientFixture { public ulong LastCommitPosition; + protected override async Task Given() { - var lastEvent = await StreamsClient.ReadAllAsync(Direction.Backwards, Position.End, 1, - userCredentials: TestCredentials.Root).FirstAsync(); - LastCommitPosition = lastEvent.OriginalPosition?.CommitPosition ?? throw new Exception(); + var lastEvent = await StreamsClient.ReadAllAsync( + Direction.Backwards, + Position.End, + 1, + userCredentials: TestCredentials.Root + ).FirstAsync(); + + LastCommitPosition = lastEvent.OriginalPosition?.CommitPosition ?? throw new(); } - protected override Task When() => Task.CompletedTask; - } - [SupportsPSToAll.Fact] - public async Task fails() { - var ex = await Assert.ThrowsAsync(() => - _fixture.Client.CreateToAllAsync("group57", - new PersistentSubscriptionSettings( - startFrom: new Position(_fixture.LastCommitPosition + 1, _fixture.LastCommitPosition)), - userCredentials: TestCredentials.Root)); - Assert.Equal(StatusCode.Internal, ex.StatusCode); + protected override Task When() => Task.CompletedTask; } } \ No newline at end of file diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/create_with_prepare_position_larger_than_commit_position.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/create_with_prepare_position_larger_than_commit_position.cs index 1c903c2f2..41327e9c0 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/create_with_prepare_position_larger_than_commit_position.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/create_with_prepare_position_larger_than_commit_position.cs @@ -1,24 +1,24 @@ -namespace EventStore.Client.SubscriptionToAll; +namespace EventStore.Client.SubscriptionToAll; public class create_with_prepare_position_larger_than_commit_position : IClassFixture { - public create_with_prepare_position_larger_than_commit_position(Fixture fixture) { - _fixture = fixture; - } + readonly Fixture _fixture; + public create_with_prepare_position_larger_than_commit_position(Fixture fixture) => _fixture = fixture; - private readonly Fixture _fixture; + [SupportsPSToAll.Fact] + public Task fails_with_argument_out_of_range_exception() => + Assert.ThrowsAsync( + () => + _fixture.Client.CreateToAllAsync( + "group57", + new(startFrom: new Position(0, 1)), + userCredentials: TestCredentials.Root + ) + ); public class Fixture : EventStoreClientFixture { protected override Task Given() => Task.CompletedTask; protected override Task When() => Task.CompletedTask; } - - [SupportsPSToAll.Fact] - public Task fails_with_argument_out_of_range_exception() => - Assert.ThrowsAsync(() => - _fixture.Client.CreateToAllAsync("group57", - new PersistentSubscriptionSettings( - startFrom: new Position(0, 1)), - userCredentials: TestCredentials.Root)); } \ No newline at end of file diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/create_without_permissions.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/create_without_permissions.cs index 08dab381f..45c398cbb 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/create_without_permissions.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/create_without_permissions.cs @@ -1,25 +1,25 @@ -namespace EventStore.Client.SubscriptionToAll; +namespace EventStore.Client.SubscriptionToAll; public class create_without_permissions : IClassFixture { - public create_without_permissions(Fixture fixture) { - _fixture = fixture; - } + readonly Fixture _fixture; + public create_without_permissions(Fixture fixture) => _fixture = fixture; - private readonly Fixture _fixture; + [SupportsPSToAll.Fact] + public Task the_completion_fails_with_access_denied() => + Assert.ThrowsAsync( + () => + _fixture.Client.CreateToAllAsync( + "group57", + new() + ) + ); public class Fixture : EventStoreClientFixture { - public Fixture () : base(noDefaultCredentials: true){ - } - + public Fixture() : base(noDefaultCredentials: true) { } + protected override Task Given() => Task.CompletedTask; protected override Task When() => Task.CompletedTask; } - - [SupportsPSToAll.Fact] - public Task the_completion_fails_with_access_denied() => - Assert.ThrowsAsync(() => - _fixture.Client.CreateToAllAsync("group57", - new PersistentSubscriptionSettings())); } \ No newline at end of file diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/deleting_existing_with_permissions.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/deleting_existing_with_permissions.cs index b6b1d537a..64eb4d326 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/deleting_existing_with_permissions.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/deleting_existing_with_permissions.cs @@ -1,25 +1,26 @@ -namespace EventStore.Client.SubscriptionToAll; +namespace EventStore.Client.SubscriptionToAll; public class deleting_existing_with_permissions : IClassFixture { + readonly Fixture _fixture; - private readonly Fixture _fixture; + public deleting_existing_with_permissions(Fixture fixture) => _fixture = fixture; - public deleting_existing_with_permissions(Fixture fixture) { - _fixture = fixture; - } + [SupportsPSToAll.Fact] + public Task the_delete_of_group_succeeds() => + _fixture.Client.DeleteToAllAsync( + "groupname123", + userCredentials: TestCredentials.Root + ); public class Fixture : EventStoreClientFixture { protected override Task Given() => Task.CompletedTask; protected override Task When() => - Client.CreateToAllAsync("groupname123", - new PersistentSubscriptionSettings(), - userCredentials: TestCredentials.Root); + Client.CreateToAllAsync( + "groupname123", + new(), + userCredentials: TestCredentials.Root + ); } - - [SupportsPSToAll.Fact] - public Task the_delete_of_group_succeeds() => - _fixture.Client.DeleteToAllAsync("groupname123", - userCredentials: TestCredentials.Root); } \ No newline at end of file diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/deleting_existing_with_subscriber.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/deleting_existing_with_subscriber.cs index 813ab9c9f..522027966 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/deleting_existing_with_subscriber.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/deleting_existing_with_subscriber.cs @@ -1,42 +1,10 @@ -namespace EventStore.Client.SubscriptionToAll; +namespace EventStore.Client.SubscriptionToAll; public class deleting_existing_with_subscriber : IClassFixture { - private readonly Fixture _fixture; + readonly Fixture _fixture; - public deleting_existing_with_subscriber(Fixture fixture) { - _fixture = fixture; - } - - public class Fixture : EventStoreClientFixture { - public Task<(SubscriptionDroppedReason, Exception?)> Dropped => _dropped.Task; - private readonly TaskCompletionSource<(SubscriptionDroppedReason, Exception?)> _dropped; - private PersistentSubscription? _subscription; - - public Fixture() { - _dropped = new TaskCompletionSource<(SubscriptionDroppedReason, Exception?)>(); - } - - protected override async Task Given() { - await Client.CreateToAllAsync("groupname123", - new PersistentSubscriptionSettings(), - userCredentials: TestCredentials.Root); - _subscription = await Client.SubscribeToAllAsync("groupname123", - async (s, e, i, ct) => await s.Ack(e), - (s, r, e) => _dropped.TrySetResult((r, e)), userCredentials: TestCredentials.Root); - // todo: investigate why this test is flaky without this delay - await Task.Delay(500); - } - - protected override Task When() => - Client.DeleteToAllAsync("groupname123", - userCredentials: TestCredentials.Root); - - public override Task DisposeAsync() { - _subscription?.Dispose(); - return base.DisposeAsync(); - } - } + public deleting_existing_with_subscriber(Fixture fixture) => _fixture = fixture; [SupportsPSToAll.Fact] public async Task the_subscription_is_dropped() { @@ -47,7 +15,7 @@ public async Task the_subscription_is_dropped() { Assert.Equal("groupname123", ex.GroupName); } - [Fact (Skip = "Isn't this how it should work?")] + [Fact(Skip = "Isn't this how it should work?")] public async Task the_subscription_is_dropped_with_not_found() { var (reason, exception) = await _fixture.Dropped.WithTimeout(); Assert.Equal(SubscriptionDroppedReason.ServerError, reason); @@ -55,4 +23,42 @@ public async Task the_subscription_is_dropped_with_not_found() { Assert.Equal(SystemStreams.AllStream, ex.StreamName); Assert.Equal("groupname123", ex.GroupName); } + + public class Fixture : EventStoreClientFixture { + readonly TaskCompletionSource<(SubscriptionDroppedReason, Exception?)> _dropped; + PersistentSubscription? _subscription; + + public Fixture() => _dropped = new(); + + public Task<(SubscriptionDroppedReason, Exception?)> Dropped => _dropped.Task; + + protected override async Task Given() { + await Client.CreateToAllAsync( + "groupname123", + new(), + userCredentials: TestCredentials.Root + ); + + _subscription = await Client.SubscribeToAllAsync( + "groupname123", + async (s, e, i, ct) => await s.Ack(e), + (s, r, e) => _dropped.TrySetResult((r, e)), + TestCredentials.Root + ); + + // todo: investigate why this test is flaky without this delay + await Task.Delay(500); + } + + protected override Task When() => + Client.DeleteToAllAsync( + "groupname123", + userCredentials: TestCredentials.Root + ); + + public override Task DisposeAsync() { + _subscription?.Dispose(); + return base.DisposeAsync(); + } + } } \ No newline at end of file diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/deleting_filtered.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/deleting_filtered.cs index 31e17f1bf..103706400 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/deleting_filtered.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/deleting_filtered.cs @@ -1,28 +1,23 @@ -namespace EventStore.Client.SubscriptionToAll; +namespace EventStore.Client.SubscriptionToAll; public class deleting_filtered : IClassFixture { + const string Group = "to-be-deleted"; + readonly Fixture _fixture; - private const string Group = "to-be-deleted"; - private readonly Fixture _fixture; - - public deleting_filtered(Fixture fixture) { - _fixture = fixture; - } + public deleting_filtered(Fixture fixture) => _fixture = fixture; [SupportsPSToAll.Fact] - public async Task the_completion_succeeds() { - await _fixture.Client.DeleteToAllAsync(Group, userCredentials: TestCredentials.Root); - } + public async Task the_completion_succeeds() => await _fixture.Client.DeleteToAllAsync(Group, userCredentials: TestCredentials.Root); public class Fixture : EventStoreClientFixture { - protected override async Task Given() { + protected override async Task Given() => await Client.CreateToAllAsync( Group, EventTypeFilter.Prefix("prefix-filter-"), - new PersistentSubscriptionSettings(), - userCredentials: TestCredentials.Root); - } + new(), + userCredentials: TestCredentials.Root + ); protected override Task When() => Task.CompletedTask; } diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/deleting_nonexistent.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/deleting_nonexistent.cs index 38d44931e..f36413d44 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/deleting_nonexistent.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/deleting_nonexistent.cs @@ -1,20 +1,16 @@ -namespace EventStore.Client.SubscriptionToAll; +namespace EventStore.Client.SubscriptionToAll; public class deleting_nonexistent : IClassFixture { - private readonly Fixture _fixture; + readonly Fixture _fixture; - - public deleting_nonexistent(Fixture fixture) { - _fixture = fixture; - } + public deleting_nonexistent(Fixture fixture) => _fixture = fixture; [SupportsPSToAll.Fact] - public async Task the_delete_fails_with_argument_exception() { + public async Task the_delete_fails_with_argument_exception() => await Assert.ThrowsAsync( - () => _fixture.Client.DeleteToAllAsync( - Guid.NewGuid().ToString(), userCredentials: TestCredentials.Root)); - } + () => _fixture.Client.DeleteToAllAsync(Guid.NewGuid().ToString(), userCredentials: TestCredentials.Root) + ); public class Fixture : EventStoreClientFixture { protected override Task Given() => Task.CompletedTask; diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/deleting_without_permissions.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/deleting_without_permissions.cs index 7354e0031..8ebff65fe 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/deleting_without_permissions.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/deleting_without_permissions.cs @@ -1,25 +1,18 @@ -namespace EventStore.Client.SubscriptionToAll; +namespace EventStore.Client.SubscriptionToAll; public class deleting_without_permissions : IClassFixture { - private readonly Fixture _fixture; + readonly Fixture _fixture; - - public deleting_without_permissions(Fixture fixture) { - _fixture = fixture; - } + public deleting_without_permissions(Fixture fixture) => _fixture = fixture; [SupportsPSToAll.Fact] - public async Task the_delete_fails_with_access_denied() { - await Assert.ThrowsAsync( - () => _fixture.Client.DeleteToAllAsync( - Guid.NewGuid().ToString())); - } + public async Task the_delete_fails_with_access_denied() => + await Assert.ThrowsAsync(() => _fixture.Client.DeleteToAllAsync(Guid.NewGuid().ToString())); public class Fixture : EventStoreClientFixture { - public Fixture () : base(noDefaultCredentials: true){ - } - + public Fixture() : base(noDefaultCredentials: true) { } + protected override Task Given() => Task.CompletedTask; protected override Task When() => Task.CompletedTask; } diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/get_info.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/get_info.cs index b63d140de..432824946 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/get_info.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/get_info.cs @@ -1,38 +1,36 @@ -namespace EventStore.Client.SubscriptionToAll; +namespace EventStore.Client.SubscriptionToAll; public class get_info : IClassFixture { - private readonly Fixture _fixture; - private const string GroupName = nameof(get_info); - private static readonly PersistentSubscriptionSettings _settings = new( - resolveLinkTos: true, - startFrom: Position.Start, - extraStatistics: true, - messageTimeout: TimeSpan.FromSeconds(9), - maxRetryCount: 11, - liveBufferSize: 303, - readBatchSize: 30, - historyBufferSize: 909, - checkPointAfter: TimeSpan.FromSeconds(1), - checkPointLowerBound: 1, - checkPointUpperBound: 1, - maxSubscriberCount: 500, - consumerStrategyName: SystemConsumerStrategies.Pinned + const string GroupName = nameof(get_info); + + static readonly PersistentSubscriptionSettings _settings = new( + true, + Position.Start, + true, + TimeSpan.FromSeconds(9), + 11, + 303, + 30, + 909, + TimeSpan.FromSeconds(1), + 1, + 1, + 500, + SystemConsumerStrategies.Pinned ); - - public get_info(Fixture fixture) { - _fixture = fixture; - } + + readonly Fixture _fixture; + + public get_info(Fixture fixture) => _fixture = fixture; [Fact] public async Task throws_when_not_supported() { - if (SupportsPSToAll.No) { - - await Assert.ThrowsAsync(async () => { - await _fixture.Client.GetInfoToAllAsync(GroupName, userCredentials: TestCredentials.Root); - }); - } + if (SupportsPSToAll.No) + await Assert.ThrowsAsync( + async () => { await _fixture.Client.GetInfoToAllAsync(GroupName, userCredentials: TestCredentials.Root); } + ); } - + [SupportsPSToAll.Fact] public async Task returns_expected_result() { var result = await _fixture.Client.GetInfoToAllAsync(GroupName, userCredentials: TestCredentials.Root); @@ -40,7 +38,7 @@ public async Task returns_expected_result() { Assert.Equal("$all", result.EventSource); Assert.Equal(GroupName, result.GroupName); Assert.Equal("Live", result.Status); - + Assert.NotNull(_settings.StartFrom); Assert.True(result.Stats.TotalItems > 0); Assert.True(result.Stats.OutstandingMessagesCount > 0); @@ -67,7 +65,7 @@ public async Task returns_expected_result() { Assert.True(connection.InFlightMessages >= 0); Assert.NotNull(connection.ExtraStatistics); Assert.NotEmpty(connection.ExtraStatistics); - + AssertKeyAndValue(connection.ExtraStatistics, PersistentSubscriptionExtraStatistic.Highest); AssertKeyAndValue(connection.ExtraStatistics, PersistentSubscriptionExtraStatistic.Mean); AssertKeyAndValue(connection.ExtraStatistics, PersistentSubscriptionExtraStatistic.Median); @@ -82,7 +80,7 @@ public async Task returns_expected_result() { AssertKeyAndValue(connection.ExtraStatistics, PersistentSubscriptionExtraStatistic.NinetyNinePercent); AssertKeyAndValue(connection.ExtraStatistics, PersistentSubscriptionExtraStatistic.NinetyNinePointFivePercent); AssertKeyAndValue(connection.ExtraStatistics, PersistentSubscriptionExtraStatistic.NinetyNinePointNinePercent); - + Assert.NotNull(result.Settings); Assert.Equal(_settings.StartFrom, result.Settings!.StartFrom); Assert.Equal(_settings.ResolveLinkTos, result.Settings!.ResolveLinkTos); @@ -98,87 +96,86 @@ public async Task returns_expected_result() { Assert.Equal(_settings.MaxSubscriberCount, result.Settings!.MaxSubscriberCount); Assert.Equal(_settings.ConsumerStrategyName, result.Settings!.ConsumerStrategyName); } - + [SupportsPSToAll.Fact] - public async Task throws_with_non_existing_subscription() { - await Assert.ThrowsAsync(async () => { - await _fixture.Client.GetInfoToAllAsync( - groupName: "NonExisting", - userCredentials: TestCredentials.Root); - }); - } + public async Task throws_with_non_existing_subscription() => + await Assert.ThrowsAsync( + async () => { + await _fixture.Client.GetInfoToAllAsync( + "NonExisting", + userCredentials: TestCredentials.Root + ); + } + ); [SupportsPSToAll.Fact] - public async Task throws_with_no_credentials() { - await Assert.ThrowsAsync(async () => { - await _fixture.Client.GetInfoToAllAsync("NonExisting"); - }); - } - + public async Task throws_with_no_credentials() => + await Assert.ThrowsAsync(async () => { await _fixture.Client.GetInfoToAllAsync("NonExisting"); }); + [SupportsPSToAll.Fact] - public async Task throws_with_non_existing_user() { - await Assert.ThrowsAsync(async () => { - await _fixture.Client.GetInfoToAllAsync( - groupName: "NonExisting", - userCredentials: TestCredentials.TestBadUser); - }); - } - + public async Task throws_with_non_existing_user() => + await Assert.ThrowsAsync( + async () => { + await _fixture.Client.GetInfoToAllAsync( + "NonExisting", + userCredentials: TestCredentials.TestBadUser + ); + } + ); + [SupportsPSToAll.Fact] public async Task returns_result_with_normal_user_credentials() { var result = await _fixture.Client.GetInfoToAllAsync( - groupName: GroupName, - userCredentials: TestCredentials.TestUser1); - + GroupName, + userCredentials: TestCredentials.TestUser1 + ); + Assert.Equal("$all", result.EventSource); } - + + void AssertKeyAndValue(IDictionary items, string key) { + Assert.True(items.ContainsKey(key)); + Assert.True(items[key] > 0); + } + public class Fixture : EventStoreClientFixture { - public Fixture () : base(noDefaultCredentials: true){ - } - + public Fixture() : base(noDefaultCredentials: true) { } + protected override async Task Given() { - if (SupportsPSToAll.No) { + if (SupportsPSToAll.No) return; - } - + await Client.CreateToAllAsync( - groupName: GroupName, - settings: _settings, - userCredentials: TestCredentials.Root); + GroupName, + _settings, + userCredentials: TestCredentials.Root + ); } protected override async Task When() { - if (SupportsPSToAll.No) { + if (SupportsPSToAll.No) return; - } var counter = 0; var tcs = new TaskCompletionSource(); await Client.SubscribeToAllAsync( GroupName, - eventAppeared: (s, e, r, ct) => { + (s, e, r, ct) => { counter++; - - if (counter == 1) { + + if (counter == 1) s.Nack(PersistentSubscriptionNakEventAction.Park, "Test", e); - } - - if (counter > 10) { + + if (counter > 10) tcs.TrySetResult(); - } - + return Task.CompletedTask; }, - userCredentials: TestCredentials.Root); + userCredentials: TestCredentials.Root + ); await tcs.Task; } } - - private void AssertKeyAndValue(IDictionary items, string key) { - Assert.True(items.ContainsKey(key)); - Assert.True(items[key] > 0); - } } \ No newline at end of file diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/happy_case_catching_up_to_link_to_events_manual_ack.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/happy_case_catching_up_to_link_to_events_manual_ack.cs index 880e9bf72..7ba3b0640 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/happy_case_catching_up_to_link_to_events_manual_ack.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/happy_case_catching_up_to_link_to_events_manual_ack.cs @@ -1,65 +1,70 @@ using System.Text; -namespace EventStore.Client.SubscriptionToAll; +namespace EventStore.Client.SubscriptionToAll; public class happy_case_catching_up_to_link_to_events_manual_ack : IClassFixture { + const string Group = nameof(Group); + const int BufferCount = 10; + const int EventWriteCount = BufferCount * 2; - private const string Group = nameof(Group); - private const int BufferCount = 10; - private const int EventWriteCount = BufferCount * 2; + readonly Fixture _fixture; - private readonly Fixture _fixture; - - public happy_case_catching_up_to_link_to_events_manual_ack(Fixture fixture) { - _fixture = fixture; - } + public happy_case_catching_up_to_link_to_events_manual_ack(Fixture fixture) => _fixture = fixture; [SupportsPSToAll.Fact] - public async Task Test() { - await _fixture.EventsReceived.WithTimeout(); - } + public async Task Test() => await _fixture.EventsReceived.WithTimeout(); public class Fixture : EventStoreClientFixture { - private readonly EventData[] _events; - private readonly TaskCompletionSource _eventsReceived; - public Task EventsReceived => _eventsReceived.Task; + readonly EventData[] _events; + readonly TaskCompletionSource _eventsReceived; + int _eventReceivedCount; - private PersistentSubscription? _subscription; - private int _eventReceivedCount; + PersistentSubscription? _subscription; public Fixture() { _events = CreateTestEvents(EventWriteCount) - .Select((e, i) => new EventData(e.EventId, SystemEventTypes.LinkTo, - Encoding.UTF8.GetBytes($"{i}@test"), - contentType: Constants.Metadata.ContentTypes.ApplicationOctetStream)) + .Select( + (e, i) => new EventData( + e.EventId, + SystemEventTypes.LinkTo, + Encoding.UTF8.GetBytes($"{i}@test"), + contentType: Constants.Metadata.ContentTypes.ApplicationOctetStream + ) + ) .ToArray(); - _eventsReceived = new TaskCompletionSource(); + + _eventsReceived = new(); } + public Task EventsReceived => _eventsReceived.Task; + protected override async Task Given() { - foreach (var e in _events) { - await StreamsClient.AppendToStreamAsync("test-" + Guid.NewGuid(), StreamState.Any, new[] {e}); - } - - await Client.CreateToAllAsync(Group, - new PersistentSubscriptionSettings(startFrom: Position.Start, resolveLinkTos: true), - userCredentials: TestCredentials.Root); - _subscription = await Client.SubscribeToAllAsync(Group, - async (subscription, e, retryCount, ct) => { - await subscription.Ack(e); - - if (e.OriginalStreamId.StartsWith("test-") - && Interlocked.Increment(ref _eventReceivedCount) == _events.Length) { - _eventsReceived.TrySetResult(true); - } - }, (s, r, e) => { - if (e != null) { - _eventsReceived.TrySetException(e); - } - }, - bufferSize: BufferCount, - userCredentials: TestCredentials.Root); + foreach (var e in _events) + await StreamsClient.AppendToStreamAsync("test-" + Guid.NewGuid(), StreamState.Any, new[] { e }); + + await Client.CreateToAllAsync( + Group, + new(startFrom: Position.Start, resolveLinkTos: true), + userCredentials: TestCredentials.Root + ); + + _subscription = await Client.SubscribeToAllAsync( + Group, + async (subscription, e, retryCount, ct) => { + await subscription.Ack(e); + + if (e.OriginalStreamId.StartsWith("test-") + && Interlocked.Increment(ref _eventReceivedCount) == _events.Length) + _eventsReceived.TrySetResult(true); + }, + (s, r, e) => { + if (e != null) + _eventsReceived.TrySetException(e); + }, + bufferSize: BufferCount, + userCredentials: TestCredentials.Root + ); } protected override Task When() => Task.CompletedTask; diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/happy_case_catching_up_to_normal_events_manual_ack.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/happy_case_catching_up_to_normal_events_manual_ack.cs index 4f69a4fe3..a5bbe1637 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/happy_case_catching_up_to_normal_events_manual_ack.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/happy_case_catching_up_to_normal_events_manual_ack.cs @@ -1,59 +1,57 @@ -namespace EventStore.Client.SubscriptionToAll; +namespace EventStore.Client.SubscriptionToAll; -public class happy_case_catching_up_to_normal_events_manual_ack : - IClassFixture { +public class happy_case_catching_up_to_normal_events_manual_ack : IClassFixture { + const string Group = nameof(Group); + const int BufferCount = 10; + const int EventWriteCount = BufferCount * 2; - private const string Group = nameof(Group); - private const int BufferCount = 10; - private const int EventWriteCount = BufferCount * 2; + readonly Fixture _fixture; - private readonly Fixture _fixture; - - public happy_case_catching_up_to_normal_events_manual_ack(Fixture fixture) { - _fixture = fixture; - } + public happy_case_catching_up_to_normal_events_manual_ack(Fixture fixture) => _fixture = fixture; [SupportsPSToAll.Fact] - public async Task Test() { - await _fixture.EventsReceived.WithTimeout(); - } + public async Task Test() => await _fixture.EventsReceived.WithTimeout(); public class Fixture : EventStoreClientFixture { - private readonly EventData[] _events; - private readonly TaskCompletionSource _eventsReceived; - public Task EventsReceived => _eventsReceived.Task; + readonly EventData[] _events; + readonly TaskCompletionSource _eventsReceived; + int _eventReceivedCount; - private PersistentSubscription? _subscription; - private int _eventReceivedCount; + PersistentSubscription? _subscription; public Fixture() { _events = CreateTestEvents(EventWriteCount).ToArray(); - _eventsReceived = new TaskCompletionSource(); + _eventsReceived = new(); } + public Task EventsReceived => _eventsReceived.Task; + protected override async Task Given() { - foreach (var e in _events) { - await StreamsClient.AppendToStreamAsync("test-" + Guid.NewGuid(), StreamState.Any, new[] {e}); - } + foreach (var e in _events) + await StreamsClient.AppendToStreamAsync("test-" + Guid.NewGuid(), StreamState.Any, new[] { e }); + + await Client.CreateToAllAsync( + Group, + new(startFrom: Position.Start, resolveLinkTos: true), + userCredentials: TestCredentials.Root + ); - await Client.CreateToAllAsync(Group, - new PersistentSubscriptionSettings(startFrom: Position.Start, resolveLinkTos: true), - userCredentials: TestCredentials.Root); - _subscription = await Client.SubscribeToAllAsync(Group, - async(subscription, e, retryCount, ct) => { - await subscription.Ack(e); + _subscription = await Client.SubscribeToAllAsync( + Group, + async (subscription, e, retryCount, ct) => { + await subscription.Ack(e); - if (e.OriginalStreamId.StartsWith("test-") - && Interlocked.Increment(ref _eventReceivedCount) == _events.Length) { - _eventsReceived.TrySetResult(true); - } - }, (s, r, e) => { - if (e != null) { - _eventsReceived.TrySetException(e); - } - }, - bufferSize: BufferCount, - userCredentials: TestCredentials.Root); + if (e.OriginalStreamId.StartsWith("test-") + && Interlocked.Increment(ref _eventReceivedCount) == _events.Length) + _eventsReceived.TrySetResult(true); + }, + (s, r, e) => { + if (e != null) + _eventsReceived.TrySetException(e); + }, + bufferSize: BufferCount, + userCredentials: TestCredentials.Root + ); } protected override Task When() => Task.CompletedTask; diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/happy_case_filtered.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/happy_case_filtered.cs index 7763ca312..91a8c47a3 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/happy_case_filtered.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/happy_case_filtered.cs @@ -1,57 +1,71 @@ -namespace EventStore.Client.SubscriptionToAll; +namespace EventStore.Client.SubscriptionToAll; public class happy_case_filtered : IClassFixture { - private readonly Fixture _fixture; + readonly Fixture _fixture; - public happy_case_filtered(Fixture fixture) { - _fixture = fixture; - } - - public static IEnumerable FilterCases() => Filters.All.Select(filter => new object[] {filter}); + public happy_case_filtered(Fixture fixture) => _fixture = fixture; + + public static IEnumerable FilterCases() => Filters.All.Select(filter => new object[] { filter }); - [SupportsPSToAll.Theory, MemberData(nameof(FilterCases))] + [SupportsPSToAll.Theory] + [MemberData(nameof(FilterCases))] public async Task reads_all_existing_filtered_events(string filterName) { var streamPrefix = $"{filterName}-{_fixture.GetStreamName()}"; var (getFilter, prepareEvent) = Filters.GetFilter(filterName); var filter = getFilter(streamPrefix); - + var appeared = new TaskCompletionSource(); var appearedEvents = new List(); var events = _fixture.CreateTestEvents(20).Select(e => prepareEvent(streamPrefix, e)).ToArray(); - foreach (var e in events) { - await _fixture.StreamsClient.AppendToStreamAsync($"{streamPrefix}_{Guid.NewGuid():n}", - StreamState.NoStream, new[] {e}); - } - - await _fixture.Client.CreateToAllAsync(filterName, filter, - new PersistentSubscriptionSettings(startFrom: Position.Start), userCredentials: TestCredentials.Root); - - using var subscription = await _fixture.Client.SubscribeToAllAsync(filterName, - eventAppeared: async (s, e, r, ct) => { - appearedEvents.Add(e.Event); - if (appearedEvents.Count >= events.Length) { - appeared.TrySetResult(true); - } - await s.Ack(e); - }, - userCredentials: TestCredentials.Root) + foreach (var e in events) + await _fixture.StreamsClient.AppendToStreamAsync( + $"{streamPrefix}_{Guid.NewGuid():n}", + StreamState.NoStream, + new[] { e } + ); + + await _fixture.Client.CreateToAllAsync( + filterName, + filter, + new(startFrom: Position.Start), + userCredentials: TestCredentials.Root + ); + + using var subscription = await _fixture.Client.SubscribeToAllAsync( + filterName, + async (s, e, r, ct) => { + appearedEvents.Add(e.Event); + if (appearedEvents.Count >= events.Length) + appeared.TrySetResult(true); + + await s.Ack(e); + }, + userCredentials: TestCredentials.Root + ) .WithTimeout(); await Task.WhenAll(appeared.Task).WithTimeout(); - + Assert.Equal(events.Select(x => x.EventId), appearedEvents.Select(x => x.EventId)); } - + public class Fixture : EventStoreClientFixture { protected override async Task Given() { - await StreamsClient.AppendToStreamAsync(Guid.NewGuid().ToString(), StreamState.NoStream, - CreateTestEvents(256)); + await StreamsClient.AppendToStreamAsync( + Guid.NewGuid().ToString(), + StreamState.NoStream, + CreateTestEvents(256) + ); - await StreamsClient.SetStreamMetadataAsync(SystemStreams.AllStream, StreamState.Any, - new StreamMetadata(acl: new StreamAcl(SystemRoles.All)), userCredentials: TestCredentials.Root); + await StreamsClient.SetStreamMetadataAsync( + SystemStreams.AllStream, + StreamState.Any, + new(acl: new(SystemRoles.All)), + userCredentials: TestCredentials.Root + ); } - + protected override Task When() => Task.CompletedTask; } } \ No newline at end of file diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/happy_case_filtered_with_start_from_set.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/happy_case_filtered_with_start_from_set.cs index fc9424e70..8d440f980 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/happy_case_filtered_with_start_from_set.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/happy_case_filtered_with_start_from_set.cs @@ -1,20 +1,19 @@ -namespace EventStore.Client.SubscriptionToAll; +namespace EventStore.Client.SubscriptionToAll; public class happy_case_filtered_with_start_from_set : IClassFixture { - private readonly Fixture _fixture; + readonly Fixture _fixture; - public happy_case_filtered_with_start_from_set(Fixture fixture) { - _fixture = fixture; - } - - public static IEnumerable FilterCases() => Filters.All.Select(filter => new object[] {filter}); + public happy_case_filtered_with_start_from_set(Fixture fixture) => _fixture = fixture; + + public static IEnumerable FilterCases() => Filters.All.Select(filter => new object[] { filter }); - [SupportsPSToAll.Theory, MemberData(nameof(FilterCases))] + [SupportsPSToAll.Theory] + [MemberData(nameof(FilterCases))] public async Task reads_all_existing_filtered_events_from_specified_start(string filterName) { var streamPrefix = $"{filterName}-{_fixture.GetStreamName()}"; var (getFilter, prepareEvent) = Filters.GetFilter(filterName); var filter = getFilter(streamPrefix); - + var appeared = new TaskCompletionSource(); var appearedEvents = new List(); var events = _fixture.CreateTestEvents(20).Select(e => prepareEvent(streamPrefix, e)).ToArray(); @@ -22,45 +21,64 @@ public async Task reads_all_existing_filtered_events_from_specified_start(string var eventsToCapture = events.Skip(10).ToArray(); IWriteResult? eventToCaptureResult = null; - foreach (var e in eventsToSkip) { - await _fixture.StreamsClient.AppendToStreamAsync($"{streamPrefix}_{Guid.NewGuid():n}", - StreamState.NoStream, new[] {e}); - } + foreach (var e in eventsToSkip) + await _fixture.StreamsClient.AppendToStreamAsync( + $"{streamPrefix}_{Guid.NewGuid():n}", + StreamState.NoStream, + new[] { e } + ); + foreach (var e in eventsToCapture) { - var result = await _fixture.StreamsClient.AppendToStreamAsync($"{streamPrefix}_{Guid.NewGuid():n}", - StreamState.NoStream, new[] {e}); + var result = await _fixture.StreamsClient.AppendToStreamAsync( + $"{streamPrefix}_{Guid.NewGuid():n}", + StreamState.NoStream, + new[] { e } + ); + eventToCaptureResult ??= result; } - - await _fixture.Client.CreateToAllAsync(filterName, filter, - new PersistentSubscriptionSettings(startFrom: eventToCaptureResult!.LogPosition), - userCredentials: TestCredentials.Root); - - using var subscription = await _fixture.Client.SubscribeToAllAsync(filterName, - eventAppeared: async (s, e, r, ct) => { - appearedEvents.Add(e.Event); - if (appearedEvents.Count >= eventsToCapture.Length) { - appeared.TrySetResult(true); - } - await s.Ack(e); - }, - userCredentials: TestCredentials.Root) + + await _fixture.Client.CreateToAllAsync( + filterName, + filter, + new(startFrom: eventToCaptureResult!.LogPosition), + userCredentials: TestCredentials.Root + ); + + using var subscription = await _fixture.Client.SubscribeToAllAsync( + filterName, + async (s, e, r, ct) => { + appearedEvents.Add(e.Event); + if (appearedEvents.Count >= eventsToCapture.Length) + appeared.TrySetResult(true); + + await s.Ack(e); + }, + userCredentials: TestCredentials.Root + ) .WithTimeout(); await Task.WhenAll(appeared.Task).WithTimeout(); - + Assert.Equal(eventsToCapture.Select(x => x.EventId), appearedEvents.Select(x => x.EventId)); } - + public class Fixture : EventStoreClientFixture { protected override async Task Given() { - await StreamsClient.AppendToStreamAsync(Guid.NewGuid().ToString(), StreamState.NoStream, - CreateTestEvents(256)); + await StreamsClient.AppendToStreamAsync( + Guid.NewGuid().ToString(), + StreamState.NoStream, + CreateTestEvents(256) + ); - await StreamsClient.SetStreamMetadataAsync(SystemStreams.AllStream, StreamState.Any, - new StreamMetadata(acl: new StreamAcl(SystemRoles.All)), userCredentials: TestCredentials.Root); + await StreamsClient.SetStreamMetadataAsync( + SystemStreams.AllStream, + StreamState.Any, + new(acl: new(SystemRoles.All)), + userCredentials: TestCredentials.Root + ); } - + protected override Task When() => Task.CompletedTask; } } \ No newline at end of file diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/happy_case_writing_and_subscribing_to_normal_events_manual_ack.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/happy_case_writing_and_subscribing_to_normal_events_manual_ack.cs index c332bcb34..d19390773 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/happy_case_writing_and_subscribing_to_normal_events_manual_ack.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/happy_case_writing_and_subscribing_to_normal_events_manual_ack.cs @@ -1,60 +1,59 @@ -namespace EventStore.Client.SubscriptionToAll; +namespace EventStore.Client.SubscriptionToAll; public class happy_case_writing_and_subscribing_to_normal_events_manual_ack : IClassFixture { + const string Group = nameof(Group); + const int BufferCount = 10; + const int EventWriteCount = BufferCount * 2; - private const string Group = nameof(Group); - private const int BufferCount = 10; - private const int EventWriteCount = BufferCount * 2; + readonly Fixture _fixture; - private readonly Fixture _fixture; - - public happy_case_writing_and_subscribing_to_normal_events_manual_ack(Fixture fixture) { - _fixture = fixture; - } + public happy_case_writing_and_subscribing_to_normal_events_manual_ack(Fixture fixture) => _fixture = fixture; [SupportsPSToAll.Fact] - public async Task Test() { - await _fixture.EventsReceived.WithTimeout(); - } + public async Task Test() => await _fixture.EventsReceived.WithTimeout(); public class Fixture : EventStoreClientFixture { - private readonly EventData[] _events; - private readonly TaskCompletionSource _eventsReceived; - public Task EventsReceived => _eventsReceived.Task; + readonly EventData[] _events; + readonly TaskCompletionSource _eventsReceived; + int _eventReceivedCount; - private PersistentSubscription? _subscription; - private int _eventReceivedCount; + PersistentSubscription? _subscription; public Fixture() { _events = CreateTestEvents(EventWriteCount).ToArray(); - _eventsReceived = new TaskCompletionSource(); + _eventsReceived = new(); } + public Task EventsReceived => _eventsReceived.Task; + protected override async Task Given() { - await Client.CreateToAllAsync(Group, - new PersistentSubscriptionSettings(startFrom: Position.End, resolveLinkTos: true), - userCredentials: TestCredentials.Root); - _subscription = await Client.SubscribeToAllAsync(Group, - async (subscription, e, retryCount, ct) => { - await subscription.Ack(e); - if (e.OriginalStreamId.StartsWith("test-") - && Interlocked.Increment(ref _eventReceivedCount) == _events.Length) { - _eventsReceived.TrySetResult(true); - } - }, (s, r, e) => { - if (e != null) { - _eventsReceived.TrySetException(e); - } - }, - bufferSize: BufferCount, - userCredentials: TestCredentials.Root); + await Client.CreateToAllAsync( + Group, + new(startFrom: Position.End, resolveLinkTos: true), + userCredentials: TestCredentials.Root + ); + + _subscription = await Client.SubscribeToAllAsync( + Group, + async (subscription, e, retryCount, ct) => { + await subscription.Ack(e); + if (e.OriginalStreamId.StartsWith("test-") + && Interlocked.Increment(ref _eventReceivedCount) == _events.Length) + _eventsReceived.TrySetResult(true); + }, + (s, r, e) => { + if (e != null) + _eventsReceived.TrySetException(e); + }, + bufferSize: BufferCount, + userCredentials: TestCredentials.Root + ); } protected override async Task When() { - foreach (var e in _events) { - await StreamsClient.AppendToStreamAsync("test-" + Guid.NewGuid(), StreamState.Any, new[] {e}); - } + foreach (var e in _events) + await StreamsClient.AppendToStreamAsync("test-" + Guid.NewGuid(), StreamState.Any, new[] { e }); } public override Task DisposeAsync() { diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/list_with_persistent_subscriptions.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/list_with_persistent_subscriptions.cs index a411ea07a..e658e48a1 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/list_with_persistent_subscriptions.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/list_with_persistent_subscriptions.cs @@ -1,30 +1,25 @@ -namespace EventStore.Client.SubscriptionToAll; +namespace EventStore.Client.SubscriptionToAll; public class list_with_persistent_subscriptions : IClassFixture { - private readonly Fixture _fixture; - private const int AllStreamSubscriptionCount = 3; - private const int StreamSubscriptionCount = 4; - private const string GroupName = nameof(list_with_persistent_subscriptions); - private const string StreamName = nameof(list_with_persistent_subscriptions); + const int AllStreamSubscriptionCount = 3; + const int StreamSubscriptionCount = 4; + const string GroupName = nameof(list_with_persistent_subscriptions); + const string StreamName = nameof(list_with_persistent_subscriptions); + readonly Fixture _fixture; - public list_with_persistent_subscriptions(Fixture fixture) { - _fixture = fixture; - } + public list_with_persistent_subscriptions(Fixture fixture) => _fixture = fixture; - private int TotalSubscriptionCount => SupportsPSToAll.No - ? StreamSubscriptionCount - : StreamSubscriptionCount + AllStreamSubscriptionCount; + int TotalSubscriptionCount => + SupportsPSToAll.No + ? StreamSubscriptionCount + : StreamSubscriptionCount + AllStreamSubscriptionCount; [Fact] public async Task throws_when_not_supported() { - if (SupportsPSToAll.No) { - - await Assert.ThrowsAsync(async () => { - await _fixture.Client.ListToAllAsync(userCredentials: TestCredentials.Root); - }); - } + if (SupportsPSToAll.No) + await Assert.ThrowsAsync(async () => { await _fixture.Client.ListToAllAsync(userCredentials: TestCredentials.Root); }); } - + [SupportsPSToAll.Fact] public async Task returns_subscriptions_to_all_stream() { var result = (await _fixture.Client.ListToAllAsync(userCredentials: TestCredentials.Root)).ToList(); @@ -37,50 +32,50 @@ public async Task returns_all_subscriptions() { var result = (await _fixture.Client.ListAllAsync(userCredentials: TestCredentials.Root)).ToList(); Assert.Equal(TotalSubscriptionCount, result.Count()); } - + [SupportsPSToAll.Fact] - public async Task throws_with_no_credentials() { - await Assert.ThrowsAsync(async () => - await _fixture.Client.ListToAllAsync()); - } - + public async Task throws_with_no_credentials() => + await Assert.ThrowsAsync( + async () => + await _fixture.Client.ListToAllAsync() + ); + [SupportsPSToAll.Fact] - public async Task throws_with_non_existing_user() { - await Assert.ThrowsAsync(async () => - await _fixture.Client.ListToAllAsync(userCredentials: TestCredentials.TestBadUser)); - } - + public async Task throws_with_non_existing_user() => + await Assert.ThrowsAsync( + async () => + await _fixture.Client.ListToAllAsync(userCredentials: TestCredentials.TestBadUser) + ); + [SupportsPSToAll.Fact] public async Task returns_result_with_normal_user_credentials() { var result = await _fixture.Client.ListToAllAsync(userCredentials: TestCredentials.TestUser1); Assert.Equal(AllStreamSubscriptionCount, result.Count()); } - + public class Fixture : EventStoreClientFixture { - public Fixture () : base(skipPSWarmUp: true, noDefaultCredentials: true) { - } - + public Fixture() : base(skipPSWarmUp: true, noDefaultCredentials: true) { } + protected override async Task Given() { - for (int i = 0; i < StreamSubscriptionCount; i++) { + for (var i = 0; i < StreamSubscriptionCount; i++) await Client.CreateToStreamAsync( StreamName, GroupName + i, - new PersistentSubscriptionSettings(), - userCredentials: TestCredentials.Root); - } + new(), + userCredentials: TestCredentials.Root + ); - if (SupportsPSToAll.No) { + if (SupportsPSToAll.No) return; - } - - for (int i = 0; i < AllStreamSubscriptionCount; i++) { + + for (var i = 0; i < AllStreamSubscriptionCount; i++) await Client.CreateToAllAsync( GroupName + i, - new PersistentSubscriptionSettings(), - userCredentials: TestCredentials.Root); - } + new(), + userCredentials: TestCredentials.Root + ); } - + protected override Task When() => Task.CompletedTask; } } \ No newline at end of file diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/list_without_persistent_subscriptions.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/list_without_persistent_subscriptions.cs index c7a21e9be..0a8aa7593 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/list_without_persistent_subscriptions.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/list_without_persistent_subscriptions.cs @@ -1,25 +1,22 @@ -namespace EventStore.Client.SubscriptionToAll; +namespace EventStore.Client.SubscriptionToAll; public class list_without_persistent_subscriptions : IClassFixture { - private readonly Fixture _fixture; - - public list_without_persistent_subscriptions(Fixture fixture) { - _fixture = fixture; - } + readonly Fixture _fixture; + + public list_without_persistent_subscriptions(Fixture fixture) => _fixture = fixture; [Fact] public async Task throws() { if (SupportsPSToAll.No) { - - await Assert.ThrowsAsync(async () => { - await _fixture.Client.ListToAllAsync(userCredentials: TestCredentials.Root); - }); - + await Assert.ThrowsAsync(async () => { await _fixture.Client.ListToAllAsync(userCredentials: TestCredentials.Root); }); + return; } - - await Assert.ThrowsAsync(async () => - await _fixture.Client.ListToAllAsync(userCredentials: TestCredentials.Root)); + + await Assert.ThrowsAsync( + async () => + await _fixture.Client.ListToAllAsync(userCredentials: TestCredentials.Root) + ); } public class Fixture : EventStoreClientFixture { diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/replay_parked.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/replay_parked.cs index 60eb344b5..eb7eddd98 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/replay_parked.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/replay_parked.cs @@ -1,82 +1,89 @@ -namespace EventStore.Client.SubscriptionToAll; +namespace EventStore.Client.SubscriptionToAll; public class replay_parked : IClassFixture { - private readonly Fixture _fixture; - private const string GroupName = nameof(replay_parked); + const string GroupName = nameof(replay_parked); + readonly Fixture _fixture; - public replay_parked(Fixture fixture) { - _fixture = fixture; - } + public replay_parked(Fixture fixture) => _fixture = fixture; [Fact] public async Task throws_when_not_supported() { - if (SupportsPSToAll.No) { - - await Assert.ThrowsAsync(async () => { - await _fixture.Client.ReplayParkedMessagesToAllAsync( - GroupName, - userCredentials: TestCredentials.Root); - }); - } + if (SupportsPSToAll.No) + await Assert.ThrowsAsync( + async () => { + await _fixture.Client.ReplayParkedMessagesToAllAsync( + GroupName, + userCredentials: TestCredentials.Root + ); + } + ); } - + [SupportsPSToAll.Fact] public async Task does_not_throw() { await _fixture.Client.ReplayParkedMessagesToAllAsync( GroupName, - userCredentials: TestCredentials.Root); - + userCredentials: TestCredentials.Root + ); + await _fixture.Client.ReplayParkedMessagesToAllAsync( GroupName, - stopAt: 100, - userCredentials: TestCredentials.Root); + 100, + userCredentials: TestCredentials.Root + ); } [SupportsPSToAll.Fact] - public async Task throws_when_given_non_existing_subscription() { - await Assert.ThrowsAsync(() => - _fixture.Client.ReplayParkedMessagesToAllAsync( - groupName: "NonExisting", - userCredentials: TestCredentials.Root)); - } - + public async Task throws_when_given_non_existing_subscription() => + await Assert.ThrowsAsync( + () => + _fixture.Client.ReplayParkedMessagesToAllAsync( + "NonExisting", + userCredentials: TestCredentials.Root + ) + ); + [SupportsPSToAll.Fact] - public async Task throws_with_no_credentials() { - await Assert.ThrowsAsync(() => - _fixture.Client.ReplayParkedMessagesToAllAsync(GroupName)); - } + public async Task throws_with_no_credentials() => + await Assert.ThrowsAsync( + () => + _fixture.Client.ReplayParkedMessagesToAllAsync(GroupName) + ); [SupportsPSToAll.Fact] - public async Task throws_with_non_existing_user() { - await Assert.ThrowsAsync(() => - _fixture.Client.ReplayParkedMessagesToAllAsync( - GroupName, - userCredentials: TestCredentials.TestBadUser)); - } - + public async Task throws_with_non_existing_user() => + await Assert.ThrowsAsync( + () => + _fixture.Client.ReplayParkedMessagesToAllAsync( + GroupName, + userCredentials: TestCredentials.TestBadUser + ) + ); + [SupportsPSToAll.Fact] - public async Task throws_with_normal_user_credentials() { - await Assert.ThrowsAsync(() => - _fixture.Client.ReplayParkedMessagesToAllAsync( - GroupName, - userCredentials: TestCredentials.TestUser1)); - } + public async Task throws_with_normal_user_credentials() => + await Assert.ThrowsAsync( + () => + _fixture.Client.ReplayParkedMessagesToAllAsync( + GroupName, + userCredentials: TestCredentials.TestUser1 + ) + ); public class Fixture : EventStoreClientFixture { - public Fixture () : base(noDefaultCredentials: true) { - } - + public Fixture() : base(noDefaultCredentials: true) { } + protected override async Task Given() { - if (SupportsPSToAll.No) { + if (SupportsPSToAll.No) return; - } - + await Client.CreateToAllAsync( GroupName, - new PersistentSubscriptionSettings(), - userCredentials: TestCredentials.Root); + new(), + userCredentials: TestCredentials.Root + ); } - + protected override Task When() => Task.CompletedTask; } } \ No newline at end of file diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/update_existing.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/update_existing.cs index c76c4e14f..c535295e7 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/update_existing.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/update_existing.cs @@ -1,26 +1,27 @@ -namespace EventStore.Client.SubscriptionToAll; +namespace EventStore.Client.SubscriptionToAll; public class update_existing : IClassFixture { + const string Group = "existing"; + readonly Fixture _fixture; - private const string Group = "existing"; - private readonly Fixture _fixture; - - public update_existing(Fixture fixture) { - _fixture = fixture; - } + public update_existing(Fixture fixture) => _fixture = fixture; [SupportsPSToAll.Fact] - public async Task the_completion_succeeds() { - await _fixture.Client.UpdateToAllAsync(Group, - new PersistentSubscriptionSettings(), userCredentials: TestCredentials.Root); - } + public async Task the_completion_succeeds() => + await _fixture.Client.UpdateToAllAsync( + Group, + new(), + userCredentials: TestCredentials.Root + ); public class Fixture : EventStoreClientFixture { - protected override async Task Given() { - await Client.CreateToAllAsync(Group, new PersistentSubscriptionSettings(), - userCredentials: TestCredentials.Root); - } + protected override async Task Given() => + await Client.CreateToAllAsync( + Group, + new(), + userCredentials: TestCredentials.Root + ); protected override Task When() => Task.CompletedTask; } diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/update_existing_filtered.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/update_existing_filtered.cs index a1517332b..a93901c81 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/update_existing_filtered.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/update_existing_filtered.cs @@ -1,31 +1,28 @@ -namespace EventStore.Client.SubscriptionToAll; +namespace EventStore.Client.SubscriptionToAll; public class update_existing_filtered : IClassFixture { + const string Group = "existing-filtered"; + readonly Fixture _fixture; - private const string Group = "existing-filtered"; - private readonly Fixture _fixture; - - public update_existing_filtered(Fixture fixture) { - _fixture = fixture; - } + public update_existing_filtered(Fixture fixture) => _fixture = fixture; [SupportsPSToAll.Fact] - public async Task the_completion_succeeds() { + public async Task the_completion_succeeds() => await _fixture.Client.UpdateToAllAsync( Group, - new PersistentSubscriptionSettings(resolveLinkTos: true), - userCredentials: TestCredentials.Root); - } + new(true), + userCredentials: TestCredentials.Root + ); public class Fixture : EventStoreClientFixture { - protected override async Task Given() { + protected override async Task Given() => await Client.CreateToAllAsync( Group, EventTypeFilter.Prefix("prefix-filter-"), - new PersistentSubscriptionSettings(), - userCredentials: TestCredentials.Root); - } + new(), + userCredentials: TestCredentials.Root + ); protected override Task When() => Task.CompletedTask; } diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/update_existing_with_check_point.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/update_existing_with_check_point.cs index d363cde80..9ec86f491 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/update_existing_with_check_point.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/update_existing_with_check_point.cs @@ -1,13 +1,11 @@ -namespace EventStore.Client.SubscriptionToAll; +namespace EventStore.Client.SubscriptionToAll; public class update_existing_with_check_point : IClassFixture { - private const string Group = "existing-with-check-point"; - private readonly Fixture _fixture; + const string Group = "existing-with-check-point"; + readonly Fixture _fixture; - public update_existing_with_check_point(Fixture fixture) { - _fixture = fixture; - } + public update_existing_with_check_point(Fixture fixture) => _fixture = fixture; [SupportsPSToAll.Fact] public async Task resumes_from_check_point() { @@ -16,65 +14,73 @@ public async Task resumes_from_check_point() { } public class Fixture : EventStoreClientFixture { - public Task Resumed => _resumedSource.Task; - public Position CheckPoint { get; private set; } + readonly TaskCompletionSource _appeared; + readonly List _appearedEvents; + readonly TaskCompletionSource _checkPointSource; - private readonly TaskCompletionSource<(SubscriptionDroppedReason, Exception?)> _droppedSource; - private readonly TaskCompletionSource _resumedSource; - private readonly TaskCompletionSource _checkPointSource; - private PersistentSubscription? _firstSubscription; - private PersistentSubscription? _secondSubscription; - private StreamSubscription? _checkPointSubscription; - private readonly TaskCompletionSource _appeared; - private readonly List _appearedEvents; - private readonly EventData[] _events; + readonly TaskCompletionSource<(SubscriptionDroppedReason, Exception?)> _droppedSource; + readonly EventData[] _events; + readonly TaskCompletionSource _resumedSource; + StreamSubscription? _checkPointSubscription; + PersistentSubscription? _firstSubscription; + PersistentSubscription? _secondSubscription; public Fixture() { - _droppedSource = new TaskCompletionSource<(SubscriptionDroppedReason, Exception?)>(); - _resumedSource = new TaskCompletionSource(); - _checkPointSource = new TaskCompletionSource(); - _appeared = new TaskCompletionSource(); - _appearedEvents = new List(); + _droppedSource = new(); + _resumedSource = new(); + _checkPointSource = new(); + _appeared = new(); + _appearedEvents = new(); _events = CreateTestEvents(5).ToArray(); } - protected override async Task Given() { - foreach (var e in _events) { - await StreamsClient.AppendToStreamAsync("test-" + Guid.NewGuid(), StreamState.Any, new[] {e}); - } + public Task Resumed => _resumedSource.Task; + public Position CheckPoint { get; private set; } - await Client.CreateToAllAsync(Group, - new PersistentSubscriptionSettings( - checkPointLowerBound: 5, - checkPointAfter: TimeSpan.FromSeconds(1), - startFrom: Position.Start), - userCredentials: TestCredentials.Root); + protected override async Task Given() { + foreach (var e in _events) + await StreamsClient.AppendToStreamAsync("test-" + Guid.NewGuid(), StreamState.Any, new[] { e }); + + await Client.CreateToAllAsync( + Group, + new( + checkPointLowerBound: 5, + checkPointAfter: TimeSpan.FromSeconds(1), + startFrom: Position.Start + ), + userCredentials: TestCredentials.Root + ); var checkPointStream = $"$persistentsubscription-$all::{Group}-checkpoint"; - _checkPointSubscription = await StreamsClient.SubscribeToStreamAsync(checkPointStream, - FromStream.Start, - (_, e, _) => { - _checkPointSource.TrySetResult(e); - return Task.CompletedTask; - }, subscriptionDropped: (_, reason, ex) => { - if (ex is not null) { - _checkPointSource.TrySetException(ex); - } else { - _checkPointSource.TrySetResult(default); - } - }, - userCredentials: TestCredentials.Root); - - _firstSubscription = await Client.SubscribeToAllAsync(Group, - eventAppeared: async (s, e, r, ct) => { - _appearedEvents.Add(e); - - if (_appearedEvents.Count == _events.Length) - _appeared.TrySetResult(true); - await s.Ack(e); - }, - (subscription, reason, ex) => _droppedSource.TrySetResult((reason, ex)), - userCredentials: TestCredentials.Root); + _checkPointSubscription = await StreamsClient.SubscribeToStreamAsync( + checkPointStream, + FromStream.Start, + (_, e, _) => { + _checkPointSource.TrySetResult(e); + return Task.CompletedTask; + }, + subscriptionDropped: (_, reason, ex) => { + if (ex is not null) + _checkPointSource.TrySetException(ex); + else + _checkPointSource.TrySetResult(default); + }, + userCredentials: TestCredentials.Root + ); + + _firstSubscription = await Client.SubscribeToAllAsync( + Group, + async (s, e, r, ct) => { + _appearedEvents.Add(e); + + if (_appearedEvents.Count == _events.Length) + _appeared.TrySetResult(true); + + await s.Ack(e); + }, + (subscription, reason, ex) => _droppedSource.TrySetResult((reason, ex)), + TestCredentials.Root + ); await Task.WhenAll(_appeared.Task, _checkPointSource.Task).WithTimeout(); @@ -83,27 +89,27 @@ await Client.CreateToAllAsync(Group, protected override async Task When() { // Force restart of the subscription - await Client.UpdateToAllAsync(Group, new PersistentSubscriptionSettings(), userCredentials: TestCredentials.Root); + await Client.UpdateToAllAsync(Group, new(), userCredentials: TestCredentials.Root); await _droppedSource.Task.WithTimeout(); - _secondSubscription = await Client.SubscribeToAllAsync(Group, - async (s, e, r, ct) => { - _resumedSource.TrySetResult(e); - await s.Ack(e); - }, - (_, reason, ex) => { - if (ex is not null) { - _resumedSource.TrySetException(ex); - } else { - _resumedSource.TrySetResult(default); - } - }, - TestCredentials.Root); - - foreach (var e in _events) { - await StreamsClient.AppendToStreamAsync("test-" + Guid.NewGuid(), StreamState.Any, new[] {e}); - } + _secondSubscription = await Client.SubscribeToAllAsync( + Group, + async (s, e, r, ct) => { + _resumedSource.TrySetResult(e); + await s.Ack(e); + }, + (_, reason, ex) => { + if (ex is not null) + _resumedSource.TrySetException(ex); + else + _resumedSource.TrySetResult(default); + }, + TestCredentials.Root + ); + + foreach (var e in _events) + await StreamsClient.AppendToStreamAsync("test-" + Guid.NewGuid(), StreamState.Any, new[] { e }); } public override Task DisposeAsync() { diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/update_existing_with_check_point_filtered.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/update_existing_with_check_point_filtered.cs index 8135fd389..facd9135b 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/update_existing_with_check_point_filtered.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/update_existing_with_check_point_filtered.cs @@ -1,13 +1,12 @@ -namespace EventStore.Client.SubscriptionToAll; +namespace EventStore.Client.SubscriptionToAll; public class update_existing_with_check_point_filtered : IClassFixture { - private const string Group = "existing-with-check-point-filtered"; - private readonly Fixture _fixture; + const string Group = "existing-with-check-point-filtered"; - public update_existing_with_check_point_filtered(Fixture fixture) { - _fixture = fixture; - } + readonly Fixture _fixture; + + public update_existing_with_check_point_filtered(Fixture fixture) => _fixture = fixture; [SupportsPSToAll.Fact] public async Task resumes_from_check_point() { @@ -16,67 +15,75 @@ public async Task resumes_from_check_point() { } public class Fixture : EventStoreClientFixture { - public Task Resumed => _resumedSource.Task; - public Position CheckPoint { get; private set; } - - private readonly TaskCompletionSource<(SubscriptionDroppedReason, Exception?)> _droppedSource; - private readonly TaskCompletionSource _resumedSource; - private readonly TaskCompletionSource _checkPointSource; - private PersistentSubscription? _firstSubscription; - private PersistentSubscription? _secondSubscription; - private StreamSubscription? _checkPointSubscription; - private readonly TaskCompletionSource _appeared; - private readonly List _appearedEvents; - private readonly EventData[] _events; + readonly TaskCompletionSource _appeared; + readonly List _appearedEvents; + readonly TaskCompletionSource _checkPointSource; + readonly TaskCompletionSource<(SubscriptionDroppedReason, Exception?)> _droppedSource; + readonly EventData[] _events; + readonly TaskCompletionSource _resumedSource; + + StreamSubscription? _checkPointSubscription; + PersistentSubscription? _firstSubscription; + PersistentSubscription? _secondSubscription; public Fixture() { - _droppedSource = new TaskCompletionSource<(SubscriptionDroppedReason, Exception?)>(); - _resumedSource = new TaskCompletionSource(); - _checkPointSource = new TaskCompletionSource(); - _appeared = new TaskCompletionSource(); - _appearedEvents = new List(); + _droppedSource = new(); + _resumedSource = new(); + _checkPointSource = new(); + _appeared = new(); + _appearedEvents = new(); _events = CreateTestEvents(5).ToArray(); } + public Task Resumed => _resumedSource.Task; + + public Position CheckPoint { get; private set; } + protected override async Task Given() { - foreach (var e in _events) { - await StreamsClient.AppendToStreamAsync("test-" + Guid.NewGuid(), StreamState.NoStream, new[] {e}); - } - - await Client.CreateToAllAsync(Group, - StreamFilter.Prefix("test"), - new PersistentSubscriptionSettings( - checkPointLowerBound: 5, - checkPointAfter: TimeSpan.FromSeconds(1), - startFrom: Position.Start), - userCredentials: TestCredentials.Root); + foreach (var e in _events) + await StreamsClient.AppendToStreamAsync("test-" + Guid.NewGuid(), StreamState.NoStream, new[] { e }); + + await Client.CreateToAllAsync( + Group, + StreamFilter.Prefix("test"), + new( + checkPointLowerBound: 5, + checkPointAfter: TimeSpan.FromSeconds(1), + startFrom: Position.Start + ), + userCredentials: TestCredentials.Root + ); var checkPointStream = $"$persistentsubscription-$all::{Group}-checkpoint"; - _checkPointSubscription = await StreamsClient.SubscribeToStreamAsync(checkPointStream, - FromStream.Start, - (_, e, ct) => { - _checkPointSource.TrySetResult(e); - return Task.CompletedTask; - }, - subscriptionDropped: (_, reason, ex) => { - if (ex is not null) { - _checkPointSource.TrySetException(ex); - } else { - _checkPointSource.TrySetResult(default); - } - }, - userCredentials: TestCredentials.Root); - - _firstSubscription = await Client.SubscribeToAllAsync(Group, - eventAppeared: async (s, e, r, ct) => { - _appearedEvents.Add(e); - - if (_appearedEvents.Count == _events.Length) - _appeared.TrySetResult(true); - await s.Ack(e); - }, - subscriptionDropped: (subscription, reason, ex) => _droppedSource.TrySetResult((reason, ex)), - userCredentials: TestCredentials.Root); + _checkPointSubscription = await StreamsClient.SubscribeToStreamAsync( + checkPointStream, + FromStream.Start, + (_, e, ct) => { + _checkPointSource.TrySetResult(e); + return Task.CompletedTask; + }, + subscriptionDropped: (_, reason, ex) => { + if (ex is not null) + _checkPointSource.TrySetException(ex); + else + _checkPointSource.TrySetResult(default); + }, + userCredentials: TestCredentials.Root + ); + + _firstSubscription = await Client.SubscribeToAllAsync( + Group, + async (s, e, r, ct) => { + _appearedEvents.Add(e); + + if (_appearedEvents.Count == _events.Length) + _appeared.TrySetResult(true); + + await s.Ack(e); + }, + (subscription, reason, ex) => _droppedSource.TrySetResult((reason, ex)), + TestCredentials.Root + ); await Task.WhenAll(_appeared.Task, _checkPointSource.Task).WithTimeout(); @@ -85,28 +92,28 @@ await Client.CreateToAllAsync(Group, protected override async Task When() { // Force restart of the subscription - await Client.UpdateToAllAsync(Group, new PersistentSubscriptionSettings(), userCredentials: TestCredentials.Root); + await Client.UpdateToAllAsync(Group, new(), userCredentials: TestCredentials.Root); await _droppedSource.Task.WithTimeout(); - _secondSubscription = await Client.SubscribeToAllAsync(Group, - eventAppeared: async (s, e, r, ct) => { - _resumedSource.TrySetResult(e); - await s.Ack(e); - s.Dispose(); - }, - (_, reason, ex) => { - if (ex is not null) { - _resumedSource.TrySetException(ex); - } else { - _resumedSource.TrySetResult(default); - } - }, - userCredentials: TestCredentials.Root); - - foreach (var e in _events) { - await StreamsClient.AppendToStreamAsync("test-" + Guid.NewGuid(), StreamState.NoStream, new[] {e}); - } + _secondSubscription = await Client.SubscribeToAllAsync( + Group, + async (s, e, r, ct) => { + _resumedSource.TrySetResult(e); + await s.Ack(e); + s.Dispose(); + }, + (_, reason, ex) => { + if (ex is not null) + _resumedSource.TrySetException(ex); + else + _resumedSource.TrySetResult(default); + }, + TestCredentials.Root + ); + + foreach (var e in _events) + await StreamsClient.AppendToStreamAsync("test-" + Guid.NewGuid(), StreamState.NoStream, new[] { e }); } public override Task DisposeAsync() { diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/update_existing_with_commit_position_equal_to_last_indexed_position.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/update_existing_with_commit_position_equal_to_last_indexed_position.cs index b2eb27c21..589c42404 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/update_existing_with_commit_position_equal_to_last_indexed_position.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/update_existing_with_commit_position_equal_to_last_indexed_position.cs @@ -1,34 +1,41 @@ -namespace EventStore.Client.SubscriptionToAll; +namespace EventStore.Client.SubscriptionToAll; public class update_existing_with_commit_position_equal_to_last_indexed_position : IClassFixture { - public update_existing_with_commit_position_equal_to_last_indexed_position(Fixture fixture) { - _fixture = fixture; - } + const string Group = "existing"; + readonly Fixture _fixture; - private const string Group = "existing"; + public update_existing_with_commit_position_equal_to_last_indexed_position(Fixture fixture) => _fixture = fixture; - private readonly Fixture _fixture; + [SupportsPSToAll.Fact] + public async Task the_completion_succeeds() => + await _fixture.Client.UpdateToAllAsync( + Group, + new(startFrom: new Position(_fixture.LastCommitPosition, _fixture.LastCommitPosition)), + userCredentials: TestCredentials.Root + ); public class Fixture : EventStoreClientFixture { public ulong LastCommitPosition; + protected override async Task Given() { - await Client.CreateToAllAsync(Group, - new PersistentSubscriptionSettings(), - userCredentials: TestCredentials.Root); + await Client.CreateToAllAsync( + Group, + new(), + userCredentials: TestCredentials.Root + ); + + var lastEvent = await StreamsClient.ReadAllAsync( + Direction.Backwards, + Position.End, + 1, + userCredentials: TestCredentials.Root + ).FirstAsync(); - var lastEvent = await StreamsClient.ReadAllAsync(Direction.Backwards, Position.End, 1, - userCredentials: TestCredentials.Root).FirstAsync(); - LastCommitPosition = lastEvent.OriginalPosition?.CommitPosition ?? throw new Exception(); + LastCommitPosition = lastEvent.OriginalPosition?.CommitPosition ?? throw new(); } + protected override Task When() => Task.CompletedTask; } - - [SupportsPSToAll.Fact] - public async Task the_completion_succeeds() => - await _fixture.Client.UpdateToAllAsync(Group, - new PersistentSubscriptionSettings( - startFrom: new Position(_fixture.LastCommitPosition, _fixture.LastCommitPosition)), - userCredentials: TestCredentials.Root); } \ No newline at end of file diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/update_existing_with_commit_position_larger_than_last_indexed_position.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/update_existing_with_commit_position_larger_than_last_indexed_position.cs index 7962a9103..1e30c037b 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/update_existing_with_commit_position_larger_than_last_indexed_position.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/update_existing_with_commit_position_larger_than_last_indexed_position.cs @@ -1,39 +1,49 @@ using Grpc.Core; -namespace EventStore.Client.SubscriptionToAll; +namespace EventStore.Client.SubscriptionToAll; public class update_existing_with_commit_position_larger_than_last_indexed_position : IClassFixture { - public update_existing_with_commit_position_larger_than_last_indexed_position(Fixture fixture) { - _fixture = fixture; - } + const string Group = "existing"; + readonly Fixture _fixture; - private const string Group = "existing"; + public update_existing_with_commit_position_larger_than_last_indexed_position(Fixture fixture) => _fixture = fixture; - private readonly Fixture _fixture; + [SupportsPSToAll.Fact] + public async Task fails() { + var ex = await Assert.ThrowsAsync( + () => + _fixture.Client.UpdateToAllAsync( + Group, + new(startFrom: new Position(_fixture.LastCommitPosition + 1, _fixture.LastCommitPosition)), + userCredentials: TestCredentials.Root + ) + ); + + Assert.Equal(StatusCode.Internal, ex.StatusCode); + } public class Fixture : EventStoreClientFixture { public ulong LastCommitPosition; + protected override async Task When() { - await Client.CreateToAllAsync(Group, - new PersistentSubscriptionSettings(), - userCredentials: TestCredentials.Root); + await Client.CreateToAllAsync( + Group, + new(), + userCredentials: TestCredentials.Root + ); - var lastEvent = await StreamsClient.ReadAllAsync(Direction.Backwards, Position.End, 1, - userCredentials: TestCredentials.Root).FirstAsync(); - LastCommitPosition = lastEvent.OriginalPosition?.CommitPosition ?? throw new Exception(); + var lastEvent = await StreamsClient.ReadAllAsync( + Direction.Backwards, + Position.End, + 1, + userCredentials: TestCredentials.Root + ).FirstAsync(); + + LastCommitPosition = lastEvent.OriginalPosition?.CommitPosition ?? throw new(); } + protected override Task Given() => Task.CompletedTask; } - - [SupportsPSToAll.Fact] - public async Task fails() { - var ex = await Assert.ThrowsAsync(() => - _fixture.Client.UpdateToAllAsync(Group, - new PersistentSubscriptionSettings( - startFrom: new Position(_fixture.LastCommitPosition + 1, _fixture.LastCommitPosition)), - userCredentials: TestCredentials.Root)); - Assert.Equal(StatusCode.Internal, ex.StatusCode); - } } \ No newline at end of file diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/update_existing_with_subscribers.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/update_existing_with_subscribers.cs index 19d6fa7c4..25ea39616 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/update_existing_with_subscribers.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/update_existing_with_subscribers.cs @@ -1,14 +1,11 @@ -namespace EventStore.Client.SubscriptionToAll; +namespace EventStore.Client.SubscriptionToAll; public class update_existing_with_subscribers : IClassFixture { + const string Group = "existing"; + readonly Fixture _fixture; - private const string Group = "existing"; - private readonly Fixture _fixture; - - public update_existing_with_subscribers(Fixture fixture) { - _fixture = fixture; - } + public update_existing_with_subscribers(Fixture fixture) => _fixture = fixture; [SupportsPSToAll.Fact] public async Task existing_subscriptions_are_dropped() { @@ -20,26 +17,37 @@ public async Task existing_subscriptions_are_dropped() { } public class Fixture : EventStoreClientFixture { - private readonly TaskCompletionSource<(SubscriptionDroppedReason, Exception?)> _droppedSource; - public Task<(SubscriptionDroppedReason, Exception?)> Dropped => _droppedSource.Task; - private PersistentSubscription? _subscription; + readonly TaskCompletionSource<(SubscriptionDroppedReason, Exception?)> _droppedSource; + PersistentSubscription? _subscription; - public Fixture() { - _droppedSource = new TaskCompletionSource<(SubscriptionDroppedReason, Exception?)>(); - } + public Fixture() => _droppedSource = new(); + + public Task<(SubscriptionDroppedReason, Exception?)> Dropped => _droppedSource.Task; protected override async Task Given() { - await Client.CreateToAllAsync(Group, new PersistentSubscriptionSettings(), - userCredentials: TestCredentials.Root); - _subscription = await Client.SubscribeToAllAsync(Group, - delegate { return Task.CompletedTask; }, - (subscription, reason, ex) => _droppedSource.TrySetResult((reason, ex)), userCredentials: TestCredentials.Root); + await Client.CreateToAllAsync( + Group, + new(), + userCredentials: TestCredentials.Root + ); + + _subscription = await Client.SubscribeToAllAsync( + Group, + delegate { return Task.CompletedTask; }, + (subscription, reason, ex) => _droppedSource.TrySetResult((reason, ex)), + TestCredentials.Root + ); + // todo: investigate why this test is flaky without this delay await Task.Delay(500); } - protected override Task When() => Client.UpdateToAllAsync(Group, - new PersistentSubscriptionSettings(), userCredentials: TestCredentials.Root); + protected override Task When() => + Client.UpdateToAllAsync( + Group, + new(), + userCredentials: TestCredentials.Root + ); public override Task DisposeAsync() { _subscription?.Dispose(); diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/update_existing_without_permissions.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/update_existing_without_permissions.cs index c673d921d..1f0556cba 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/update_existing_without_permissions.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/update_existing_without_permissions.cs @@ -1,30 +1,30 @@ -namespace EventStore.Client.SubscriptionToAll; +namespace EventStore.Client.SubscriptionToAll; public class update_existing_without_permissions : IClassFixture { + const string Group = "existing"; + readonly Fixture _fixture; - private const string Group = "existing"; - private readonly Fixture _fixture; - - public update_existing_without_permissions(Fixture fixture) { - _fixture = fixture; - } + public update_existing_without_permissions(Fixture fixture) => _fixture = fixture; [SupportsPSToAll.Fact] - public async Task the_completion_fails_with_access_denied() { + public async Task the_completion_fails_with_access_denied() => await Assert.ThrowsAsync( - () => _fixture.Client.UpdateToAllAsync(Group, - new PersistentSubscriptionSettings())); - } + () => _fixture.Client.UpdateToAllAsync( + Group, + new() + ) + ); public class Fixture : EventStoreClientFixture { - public Fixture () : base(noDefaultCredentials: true){ - } - - protected override async Task Given() { - await Client.CreateToAllAsync(Group, new PersistentSubscriptionSettings(), - userCredentials: TestCredentials.Root); - } + public Fixture() : base(noDefaultCredentials: true) { } + + protected override async Task Given() => + await Client.CreateToAllAsync( + Group, + new(), + userCredentials: TestCredentials.Root + ); protected override Task When() => Task.CompletedTask; } diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/update_non_existent.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/update_non_existent.cs index 7b2e25c17..f2c5aaea2 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/update_non_existent.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/update_non_existent.cs @@ -1,21 +1,21 @@ -namespace EventStore.Client.SubscriptionToAll; +namespace EventStore.Client.SubscriptionToAll; public class update_non_existent : IClassFixture { + const string Group = "nonexistent"; + readonly Fixture _fixture; - private const string Group = "nonexistent"; - private readonly Fixture _fixture; - - public update_non_existent(Fixture fixture) { - _fixture = fixture; - } + public update_non_existent(Fixture fixture) => _fixture = fixture; [SupportsPSToAll.Fact] - public async Task the_completion_fails_with_not_found() { + public async Task the_completion_fails_with_not_found() => await Assert.ThrowsAsync( - () => _fixture.Client.UpdateToAllAsync(Group, - new PersistentSubscriptionSettings(), userCredentials: TestCredentials.Root)); - } + () => _fixture.Client.UpdateToAllAsync( + Group, + new(), + userCredentials: TestCredentials.Root + ) + ); public class Fixture : EventStoreClientFixture { protected override Task Given() => Task.CompletedTask; diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/update_with_prepare_position_larger_than_commit_position.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/update_with_prepare_position_larger_than_commit_position.cs index 6ee9cb86a..c232182d3 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/update_with_prepare_position_larger_than_commit_position.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/update_with_prepare_position_larger_than_commit_position.cs @@ -1,26 +1,26 @@ -namespace EventStore.Client.SubscriptionToAll; +namespace EventStore.Client.SubscriptionToAll; public class update_with_prepare_position_larger_than_commit_position : IClassFixture { - public update_with_prepare_position_larger_than_commit_position(Fixture fixture) { - _fixture = fixture; - } + const string Group = "existing"; + readonly Fixture _fixture; - private const string Group = "existing"; + public update_with_prepare_position_larger_than_commit_position(Fixture fixture) => _fixture = fixture; - private readonly Fixture _fixture; + [SupportsPSToAll.Fact] + public Task fails_with_argument_out_of_range_exception() => + Assert.ThrowsAsync( + () => + _fixture.Client.UpdateToAllAsync( + Group, + new(startFrom: new Position(0, 1)), + userCredentials: TestCredentials.Root + ) + ); public class Fixture : EventStoreClientFixture { protected override Task Given() => Task.CompletedTask; protected override Task When() => Task.CompletedTask; } - - [SupportsPSToAll.Fact] - public Task fails_with_argument_out_of_range_exception() => - Assert.ThrowsAsync(() => - _fixture.Client.UpdateToAllAsync(Group, - new PersistentSubscriptionSettings( - startFrom: new Position(0, 1)), - userCredentials: TestCredentials.Root)); } \ No newline at end of file diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/when_writing_and_filtering_out_events.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/when_writing_and_filtering_out_events.cs index 5af9632c5..0aacd49e1 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/when_writing_and_filtering_out_events.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/when_writing_and_filtering_out_events.cs @@ -1,82 +1,89 @@ -namespace EventStore.Client.SubscriptionToAll; +namespace EventStore.Client.SubscriptionToAll; public class when_writing_and_filtering_out_events : IClassFixture { - private const string Group = "filtering-out-events"; - private readonly Fixture _fixture; + const string Group = "filtering-out-events"; + readonly Fixture _fixture; - public when_writing_and_filtering_out_events(Fixture fixture) { - _fixture = fixture; - } + public when_writing_and_filtering_out_events(Fixture fixture) => _fixture = fixture; [SupportsPSToAll.Fact] public async Task it_should_write_a_check_point() { await _fixture.SecondCheckPoint.WithTimeout(); var secondCheckPoint = _fixture.SecondCheckPoint.Result.Event.Data.ParsePosition(); Assert.True(secondCheckPoint > _fixture.FirstCheckPoint); - Assert.Equal(_fixture.Events.Select(e => e.EventId), - _fixture.AppearedEvents.Select(e => e.Event.EventId)); + Assert.Equal( + _fixture.Events.Select(e => e.EventId), + _fixture.AppearedEvents.Select(e => e.Event.EventId) + ); } public class Fixture : EventStoreClientFixture { - public Task SecondCheckPoint => _secondCheckPointSource.Task; - public Position FirstCheckPoint { get; private set; } - public EventData[] Events => _events.ToArray(); - public ResolvedEvent[] AppearedEvents => _appearedEvents.ToArray(); + readonly TaskCompletionSource _appeared; + readonly List _appearedEvents, _checkPoints; + readonly string _checkPointStream = $"$persistentsubscription-$all::{Group}-checkpoint"; + readonly EventData[] _events; - private readonly TaskCompletionSource _firstCheckPointSource, _secondCheckPointSource; - private PersistentSubscription? _subscription; - private StreamSubscription? _checkPointSubscription; - private readonly TaskCompletionSource _appeared; - private readonly List _appearedEvents, _checkPoints; - private readonly EventData[] _events; - private readonly string _checkPointStream = $"$persistentsubscription-$all::{Group}-checkpoint"; + readonly TaskCompletionSource _firstCheckPointSource, _secondCheckPointSource; + StreamSubscription? _checkPointSubscription; + PersistentSubscription? _subscription; public Fixture() { - _firstCheckPointSource = new TaskCompletionSource(); - _secondCheckPointSource = new TaskCompletionSource(); - _appeared = new TaskCompletionSource(); - _appearedEvents = new List(); - _checkPoints = new List(); + _firstCheckPointSource = new(); + _secondCheckPointSource = new(); + _appeared = new(); + _appearedEvents = new(); + _checkPoints = new(); _events = CreateTestEvents(5).ToArray(); } + public Task SecondCheckPoint => _secondCheckPointSource.Task; + public Position FirstCheckPoint { get; private set; } + public EventData[] Events => _events.ToArray(); + public ResolvedEvent[] AppearedEvents => _appearedEvents.ToArray(); + protected override async Task Given() { - foreach (var e in _events) { - await StreamsClient.AppendToStreamAsync("test-" + Guid.NewGuid(), StreamState.Any, new[] {e}); - } - - await Client.CreateToAllAsync(Group, - StreamFilter.Prefix("test"), - new PersistentSubscriptionSettings( - checkPointLowerBound: 5, - checkPointAfter: TimeSpan.FromSeconds(1), - startFrom: Position.Start), - userCredentials: TestCredentials.Root); - - _checkPointSubscription = await StreamsClient.SubscribeToStreamAsync(_checkPointStream, - FromStream.Start, - (_, e, _) => { - if (_checkPoints.Count == 0) { - _firstCheckPointSource.TrySetResult(e); - } else { - _secondCheckPointSource.TrySetResult(e); - } - - _checkPoints.Add(e); - return Task.CompletedTask; - }, - userCredentials: TestCredentials.Root); - - _subscription = await Client.SubscribeToAllAsync(Group, - eventAppeared: async (s, e, r, ct) => { - _appearedEvents.Add(e); - - if (_appearedEvents.Count == _events.Length) - _appeared.TrySetResult(true); - await s.Ack(e); - }, - userCredentials: TestCredentials.Root); + foreach (var e in _events) + await StreamsClient.AppendToStreamAsync("test-" + Guid.NewGuid(), StreamState.Any, new[] { e }); + + await Client.CreateToAllAsync( + Group, + StreamFilter.Prefix("test"), + new( + checkPointLowerBound: 5, + checkPointAfter: TimeSpan.FromSeconds(1), + startFrom: Position.Start + ), + userCredentials: TestCredentials.Root + ); + + _checkPointSubscription = await StreamsClient.SubscribeToStreamAsync( + _checkPointStream, + FromStream.Start, + (_, e, _) => { + if (_checkPoints.Count == 0) + _firstCheckPointSource.TrySetResult(e); + else + _secondCheckPointSource.TrySetResult(e); + + _checkPoints.Add(e); + return Task.CompletedTask; + }, + userCredentials: TestCredentials.Root + ); + + _subscription = await Client.SubscribeToAllAsync( + Group, + async (s, e, r, ct) => { + _appearedEvents.Add(e); + + if (_appearedEvents.Count == _events.Length) + _appeared.TrySetResult(true); + + await s.Ack(e); + }, + userCredentials: TestCredentials.Root + ); await Task.WhenAll(_appeared.Task, _firstCheckPointSource.Task).WithTimeout(); @@ -84,10 +91,12 @@ await Client.CreateToAllAsync(Group, } protected override async Task When() { - foreach (var e in _events) { - await StreamsClient.AppendToStreamAsync("filtered-out-stream-" + Guid.NewGuid(), - StreamState.Any, new[] {e}); - } + foreach (var e in _events) + await StreamsClient.AppendToStreamAsync( + "filtered-out-stream-" + Guid.NewGuid(), + StreamState.Any, + new[] { e } + ); } public override Task DisposeAsync() { diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/when_writing_and_subscribing_to_normal_events_manual_nack.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/when_writing_and_subscribing_to_normal_events_manual_nack.cs index 6839e21e1..d3c354063 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/when_writing_and_subscribing_to_normal_events_manual_nack.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToAll/when_writing_and_subscribing_to_normal_events_manual_nack.cs @@ -1,62 +1,62 @@ -namespace EventStore.Client.SubscriptionToAll; +namespace EventStore.Client.SubscriptionToAll; public class when_writing_and_subscribing_to_normal_events_manual_nack : IClassFixture { + const string Group = nameof(Group); + const int BufferCount = 10; + const int EventWriteCount = BufferCount * 2; - private const string Group = nameof(Group); - private const int BufferCount = 10; - private const int EventWriteCount = BufferCount * 2; + readonly Fixture _fixture; - private readonly Fixture _fixture; - - public when_writing_and_subscribing_to_normal_events_manual_nack(Fixture fixture) { - _fixture = fixture; - } + public when_writing_and_subscribing_to_normal_events_manual_nack(Fixture fixture) => _fixture = fixture; [SupportsPSToAll.Fact] - public async Task Test() { - await _fixture.EventsReceived.WithTimeout(); - } + public async Task Test() => await _fixture.EventsReceived.WithTimeout(); public class Fixture : EventStoreClientFixture { - private readonly EventData[] _events; - private readonly TaskCompletionSource _eventsReceived; - public Task EventsReceived => _eventsReceived.Task; + readonly EventData[] _events; + readonly TaskCompletionSource _eventsReceived; + int _eventReceivedCount; - private PersistentSubscription? _subscription; - private int _eventReceivedCount; + PersistentSubscription? _subscription; - public Fixture() { + public Fixture() { _events = CreateTestEvents(EventWriteCount) .ToArray(); - _eventsReceived = new TaskCompletionSource(); + + _eventsReceived = new(); } + public Task EventsReceived => _eventsReceived.Task; + protected override async Task Given() { - await Client.CreateToAllAsync(Group, - new PersistentSubscriptionSettings(startFrom: Position.Start, resolveLinkTos: true), - userCredentials: TestCredentials.Root); - _subscription = await Client.SubscribeToAllAsync(Group, - async (subscription, e, retryCount, ct) => { - await subscription.Nack(PersistentSubscriptionNakEventAction.Park, "fail", e); + await Client.CreateToAllAsync( + Group, + new(startFrom: Position.Start, resolveLinkTos: true), + userCredentials: TestCredentials.Root + ); + + _subscription = await Client.SubscribeToAllAsync( + Group, + async (subscription, e, retryCount, ct) => { + await subscription.Nack(PersistentSubscriptionNakEventAction.Park, "fail", e); - if (e.OriginalStreamId.StartsWith("test-") - && Interlocked.Increment(ref _eventReceivedCount) == _events.Length) { - _eventsReceived.TrySetResult(true); - } - }, (s, r, e) => { - if (e != null) { - _eventsReceived.TrySetException(e); - } - }, - bufferSize: BufferCount, - userCredentials: TestCredentials.Root); + if (e.OriginalStreamId.StartsWith("test-") + && Interlocked.Increment(ref _eventReceivedCount) == _events.Length) + _eventsReceived.TrySetResult(true); + }, + (s, r, e) => { + if (e != null) + _eventsReceived.TrySetException(e); + }, + bufferSize: BufferCount, + userCredentials: TestCredentials.Root + ); } protected override async Task When() { - foreach (var e in _events) { - await StreamsClient.AppendToStreamAsync("test-" + Guid.NewGuid(), StreamState.Any, new[] {e}); - } + foreach (var e in _events) + await StreamsClient.AppendToStreamAsync("test-" + Guid.NewGuid(), StreamState.Any, new[] { e }); } public override Task DisposeAsync() { diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/can_create_duplicate_name_on_different_streams.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/can_create_duplicate_name_on_different_streams.cs index a78de3361..0f9f67121 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/can_create_duplicate_name_on_different_streams.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/can_create_duplicate_name_on_different_streams.cs @@ -1,26 +1,32 @@ -namespace EventStore.Client.SubscriptionToStream; +namespace EventStore.Client.SubscriptionToStream; public class can_create_duplicate_name_on_different_streams : IClassFixture { - public can_create_duplicate_name_on_different_streams(Fixture fixture) { - _fixture = fixture; - } - - private const string Stream = + const string Stream = nameof(can_create_duplicate_name_on_different_streams); - private readonly Fixture _fixture; + readonly Fixture _fixture; + + public can_create_duplicate_name_on_different_streams(Fixture fixture) => _fixture = fixture; + + [Fact] + public Task the_completion_succeeds() => + _fixture.Client.CreateToStreamAsync( + "someother" + Stream, + "group3211", + new(), + userCredentials: TestCredentials.Root + ); public class Fixture : EventStoreClientFixture { protected override Task Given() => Task.CompletedTask; protected override Task When() => - Client.CreateToStreamAsync(Stream, "group3211", - new PersistentSubscriptionSettings(), userCredentials: TestCredentials.Root); + Client.CreateToStreamAsync( + Stream, + "group3211", + new(), + userCredentials: TestCredentials.Root + ); } - - [Fact] - public Task the_completion_succeeds() => - _fixture.Client.CreateToStreamAsync("someother" + Stream, - "group3211", new PersistentSubscriptionSettings(), userCredentials: TestCredentials.Root); } \ No newline at end of file diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_to_existing_with_max_one_client.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_to_existing_with_max_one_client.cs index fa15838f5..30e70dfd1 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_to_existing_with_max_one_client.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_to_existing_with_max_one_client.cs @@ -1,26 +1,32 @@ -namespace EventStore.Client.SubscriptionToStream; +namespace EventStore.Client.SubscriptionToStream; public class connect_to_existing_with_max_one_client : IClassFixture { - private const string Group = "startinbeginning1"; - private const string Stream = nameof(connect_to_existing_with_max_one_client); - private readonly Fixture _fixture; + const string Group = "startinbeginning1"; + const string Stream = nameof(connect_to_existing_with_max_one_client); + readonly Fixture _fixture; - public connect_to_existing_with_max_one_client(Fixture fixture) { - _fixture = fixture; - } + public connect_to_existing_with_max_one_client(Fixture fixture) => _fixture = fixture; [Fact] public async Task the_second_subscription_fails_to_connect() { - using var first = await _fixture.Client.SubscribeToStreamAsync(Stream, Group, - delegate { return Task.CompletedTask; }, - userCredentials: TestCredentials.Root).WithTimeout(); + using var first = await _fixture.Client.SubscribeToStreamAsync( + Stream, + Group, + delegate { return Task.CompletedTask; }, + userCredentials: TestCredentials.Root + ).WithTimeout(); - var ex = await Assert.ThrowsAsync(async () => { - using var _ = await _fixture.Client.SubscribeToStreamAsync(Stream, Group, - delegate { return Task.CompletedTask; }, - userCredentials: TestCredentials.Root); - }).WithTimeout(); + var ex = await Assert.ThrowsAsync( + async () => { + using var _ = await _fixture.Client.SubscribeToStreamAsync( + Stream, + Group, + delegate { return Task.CompletedTask; }, + userCredentials: TestCredentials.Root + ); + } + ).WithTimeout(); Assert.Equal(Stream, ex.StreamName); Assert.Equal(Group, ex.GroupName); @@ -31,8 +37,9 @@ protected override Task Given() => Client.CreateToStreamAsync( Stream, Group, - new PersistentSubscriptionSettings(maxSubscriberCount: 1), - userCredentials: TestCredentials.Root); + new(maxSubscriberCount: 1), + userCredentials: TestCredentials.Root + ); protected override Task When() => Task.CompletedTask; } diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_to_existing_with_permissions.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_to_existing_with_permissions.cs index d3c99b41f..51b1eb5b0 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_to_existing_with_permissions.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_to_existing_with_permissions.cs @@ -1,21 +1,24 @@ -namespace EventStore.Client.SubscriptionToStream; +namespace EventStore.Client.SubscriptionToStream; public class connect_to_existing_with_permissions : IClassFixture { - private const string Stream = nameof(connect_to_existing_with_permissions); + const string Stream = nameof(connect_to_existing_with_permissions); - private readonly Fixture _fixture; + readonly Fixture _fixture; - public connect_to_existing_with_permissions(Fixture fixture) { - _fixture = fixture; - } + public connect_to_existing_with_permissions(Fixture fixture) => _fixture = fixture; [Fact] public async Task the_subscription_succeeds() { var dropped = new TaskCompletionSource<(SubscriptionDroppedReason, Exception?)>(); - using var subscription = await _fixture.Client.SubscribeToStreamAsync(Stream, "agroupname17", - delegate { return Task.CompletedTask; }, (s, reason, ex) => dropped.TrySetResult((reason, ex)), - TestCredentials.Root).WithTimeout(); + using var subscription = await _fixture.Client.SubscribeToStreamAsync( + Stream, + "agroupname17", + delegate { return Task.CompletedTask; }, + (s, reason, ex) => dropped.TrySetResult((reason, ex)), + TestCredentials.Root + ).WithTimeout(); + Assert.NotNull(subscription); await Assert.ThrowsAsync(() => dropped.Task.WithTimeout()); @@ -26,8 +29,9 @@ protected override Task Given() => Client.CreateToStreamAsync( Stream, "agroupname17", - new PersistentSubscriptionSettings(), - userCredentials: TestCredentials.Root); + new(), + userCredentials: TestCredentials.Root + ); protected override Task When() => Task.CompletedTask; } diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_to_existing_with_start_from_beginning_and_events_in_it.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_to_existing_with_start_from_beginning_and_events_in_it.cs index 64ed8b7c3..a30c512f6 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_to_existing_with_start_from_beginning_and_events_in_it.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_to_existing_with_start_from_beginning_and_events_in_it.cs @@ -1,18 +1,16 @@ -namespace EventStore.Client.SubscriptionToStream; +namespace EventStore.Client.SubscriptionToStream; public class connect_to_existing_with_start_from_beginning_and_events_in_it : IClassFixture { - private readonly Fixture _fixture; + const string Group = "startinbeginning1"; - private const string Group = "startinbeginning1"; - - private const string Stream = + const string Stream = nameof(connect_to_existing_with_start_from_beginning_and_events_in_it); - public connect_to_existing_with_start_from_beginning_and_events_in_it(Fixture fixture) { - _fixture = fixture; - } + readonly Fixture _fixture; + + public connect_to_existing_with_start_from_beginning_and_events_in_it(Fixture fixture) => _fixture = fixture; [Fact] public async Task the_subscription_gets_event_zero_as_its_first_event() { @@ -22,33 +20,41 @@ public async Task the_subscription_gets_event_zero_as_its_first_event() { } public class Fixture : EventStoreClientFixture { - private readonly TaskCompletionSource _firstEventSource; - public Task FirstEvent => _firstEventSource.Task; - public readonly EventData[] Events; - private PersistentSubscription? _subscription; + readonly TaskCompletionSource _firstEventSource; + public readonly EventData[] Events; + PersistentSubscription? _subscription; public Fixture() { - _firstEventSource = new TaskCompletionSource(); + _firstEventSource = new(); Events = CreateTestEvents(10).ToArray(); } + public Task FirstEvent => _firstEventSource.Task; + protected override async Task Given() { await StreamsClient.AppendToStreamAsync(Stream, StreamState.NoStream, Events); - await Client.CreateToStreamAsync(Stream, Group, - new PersistentSubscriptionSettings(startFrom: StreamPosition.Start), userCredentials: TestCredentials.Root); + await Client.CreateToStreamAsync( + Stream, + Group, + new(startFrom: StreamPosition.Start), + userCredentials: TestCredentials.Root + ); } - protected override async Task When() { - _subscription = await Client.SubscribeToStreamAsync(Stream, Group, - async (subscription, e, r, ct) => { - _firstEventSource.TrySetResult(e); - await subscription.Ack(e); - }, (subscription, reason, ex) => { - if (reason != SubscriptionDroppedReason.Disposed) { - _firstEventSource.TrySetException(ex!); - } - }, TestCredentials.TestUser1); - } + protected override async Task When() => + _subscription = await Client.SubscribeToStreamAsync( + Stream, + Group, + async (subscription, e, r, ct) => { + _firstEventSource.TrySetResult(e); + await subscription.Ack(e); + }, + (subscription, reason, ex) => { + if (reason != SubscriptionDroppedReason.Disposed) + _firstEventSource.TrySetException(ex!); + }, + TestCredentials.TestUser1 + ); public override Task DisposeAsync() { _subscription?.Dispose(); diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_to_existing_with_start_from_beginning_and_no_stream.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_to_existing_with_start_from_beginning_and_no_stream.cs index 225389b48..3255f67a9 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_to_existing_with_start_from_beginning_and_no_stream.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_to_existing_with_start_from_beginning_and_no_stream.cs @@ -1,17 +1,15 @@ -namespace EventStore.Client.SubscriptionToStream; +namespace EventStore.Client.SubscriptionToStream; public class connect_to_existing_with_start_from_beginning_and_no_stream : IClassFixture { - private readonly Fixture _fixture; + const string Group = "startinbeginning1"; - private const string Group = "startinbeginning1"; - - private const string Stream = + const string Stream = nameof(connect_to_existing_with_start_from_beginning_and_no_stream); - public connect_to_existing_with_start_from_beginning_and_no_stream(Fixture fixture) { - _fixture = fixture; - } + readonly Fixture _fixture; + + public connect_to_existing_with_start_from_beginning_and_no_stream(Fixture fixture) => _fixture = fixture; [Fact] public async Task the_subscription_gets_event_zero_as_its_first_event() { @@ -21,33 +19,42 @@ public async Task the_subscription_gets_event_zero_as_its_first_event() { } public class Fixture : EventStoreClientFixture { - private readonly TaskCompletionSource _firstEventSource; - public Task FirstEvent => _firstEventSource.Task; - public Uuid EventId => Events.Single().EventId; - public readonly EventData[] Events; - private PersistentSubscription? _subscription; + readonly TaskCompletionSource _firstEventSource; + public readonly EventData[] Events; + PersistentSubscription? _subscription; public Fixture() { - _firstEventSource = new TaskCompletionSource(); + _firstEventSource = new(); Events = CreateTestEvents().ToArray(); } + public Task FirstEvent => _firstEventSource.Task; + public Uuid EventId => Events.Single().EventId; + protected override async Task Given() { - await Client.CreateToStreamAsync(Stream, Group, - new PersistentSubscriptionSettings(), userCredentials: TestCredentials.Root); - _subscription = await Client.SubscribeToStreamAsync(Stream, Group, - async (subscription, e, r, ct) => { - _firstEventSource.TrySetResult(e); - await subscription.Ack(e); - }, (subscription, reason, ex) => { - if (reason != SubscriptionDroppedReason.Disposed) { - _firstEventSource.TrySetException(ex!); - } - }, TestCredentials.TestUser1); + await Client.CreateToStreamAsync( + Stream, + Group, + new(), + userCredentials: TestCredentials.Root + ); + + _subscription = await Client.SubscribeToStreamAsync( + Stream, + Group, + async (subscription, e, r, ct) => { + _firstEventSource.TrySetResult(e); + await subscription.Ack(e); + }, + (subscription, reason, ex) => { + if (reason != SubscriptionDroppedReason.Disposed) + _firstEventSource.TrySetException(ex!); + }, + TestCredentials.TestUser1 + ); } - protected override Task When() - => StreamsClient.AppendToStreamAsync(Stream, StreamState.NoStream, Events); + protected override Task When() => StreamsClient.AppendToStreamAsync(Stream, StreamState.NoStream, Events); public override Task DisposeAsync() { _subscription?.Dispose(); diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_to_existing_with_start_from_not_set_and_events_in_it.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_to_existing_with_start_from_not_set_and_events_in_it.cs index f27b35876..45c5487ed 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_to_existing_with_start_from_not_set_and_events_in_it.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_to_existing_with_start_from_not_set_and_events_in_it.cs @@ -1,52 +1,56 @@ -namespace EventStore.Client.SubscriptionToStream; +namespace EventStore.Client.SubscriptionToStream; public class connect_to_existing_with_start_from_not_set_and_events_in_it : IClassFixture { - private readonly Fixture _fixture; - private const string Group = "startinbeginning1"; + const string Group = "startinbeginning1"; - private const string Stream = + const string Stream = nameof(connect_to_existing_with_start_from_not_set_and_events_in_it); - public connect_to_existing_with_start_from_not_set_and_events_in_it( - Fixture fixture) { - _fixture = fixture; - } + readonly Fixture _fixture; + + public connect_to_existing_with_start_from_not_set_and_events_in_it(Fixture fixture) => _fixture = fixture; [Fact] - public async Task the_subscription_gets_no_events() { - await Assert.ThrowsAsync(() => _fixture.FirstEvent.WithTimeout()); - } + public async Task the_subscription_gets_no_events() => await Assert.ThrowsAsync(() => _fixture.FirstEvent.WithTimeout()); public class Fixture : EventStoreClientFixture { - private readonly TaskCompletionSource _firstEventSource; - public Task FirstEvent => _firstEventSource.Task; - public readonly EventData[] Events; - private PersistentSubscription? _subscription; + readonly TaskCompletionSource _firstEventSource; + public readonly EventData[] Events; + PersistentSubscription? _subscription; public Fixture() { - _firstEventSource = new TaskCompletionSource(); + _firstEventSource = new(); Events = CreateTestEvents(10).ToArray(); } + public Task FirstEvent => _firstEventSource.Task; + protected override async Task Given() { await StreamsClient.AppendToStreamAsync(Stream, StreamState.NoStream, Events); - await Client.CreateToStreamAsync(Stream, Group, - new PersistentSubscriptionSettings(), userCredentials: TestCredentials.Root); + await Client.CreateToStreamAsync( + Stream, + Group, + new(), + userCredentials: TestCredentials.Root + ); } - protected override async Task When() { - _subscription = await Client.SubscribeToStreamAsync(Stream, Group, - async (subscription, e, r, ct) => { - _firstEventSource.TrySetResult(e); - await subscription.Ack(e); - }, (subscription, reason, ex) => { - if (reason != SubscriptionDroppedReason.Disposed) { - _firstEventSource.TrySetException(ex!); - } - }, TestCredentials.TestUser1); - } + protected override async Task When() => + _subscription = await Client.SubscribeToStreamAsync( + Stream, + Group, + async (subscription, e, r, ct) => { + _firstEventSource.TrySetResult(e); + await subscription.Ack(e); + }, + (subscription, reason, ex) => { + if (reason != SubscriptionDroppedReason.Disposed) + _firstEventSource.TrySetException(ex!); + }, + TestCredentials.TestUser1 + ); public override Task DisposeAsync() { _subscription?.Dispose(); diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_to_existing_with_start_from_not_set_and_events_in_it_then_event_written.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_to_existing_with_start_from_not_set_and_events_in_it_then_event_written.cs index c75c7e5db..0ef5210ea 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_to_existing_with_start_from_not_set_and_events_in_it_then_event_written.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_to_existing_with_start_from_not_set_and_events_in_it_then_event_written.cs @@ -1,59 +1,62 @@ -namespace EventStore.Client.SubscriptionToStream; +namespace EventStore.Client.SubscriptionToStream; -public class - connect_to_existing_with_start_from_not_set_and_events_in_it_then_event_written - : IClassFixture< - connect_to_existing_with_start_from_not_set_and_events_in_it_then_event_written - .Fixture> { - private readonly Fixture _fixture; - private const string Group = "startinbeginning1"; +public class connect_to_existing_with_start_from_not_set_and_events_in_it_then_event_written + : IClassFixture { + const string Group = "startinbeginning1"; + const string Stream = nameof(connect_to_existing_with_start_from_not_set_and_events_in_it_then_event_written); - private const string Stream = - nameof( - connect_to_existing_with_start_from_not_set_and_events_in_it_then_event_written - ); + readonly Fixture _fixture; public - connect_to_existing_with_start_from_not_set_and_events_in_it_then_event_written( - Fixture fixture) { + connect_to_existing_with_start_from_not_set_and_events_in_it_then_event_written(Fixture fixture) => _fixture = fixture; - } [Fact] public async Task the_subscription_gets_the_written_event_as_its_first_event() { var resolvedEvent = await _fixture.FirstEvent.WithTimeout(); - Assert.Equal(new StreamPosition(10), resolvedEvent.Event.EventNumber); + Assert.Equal(new(10), resolvedEvent.Event.EventNumber); Assert.Equal(_fixture.Events.Last().EventId, resolvedEvent.Event.EventId); } public class Fixture : EventStoreClientFixture { - private readonly TaskCompletionSource _firstEventSource; - public Task FirstEvent => _firstEventSource.Task; - public readonly EventData[] Events; - private PersistentSubscription? _subscription; + readonly TaskCompletionSource _firstEventSource; + + public readonly EventData[] Events; + + PersistentSubscription? _subscription; public Fixture() { - _firstEventSource = new TaskCompletionSource(); + _firstEventSource = new(); Events = CreateTestEvents(11).ToArray(); } + public Task FirstEvent => _firstEventSource.Task; + protected override async Task Given() { await StreamsClient.AppendToStreamAsync(Stream, StreamState.NoStream, Events.Take(10)); - await Client.CreateToStreamAsync(Stream, Group, - new PersistentSubscriptionSettings(), userCredentials: TestCredentials.Root); - _subscription = await Client.SubscribeToStreamAsync(Stream, Group, - async (subscription, e, r, ct) => { - _firstEventSource.TrySetResult(e); - await subscription.Ack(e); - }, (subscription, reason, ex) => { - if (reason != SubscriptionDroppedReason.Disposed) { - _firstEventSource.TrySetException(ex!); - } - }, TestCredentials.TestUser1); + await Client.CreateToStreamAsync( + Stream, + Group, + new(), + userCredentials: TestCredentials.Root + ); + + _subscription = await Client.SubscribeToStreamAsync( + Stream, + Group, + async (subscription, e, r, ct) => { + _firstEventSource.TrySetResult(e); + await subscription.Ack(e); + }, + (subscription, reason, ex) => { + if (reason != SubscriptionDroppedReason.Disposed) + _firstEventSource.TrySetException(ex!); + }, + TestCredentials.TestUser1 + ); } - protected override Task When() => - StreamsClient.AppendToStreamAsync(Stream, new StreamRevision(9), Events.Skip(10)); + protected override Task When() => StreamsClient.AppendToStreamAsync(Stream, new StreamRevision(9), Events.Skip(10)); public override Task DisposeAsync() { _subscription?.Dispose(); diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_to_existing_with_start_from_set_to_end_position_and_events_in_it.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_to_existing_with_start_from_set_to_end_position_and_events_in_it.cs index 806ef37ec..479ec04e0 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_to_existing_with_start_from_set_to_end_position_and_events_in_it.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_to_existing_with_start_from_set_to_end_position_and_events_in_it.cs @@ -1,51 +1,55 @@ -namespace EventStore.Client.SubscriptionToStream; +namespace EventStore.Client.SubscriptionToStream; public class connect_to_existing_with_start_from_set_to_end_position_and_events_in_it : IClassFixture { - private readonly Fixture _fixture; - private const string Group = "startinbeginning1"; + const string Group = "startinbeginning1"; - private const string Stream = + const string Stream = nameof(connect_to_existing_with_start_from_set_to_end_position_and_events_in_it); - public connect_to_existing_with_start_from_set_to_end_position_and_events_in_it( - Fixture fixture) { - _fixture = fixture; - } + readonly Fixture _fixture; + + public connect_to_existing_with_start_from_set_to_end_position_and_events_in_it(Fixture fixture) => _fixture = fixture; [Fact] - public async Task the_subscription_gets_no_events() { - await Assert.ThrowsAsync(() => _fixture.FirstEvent.WithTimeout()); - } + public async Task the_subscription_gets_no_events() => await Assert.ThrowsAsync(() => _fixture.FirstEvent.WithTimeout()); public class Fixture : EventStoreClientFixture { - private readonly TaskCompletionSource _firstEventSource; - public Task FirstEvent => _firstEventSource.Task; - public readonly EventData[] Events; - private PersistentSubscription? _subscription; + readonly TaskCompletionSource _firstEventSource; + public readonly EventData[] Events; + PersistentSubscription? _subscription; public Fixture() { - _firstEventSource = new TaskCompletionSource(); + _firstEventSource = new(); Events = CreateTestEvents(10).ToArray(); } + public Task FirstEvent => _firstEventSource.Task; + protected override async Task Given() { await StreamsClient.AppendToStreamAsync(Stream, StreamState.NoStream, Events); - await Client.CreateToStreamAsync(Stream, Group, - new PersistentSubscriptionSettings(startFrom: StreamPosition.End), userCredentials: TestCredentials.Root); + await Client.CreateToStreamAsync( + Stream, + Group, + new(startFrom: StreamPosition.End), + userCredentials: TestCredentials.Root + ); } - protected override async Task When() { - _subscription = await Client.SubscribeToStreamAsync(Stream, Group, - async (subscription, e, r, ct) => { - _firstEventSource.TrySetResult(e); - await subscription.Ack(e); - }, (subscription, reason, ex) => { - if (reason != SubscriptionDroppedReason.Disposed) { - _firstEventSource.TrySetException(ex!); - } - }, TestCredentials.TestUser1); - } + protected override async Task When() => + _subscription = await Client.SubscribeToStreamAsync( + Stream, + Group, + async (subscription, e, r, ct) => { + _firstEventSource.TrySetResult(e); + await subscription.Ack(e); + }, + (subscription, reason, ex) => { + if (reason != SubscriptionDroppedReason.Disposed) + _firstEventSource.TrySetException(ex!); + }, + TestCredentials.TestUser1 + ); public override Task DisposeAsync() { _subscription?.Dispose(); diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_to_existing_with_start_from_set_to_end_position_and_events_in_it_then_event_written.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_to_existing_with_start_from_set_to_end_position_and_events_in_it_then_event_written.cs index f84bdc109..73153aaaa 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_to_existing_with_start_from_set_to_end_position_and_events_in_it_then_event_written.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_to_existing_with_start_from_set_to_end_position_and_events_in_it_then_event_written.cs @@ -1,59 +1,67 @@ -namespace EventStore.Client.SubscriptionToStream; +namespace EventStore.Client.SubscriptionToStream; public class connect_to_existing_with_start_from_set_to_end_position_and_events_in_it_then_event_written : IClassFixture< connect_to_existing_with_start_from_set_to_end_position_and_events_in_it_then_event_written .Fixture> { - private readonly Fixture _fixture; - private const string Group = "startinbeginning1"; + const string Group = "startinbeginning1"; - private const string Stream = + const string Stream = nameof( connect_to_existing_with_start_from_set_to_end_position_and_events_in_it_then_event_written ); + readonly Fixture _fixture; + public - connect_to_existing_with_start_from_set_to_end_position_and_events_in_it_then_event_written( - Fixture fixture) { + connect_to_existing_with_start_from_set_to_end_position_and_events_in_it_then_event_written(Fixture fixture) => _fixture = fixture; - } [Fact] public async Task the_subscription_gets_the_written_event_as_its_first_event() { var resolvedEvent = await _fixture.FirstEvent.WithTimeout(); - Assert.Equal(new StreamPosition(10), resolvedEvent.Event.EventNumber); + Assert.Equal(new(10), resolvedEvent.Event.EventNumber); Assert.Equal(_fixture.Events.Last().EventId, resolvedEvent.Event.EventId); } public class Fixture : EventStoreClientFixture { - private readonly TaskCompletionSource _firstEventSource; - public Task FirstEvent => _firstEventSource.Task; - public readonly EventData[] Events; - private PersistentSubscription? _subscription; + readonly TaskCompletionSource _firstEventSource; + public readonly EventData[] Events; + PersistentSubscription? _subscription; public Fixture() { - _firstEventSource = new TaskCompletionSource(); + _firstEventSource = new(); Events = CreateTestEvents(11).ToArray(); } + public Task FirstEvent => _firstEventSource.Task; + protected override async Task Given() { await StreamsClient.AppendToStreamAsync(Stream, StreamState.NoStream, Events.Take(10)); - await Client.CreateToStreamAsync(Stream, Group, - new PersistentSubscriptionSettings(startFrom: StreamPosition.End), userCredentials: TestCredentials.Root); - _subscription = await Client.SubscribeToStreamAsync(Stream, Group, - async (subscription, e, r, ct) => { - _firstEventSource.TrySetResult(e); - await subscription.Ack(e); - }, (subscription, reason, ex) => { - if (reason != SubscriptionDroppedReason.Disposed) { - _firstEventSource.TrySetException(ex!); - } - }, TestCredentials.TestUser1); + await Client.CreateToStreamAsync( + Stream, + Group, + new(startFrom: StreamPosition.End), + userCredentials: TestCredentials.Root + ); + + _subscription = await Client.SubscribeToStreamAsync( + Stream, + Group, + async (subscription, e, r, ct) => { + _firstEventSource.TrySetResult(e); + await subscription.Ack(e); + }, + (subscription, reason, ex) => { + if (reason != SubscriptionDroppedReason.Disposed) + _firstEventSource.TrySetException(ex!); + }, + TestCredentials.TestUser1 + ); } - protected override Task When() => - StreamsClient.AppendToStreamAsync(Stream, new StreamRevision(9), Events.Skip(10)); + protected override Task When() => StreamsClient.AppendToStreamAsync(Stream, new StreamRevision(9), Events.Skip(10)); public override Task DisposeAsync() { _subscription?.Dispose(); diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_to_existing_with_start_from_two_and_no_stream.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_to_existing_with_start_from_two_and_no_stream.cs index 56dc44f20..cea639d17 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_to_existing_with_start_from_two_and_no_stream.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_to_existing_with_start_from_two_and_no_stream.cs @@ -1,52 +1,60 @@ -namespace EventStore.Client.SubscriptionToStream; +namespace EventStore.Client.SubscriptionToStream; public class connect_to_existing_with_start_from_two_and_no_stream : IClassFixture { - private readonly Fixture _fixture; - private const string Group = "startinbeginning1"; + const string Group = "startinbeginning1"; - private const string Stream = + const string Stream = nameof(connect_to_existing_with_start_from_two_and_no_stream); - public connect_to_existing_with_start_from_two_and_no_stream(Fixture fixture) { - _fixture = fixture; - } + readonly Fixture _fixture; + + public connect_to_existing_with_start_from_two_and_no_stream(Fixture fixture) => _fixture = fixture; [Fact] public async Task the_subscription_gets_event_two_as_its_first_event() { var resolvedEvent = await _fixture.FirstEvent.WithTimeout(TimeSpan.FromSeconds(10)); - Assert.Equal(new StreamPosition(2), resolvedEvent.Event.EventNumber); + Assert.Equal(new(2), resolvedEvent.Event.EventNumber); Assert.Equal(_fixture.EventId, resolvedEvent.Event.EventId); } public class Fixture : EventStoreClientFixture { - private readonly TaskCompletionSource _firstEventSource; - public Task FirstEvent => _firstEventSource.Task; - public Uuid EventId => Events.Last().EventId; - public readonly EventData[] Events; - private PersistentSubscription? _subscription; + readonly TaskCompletionSource _firstEventSource; + public readonly EventData[] Events; + PersistentSubscription? _subscription; public Fixture() { - _firstEventSource = new TaskCompletionSource(); + _firstEventSource = new(); Events = CreateTestEvents(3).ToArray(); } + public Task FirstEvent => _firstEventSource.Task; + public Uuid EventId => Events.Last().EventId; + protected override async Task Given() { - await Client.CreateToStreamAsync(Stream, Group, - new PersistentSubscriptionSettings(startFrom: new StreamPosition(2)), userCredentials: TestCredentials.Root); - _subscription = await Client.SubscribeToStreamAsync(Stream, Group, - async (subscription, e, r, ct) => { - _firstEventSource.TrySetResult(e); - await subscription.Ack(e); - }, (subscription, reason, ex) => { - if (reason != SubscriptionDroppedReason.Disposed) { - _firstEventSource.TrySetException(ex!); - } - }, TestCredentials.TestUser1); + await Client.CreateToStreamAsync( + Stream, + Group, + new(startFrom: new StreamPosition(2)), + userCredentials: TestCredentials.Root + ); + + _subscription = await Client.SubscribeToStreamAsync( + Stream, + Group, + async (subscription, e, r, ct) => { + _firstEventSource.TrySetResult(e); + await subscription.Ack(e); + }, + (subscription, reason, ex) => { + if (reason != SubscriptionDroppedReason.Disposed) + _firstEventSource.TrySetException(ex!); + }, + TestCredentials.TestUser1 + ); } - protected override Task When() - => StreamsClient.AppendToStreamAsync(Stream, StreamState.NoStream, Events); + protected override Task When() => StreamsClient.AppendToStreamAsync(Stream, StreamState.NoStream, Events); public override Task DisposeAsync() { _subscription?.Dispose(); diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_to_existing_with_start_from_x_set_and_events_in_it.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_to_existing_with_start_from_x_set_and_events_in_it.cs index 433e7fb2f..b21bcf910 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_to_existing_with_start_from_x_set_and_events_in_it.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_to_existing_with_start_from_x_set_and_events_in_it.cs @@ -1,52 +1,60 @@ -namespace EventStore.Client.SubscriptionToStream; +namespace EventStore.Client.SubscriptionToStream; public class connect_to_existing_with_start_from_x_set_and_events_in_it : IClassFixture { - private readonly Fixture _fixture; - private const string Group = "startinx2"; + const string Group = "startinx2"; - private const string Stream = + const string Stream = nameof(connect_to_existing_with_start_from_x_set_and_events_in_it); - public connect_to_existing_with_start_from_x_set_and_events_in_it(Fixture fixture) { - _fixture = fixture; - } + readonly Fixture _fixture; + + public connect_to_existing_with_start_from_x_set_and_events_in_it(Fixture fixture) => _fixture = fixture; [Fact] public async Task the_subscription_gets_the_written_event_as_its_first_event() { var resolvedEvent = await _fixture.FirstEvent.WithTimeout(); - Assert.Equal(new StreamPosition(4), resolvedEvent.Event.EventNumber); + Assert.Equal(new(4), resolvedEvent.Event.EventNumber); Assert.Equal(_fixture.Events.Skip(4).First().EventId, resolvedEvent.Event.EventId); } public class Fixture : EventStoreClientFixture { - private readonly TaskCompletionSource _firstEventSource; - public Task FirstEvent => _firstEventSource.Task; - public readonly EventData[] Events; - private PersistentSubscription? _subscription; + readonly TaskCompletionSource _firstEventSource; + public readonly EventData[] Events; + PersistentSubscription? _subscription; public Fixture() { - _firstEventSource = new TaskCompletionSource(); + _firstEventSource = new(); Events = CreateTestEvents(10).ToArray(); } + public Task FirstEvent => _firstEventSource.Task; + protected override async Task Given() { await StreamsClient.AppendToStreamAsync(Stream, StreamState.NoStream, Events.Take(10)); - await Client.CreateToStreamAsync(Stream, Group, - new PersistentSubscriptionSettings(startFrom: new StreamPosition(4)), userCredentials: TestCredentials.Root); - _subscription = await Client.SubscribeToStreamAsync(Stream, Group, - async (subscription, e, r, ct) => { - _firstEventSource.TrySetResult(e); - await subscription.Ack(e); - }, (subscription, reason, ex) => { - if (reason != SubscriptionDroppedReason.Disposed) { - _firstEventSource.TrySetException(ex!); - } - }, TestCredentials.TestUser1); + await Client.CreateToStreamAsync( + Stream, + Group, + new(startFrom: new StreamPosition(4)), + userCredentials: TestCredentials.Root + ); + + _subscription = await Client.SubscribeToStreamAsync( + Stream, + Group, + async (subscription, e, r, ct) => { + _firstEventSource.TrySetResult(e); + await subscription.Ack(e); + }, + (subscription, reason, ex) => { + if (reason != SubscriptionDroppedReason.Disposed) + _firstEventSource.TrySetException(ex!); + }, + TestCredentials.TestUser1 + ); } - protected override Task When() => - StreamsClient.AppendToStreamAsync(Stream, new StreamRevision(9), Events.Skip(10)); + protected override Task When() => StreamsClient.AppendToStreamAsync(Stream, new StreamRevision(9), Events.Skip(10)); public override Task DisposeAsync() { _subscription?.Dispose(); diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_to_existing_with_start_from_x_set_and_events_in_it_then_event_written.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_to_existing_with_start_from_x_set_and_events_in_it_then_event_written.cs index 04c948728..69cb11385 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_to_existing_with_start_from_x_set_and_events_in_it_then_event_written.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_to_existing_with_start_from_x_set_and_events_in_it_then_event_written.cs @@ -1,57 +1,63 @@ -namespace EventStore.Client.SubscriptionToStream; +namespace EventStore.Client.SubscriptionToStream; public class connect_to_existing_with_start_from_x_set_and_events_in_it_then_event_written : IClassFixture< connect_to_existing_with_start_from_x_set_and_events_in_it_then_event_written. Fixture> { - private const string Group = "startinbeginning1"; + const string Group = "startinbeginning1"; - private const string Stream = + const string Stream = nameof(connect_to_existing_with_start_from_x_set_and_events_in_it_then_event_written ); - private readonly Fixture _fixture; + readonly Fixture _fixture; - public connect_to_existing_with_start_from_x_set_and_events_in_it_then_event_written( - Fixture fixture) { - _fixture = fixture; - } + public connect_to_existing_with_start_from_x_set_and_events_in_it_then_event_written(Fixture fixture) => _fixture = fixture; [Fact] public async Task the_subscription_gets_the_written_event_as_its_first_event() { var resolvedEvent = await _fixture.FirstEvent.WithTimeout(); - Assert.Equal(new StreamPosition(10), resolvedEvent.Event.EventNumber); + Assert.Equal(new(10), resolvedEvent.Event.EventNumber); Assert.Equal(_fixture.Events.Last().EventId, resolvedEvent.Event.EventId); } public class Fixture : EventStoreClientFixture { - private readonly TaskCompletionSource _firstEventSource; - public Task FirstEvent => _firstEventSource.Task; - public readonly EventData[] Events; - private PersistentSubscription? _subscription; + readonly TaskCompletionSource _firstEventSource; + public readonly EventData[] Events; + PersistentSubscription? _subscription; public Fixture() { - _firstEventSource = new TaskCompletionSource(); + _firstEventSource = new(); Events = CreateTestEvents(11).ToArray(); } + public Task FirstEvent => _firstEventSource.Task; + protected override async Task Given() { await StreamsClient.AppendToStreamAsync(Stream, StreamState.NoStream, Events.Take(10)); - await Client.CreateToStreamAsync(Stream, Group, - new PersistentSubscriptionSettings(startFrom: new StreamPosition(10)), userCredentials: TestCredentials.Root); - _subscription = await Client.SubscribeToStreamAsync(Stream, Group, - async (subscription, e, r, ct) => { - _firstEventSource.TrySetResult(e); - await subscription.Ack(e); - }, (subscription, reason, ex) => { - if (reason != SubscriptionDroppedReason.Disposed) { - _firstEventSource.TrySetException(ex!); - } - }, TestCredentials.TestUser1); + await Client.CreateToStreamAsync( + Stream, + Group, + new(startFrom: new StreamPosition(10)), + userCredentials: TestCredentials.Root + ); + + _subscription = await Client.SubscribeToStreamAsync( + Stream, + Group, + async (subscription, e, r, ct) => { + _firstEventSource.TrySetResult(e); + await subscription.Ack(e); + }, + (subscription, reason, ex) => { + if (reason != SubscriptionDroppedReason.Disposed) + _firstEventSource.TrySetException(ex!); + }, + TestCredentials.TestUser1 + ); } - protected override Task When() => - StreamsClient.AppendToStreamAsync(Stream, new StreamRevision(9), Events.Skip(10)); + protected override Task When() => StreamsClient.AppendToStreamAsync(Stream, new StreamRevision(9), Events.Skip(10)); public override Task DisposeAsync() { _subscription?.Dispose(); diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_to_existing_with_start_from_x_set_higher_than_x_and_events_in_it_then_event_written.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_to_existing_with_start_from_x_set_higher_than_x_and_events_in_it_then_event_written.cs index cba11675c..7f281a78a 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_to_existing_with_start_from_x_set_higher_than_x_and_events_in_it_then_event_written.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_to_existing_with_start_from_x_set_higher_than_x_and_events_in_it_then_event_written.cs @@ -1,60 +1,67 @@ -namespace EventStore.Client.SubscriptionToStream; +namespace EventStore.Client.SubscriptionToStream; public class connect_to_existing_with_start_from_x_set_higher_than_x_and_events_in_it_then_event_written : IClassFixture< connect_to_existing_with_start_from_x_set_higher_than_x_and_events_in_it_then_event_written .Fixture> { - private const string Group = "startinbeginning1"; + const string Group = "startinbeginning1"; - private const string Stream = + const string Stream = nameof( connect_to_existing_with_start_from_x_set_higher_than_x_and_events_in_it_then_event_written ); - private readonly Fixture _fixture; + readonly Fixture _fixture; public - connect_to_existing_with_start_from_x_set_higher_than_x_and_events_in_it_then_event_written( - Fixture fixture) { + connect_to_existing_with_start_from_x_set_higher_than_x_and_events_in_it_then_event_written(Fixture fixture) => _fixture = fixture; - } [Fact] public async Task the_subscription_gets_the_written_event_as_its_first_event() { var resolvedEvent = await _fixture.FirstEvent.WithTimeout(); - Assert.Equal(new StreamPosition(11), resolvedEvent.Event.EventNumber); + Assert.Equal(new(11), resolvedEvent.Event.EventNumber); Assert.Equal(_fixture.Events.Last().EventId, resolvedEvent.Event.EventId); } public class Fixture : EventStoreClientFixture { - private readonly TaskCompletionSource _firstEventSource; - public Task FirstEvent => _firstEventSource.Task; - public readonly EventData[] Events; - private PersistentSubscription? _subscription; + readonly TaskCompletionSource _firstEventSource; + public readonly EventData[] Events; + PersistentSubscription? _subscription; public Fixture() { - _firstEventSource = new TaskCompletionSource(); + _firstEventSource = new(); Events = CreateTestEvents(12).ToArray(); } + public Task FirstEvent => _firstEventSource.Task; + protected override async Task Given() { await StreamsClient.AppendToStreamAsync(Stream, StreamState.NoStream, Events.Take(11)); - await Client.CreateToStreamAsync(Stream, Group, - new PersistentSubscriptionSettings(startFrom: new StreamPosition(11)), userCredentials: TestCredentials.Root); - _subscription = await Client.SubscribeToStreamAsync(Stream, Group, - async (subscription, e, r, ct) => { - _firstEventSource.TrySetResult(e); - await subscription.Ack(e); - }, (subscription, reason, ex) => { - if (reason != SubscriptionDroppedReason.Disposed) { - _firstEventSource.TrySetException(ex!); - } - }, TestCredentials.TestUser1); + await Client.CreateToStreamAsync( + Stream, + Group, + new(startFrom: new StreamPosition(11)), + userCredentials: TestCredentials.Root + ); + + _subscription = await Client.SubscribeToStreamAsync( + Stream, + Group, + async (subscription, e, r, ct) => { + _firstEventSource.TrySetResult(e); + await subscription.Ack(e); + }, + (subscription, reason, ex) => { + if (reason != SubscriptionDroppedReason.Disposed) + _firstEventSource.TrySetException(ex!); + }, + TestCredentials.TestUser1 + ); } - protected override Task When() => - StreamsClient.AppendToStreamAsync(Stream, new StreamRevision(10), Events.Skip(11)); + protected override Task When() => StreamsClient.AppendToStreamAsync(Stream, new StreamRevision(10), Events.Skip(11)); public override Task DisposeAsync() { _subscription?.Dispose(); diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_to_existing_without_permissions.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_to_existing_without_permissions.cs index 27c97db52..01ec9be5a 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_to_existing_without_permissions.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_to_existing_without_permissions.cs @@ -1,28 +1,33 @@ -namespace EventStore.Client.SubscriptionToStream; +namespace EventStore.Client.SubscriptionToStream; public class connect_to_existing_without_permissions : IClassFixture { - private const string Stream = "$" + nameof(connect_to_existing_without_permissions); - private readonly Fixture _fixture; - public connect_to_existing_without_permissions(Fixture fixture) { _fixture = fixture; } + const string Stream = "$" + nameof(connect_to_existing_without_permissions); + readonly Fixture _fixture; + public connect_to_existing_without_permissions(Fixture fixture) => _fixture = fixture; [Fact] public Task throws_access_denied() => - Assert.ThrowsAsync(async () => { - using var _ = await _fixture.Client.SubscribeToStreamAsync(Stream, "agroupname55", - delegate { return Task.CompletedTask; }); - }).WithTimeout(); + Assert.ThrowsAsync( + async () => { + using var _ = await _fixture.Client.SubscribeToStreamAsync( + Stream, + "agroupname55", + delegate { return Task.CompletedTask; } + ); + } + ).WithTimeout(); public class Fixture : EventStoreClientFixture { - public Fixture () : base(noDefaultCredentials: true){ - } - + public Fixture() : base(noDefaultCredentials: true) { } + protected override Task Given() => Client.CreateToStreamAsync( Stream, "agroupname55", - new PersistentSubscriptionSettings(), - userCredentials: TestCredentials.Root); + new(), + userCredentials: TestCredentials.Root + ); protected override Task When() => Task.CompletedTask; } diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_to_non_existing_with_permissions.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_to_non_existing_with_permissions.cs index 9009fe19b..5c7a437a8 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_to_non_existing_with_permissions.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_to_non_existing_with_permissions.cs @@ -1,27 +1,26 @@ -namespace EventStore.Client.SubscriptionToStream; +namespace EventStore.Client.SubscriptionToStream; public class connect_to_non_existing_with_permissions : IClassFixture { - private const string Stream = nameof(connect_to_non_existing_with_permissions); - private const string Group = "foo"; + const string Stream = nameof(connect_to_non_existing_with_permissions); + const string Group = "foo"; - private readonly Fixture _fixture; + readonly Fixture _fixture; - public connect_to_non_existing_with_permissions(Fixture fixture) { - _fixture = fixture; - } + public connect_to_non_existing_with_permissions(Fixture fixture) => _fixture = fixture; [Fact] public async Task throws_persistent_subscription_not_found() { - var ex = await Assert.ThrowsAsync(async () => { - using var _ = await _fixture.Client.SubscribeToStreamAsync( - Stream, - Group, - delegate { - return Task.CompletedTask; - }, - userCredentials: TestCredentials.Root); - }).WithTimeout(); + var ex = await Assert.ThrowsAsync( + async () => { + using var _ = await _fixture.Client.SubscribeToStreamAsync( + Stream, + Group, + delegate { return Task.CompletedTask; }, + userCredentials: TestCredentials.Root + ); + } + ).WithTimeout(); Assert.Equal(Stream, ex.StreamName); Assert.Equal(Group, ex.GroupName); diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_with_retries.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_with_retries.cs index 206c63c8f..5970d2275 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_with_retries.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connect_with_retries.cs @@ -1,54 +1,66 @@ -namespace EventStore.Client.SubscriptionToStream; +namespace EventStore.Client.SubscriptionToStream; public class connect_with_retries : IClassFixture { - private readonly Fixture _fixture; - private const string Group = "retries"; + const string Group = "retries"; + const string Stream = nameof(connect_with_retries); - private const string Stream = nameof(connect_with_retries); + readonly Fixture _fixture; - public connect_with_retries(Fixture fixture) { - _fixture = fixture; - } + public connect_with_retries(Fixture fixture) => _fixture = fixture; [Fact] - public async Task events_are_retried_until_success() { - Assert.Equal(5, await _fixture.RetryCount.WithTimeout()); - } + public async Task events_are_retried_until_success() => Assert.Equal(5, await _fixture.RetryCount.WithTimeout()); public class Fixture : EventStoreClientFixture { - private readonly TaskCompletionSource _retryCountSource; - public Task RetryCount => _retryCountSource.Task; - public readonly EventData[] Events; - private PersistentSubscription? _subscription; + readonly TaskCompletionSource _retryCountSource; + + public readonly EventData[] Events; + + PersistentSubscription? _subscription; public Fixture() { - _retryCountSource = new TaskCompletionSource(); - Events = CreateTestEvents().ToArray(); + _retryCountSource = new(); + + Events = CreateTestEvents().ToArray(); } + public Task RetryCount => _retryCountSource.Task; + protected override async Task Given() { await StreamsClient.AppendToStreamAsync(Stream, StreamState.NoStream, Events); - await Client.CreateToStreamAsync(Stream, Group, - new PersistentSubscriptionSettings(startFrom: StreamPosition.Start), userCredentials: TestCredentials.Root); - _subscription = await Client.SubscribeToStreamAsync(Stream, Group, - async (subscription, e, r, ct) => { - if (r > 4) { - _retryCountSource.TrySetResult(r.Value); - await subscription.Ack(e.Event.EventId); - } else { - await subscription.Nack(PersistentSubscriptionNakEventAction.Retry, - "Not yet tried enough times", e); - } - }, subscriptionDropped: (subscription, reason, ex) => { - if (reason != SubscriptionDroppedReason.Disposed) { - _retryCountSource.TrySetException(ex!); - } - }, userCredentials:TestCredentials.TestUser1); + await Client.CreateToStreamAsync( + Stream, + Group, + new(startFrom: StreamPosition.Start), + userCredentials: TestCredentials.Root + ); + + _subscription = await Client.SubscribeToStreamAsync( + Stream, + Group, + async (subscription, e, r, ct) => { + if (r > 4) { + _retryCountSource.TrySetResult(r.Value); + await subscription.Ack(e.Event.EventId); + } + else { + await subscription.Nack( + PersistentSubscriptionNakEventAction.Retry, + "Not yet tried enough times", + e + ); + } + }, + (subscription, reason, ex) => { + if (reason != SubscriptionDroppedReason.Disposed) + _retryCountSource.TrySetException(ex!); + }, + TestCredentials.TestUser1 + ); } - protected override Task When() => - StreamsClient.AppendToStreamAsync(Stream, StreamState.NoStream, Events); + protected override Task When() => StreamsClient.AppendToStreamAsync(Stream, StreamState.NoStream, Events); public override Task DisposeAsync() { _subscription?.Dispose(); diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connecting_to_a_persistent_subscription.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connecting_to_a_persistent_subscription.cs index f42b85166..4d97a6ff8 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connecting_to_a_persistent_subscription.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/connecting_to_a_persistent_subscription.cs @@ -1,60 +1,67 @@ -namespace EventStore.Client.SubscriptionToStream; +namespace EventStore.Client.SubscriptionToStream; public class connecting_to_a_persistent_subscription : IClassFixture< connecting_to_a_persistent_subscription .Fixture> { - private const string Group = "startinbeginning1"; + const string Group = "startinbeginning1"; - private const string Stream = + const string Stream = nameof( connecting_to_a_persistent_subscription ); - private readonly Fixture _fixture; + readonly Fixture _fixture; public - connecting_to_a_persistent_subscription( - Fixture fixture) { + connecting_to_a_persistent_subscription(Fixture fixture) => _fixture = fixture; - } [Fact] public async Task the_subscription_gets_the_written_event_as_its_first_event() { var resolvedEvent = await _fixture.FirstEvent.WithTimeout(); - Assert.Equal(new StreamPosition(11), resolvedEvent.Event.EventNumber); + Assert.Equal(new(11), resolvedEvent.Event.EventNumber); Assert.Equal(_fixture.Events.Last().EventId, resolvedEvent.Event.EventId); } public class Fixture : EventStoreClientFixture { - private readonly TaskCompletionSource _firstEventSource; - public Task FirstEvent => _firstEventSource.Task; - public readonly EventData[] Events; - private PersistentSubscription? _subscription; + readonly TaskCompletionSource _firstEventSource; + public readonly EventData[] Events; + PersistentSubscription? _subscription; public Fixture() { - _firstEventSource = new TaskCompletionSource(); + _firstEventSource = new(); Events = CreateTestEvents(12).ToArray(); } + public Task FirstEvent => _firstEventSource.Task; + protected override async Task Given() { await StreamsClient.AppendToStreamAsync(Stream, StreamState.NoStream, Events.Take(11)); - await Client.CreateToStreamAsync(Stream, Group, - new PersistentSubscriptionSettings(startFrom: new StreamPosition(11)), userCredentials: TestCredentials.Root); - _subscription = await Client.SubscribeToStreamAsync(Stream, Group, - async (subscription, e, r, ct) => { - _firstEventSource.TrySetResult(e); - await subscription.Ack(e); - }, (subscription, reason, ex) => { - if (reason != SubscriptionDroppedReason.Disposed) { - _firstEventSource.TrySetException(ex!); - } - }, TestCredentials.TestUser1); + await Client.CreateToStreamAsync( + Stream, + Group, + new(startFrom: new StreamPosition(11)), + userCredentials: TestCredentials.Root + ); + + _subscription = await Client.SubscribeToStreamAsync( + Stream, + Group, + async (subscription, e, r, ct) => { + _firstEventSource.TrySetResult(e); + await subscription.Ack(e); + }, + (subscription, reason, ex) => { + if (reason != SubscriptionDroppedReason.Disposed) + _firstEventSource.TrySetException(ex!); + }, + TestCredentials.TestUser1 + ); } - protected override Task When() => - StreamsClient.AppendToStreamAsync(Stream, new StreamRevision(10), Events.Skip(11)); + protected override Task When() => StreamsClient.AppendToStreamAsync(Stream, new StreamRevision(10), Events.Skip(11)); public override Task DisposeAsync() { _subscription?.Dispose(); diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/create_after_deleting_the_same.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/create_after_deleting_the_same.cs index 588728ff3..ed03e8541 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/create_after_deleting_the_same.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/create_after_deleting_the_same.cs @@ -1,29 +1,38 @@ -namespace EventStore.Client.SubscriptionToStream; +namespace EventStore.Client.SubscriptionToStream; public class create_after_deleting_the_same : IClassFixture { - public create_after_deleting_the_same(Fixture fixture) { - _fixture = fixture; - } + const string Stream = nameof(create_after_deleting_the_same); + readonly Fixture _fixture; + + public create_after_deleting_the_same(Fixture fixture) => _fixture = fixture; - private const string Stream = nameof(create_after_deleting_the_same); - private readonly Fixture _fixture; + [Fact] + public async Task the_completion_succeeds() => + await _fixture.Client.CreateToStreamAsync( + Stream, + "existing", + new(), + userCredentials: TestCredentials.Root + ); public class Fixture : EventStoreClientFixture { protected override Task Given() => Task.CompletedTask; protected override async Task When() { await StreamsClient.AppendToStreamAsync(Stream, StreamState.Any, CreateTestEvents()); - await Client.CreateToStreamAsync(Stream, "existing", - new PersistentSubscriptionSettings(), userCredentials: TestCredentials.Root); - await Client.DeleteToStreamAsync(Stream, "existing", - userCredentials: TestCredentials.Root); - } - } + await Client.CreateToStreamAsync( + Stream, + "existing", + new(), + userCredentials: TestCredentials.Root + ); - [Fact] - public async Task the_completion_succeeds() { - await _fixture.Client.CreateToStreamAsync(Stream, "existing", - new PersistentSubscriptionSettings(), userCredentials: TestCredentials.Root); + await Client.DeleteToStreamAsync( + Stream, + "existing", + userCredentials: TestCredentials.Root + ); + } } } \ No newline at end of file diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/create_duplicate.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/create_duplicate.cs index 5334c4593..0bf4c6197 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/create_duplicate.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/create_duplicate.cs @@ -1,30 +1,37 @@ using Grpc.Core; -namespace EventStore.Client.SubscriptionToStream; +namespace EventStore.Client.SubscriptionToStream; public class create_duplicate : IClassFixture { - public create_duplicate(Fixture fixture) { - _fixture = fixture; - } - - private const string Stream = nameof(create_duplicate); - private readonly Fixture _fixture; + const string Stream = nameof(create_duplicate); + readonly Fixture _fixture; - public class Fixture : EventStoreClientFixture { - protected override Task Given() => Task.CompletedTask; - - protected override Task When() => - Client.CreateToStreamAsync(Stream, "group32", - new PersistentSubscriptionSettings(), userCredentials: TestCredentials.Root); - } + public create_duplicate(Fixture fixture) => _fixture = fixture; [Fact] public async Task the_completion_fails() { var ex = await Assert.ThrowsAsync( - () => _fixture.Client.CreateToStreamAsync(Stream, "group32", - new PersistentSubscriptionSettings(), - userCredentials: TestCredentials.Root)); + () => _fixture.Client.CreateToStreamAsync( + Stream, + "group32", + new(), + userCredentials: TestCredentials.Root + ) + ); + Assert.Equal(StatusCode.AlreadyExists, ex.StatusCode); } + + public class Fixture : EventStoreClientFixture { + protected override Task Given() => Task.CompletedTask; + + protected override Task When() => + Client.CreateToStreamAsync( + Stream, + "group32", + new(), + userCredentials: TestCredentials.Root + ); + } } \ No newline at end of file diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/create_on_existing_stream.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/create_on_existing_stream.cs index 52ecb74e7..e1cb47746 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/create_on_existing_stream.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/create_on_existing_stream.cs @@ -1,23 +1,24 @@ -namespace EventStore.Client.SubscriptionToStream; +namespace EventStore.Client.SubscriptionToStream; public class create_on_existing_stream : IClassFixture { - public create_on_existing_stream(Fixture fixture) { - _fixture = fixture; - } + const string Stream = nameof(create_on_existing_stream); + readonly Fixture _fixture; + + public create_on_existing_stream(Fixture fixture) => _fixture = fixture; - private const string Stream = nameof(create_on_existing_stream); - private readonly Fixture _fixture; + [Fact] + public Task the_completion_succeeds() => + _fixture.Client.CreateToStreamAsync( + Stream, + "existing", + new(), + userCredentials: TestCredentials.Root + ); public class Fixture : EventStoreClientFixture { protected override Task Given() => Task.CompletedTask; - protected override async Task When() => - await StreamsClient.AppendToStreamAsync(Stream, StreamState.Any, CreateTestEvents()); + protected override async Task When() => await StreamsClient.AppendToStreamAsync(Stream, StreamState.Any, CreateTestEvents()); } - - [Fact] - public Task the_completion_succeeds() - => _fixture.Client.CreateToStreamAsync( - Stream, "existing", new PersistentSubscriptionSettings(), userCredentials: TestCredentials.Root); } \ No newline at end of file diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/create_on_non_existing_stream.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/create_on_non_existing_stream.cs index 506a78a6f..762cc052e 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/create_on_non_existing_stream.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/create_on_non_existing_stream.cs @@ -1,23 +1,23 @@ -namespace EventStore.Client.SubscriptionToStream; +namespace EventStore.Client.SubscriptionToStream; public class create_on_non_existing_stream : IClassFixture { - public create_on_non_existing_stream(Fixture fixture) { - _fixture = fixture; - } + const string Stream = nameof(create_on_non_existing_stream); + readonly Fixture _fixture; + + public create_on_non_existing_stream(Fixture fixture) => _fixture = fixture; - private const string Stream = nameof(create_on_non_existing_stream); - private readonly Fixture _fixture; + [Fact] + public async Task the_completion_succeeds() => + await _fixture.Client.CreateToStreamAsync( + Stream, + "nonexistinggroup", + new(), + userCredentials: TestCredentials.Root + ); public class Fixture : EventStoreClientFixture { protected override Task Given() => Task.CompletedTask; protected override Task When() => Task.CompletedTask; } - - [Fact] - public async Task the_completion_succeeds() { - await _fixture.Client.CreateToStreamAsync(Stream, "nonexistinggroup", - new PersistentSubscriptionSettings(), - userCredentials: TestCredentials.Root); - } } \ No newline at end of file diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/create_persistent_subscription_with_dont_timeout.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/create_persistent_subscription_with_dont_timeout.cs index fbd65802d..fe56e5e09 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/create_persistent_subscription_with_dont_timeout.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/create_persistent_subscription_with_dont_timeout.cs @@ -1,22 +1,23 @@ -namespace EventStore.Client.SubscriptionToStream; +namespace EventStore.Client.SubscriptionToStream; public class create_with_dont_timeout : IClassFixture { - public create_with_dont_timeout(Fixture fixture) { - _fixture = fixture; - } + const string Stream = nameof(create_with_dont_timeout); + readonly Fixture _fixture; + + public create_with_dont_timeout(Fixture fixture) => _fixture = fixture; - private const string Stream = nameof(create_with_dont_timeout); - private readonly Fixture _fixture; + [Fact] + public Task the_subscription_is_created_without_error() => + _fixture.Client.CreateToStreamAsync( + Stream, + "dont-timeout", + new(messageTimeout: TimeSpan.Zero), + userCredentials: TestCredentials.Root + ); public class Fixture : EventStoreClientFixture { protected override Task Given() => Task.CompletedTask; protected override Task When() => Task.CompletedTask; } - - [Fact] - public Task the_subscription_is_created_without_error() => - _fixture.Client.CreateToStreamAsync(Stream, "dont-timeout", - new PersistentSubscriptionSettings(messageTimeout: TimeSpan.Zero), - userCredentials: TestCredentials.Root); } \ No newline at end of file diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/create_without_permissions.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/create_without_permissions.cs index b6e506d02..15e575ea6 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/create_without_permissions.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/create_without_permissions.cs @@ -1,25 +1,27 @@ -namespace EventStore.Client.SubscriptionToStream; +namespace EventStore.Client.SubscriptionToStream; public class create_without_permissions : IClassFixture { - public create_without_permissions(Fixture fixture) { - _fixture = fixture; - } + const string Stream = nameof(create_without_permissions); + readonly Fixture _fixture; + + public create_without_permissions(Fixture fixture) => _fixture = fixture; - private const string Stream = nameof(create_without_permissions); - private readonly Fixture _fixture; + [Fact] + public Task the_completion_fails_with_access_denied() => + Assert.ThrowsAsync( + () => + _fixture.Client.CreateToStreamAsync( + Stream, + "group57", + new() + ) + ); public class Fixture : EventStoreClientFixture { - public Fixture () : base(noDefaultCredentials: true){ - } - + public Fixture() : base(noDefaultCredentials: true) { } + protected override Task Given() => Task.CompletedTask; protected override Task When() => Task.CompletedTask; } - - [Fact] - public Task the_completion_fails_with_access_denied() => - Assert.ThrowsAsync(() => - _fixture.Client.CreateToStreamAsync(Stream, "group57", - new PersistentSubscriptionSettings())); } \ No newline at end of file diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/deleting_existing_with_permissions.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/deleting_existing_with_permissions.cs index 0fa7a3b90..20aab69c6 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/deleting_existing_with_permissions.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/deleting_existing_with_permissions.cs @@ -1,25 +1,29 @@ -namespace EventStore.Client.SubscriptionToStream; +namespace EventStore.Client.SubscriptionToStream; public class deleting_existing_with_permissions : IClassFixture { - private const string Stream = nameof(deleting_existing_with_permissions); - private readonly Fixture _fixture; + const string Stream = nameof(deleting_existing_with_permissions); + readonly Fixture _fixture; - public deleting_existing_with_permissions(Fixture fixture) { - _fixture = fixture; - } + public deleting_existing_with_permissions(Fixture fixture) => _fixture = fixture; + + [Fact] + public Task the_delete_of_group_succeeds() => + _fixture.Client.DeleteToStreamAsync( + Stream, + "groupname123", + userCredentials: TestCredentials.Root + ); public class Fixture : EventStoreClientFixture { protected override Task Given() => Task.CompletedTask; protected override Task When() => - Client.CreateToStreamAsync(Stream, "groupname123", - new PersistentSubscriptionSettings(), - userCredentials: TestCredentials.Root); + Client.CreateToStreamAsync( + Stream, + "groupname123", + new(), + userCredentials: TestCredentials.Root + ); } - - [Fact] - public Task the_delete_of_group_succeeds() => - _fixture.Client.DeleteToStreamAsync(Stream, "groupname123", - userCredentials: TestCredentials.Root); } \ No newline at end of file diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/deleting_existing_with_subscriber.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/deleting_existing_with_subscriber.cs index 56d4a03e6..bf0157473 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/deleting_existing_with_subscriber.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/deleting_existing_with_subscriber.cs @@ -1,41 +1,11 @@ -namespace EventStore.Client.SubscriptionToStream; +namespace EventStore.Client.SubscriptionToStream; public class deleting_existing_with_subscriber : IClassFixture { - private readonly Fixture _fixture; - private const string Stream = nameof(deleting_existing_with_subscriber); + const string Stream = nameof(deleting_existing_with_subscriber); + readonly Fixture _fixture; - public deleting_existing_with_subscriber(Fixture fixture) { - _fixture = fixture; - } - - public class Fixture : EventStoreClientFixture { - public Task<(SubscriptionDroppedReason, Exception?)> Dropped => _dropped.Task; - private readonly TaskCompletionSource<(SubscriptionDroppedReason, Exception?)> _dropped; - private PersistentSubscription? _subscription; - - public Fixture() { - _dropped = new TaskCompletionSource<(SubscriptionDroppedReason, Exception?)>(); - } - - protected override async Task Given() { - await Client.CreateToStreamAsync(Stream, "groupname123", - new PersistentSubscriptionSettings(), - userCredentials: TestCredentials.Root); - _subscription = await Client.SubscribeToStreamAsync(Stream, "groupname123", - (_, _, _, _) => Task.CompletedTask, - (_, r, e) => _dropped.TrySetResult((r, e)), TestCredentials.Root); - } - - protected override Task When() => - Client.DeleteToStreamAsync(Stream, "groupname123", - userCredentials: TestCredentials.Root); - - public override Task DisposeAsync() { - _subscription?.Dispose(); - return base.DisposeAsync(); - } - } + public deleting_existing_with_subscriber(Fixture fixture) => _fixture = fixture; [Fact] public async Task the_subscription_is_dropped() { @@ -46,7 +16,7 @@ public async Task the_subscription_is_dropped() { Assert.Equal("groupname123", ex.GroupName); } - [Fact (Skip = "Isn't this how it should work?")] + [Fact(Skip = "Isn't this how it should work?")] public async Task the_subscription_is_dropped_with_not_found() { var (reason, exception) = await _fixture.Dropped.WithTimeout(); Assert.Equal(SubscriptionDroppedReason.ServerError, reason); @@ -54,4 +24,42 @@ public async Task the_subscription_is_dropped_with_not_found() { Assert.Equal(Stream, ex.StreamName); Assert.Equal("groupname123", ex.GroupName); } + + public class Fixture : EventStoreClientFixture { + readonly TaskCompletionSource<(SubscriptionDroppedReason, Exception?)> _dropped; + PersistentSubscription? _subscription; + + public Fixture() => _dropped = new(); + + public Task<(SubscriptionDroppedReason, Exception?)> Dropped => _dropped.Task; + + protected override async Task Given() { + await Client.CreateToStreamAsync( + Stream, + "groupname123", + new(), + userCredentials: TestCredentials.Root + ); + + _subscription = await Client.SubscribeToStreamAsync( + Stream, + "groupname123", + (_, _, _, _) => Task.CompletedTask, + (_, r, e) => _dropped.TrySetResult((r, e)), + TestCredentials.Root + ); + } + + protected override Task When() => + Client.DeleteToStreamAsync( + Stream, + "groupname123", + userCredentials: TestCredentials.Root + ); + + public override Task DisposeAsync() { + _subscription?.Dispose(); + return base.DisposeAsync(); + } + } } \ No newline at end of file diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/deleting_nonexistent.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/deleting_nonexistent.cs index 5b72fce80..dd170c664 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/deleting_nonexistent.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/deleting_nonexistent.cs @@ -1,20 +1,21 @@ -namespace EventStore.Client.SubscriptionToStream; +namespace EventStore.Client.SubscriptionToStream; public class deleting_nonexistent : IClassFixture { - private readonly Fixture _fixture; - private const string Stream = nameof(deleting_nonexistent); + const string Stream = nameof(deleting_nonexistent); + readonly Fixture _fixture; - public deleting_nonexistent(Fixture fixture) { - _fixture = fixture; - } + public deleting_nonexistent(Fixture fixture) => _fixture = fixture; [Fact] - public async Task the_delete_fails_with_argument_exception() { + public async Task the_delete_fails_with_argument_exception() => await Assert.ThrowsAsync( - () => _fixture.Client.DeleteToStreamAsync(Stream, - Guid.NewGuid().ToString(), userCredentials: TestCredentials.Root)); - } + () => _fixture.Client.DeleteToStreamAsync( + Stream, + Guid.NewGuid().ToString(), + userCredentials: TestCredentials.Root + ) + ); public class Fixture : EventStoreClientFixture { protected override Task Given() => Task.CompletedTask; diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/deleting_without_permissions.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/deleting_without_permissions.cs index 3c56faf13..d362bd94e 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/deleting_without_permissions.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/deleting_without_permissions.cs @@ -1,25 +1,24 @@ -namespace EventStore.Client.SubscriptionToStream; +namespace EventStore.Client.SubscriptionToStream; public class deleting_without_permissions : IClassFixture { - private readonly Fixture _fixture; - private const string Stream = nameof(deleting_without_permissions); + const string Stream = nameof(deleting_without_permissions); + readonly Fixture _fixture; - public deleting_without_permissions(Fixture fixture) { - _fixture = fixture; - } + public deleting_without_permissions(Fixture fixture) => _fixture = fixture; [Fact] - public async Task the_delete_fails_with_access_denied() { + public async Task the_delete_fails_with_access_denied() => await Assert.ThrowsAsync( - () => _fixture.Client.DeleteToStreamAsync(Stream, - Guid.NewGuid().ToString())); - } + () => _fixture.Client.DeleteToStreamAsync( + Stream, + Guid.NewGuid().ToString() + ) + ); public class Fixture : EventStoreClientFixture { - public Fixture () : base(noDefaultCredentials: true){ - } - + public Fixture() : base(noDefaultCredentials: true) { } + protected override Task Given() => Task.CompletedTask; protected override Task When() => Task.CompletedTask; } diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/get_info.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/get_info.cs index 30a2dd46d..b7229d395 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/get_info.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/get_info.cs @@ -1,40 +1,42 @@ -namespace EventStore.Client.SubscriptionToStream; +namespace EventStore.Client.SubscriptionToStream; public class get_info : IClassFixture { - private readonly Fixture _fixture; - private const string GroupName = nameof(get_info); - private const string StreamName = nameof(get_info); - private static readonly PersistentSubscriptionSettings _settings = new( - resolveLinkTos: true, - startFrom: StreamPosition.Start, - extraStatistics: true, - messageTimeout: TimeSpan.FromSeconds(9), - maxRetryCount: 11, - liveBufferSize: 303, - readBatchSize: 30, - historyBufferSize: 909, - checkPointAfter: TimeSpan.FromSeconds(1), - checkPointLowerBound: 1, - checkPointUpperBound: 1, - maxSubscriberCount: 500, - consumerStrategyName: SystemConsumerStrategies.RoundRobin + const string GroupName = nameof(get_info); + const string StreamName = nameof(get_info); + + static readonly PersistentSubscriptionSettings _settings = new( + true, + StreamPosition.Start, + true, + TimeSpan.FromSeconds(9), + 11, + 303, + 30, + 909, + TimeSpan.FromSeconds(1), + 1, + 1, + 500, + SystemConsumerStrategies.RoundRobin ); - public get_info(Fixture fixture) { - _fixture = fixture; - } + readonly Fixture _fixture; + + public get_info(Fixture fixture) => _fixture = fixture; public static IEnumerable AllowedUsers() { - yield return new object[] {TestCredentials.Root}; - yield return new object[] {TestCredentials.TestUser1}; + yield return new object[] { TestCredentials.Root }; + yield return new object[] { TestCredentials.TestUser1 }; } - - [Theory, MemberData(nameof(AllowedUsers))] + + [Theory] + [MemberData(nameof(AllowedUsers))] public async Task returns_expected_result(UserCredentials credentials) { var result = await _fixture.Client.GetInfoToStreamAsync( StreamName, GroupName, - userCredentials: credentials); + userCredentials: credentials + ); Assert.Equal(StreamName, result.EventSource); Assert.Equal(GroupName, result.GroupName); @@ -65,7 +67,7 @@ public async Task returns_expected_result(UserCredentials credentials) { Assert.True(connection.InFlightMessages >= 0); Assert.NotNull(connection.ExtraStatistics); Assert.NotEmpty(connection.ExtraStatistics); - + AssertKeyAndValue(connection.ExtraStatistics, PersistentSubscriptionExtraStatistic.Highest); AssertKeyAndValue(connection.ExtraStatistics, PersistentSubscriptionExtraStatistic.Mean); AssertKeyAndValue(connection.ExtraStatistics, PersistentSubscriptionExtraStatistic.Median); @@ -80,7 +82,7 @@ public async Task returns_expected_result(UserCredentials credentials) { AssertKeyAndValue(connection.ExtraStatistics, PersistentSubscriptionExtraStatistic.NinetyNinePercent); AssertKeyAndValue(connection.ExtraStatistics, PersistentSubscriptionExtraStatistic.NinetyNinePointFivePercent); AssertKeyAndValue(connection.ExtraStatistics, PersistentSubscriptionExtraStatistic.NinetyNinePointNinePercent); - + Assert.NotNull(result.Settings); Assert.Equal(_settings.StartFrom, result.Settings!.StartFrom); Assert.Equal(_settings.ResolveLinkTos, result.Settings!.ResolveLinkTos); @@ -98,89 +100,99 @@ public async Task returns_expected_result(UserCredentials credentials) { } [Fact] - public async Task throws_when_given_non_existing_subscription() { - await Assert.ThrowsAsync(async () => { - await _fixture.Client.GetInfoToStreamAsync( - streamName: "NonExisting", - groupName: "NonExisting", - userCredentials: TestCredentials.Root); - }); - } - + public async Task throws_when_given_non_existing_subscription() => + await Assert.ThrowsAsync( + async () => { + await _fixture.Client.GetInfoToStreamAsync( + "NonExisting", + "NonExisting", + userCredentials: TestCredentials.Root + ); + } + ); + [Fact(Skip = "Unable to produce same behavior with HTTP fallback!")] - public async Task throws_with_non_existing_user() { - await Assert.ThrowsAsync(async () => { - await _fixture.Client.GetInfoToStreamAsync( - streamName: "NonExisting", - groupName: "NonExisting", - userCredentials: TestCredentials.TestBadUser); - }); - } - + public async Task throws_with_non_existing_user() => + await Assert.ThrowsAsync( + async () => { + await _fixture.Client.GetInfoToStreamAsync( + "NonExisting", + "NonExisting", + userCredentials: TestCredentials.TestBadUser + ); + } + ); + [Fact] - public async Task throws_with_no_credentials() { - await Assert.ThrowsAsync(async () => { - await _fixture.Client.GetInfoToStreamAsync( - streamName: "NonExisting", - groupName: "NonExisting"); - }); - } - + public async Task throws_with_no_credentials() => + await Assert.ThrowsAsync( + async () => { + await _fixture.Client.GetInfoToStreamAsync( + "NonExisting", + "NonExisting" + ); + } + ); + [Fact] public async Task returns_result_for_normal_user() { var result = await _fixture.Client.GetInfoToStreamAsync( StreamName, GroupName, - userCredentials: TestCredentials.TestUser1); - + userCredentials: TestCredentials.TestUser1 + ); + Assert.NotNull(result); } - + + void AssertKeyAndValue(IDictionary items, string key) { + Assert.True(items.ContainsKey(key)); + Assert.True(items[key] > 0); + } + public class Fixture : EventStoreClientFixture { - public Fixture () : base(noDefaultCredentials: true) { - } - + public Fixture() : base(noDefaultCredentials: true) { } + protected override Task Given() => Client.CreateToStreamAsync( groupName: GroupName, streamName: StreamName, settings: _settings, - userCredentials: TestCredentials.Root); + userCredentials: TestCredentials.Root + ); protected override async Task When() { var counter = 0; var tcs = new TaskCompletionSource(); - + await Client.SubscribeToStreamAsync( StreamName, GroupName, - eventAppeared: (s, e, r, ct) => { + (s, e, r, ct) => { counter++; - - if (counter == 1) { + + if (counter == 1) s.Nack(PersistentSubscriptionNakEventAction.Park, "Test", e); - } - - if (counter > 10) { + + if (counter > 10) tcs.TrySetResult(); - } - + return Task.CompletedTask; }, - userCredentials: TestCredentials.Root); + userCredentials: TestCredentials.Root + ); + + for (var i = 0; i < 15; i++) + await StreamsClient.AppendToStreamAsync( + StreamName, + StreamState.Any, + new[] { + new EventData(Uuid.NewUuid(), "test-event", ReadOnlyMemory.Empty) + }, + userCredentials: TestCredentials.Root + ); - for (int i = 0; i < 15; i++) { - await StreamsClient.AppendToStreamAsync(StreamName, StreamState.Any, new [] { - new EventData(Uuid.NewUuid(), "test-event", ReadOnlyMemory.Empty) - }, userCredentials: TestCredentials.Root); - } - await tcs.Task; } } - - private void AssertKeyAndValue(IDictionary items, string key) { - Assert.True(items.ContainsKey(key)); - Assert.True(items[key] > 0); - } } \ No newline at end of file diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/happy_case_catching_up_to_link_to_events_manual_ack.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/happy_case_catching_up_to_link_to_events_manual_ack.cs index 104b7b894..95700d29c 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/happy_case_catching_up_to_link_to_events_manual_ack.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/happy_case_catching_up_to_link_to_events_manual_ack.cs @@ -1,64 +1,72 @@ using System.Text; -namespace EventStore.Client.SubscriptionToStream; +namespace EventStore.Client.SubscriptionToStream; public class happy_case_catching_up_to_link_to_events_manual_ack : IClassFixture { - private const string Stream = nameof(happy_case_catching_up_to_link_to_events_manual_ack); - private const string Group = nameof(Group); - private const int BufferCount = 10; - private const int EventWriteCount = BufferCount * 2; + const string Stream = nameof(happy_case_catching_up_to_link_to_events_manual_ack); + const string Group = nameof(Group); + const int BufferCount = 10; + const int EventWriteCount = BufferCount * 2; - private readonly Fixture _fixture; + readonly Fixture _fixture; - public happy_case_catching_up_to_link_to_events_manual_ack(Fixture fixture) { - _fixture = fixture; - } + public happy_case_catching_up_to_link_to_events_manual_ack(Fixture fixture) => _fixture = fixture; [Fact] - public async Task Test() { - await _fixture.EventsReceived.WithTimeout(); - } + public async Task Test() => await _fixture.EventsReceived.WithTimeout(); public class Fixture : EventStoreClientFixture { - private readonly EventData[] _events; - private readonly TaskCompletionSource _eventsReceived; - public Task EventsReceived => _eventsReceived.Task; + readonly EventData[] _events; + readonly TaskCompletionSource _eventsReceived; + int _eventReceivedCount; - private PersistentSubscription? _subscription; - private int _eventReceivedCount; + PersistentSubscription? _subscription; public Fixture() { _events = CreateTestEvents(EventWriteCount) - .Select((e, i) => new EventData(e.EventId, SystemEventTypes.LinkTo, - Encoding.UTF8.GetBytes($"{i}@{Stream}"), - contentType: Constants.Metadata.ContentTypes.ApplicationOctetStream)) + .Select( + (e, i) => new EventData( + e.EventId, + SystemEventTypes.LinkTo, + Encoding.UTF8.GetBytes($"{i}@{Stream}"), + contentType: Constants.Metadata.ContentTypes.ApplicationOctetStream + ) + ) .ToArray(); - _eventsReceived = new TaskCompletionSource(); + + _eventsReceived = new(); } + public Task EventsReceived => _eventsReceived.Task; + protected override async Task Given() { - foreach (var e in _events) { - await StreamsClient.AppendToStreamAsync(Stream, StreamState.Any, new[] {e}); - } - - await Client.CreateToStreamAsync(Stream, Group, - new PersistentSubscriptionSettings(startFrom: StreamPosition.Start, resolveLinkTos: true), - userCredentials: TestCredentials.Root); - _subscription = await Client.SubscribeToStreamAsync(Stream, Group, - async (subscription, e, retryCount, ct) => { - await subscription.Ack(e); - - if (Interlocked.Increment(ref _eventReceivedCount) == _events.Length) { - _eventsReceived.TrySetResult(true); - } - }, (s, r, e) => { - if (e != null) { - _eventsReceived.TrySetException(e); - } - }, - bufferSize: BufferCount, - userCredentials: TestCredentials.Root); + foreach (var e in _events) + await StreamsClient.AppendToStreamAsync(Stream, StreamState.Any, new[] { e }); + + await Client.CreateToStreamAsync( + Stream, + Group, + new(startFrom: StreamPosition.Start, resolveLinkTos: true), + userCredentials: TestCredentials.Root + ); + + _subscription = await Client.SubscribeToStreamAsync( + Stream, + Group, + async (subscription, e, retryCount, ct) => { + await subscription.Ack(e); + + if (Interlocked.Increment(ref _eventReceivedCount) == _events.Length) + _eventsReceived.TrySetResult(true); + }, + (s, r, e) => { + if (e != null) + _eventsReceived.TrySetException(e); + }, + bufferSize: BufferCount, + userCredentials: TestCredentials.Root + ); } protected override Task When() => Task.CompletedTask; diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/happy_case_catching_up_to_normal_events_manual_ack.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/happy_case_catching_up_to_normal_events_manual_ack.cs index 1eabfe8e1..242cf4c9c 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/happy_case_catching_up_to_normal_events_manual_ack.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/happy_case_catching_up_to_normal_events_manual_ack.cs @@ -1,58 +1,59 @@ -namespace EventStore.Client.SubscriptionToStream; +namespace EventStore.Client.SubscriptionToStream; -public class happy_case_catching_up_to_normal_events_manual_ack : - IClassFixture { - private const string Stream = nameof(happy_case_catching_up_to_normal_events_manual_ack); - private const string Group = nameof(Group); - private const int BufferCount = 10; - private const int EventWriteCount = BufferCount * 2; +public class happy_case_catching_up_to_normal_events_manual_ack : IClassFixture { + const string Stream = nameof(happy_case_catching_up_to_normal_events_manual_ack); + const string Group = nameof(Group); + const int BufferCount = 10; + const int EventWriteCount = BufferCount * 2; - private readonly Fixture _fixture; + readonly Fixture _fixture; - public happy_case_catching_up_to_normal_events_manual_ack(Fixture fixture) { - _fixture = fixture; - } + public happy_case_catching_up_to_normal_events_manual_ack(Fixture fixture) => _fixture = fixture; [Fact] - public async Task Test() { - await _fixture.EventsReceived.WithTimeout(); - } + public async Task Test() => await _fixture.EventsReceived.WithTimeout(); public class Fixture : EventStoreClientFixture { - private readonly EventData[] _events; - private readonly TaskCompletionSource _eventsReceived; - public Task EventsReceived => _eventsReceived.Task; + readonly EventData[] _events; + readonly TaskCompletionSource _eventsReceived; + int _eventReceivedCount; - private PersistentSubscription? _subscription; - private int _eventReceivedCount; + PersistentSubscription? _subscription; public Fixture() { _events = CreateTestEvents(EventWriteCount).ToArray(); - _eventsReceived = new TaskCompletionSource(); + _eventsReceived = new(); } + public Task EventsReceived => _eventsReceived.Task; + protected override async Task Given() { - foreach (var e in _events) { - await StreamsClient.AppendToStreamAsync(Stream, StreamState.Any, new[] {e}); - } + foreach (var e in _events) + await StreamsClient.AppendToStreamAsync(Stream, StreamState.Any, new[] { e }); + + await Client.CreateToStreamAsync( + Stream, + Group, + new(startFrom: StreamPosition.Start, resolveLinkTos: true), + userCredentials: TestCredentials.Root + ); - await Client.CreateToStreamAsync(Stream, Group, - new PersistentSubscriptionSettings(startFrom: StreamPosition.Start, resolveLinkTos: true), - userCredentials: TestCredentials.Root); - _subscription = await Client.SubscribeToStreamAsync(Stream, Group, - async(subscription, e, retryCount, ct) => { - await subscription.Ack(e); + _subscription = await Client.SubscribeToStreamAsync( + Stream, + Group, + async (subscription, e, retryCount, ct) => { + await subscription.Ack(e); - if (Interlocked.Increment(ref _eventReceivedCount) == _events.Length) { - _eventsReceived.TrySetResult(true); - } - }, (s, r, e) => { - if (e != null) { - _eventsReceived.TrySetException(e); - } - }, - bufferSize: BufferCount, - userCredentials: TestCredentials.Root); + if (Interlocked.Increment(ref _eventReceivedCount) == _events.Length) + _eventsReceived.TrySetResult(true); + }, + (s, r, e) => { + if (e != null) + _eventsReceived.TrySetException(e); + }, + bufferSize: BufferCount, + userCredentials: TestCredentials.Root + ); } protected override Task When() => Task.CompletedTask; diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/happy_case_writing_and_subscribing_to_normal_events_manual_ack.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/happy_case_writing_and_subscribing_to_normal_events_manual_ack.cs index 572b09b17..9a9fd1803 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/happy_case_writing_and_subscribing_to_normal_events_manual_ack.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/happy_case_writing_and_subscribing_to_normal_events_manual_ack.cs @@ -1,59 +1,61 @@ -namespace EventStore.Client.SubscriptionToStream; +namespace EventStore.Client.SubscriptionToStream; public class happy_case_writing_and_subscribing_to_normal_events_manual_ack : IClassFixture { - private const string Stream = nameof(happy_case_writing_and_subscribing_to_normal_events_manual_ack); - private const string Group = nameof(Group); - private const int BufferCount = 10; - private const int EventWriteCount = BufferCount * 2; + const string Stream = nameof(happy_case_writing_and_subscribing_to_normal_events_manual_ack); + const string Group = nameof(Group); + const int BufferCount = 10; + const int EventWriteCount = BufferCount * 2; - private readonly Fixture _fixture; + readonly Fixture _fixture; - public happy_case_writing_and_subscribing_to_normal_events_manual_ack(Fixture fixture) { - _fixture = fixture; - } + public happy_case_writing_and_subscribing_to_normal_events_manual_ack(Fixture fixture) => _fixture = fixture; [Fact] - public async Task Test() { - await _fixture.EventsReceived.WithTimeout(); - } + public async Task Test() => await _fixture.EventsReceived.WithTimeout(); public class Fixture : EventStoreClientFixture { - private readonly EventData[] _events; - private readonly TaskCompletionSource _eventsReceived; - public Task EventsReceived => _eventsReceived.Task; + readonly EventData[] _events; + readonly TaskCompletionSource _eventsReceived; + int _eventReceivedCount; - private PersistentSubscription? _subscription; - private int _eventReceivedCount; + PersistentSubscription? _subscription; public Fixture() { _events = CreateTestEvents(EventWriteCount).ToArray(); - _eventsReceived = new TaskCompletionSource(); + _eventsReceived = new(); } + public Task EventsReceived => _eventsReceived.Task; + protected override async Task Given() { - await Client.CreateToStreamAsync(Stream, Group, - new PersistentSubscriptionSettings(startFrom: StreamPosition.End, resolveLinkTos: true), - userCredentials: TestCredentials.Root); - _subscription = await Client.SubscribeToStreamAsync(Stream, Group, - async (subscription, e, retryCount, ct) => { - await subscription.Ack(e); - if (Interlocked.Increment(ref _eventReceivedCount) == _events.Length) { - _eventsReceived.TrySetResult(true); - } - }, (s, r, e) => { - if (e != null) { - _eventsReceived.TrySetException(e); - } - }, - bufferSize: BufferCount, - userCredentials: TestCredentials.Root); + await Client.CreateToStreamAsync( + Stream, + Group, + new(startFrom: StreamPosition.End, resolveLinkTos: true), + userCredentials: TestCredentials.Root + ); + + _subscription = await Client.SubscribeToStreamAsync( + Stream, + Group, + async (subscription, e, retryCount, ct) => { + await subscription.Ack(e); + if (Interlocked.Increment(ref _eventReceivedCount) == _events.Length) + _eventsReceived.TrySetResult(true); + }, + (s, r, e) => { + if (e != null) + _eventsReceived.TrySetException(e); + }, + bufferSize: BufferCount, + userCredentials: TestCredentials.Root + ); } protected override async Task When() { - foreach (var e in _events) { - await StreamsClient.AppendToStreamAsync(Stream, StreamState.Any, new[] {e}); - } + foreach (var e in _events) + await StreamsClient.AppendToStreamAsync(Stream, StreamState.Any, new[] { e }); } public override Task DisposeAsync() { diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/list_with_persistent_subscriptions.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/list_with_persistent_subscriptions.cs index 6f59c5db8..038fcf9a3 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/list_with_persistent_subscriptions.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/list_with_persistent_subscriptions.cs @@ -1,20 +1,19 @@ -namespace EventStore.Client.SubscriptionToStream; +namespace EventStore.Client.SubscriptionToStream; public class list_with_persistent_subscriptions : IClassFixture { - private readonly Fixture _fixture; - private const int AllStreamSubscriptionCount = 4; - private const int StreamSubscriptionCount = 3; - private const string GroupName = nameof(list_with_persistent_subscriptions); - private const string StreamName = nameof(list_with_persistent_subscriptions); + const int AllStreamSubscriptionCount = 4; + const int StreamSubscriptionCount = 3; + const string GroupName = nameof(list_with_persistent_subscriptions); + const string StreamName = nameof(list_with_persistent_subscriptions); + readonly Fixture _fixture; - public list_with_persistent_subscriptions(Fixture fixture) { - _fixture = fixture; - } + public list_with_persistent_subscriptions(Fixture fixture) => _fixture = fixture; + + int TotalSubscriptionCount => + SupportsPSToAll.No + ? StreamSubscriptionCount + : AllStreamSubscriptionCount + StreamSubscriptionCount; - private int TotalSubscriptionCount => SupportsPSToAll.No - ? StreamSubscriptionCount - : AllStreamSubscriptionCount + StreamSubscriptionCount; - [Fact] public async Task returns_subscriptions_to_stream() { var result = (await _fixture.Client.ListToStreamAsync(StreamName, userCredentials: TestCredentials.Root)).ToList(); @@ -29,23 +28,26 @@ public async Task returns_all_subscriptions() { } [Fact] - public async Task throws_for_non_existing() { - await Assert.ThrowsAsync(async () => - await _fixture.Client.ListToStreamAsync("NonExistingStream", userCredentials: TestCredentials.Root)); - } + public async Task throws_for_non_existing() => + await Assert.ThrowsAsync( + async () => + await _fixture.Client.ListToStreamAsync("NonExistingStream", userCredentials: TestCredentials.Root) + ); [Fact] - public async Task throws_with_no_credentials() { - await Assert.ThrowsAsync(async () => - await _fixture.Client.ListToStreamAsync("NonExistingStream")); - } - + public async Task throws_with_no_credentials() => + await Assert.ThrowsAsync( + async () => + await _fixture.Client.ListToStreamAsync("NonExistingStream") + ); + [Fact] - public async Task throws_with_non_existing_user() { - await Assert.ThrowsAsync(async () => - await _fixture.Client.ListAllAsync(userCredentials: TestCredentials.TestBadUser)); - } - + public async Task throws_with_non_existing_user() => + await Assert.ThrowsAsync( + async () => + await _fixture.Client.ListAllAsync(userCredentials: TestCredentials.TestBadUser) + ); + [Fact] public async Task returns_result_with_normal_user_credentials() { var result = await _fixture.Client.ListAllAsync(userCredentials: TestCredentials.TestUser1); @@ -53,30 +55,28 @@ public async Task returns_result_with_normal_user_credentials() { } public class Fixture : EventStoreClientFixture { - public Fixture () : base(skipPSWarmUp: true, noDefaultCredentials: true) { - } - + public Fixture() : base(skipPSWarmUp: true, noDefaultCredentials: true) { } + protected override async Task Given() { - for (int i = 0; i < StreamSubscriptionCount; i++) { + for (var i = 0; i < StreamSubscriptionCount; i++) await Client.CreateToStreamAsync( StreamName, GroupName + i, - new PersistentSubscriptionSettings(), - userCredentials: TestCredentials.Root); - } + new(), + userCredentials: TestCredentials.Root + ); - if (SupportsPSToAll.No) { + if (SupportsPSToAll.No) return; - } - - for (int i = 0; i < AllStreamSubscriptionCount; i++) { + + for (var i = 0; i < AllStreamSubscriptionCount; i++) await Client.CreateToAllAsync( GroupName + i, - new PersistentSubscriptionSettings(), - userCredentials: TestCredentials.Root); - } + new(), + userCredentials: TestCredentials.Root + ); } - + protected override Task When() => Task.CompletedTask; } } \ No newline at end of file diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/list_without_persistent_subscriptions.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/list_without_persistent_subscriptions.cs index ddc4e970d..632a6ec33 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/list_without_persistent_subscriptions.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/list_without_persistent_subscriptions.cs @@ -1,39 +1,36 @@ namespace EventStore.Client.SubscriptionToStream; public class list_without_persistent_subscriptions : IClassFixture { - private readonly Fixture _fixture; - - public list_without_persistent_subscriptions(Fixture fixture) { - _fixture = fixture; - } - - [SupportsPSToAll.Fact] - public async Task throws() { - if (SupportsPSToAll.No) { - return; - } - - await Assert.ThrowsAsync(async () => - await _fixture.Client.ListToStreamAsync("stream", userCredentials: TestCredentials.Root)); - } - - [Fact] - public async Task returns_empty_collection() { - if (SupportsPSToAll.No) { - return; - } - - var result = await _fixture.Client.ListAllAsync(userCredentials: TestCredentials.Root); - - Assert.Empty(result); - } - - public class Fixture : EventStoreClientFixture { - public Fixture () : base(skipPSWarmUp: true) { - } - - protected override Task Given() => Task.CompletedTask; - - protected override Task When() => Task.CompletedTask; - } -} + readonly Fixture _fixture; + + public list_without_persistent_subscriptions(Fixture fixture) => _fixture = fixture; + + [SupportsPSToAll.Fact] + public async Task throws() { + if (SupportsPSToAll.No) + return; + + await Assert.ThrowsAsync( + async () => + await _fixture.Client.ListToStreamAsync("stream", userCredentials: TestCredentials.Root) + ); + } + + [Fact] + public async Task returns_empty_collection() { + if (SupportsPSToAll.No) + return; + + var result = await _fixture.Client.ListAllAsync(userCredentials: TestCredentials.Root); + + Assert.Empty(result); + } + + public class Fixture : EventStoreClientFixture { + public Fixture() : base(skipPSWarmUp: true) { } + + protected override Task Given() => Task.CompletedTask; + + protected override Task When() => Task.CompletedTask; + } +} \ No newline at end of file diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/replay_parked.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/replay_parked.cs index aafd83332..36989ff58 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/replay_parked.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/replay_parked.cs @@ -1,71 +1,80 @@ -namespace EventStore.Client.SubscriptionToStream; +namespace EventStore.Client.SubscriptionToStream; public class replay_parked : IClassFixture { - private readonly Fixture _fixture; - private const string GroupName = nameof(replay_parked); - private const string StreamName = nameof(replay_parked); + const string GroupName = nameof(replay_parked); + const string StreamName = nameof(replay_parked); + + readonly Fixture _fixture; + + public replay_parked(Fixture fixture) => _fixture = fixture; - public replay_parked(Fixture fixture) { - _fixture = fixture; - } - [Fact] public async Task does_not_throw() { await _fixture.Client.ReplayParkedMessagesToStreamAsync( StreamName, GroupName, - userCredentials: TestCredentials.Root); - + userCredentials: TestCredentials.Root + ); + await _fixture.Client.ReplayParkedMessagesToStreamAsync( StreamName, GroupName, - stopAt: 100, - userCredentials: TestCredentials.Root); + 100, + userCredentials: TestCredentials.Root + ); } [Fact] - public async Task throws_when_given_non_existing_subscription() { - await Assert.ThrowsAsync(() => - _fixture.Client.ReplayParkedMessagesToStreamAsync( - streamName: "NonExisting", - groupName: "NonExisting", - userCredentials: TestCredentials.Root)); - } - + public async Task throws_when_given_non_existing_subscription() => + await Assert.ThrowsAsync( + () => + _fixture.Client.ReplayParkedMessagesToStreamAsync( + "NonExisting", + "NonExisting", + userCredentials: TestCredentials.Root + ) + ); + [Fact] - public async Task throws_with_no_credentials() { - await Assert.ThrowsAsync(() => - _fixture.Client.ReplayParkedMessagesToStreamAsync(StreamName, GroupName)); - } + public async Task throws_with_no_credentials() => + await Assert.ThrowsAsync( + () => + _fixture.Client.ReplayParkedMessagesToStreamAsync(StreamName, GroupName) + ); [Fact(Skip = "Unable to produce same behavior with HTTP fallback!")] - public async Task throws_with_non_existing_user() { - await Assert.ThrowsAsync(() => - _fixture.Client.ReplayParkedMessagesToStreamAsync( - StreamName, - GroupName, - userCredentials: TestCredentials.TestBadUser)); - } - + public async Task throws_with_non_existing_user() => + await Assert.ThrowsAsync( + () => + _fixture.Client.ReplayParkedMessagesToStreamAsync( + StreamName, + GroupName, + userCredentials: TestCredentials.TestBadUser + ) + ); + [Fact] - public async Task throws_with_normal_user_credentials() { - await Assert.ThrowsAsync(() => - _fixture.Client.ReplayParkedMessagesToStreamAsync( - StreamName, - GroupName, - userCredentials: TestCredentials.TestUser1)); - } - + public async Task throws_with_normal_user_credentials() => + await Assert.ThrowsAsync( + () => + _fixture.Client.ReplayParkedMessagesToStreamAsync( + StreamName, + GroupName, + userCredentials: TestCredentials.TestUser1 + ) + ); + public class Fixture : EventStoreClientFixture { - public Fixture () : base(noDefaultCredentials: true) { - } - + public Fixture() : base(noDefaultCredentials: true) { } + protected override Task Given() => Client.CreateToStreamAsync( StreamName, GroupName, - new PersistentSubscriptionSettings(), - userCredentials: TestCredentials.Root); + new(), + userCredentials: TestCredentials.Root + ); + protected override Task When() => Task.CompletedTask; } } \ No newline at end of file diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/update_existing.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/update_existing.cs index bd298072c..ed14b0819 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/update_existing.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/update_existing.cs @@ -1,26 +1,31 @@ -namespace EventStore.Client.SubscriptionToStream; +namespace EventStore.Client.SubscriptionToStream; public class update_existing : IClassFixture { - private const string Stream = nameof(update_existing); - private const string Group = "existing"; - private readonly Fixture _fixture; + const string Stream = nameof(update_existing); + const string Group = "existing"; + readonly Fixture _fixture; - public update_existing(Fixture fixture) { - _fixture = fixture; - } + public update_existing(Fixture fixture) => _fixture = fixture; [Fact] - public async Task the_completion_succeeds() { - await _fixture.Client.UpdateToStreamAsync(Stream, Group, - new PersistentSubscriptionSettings(), userCredentials: TestCredentials.Root); - } + public async Task the_completion_succeeds() => + await _fixture.Client.UpdateToStreamAsync( + Stream, + Group, + new(), + userCredentials: TestCredentials.Root + ); public class Fixture : EventStoreClientFixture { protected override async Task Given() { await StreamsClient.AppendToStreamAsync(Stream, StreamState.NoStream, CreateTestEvents()); - await Client.CreateToStreamAsync(Stream, Group, new PersistentSubscriptionSettings(), - userCredentials: TestCredentials.Root); + await Client.CreateToStreamAsync( + Stream, + Group, + new(), + userCredentials: TestCredentials.Root + ); } protected override Task When() => Task.CompletedTask; diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/update_existing_with_check_point.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/update_existing_with_check_point.cs index fba30ae03..c84a9825c 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/update_existing_with_check_point.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/update_existing_with_check_point.cs @@ -1,14 +1,12 @@ -namespace EventStore.Client.SubscriptionToStream; +namespace EventStore.Client.SubscriptionToStream; public class update_existing_with_check_point : IClassFixture { - private const string Stream = nameof(update_existing_with_check_point); - private const string Group = "existing-with-check-point"; - private readonly Fixture _fixture; + const string Stream = nameof(update_existing_with_check_point); + const string Group = "existing-with-check-point"; + readonly Fixture _fixture; - public update_existing_with_check_point(Fixture fixture) { - _fixture = fixture; - } + public update_existing_with_check_point(Fixture fixture) => _fixture = fixture; [Fact] public async Task resumes_from_check_point() { @@ -17,63 +15,72 @@ public async Task resumes_from_check_point() { } public class Fixture : EventStoreClientFixture { - public Task Resumed => _resumedSource.Task; - public StreamPosition CheckPoint { get; private set; } + readonly TaskCompletionSource _appeared; + readonly List _appearedEvents; + readonly TaskCompletionSource _checkPointSource; - private readonly TaskCompletionSource<(SubscriptionDroppedReason, Exception?)> _droppedSource; - private readonly TaskCompletionSource _resumedSource; - private readonly TaskCompletionSource _checkPointSource; - private PersistentSubscription? _firstSubscription; - private PersistentSubscription? _secondSubscription; - private readonly TaskCompletionSource _appeared; - private readonly List _appearedEvents; - private readonly EventData[] _events; + readonly TaskCompletionSource<(SubscriptionDroppedReason, Exception?)> _droppedSource; + readonly EventData[] _events; + readonly TaskCompletionSource _resumedSource; + PersistentSubscription? _firstSubscription; + PersistentSubscription? _secondSubscription; public Fixture() { - _droppedSource = new TaskCompletionSource<(SubscriptionDroppedReason, Exception?)>(); - _resumedSource = new TaskCompletionSource(); - _checkPointSource = new TaskCompletionSource(); - _appeared = new TaskCompletionSource(); - _appearedEvents = new List(); + _droppedSource = new(); + _resumedSource = new(); + _checkPointSource = new(); + _appeared = new(); + _appearedEvents = new(); _events = CreateTestEvents(5).ToArray(); } + public Task Resumed => _resumedSource.Task; + public StreamPosition CheckPoint { get; private set; } + protected override async Task Given() { await StreamsClient.AppendToStreamAsync(Stream, StreamState.NoStream, _events); - await Client.CreateToStreamAsync(Stream, Group, - new PersistentSubscriptionSettings( - checkPointLowerBound: 5, - checkPointAfter: TimeSpan.FromSeconds(1), - startFrom: StreamPosition.Start), - userCredentials: TestCredentials.Root); + await Client.CreateToStreamAsync( + Stream, + Group, + new( + checkPointLowerBound: 5, + checkPointAfter: TimeSpan.FromSeconds(1), + startFrom: StreamPosition.Start + ), + userCredentials: TestCredentials.Root + ); var checkPointStream = $"$persistentsubscription-{Stream}::{Group}-checkpoint"; - await StreamsClient.SubscribeToStreamAsync(checkPointStream, - FromStream.Start, - (_, e, _) => { - _checkPointSource.TrySetResult(e); - return Task.CompletedTask; - }, - subscriptionDropped: (_, _, ex) => { - if (ex != null) { - _checkPointSource.TrySetException(ex); - } else { - _checkPointSource.TrySetResult(default); - } - }, - userCredentials: TestCredentials.Root); - - _firstSubscription = await Client.SubscribeToStreamAsync(Stream, Group, - eventAppeared: async (s, e, _, _) => { - _appearedEvents.Add(e); - await s.Ack(e); - - if (_appearedEvents.Count == _events.Length) - _appeared.TrySetResult(true); - }, - (_, reason, ex) => _droppedSource.TrySetResult((reason, ex)), - TestCredentials.Root); + await StreamsClient.SubscribeToStreamAsync( + checkPointStream, + FromStream.Start, + (_, e, _) => { + _checkPointSource.TrySetResult(e); + return Task.CompletedTask; + }, + subscriptionDropped: (_, _, ex) => { + if (ex != null) + _checkPointSource.TrySetException(ex); + else + _checkPointSource.TrySetResult(default); + }, + userCredentials: TestCredentials.Root + ); + + _firstSubscription = await Client.SubscribeToStreamAsync( + Stream, + Group, + async (s, e, _, _) => { + _appearedEvents.Add(e); + await s.Ack(e); + + if (_appearedEvents.Count == _events.Length) + _appeared.TrySetResult(true); + }, + (_, reason, ex) => _droppedSource.TrySetResult((reason, ex)), + TestCredentials.Root + ); await Task.WhenAll(_appeared.Task, _checkPointSource.Task).WithTimeout(); @@ -82,24 +89,30 @@ await StreamsClient.SubscribeToStreamAsync(checkPointStream, protected override async Task When() { // Force restart of the subscription - await Client.UpdateToStreamAsync(Stream, Group, new PersistentSubscriptionSettings(), - userCredentials: TestCredentials.Root); + await Client.UpdateToStreamAsync( + Stream, + Group, + new(), + userCredentials: TestCredentials.Root + ); await _droppedSource.Task.WithTimeout(); - _secondSubscription = await Client.SubscribeToStreamAsync(Stream, Group, - eventAppeared: async (s, e, _, _) => { - _resumedSource.TrySetResult(e); - await s.Ack(e); - }, - (_, reason, ex) => { - if (ex is not null) { - _resumedSource.TrySetException(ex); - } else { - _resumedSource.TrySetResult(default); - } - }, - userCredentials: TestCredentials.Root); + _secondSubscription = await Client.SubscribeToStreamAsync( + Stream, + Group, + async (s, e, _, _) => { + _resumedSource.TrySetResult(e); + await s.Ack(e); + }, + (_, reason, ex) => { + if (ex is not null) + _resumedSource.TrySetException(ex); + else + _resumedSource.TrySetResult(default); + }, + TestCredentials.Root + ); await StreamsClient.AppendToStreamAsync(Stream, StreamState.Any, CreateTestEvents(1)); } diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/update_existing_with_subscribers.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/update_existing_with_subscribers.cs index 80968c525..c803ef64c 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/update_existing_with_subscribers.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/update_existing_with_subscribers.cs @@ -1,14 +1,12 @@ -namespace EventStore.Client.SubscriptionToStream; +namespace EventStore.Client.SubscriptionToStream; public class update_existing_with_subscribers : IClassFixture { - private const string Stream = nameof(update_existing_with_subscribers); - private const string Group = "existing"; - private readonly Fixture _fixture; + const string Stream = nameof(update_existing_with_subscribers); + const string Group = "existing"; + readonly Fixture _fixture; - public update_existing_with_subscribers(Fixture fixture) { - _fixture = fixture; - } + public update_existing_with_subscribers(Fixture fixture) => _fixture = fixture; [Fact] public async Task existing_subscriptions_are_dropped() { @@ -20,25 +18,38 @@ public async Task existing_subscriptions_are_dropped() { } public class Fixture : EventStoreClientFixture { - private readonly TaskCompletionSource<(SubscriptionDroppedReason, Exception?)> _droppedSource; - public Task<(SubscriptionDroppedReason, Exception?)> Dropped => _droppedSource.Task; - private PersistentSubscription? _subscription; + readonly TaskCompletionSource<(SubscriptionDroppedReason, Exception?)> _droppedSource; + PersistentSubscription? _subscription; - public Fixture() { - _droppedSource = new TaskCompletionSource<(SubscriptionDroppedReason, Exception?)>(); - } + public Fixture() => _droppedSource = new(); + + public Task<(SubscriptionDroppedReason, Exception?)> Dropped => _droppedSource.Task; protected override async Task Given() { await StreamsClient.AppendToStreamAsync(Stream, StreamState.NoStream, CreateTestEvents()); - await Client.CreateToStreamAsync(Stream, Group, new PersistentSubscriptionSettings(), - userCredentials: TestCredentials.Root); - _subscription = await Client.SubscribeToStreamAsync(Stream, Group, - delegate { return Task.CompletedTask; }, - (_, reason, ex) => _droppedSource.TrySetResult((reason, ex)), TestCredentials.Root); + await Client.CreateToStreamAsync( + Stream, + Group, + new(), + userCredentials: TestCredentials.Root + ); + + _subscription = await Client.SubscribeToStreamAsync( + Stream, + Group, + delegate { return Task.CompletedTask; }, + (_, reason, ex) => _droppedSource.TrySetResult((reason, ex)), + TestCredentials.Root + ); } - protected override Task When() => Client.UpdateToStreamAsync(Stream, Group, - new PersistentSubscriptionSettings(), userCredentials: TestCredentials.Root); + protected override Task When() => + Client.UpdateToStreamAsync( + Stream, + Group, + new(), + userCredentials: TestCredentials.Root + ); public override Task DisposeAsync() { _subscription?.Dispose(); diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/update_existing_without_permissions.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/update_existing_without_permissions.cs index 5d9898d6d..bc0c5720d 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/update_existing_without_permissions.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/update_existing_without_permissions.cs @@ -1,31 +1,40 @@ -namespace EventStore.Client.SubscriptionToStream; +namespace EventStore.Client.SubscriptionToStream; public class update_existing_without_permissions : IClassFixture { - private const string Stream = nameof(update_existing_without_permissions); - private const string Group = "existing"; - private readonly Fixture _fixture; + const string Stream = nameof(update_existing_without_permissions); + const string Group = "existing"; + readonly Fixture _fixture; - public update_existing_without_permissions(Fixture fixture) { - _fixture = fixture; - } + public update_existing_without_permissions(Fixture fixture) => _fixture = fixture; [Fact] - public async Task the_completion_fails_with_access_denied() { + public async Task the_completion_fails_with_access_denied() => await Assert.ThrowsAsync( - () => _fixture.Client.UpdateToStreamAsync(Stream, Group, - new PersistentSubscriptionSettings())); - } + () => _fixture.Client.UpdateToStreamAsync( + Stream, + Group, + new() + ) + ); public class Fixture : EventStoreClientFixture { - public Fixture () : base(noDefaultCredentials: true){ - } - + public Fixture() : base(noDefaultCredentials: true) { } + protected override async Task Given() { - await StreamsClient.AppendToStreamAsync(Stream, StreamState.NoStream, CreateTestEvents(), - userCredentials: TestCredentials.Root); - await Client.CreateToStreamAsync(Stream, Group, new PersistentSubscriptionSettings(), - userCredentials: TestCredentials.Root); + await StreamsClient.AppendToStreamAsync( + Stream, + StreamState.NoStream, + CreateTestEvents(), + userCredentials: TestCredentials.Root + ); + + await Client.CreateToStreamAsync( + Stream, + Group, + new(), + userCredentials: TestCredentials.Root + ); } protected override Task When() => Task.CompletedTask; diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/update_non_existent.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/update_non_existent.cs index bdc01ca84..609d3a241 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/update_non_existent.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/update_non_existent.cs @@ -1,21 +1,23 @@ -namespace EventStore.Client.SubscriptionToStream; +namespace EventStore.Client.SubscriptionToStream; public class update_non_existent : IClassFixture { - private const string Stream = nameof(update_non_existent); - private const string Group = "nonexistent"; - private readonly Fixture _fixture; + const string Stream = nameof(update_non_existent); + const string Group = "nonexistent"; + readonly Fixture _fixture; - public update_non_existent(Fixture fixture) { - _fixture = fixture; - } + public update_non_existent(Fixture fixture) => _fixture = fixture; [Regression.Fact(21, "20.x returns the wrong exception")] - public async Task the_completion_fails_with_not_found() { + public async Task the_completion_fails_with_not_found() => await Assert.ThrowsAsync( - () => _fixture.Client.UpdateToStreamAsync(Stream, Group, - new PersistentSubscriptionSettings(), userCredentials: TestCredentials.Root)); - } + () => _fixture.Client.UpdateToStreamAsync( + Stream, + Group, + new(), + userCredentials: TestCredentials.Root + ) + ); public class Fixture : EventStoreClientFixture { protected override Task Given() => Task.CompletedTask; diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/when_writing_and_subscribing_to_normal_events_manual_nack.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/when_writing_and_subscribing_to_normal_events_manual_nack.cs index 289a8fef1..72e6d133f 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/when_writing_and_subscribing_to_normal_events_manual_nack.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SubscriptionToStream/when_writing_and_subscribing_to_normal_events_manual_nack.cs @@ -1,61 +1,64 @@ -namespace EventStore.Client.SubscriptionToStream; +namespace EventStore.Client.SubscriptionToStream; public class when_writing_and_subscribing_to_normal_events_manual_nack : IClassFixture { - private const string Stream = nameof(when_writing_and_subscribing_to_normal_events_manual_nack); - private const string Group = nameof(Group); - private const int BufferCount = 10; - private const int EventWriteCount = BufferCount * 2; + const string Stream = nameof(when_writing_and_subscribing_to_normal_events_manual_nack); + const string Group = nameof(Group); + const int BufferCount = 10; + const int EventWriteCount = BufferCount * 2; - private readonly Fixture _fixture; + readonly Fixture _fixture; - public when_writing_and_subscribing_to_normal_events_manual_nack(Fixture fixture) { - _fixture = fixture; - } + public when_writing_and_subscribing_to_normal_events_manual_nack(Fixture fixture) => _fixture = fixture; [Fact] - public async Task Test() { - await _fixture.EventsReceived.WithTimeout(); - } + public async Task Test() => await _fixture.EventsReceived.WithTimeout(); public class Fixture : EventStoreClientFixture { - private readonly EventData[] _events; - private readonly TaskCompletionSource _eventsReceived; - public Task EventsReceived => _eventsReceived.Task; + readonly EventData[] _events; + readonly TaskCompletionSource _eventsReceived; + int _eventReceivedCount; - private PersistentSubscription? _subscription; - private int _eventReceivedCount; + PersistentSubscription? _subscription; - public Fixture() { + public Fixture() { _events = CreateTestEvents(EventWriteCount) .ToArray(); - _eventsReceived = new TaskCompletionSource(); + + _eventsReceived = new(); } + public Task EventsReceived => _eventsReceived.Task; + protected override async Task Given() { - await Client.CreateToStreamAsync(Stream, Group, - new PersistentSubscriptionSettings(startFrom: StreamPosition.Start, resolveLinkTos: true), - userCredentials: TestCredentials.Root); - _subscription = await Client.SubscribeToStreamAsync(Stream, Group, - async (subscription, e, retryCount, ct) => { - await subscription.Nack(PersistentSubscriptionNakEventAction.Park, "fail", e); + await Client.CreateToStreamAsync( + Stream, + Group, + new(startFrom: StreamPosition.Start, resolveLinkTos: true), + userCredentials: TestCredentials.Root + ); + + _subscription = await Client.SubscribeToStreamAsync( + Stream, + Group, + async (subscription, e, retryCount, ct) => { + await subscription.Nack(PersistentSubscriptionNakEventAction.Park, "fail", e); - if (Interlocked.Increment(ref _eventReceivedCount) == _events.Length) { - _eventsReceived.TrySetResult(true); - } - }, (s, r, e) => { - if (e != null) { - _eventsReceived.TrySetException(e); - } - }, - bufferSize: BufferCount, - userCredentials: TestCredentials.Root); + if (Interlocked.Increment(ref _eventReceivedCount) == _events.Length) + _eventsReceived.TrySetResult(true); + }, + (s, r, e) => { + if (e != null) + _eventsReceived.TrySetException(e); + }, + bufferSize: BufferCount, + userCredentials: TestCredentials.Root + ); } protected override async Task When() { - foreach (var e in _events) { - await StreamsClient.AppendToStreamAsync(Stream, StreamState.Any, new[] {e}); - } + foreach (var e in _events) + await StreamsClient.AppendToStreamAsync(Stream, StreamState.Any, new[] { e }); } public override Task DisposeAsync() { diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/SupportsPSToAllFact.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/SupportsPSToAllFact.cs index 35cd1c36e..a11563677 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/SupportsPSToAllFact.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/SupportsPSToAllFact.cs @@ -1,11 +1,15 @@ -namespace EventStore.Client; +namespace EventStore.Client; public class SupportsPSToAll { - private const int SupportedFromMajorVersion = 21; - private static readonly string SkipMessage = + const int SupportedFromMajorVersion = 21; + + static readonly string SkipMessage = "Persistent Subscriptions to $all are not supported on " + $"{EventStoreTestServer.Version?.ToString(3) ?? "unknown"}"; + internal static bool No => !Yes; + internal static bool Yes => (EventStoreTestServer.Version?.Major ?? int.MaxValue) >= SupportedFromMajorVersion; + public class FactAttribute : Regression.FactAttribute { public FactAttribute() : base(SupportedFromMajorVersion, SkipMessage) { } } @@ -13,7 +17,4 @@ public FactAttribute() : base(SupportedFromMajorVersion, SkipMessage) { } public class TheoryAttribute : Regression.TheoryAttribute { public TheoryAttribute() : base(SupportedFromMajorVersion, SkipMessage) { } } - - internal static bool No => !Yes; - internal static bool Yes => (EventStoreTestServer.Version?.Major ?? int.MaxValue) >= SupportedFromMajorVersion; } \ No newline at end of file diff --git a/test/EventStore.Client.PersistentSubscriptions.Tests/restart_subsystem.cs b/test/EventStore.Client.PersistentSubscriptions.Tests/restart_subsystem.cs index 9dae514f2..c2de73203 100644 --- a/test/EventStore.Client.PersistentSubscriptions.Tests/restart_subsystem.cs +++ b/test/EventStore.Client.PersistentSubscriptions.Tests/restart_subsystem.cs @@ -1,39 +1,33 @@ -namespace EventStore.Client; +namespace EventStore.Client; public class restart_subsystem : IClassFixture { - private readonly Fixture _fixture; - - public restart_subsystem(Fixture fixture) { - _fixture = fixture; - } + readonly Fixture _fixture; + + public restart_subsystem(Fixture fixture) => _fixture = fixture; [Fact] - public async Task does_not_throw() { - await _fixture.Client.RestartSubsystemAsync(userCredentials: TestCredentials.Root); - } + public async Task does_not_throw() => await _fixture.Client.RestartSubsystemAsync(userCredentials: TestCredentials.Root); [Fact] - public async Task throws_with_no_credentials() { - await Assert.ThrowsAsync(async () => - await _fixture.Client.RestartSubsystemAsync()); - } + public async Task throws_with_no_credentials() => + await Assert.ThrowsAsync( + async () => + await _fixture.Client.RestartSubsystemAsync() + ); [Fact(Skip = "Unable to produce same behavior with HTTP fallback!")] - public async Task throws_with_non_existing_user() { - await Assert.ThrowsAsync(async () => - await _fixture.Client.RestartSubsystemAsync(userCredentials: TestCredentials.TestBadUser)); - } - + public async Task throws_with_non_existing_user() => + await Assert.ThrowsAsync( + async () => await _fixture.Client.RestartSubsystemAsync(userCredentials: TestCredentials.TestBadUser) + ); + [Fact] - public async Task throws_with_normal_user_credentials() { - await Assert.ThrowsAsync(async () => - await _fixture.Client.RestartSubsystemAsync(userCredentials: TestCredentials.TestUser1)); - } - + public async Task throws_with_normal_user_credentials() => + await Assert.ThrowsAsync(async () => await _fixture.Client.RestartSubsystemAsync(userCredentials: TestCredentials.TestUser1)); + public class Fixture : EventStoreClientFixture { - public Fixture () : base(noDefaultCredentials: true) { - } - + public Fixture() : base(noDefaultCredentials: true) { } + protected override Task Given() => Task.CompletedTask; protected override Task When() => Task.CompletedTask; } diff --git a/test/EventStore.Client.ProjectionManagement.Tests/AssertEx.cs b/test/EventStore.Client.ProjectionManagement.Tests/AssertEx.cs index 8d13075d0..50618a3ae 100644 --- a/test/EventStore.Client.ProjectionManagement.Tests/AssertEx.cs +++ b/test/EventStore.Client.ProjectionManagement.Tests/AssertEx.cs @@ -1,7 +1,7 @@ using System.Runtime.CompilerServices; using Xunit.Sdk; -namespace EventStore.Client; +namespace EventStore.Client; public static class AssertEx { /// @@ -16,25 +16,29 @@ public static class AssertEx { /// A message to display if the condition is not satisfied. /// If true, the thread relinquishes the remainder of its time /// slice to any thread of equal priority that is ready to run. - public static async Task IsOrBecomesTrue(Func> func, TimeSpan? timeout = null, - string msg = "AssertEx.IsOrBecomesTrue() timed out", bool yieldThread = false, - [CallerMemberName] string memberName = "", - [CallerFilePath] string sourceFilePath = "", - [CallerLineNumber] int sourceLineNumber = 0) { - + public static async Task IsOrBecomesTrue( + Func> func, TimeSpan? timeout = null, + string msg = "AssertEx.IsOrBecomesTrue() timed out", bool yieldThread = false, + [CallerMemberName] + string memberName = "", + [CallerFilePath] + string sourceFilePath = "", + [CallerLineNumber] + int sourceLineNumber = 0 + ) { if (await IsOrBecomesTrueImpl(func, timeout, yieldThread)) return; throw new XunitException($"{msg} in {memberName} {sourceFilePath}:{sourceLineNumber}"); } - + private static async Task IsOrBecomesTrueImpl( Func> func, TimeSpan? timeout = null, - bool yieldThread = false) { - + bool yieldThread = false + ) { if (await func()) { - return true; + return true; } var expire = DateTime.UtcNow + (timeout ?? TimeSpan.FromMilliseconds(1000)); @@ -46,11 +50,11 @@ private static async Task IsOrBecomesTrueImpl( } while (!spin.NextSpinWillYield) { - spin.SpinOnce(); + spin.SpinOnce(); } if (await func()) { - return true; + return true; } spin = new SpinWait(); diff --git a/test/EventStore.Client.ProjectionManagement.Tests/EventStore.Client.ProjectionManagement.Tests.csproj b/test/EventStore.Client.ProjectionManagement.Tests/EventStore.Client.ProjectionManagement.Tests.csproj index 91181e38d..e924bdc41 100644 --- a/test/EventStore.Client.ProjectionManagement.Tests/EventStore.Client.ProjectionManagement.Tests.csproj +++ b/test/EventStore.Client.ProjectionManagement.Tests/EventStore.Client.ProjectionManagement.Tests.csproj @@ -1,9 +1,6 @@  - - - - + diff --git a/test/EventStore.Client.ProjectionManagement.Tests/EventStoreClientFixture.cs b/test/EventStore.Client.ProjectionManagement.Tests/EventStoreClientFixture.cs index e5fbd1ebf..4d17b2b59 100644 --- a/test/EventStore.Client.ProjectionManagement.Tests/EventStoreClientFixture.cs +++ b/test/EventStore.Client.ProjectionManagement.Tests/EventStoreClientFixture.cs @@ -1,4 +1,4 @@ -namespace EventStore.Client; +namespace EventStore.Client; public abstract class EventStoreClientFixture : EventStoreClientFixtureBase { public EventStoreUserManagementClient UserManagementClient { get; } @@ -6,10 +6,14 @@ public abstract class EventStoreClientFixture : EventStoreClientFixtureBase { public EventStoreProjectionManagementClient Client { get; } protected EventStoreClientFixture(EventStoreClientSettings? settings = null, bool noDefaultCredentials = false) : - base(settings, new Dictionary { - ["EVENTSTORE_RUN_PROJECTIONS"] = "ALL", - ["EVENTSTORE_START_STANDARD_PROJECTIONS"] = "True" - }, noDefaultCredentials) { + base( + settings, + new Dictionary { + ["EVENTSTORE_RUN_PROJECTIONS"] = "ALL", + ["EVENTSTORE_START_STANDARD_PROJECTIONS"] = "True" + }, + noDefaultCredentials + ) { Client = new EventStoreProjectionManagementClient(Settings); UserManagementClient = new EventStoreUserManagementClient(Settings); StreamsClient = new EventStoreClient(Settings); @@ -21,15 +25,19 @@ protected override async Task OnServerUpAsync() { await StreamsClient.WarmUp(); await UserManagementClient.WarmUp(); await Client.WarmUp(); - await UserManagementClient.CreateUserWithRetry(TestCredentials.TestUser1.Username!, - TestCredentials.TestUser1.Username!, Array.Empty(), TestCredentials.TestUser1.Password!, - TestCredentials.Root).WithTimeout(); + await UserManagementClient.CreateUserWithRetry( + TestCredentials.TestUser1.Username!, + TestCredentials.TestUser1.Username!, + Array.Empty(), + TestCredentials.TestUser1.Password!, + TestCredentials.Root + ).WithTimeout(); + await StandardProjections.Created(Client).WithTimeout(TimeSpan.FromMinutes(2)); if (RunStandardProjections) { await Task - .WhenAll(StandardProjections.Names.Select(name => - Client.EnableAsync(name, userCredentials: TestCredentials.Root))) + .WhenAll(StandardProjections.Names.Select(name => Client.EnableAsync(name, userCredentials: TestCredentials.Root))) .WithTimeout(TimeSpan.FromMinutes(2)); } } diff --git a/test/EventStore.Client.ProjectionManagement.Tests/StandardProjections.cs b/test/EventStore.Client.ProjectionManagement.Tests/StandardProjections.cs index 6d48817f2..892e9d6b7 100644 --- a/test/EventStore.Client.ProjectionManagement.Tests/StandardProjections.cs +++ b/test/EventStore.Client.ProjectionManagement.Tests/StandardProjections.cs @@ -1,6 +1,6 @@ -namespace EventStore.Client; +namespace EventStore.Client; -internal static class StandardProjections { +static class StandardProjections { public static readonly string[] Names = { "$streams", "$stream_by_category", @@ -10,19 +10,20 @@ internal static class StandardProjections { }; public static Task Created(EventStoreProjectionManagementClient client) { - var systemProjectionsReady = Names.Select(async name => { - bool ready = false; + var systemProjectionsReady = Names.Select( + async name => { + var ready = false; - while (!ready) { - var result = await client.GetStatusAsync(name, userCredentials: TestCredentials.Root); - - if (result?.Status.Contains("Running") ?? false) { - ready = true; - } else { - await Task.Delay(100); + while (!ready) { + var result = await client.GetStatusAsync(name, userCredentials: TestCredentials.Root); + + if (result?.Status.Contains("Running") ?? false) + ready = true; + else + await Task.Delay(100); } } - }); + ); return Task.WhenAll(systemProjectionsReady); } diff --git a/test/EventStore.Client.ProjectionManagement.Tests/create.cs b/test/EventStore.Client.ProjectionManagement.Tests/create.cs index 07fb51732..0594f9148 100644 --- a/test/EventStore.Client.ProjectionManagement.Tests/create.cs +++ b/test/EventStore.Client.ProjectionManagement.Tests/create.cs @@ -1,4 +1,4 @@ -namespace EventStore.Client; +namespace EventStore.Client; public class @create : IClassFixture { private readonly Fixture _fixture; @@ -9,23 +9,26 @@ public create(Fixture fixture) { [Fact] public async Task one_time() { - await _fixture.Client.CreateOneTimeAsync( - "fromAll().when({$init: function (state, ev) {return {};}});", userCredentials: TestCredentials.Root); + await _fixture.Client.CreateOneTimeAsync("fromAll().when({$init: function (state, ev) {return {};}});", userCredentials: TestCredentials.Root); } [Theory, InlineData(true), InlineData(false)] public async Task continuous(bool trackEmittedStreams) { await _fixture.Client.CreateContinuousAsync( $"{nameof(continuous)}_{trackEmittedStreams}", - "fromAll().when({$init: function (state, ev) {return {};}});", trackEmittedStreams, - userCredentials: TestCredentials.Root); + "fromAll().when({$init: function (state, ev) {return {};}});", + trackEmittedStreams, + userCredentials: TestCredentials.Root + ); } [Fact] public async Task transient() { await _fixture.Client.CreateTransientAsync( nameof(transient), - "fromAll().when({$init: function (state, ev) {return {};}});", userCredentials: TestCredentials.Root); + "fromAll().when({$init: function (state, ev) {return {};}});", + userCredentials: TestCredentials.Root + ); } public class Fixture : EventStoreClientFixture { diff --git a/test/EventStore.Client.ProjectionManagement.Tests/disable.cs b/test/EventStore.Client.ProjectionManagement.Tests/disable.cs index bd97dcaca..ac48ddde3 100644 --- a/test/EventStore.Client.ProjectionManagement.Tests/disable.cs +++ b/test/EventStore.Client.ProjectionManagement.Tests/disable.cs @@ -1,11 +1,9 @@ -namespace EventStore.Client; +namespace EventStore.Client; public class @disable : IClassFixture { - private readonly Fixture _fixture; + readonly Fixture _fixture; - public disable(Fixture fixture) { - _fixture = fixture; - } + public disable(Fixture fixture) => _fixture = fixture; [Fact] public async Task status_is_stopped() { @@ -13,8 +11,7 @@ public async Task status_is_stopped() { await _fixture.Client.DisableAsync(name, userCredentials: TestCredentials.Root); var result = await _fixture.Client.GetStatusAsync(name, userCredentials: TestCredentials.Root); Assert.NotNull(result); - Assert.Contains(new[] {"Aborted/Stopped", "Stopped"}, x => x == result!.Status); - + Assert.Contains(new[] { "Aborted/Stopped", "Stopped" }, x => x == result!.Status); } public class Fixture : EventStoreClientFixture { diff --git a/test/EventStore.Client.ProjectionManagement.Tests/enable.cs b/test/EventStore.Client.ProjectionManagement.Tests/enable.cs index c5be94ceb..57f65b4e5 100644 --- a/test/EventStore.Client.ProjectionManagement.Tests/enable.cs +++ b/test/EventStore.Client.ProjectionManagement.Tests/enable.cs @@ -1,11 +1,9 @@ -namespace EventStore.Client; +namespace EventStore.Client; public class @enable : IClassFixture { - private readonly Fixture _fixture; + readonly Fixture _fixture; - public enable(Fixture fixture) { - _fixture = fixture; - } + public enable(Fixture fixture) => _fixture = fixture; [Fact] public async Task status_is_running() { @@ -17,8 +15,8 @@ public async Task status_is_running() { } public class Fixture : EventStoreClientFixture { + protected override bool RunStandardProjections => false; protected override Task Given() => Task.CompletedTask; protected override Task When() => Task.CompletedTask; - protected override bool RunStandardProjections => false; } } \ No newline at end of file diff --git a/test/EventStore.Client.ProjectionManagement.Tests/get_result.cs b/test/EventStore.Client.ProjectionManagement.Tests/get_result.cs index 2490f8d1f..2c5aab600 100644 --- a/test/EventStore.Client.ProjectionManagement.Tests/get_result.cs +++ b/test/EventStore.Client.ProjectionManagement.Tests/get_result.cs @@ -1,4 +1,4 @@ -namespace EventStore.Client; +namespace EventStore.Client; public class get_result : IClassFixture { private readonly Fixture _fixture; @@ -11,12 +11,14 @@ public get_result(Fixture fixture) { public async Task returns_expected_result() { Result? result = null; - await AssertEx.IsOrBecomesTrue(async () => { - result = await _fixture.Client - .GetResultAsync(nameof(get_result), userCredentials: TestCredentials.TestUser1); + await AssertEx.IsOrBecomesTrue( + async () => { + result = await _fixture.Client + .GetResultAsync(nameof(get_result), userCredentials: TestCredentials.TestUser1); - return result.Count > 0; - }); + return result.Count > 0; + } + ); Assert.NotNull(result); Assert.Equal(1, result!.Count); @@ -34,12 +36,19 @@ public class Fixture : EventStoreClientFixture { }}); "; - protected override Task Given() => Client.CreateContinuousAsync(nameof(get_result), - Projection, userCredentials: TestCredentials.Root); + protected override Task Given() => + Client.CreateContinuousAsync( + nameof(get_result), + Projection, + userCredentials: TestCredentials.Root + ); protected override async Task When() { - await StreamsClient.AppendToStreamAsync(nameof(get_result), StreamState.NoStream, - CreateTestEvents()); + await StreamsClient.AppendToStreamAsync( + nameof(get_result), + StreamState.NoStream, + CreateTestEvents() + ); } } } \ No newline at end of file diff --git a/test/EventStore.Client.ProjectionManagement.Tests/get_state.cs b/test/EventStore.Client.ProjectionManagement.Tests/get_state.cs index 70884a997..13e790772 100644 --- a/test/EventStore.Client.ProjectionManagement.Tests/get_state.cs +++ b/test/EventStore.Client.ProjectionManagement.Tests/get_state.cs @@ -1,4 +1,4 @@ -namespace EventStore.Client; +namespace EventStore.Client; public class get_state : IClassFixture { private readonly Fixture _fixture; @@ -10,14 +10,16 @@ public get_state(Fixture fixture) { [Fact] public async Task returns_expected_result() { Result? result = null; - - await AssertEx.IsOrBecomesTrue(async () => { - result = await _fixture.Client - .GetStateAsync(nameof(get_state), userCredentials: TestCredentials.TestUser1); - - return result.Count > 0; - }); - + + await AssertEx.IsOrBecomesTrue( + async () => { + result = await _fixture.Client + .GetStateAsync(nameof(get_state), userCredentials: TestCredentials.TestUser1); + + return result.Count > 0; + } + ); + Assert.NotNull(result); Assert.Equal(1, result!.Count); } @@ -34,10 +36,18 @@ public class Fixture : EventStoreClientFixture { }}); "; - protected override Task Given() => Client.CreateContinuousAsync(nameof(get_state), - Projection, userCredentials: TestCredentials.Root); - - protected override Task When() => StreamsClient.AppendToStreamAsync(nameof(get_state), StreamState.NoStream, - CreateTestEvents()); + protected override Task Given() => + Client.CreateContinuousAsync( + nameof(get_state), + Projection, + userCredentials: TestCredentials.Root + ); + + protected override Task When() => + StreamsClient.AppendToStreamAsync( + nameof(get_state), + StreamState.NoStream, + CreateTestEvents() + ); } } \ No newline at end of file diff --git a/test/EventStore.Client.ProjectionManagement.Tests/get_status.cs b/test/EventStore.Client.ProjectionManagement.Tests/get_status.cs index 693859091..a2392e0d9 100644 --- a/test/EventStore.Client.ProjectionManagement.Tests/get_status.cs +++ b/test/EventStore.Client.ProjectionManagement.Tests/get_status.cs @@ -1,11 +1,9 @@ -namespace EventStore.Client; +namespace EventStore.Client; public class get_status : IClassFixture { - private readonly Fixture _fixture; + readonly Fixture _fixture; - public get_status(Fixture fixture) { - _fixture = fixture; - } + public get_status(Fixture fixture) => _fixture = fixture; [Fact] public async Task returns_expected_result() { diff --git a/test/EventStore.Client.ProjectionManagement.Tests/list_all_projections.cs b/test/EventStore.Client.ProjectionManagement.Tests/list_all_projections.cs index c58b899d6..4f2457870 100644 --- a/test/EventStore.Client.ProjectionManagement.Tests/list_all_projections.cs +++ b/test/EventStore.Client.ProjectionManagement.Tests/list_all_projections.cs @@ -1,11 +1,9 @@ -namespace EventStore.Client; +namespace EventStore.Client; public class list_all_projections : IClassFixture { - private readonly Fixture _fixture; + readonly Fixture _fixture; - public list_all_projections(Fixture fixture) { - _fixture = fixture; - } + public list_all_projections(Fixture fixture) => _fixture = fixture; [Fact] public async Task returns_expected_result() { diff --git a/test/EventStore.Client.ProjectionManagement.Tests/list_continuous_projections.cs b/test/EventStore.Client.ProjectionManagement.Tests/list_continuous_projections.cs index cb677322a..90f3c6d31 100644 --- a/test/EventStore.Client.ProjectionManagement.Tests/list_continuous_projections.cs +++ b/test/EventStore.Client.ProjectionManagement.Tests/list_continuous_projections.cs @@ -1,19 +1,20 @@ -namespace EventStore.Client; +namespace EventStore.Client; public class list_continuous_projections : IClassFixture { - private readonly Fixture _fixture; + readonly Fixture _fixture; - public list_continuous_projections(Fixture fixture) { - _fixture = fixture; - } + public list_continuous_projections(Fixture fixture) => _fixture = fixture; [Fact] public async Task returns_expected_result() { var result = await _fixture.Client.ListContinuousAsync(userCredentials: TestCredentials.Root) .ToArrayAsync(); - Assert.Equal(result.Select(x => x.Name).OrderBy(x => x), - StandardProjections.Names.Concat(new[] {nameof(list_continuous_projections)}).OrderBy(x => x)); + Assert.Equal( + result.Select(x => x.Name).OrderBy(x => x), + StandardProjections.Names.Concat(new[] { nameof(list_continuous_projections) }).OrderBy(x => x) + ); + Assert.True(result.All(x => x.Mode == "Continuous")); } @@ -22,7 +23,8 @@ protected override Task Given() => Client.CreateContinuousAsync( nameof(list_continuous_projections), "fromAll().when({$init: function (state, ev) {return {};}});", - userCredentials: TestCredentials.Root); + userCredentials: TestCredentials.Root + ); protected override Task When() => Task.CompletedTask; } diff --git a/test/EventStore.Client.ProjectionManagement.Tests/list_one_time_projections.cs b/test/EventStore.Client.ProjectionManagement.Tests/list_one_time_projections.cs index 7a75eac2b..0de991941 100644 --- a/test/EventStore.Client.ProjectionManagement.Tests/list_one_time_projections.cs +++ b/test/EventStore.Client.ProjectionManagement.Tests/list_one_time_projections.cs @@ -1,11 +1,9 @@ -namespace EventStore.Client; +namespace EventStore.Client; public class list_one_time_projections : IClassFixture { - private readonly Fixture _fixture; + readonly Fixture _fixture; - public list_one_time_projections(Fixture fixture) { - _fixture = fixture; - } + public list_one_time_projections(Fixture fixture) => _fixture = fixture; [Fact] public async Task returns_expected_result() { @@ -18,8 +16,7 @@ public async Task returns_expected_result() { public class Fixture : EventStoreClientFixture { protected override Task Given() => - Client.CreateOneTimeAsync( - "fromAll().when({$init: function (state, ev) {return {};}});", userCredentials: TestCredentials.Root); + Client.CreateOneTimeAsync("fromAll().when({$init: function (state, ev) {return {};}});", userCredentials: TestCredentials.Root); protected override Task When() => Task.CompletedTask; } diff --git a/test/EventStore.Client.ProjectionManagement.Tests/reset.cs b/test/EventStore.Client.ProjectionManagement.Tests/reset.cs index b9ca8ae9b..e56f857ad 100644 --- a/test/EventStore.Client.ProjectionManagement.Tests/reset.cs +++ b/test/EventStore.Client.ProjectionManagement.Tests/reset.cs @@ -1,18 +1,16 @@ -namespace EventStore.Client; +namespace EventStore.Client; public class @reset : IClassFixture { - private readonly Fixture _fixture; + readonly Fixture _fixture; - public reset(Fixture fixture) { - _fixture = fixture; - } + public reset(Fixture fixture) => _fixture = fixture; [Fact] public async Task status_is_running() { var name = StandardProjections.Names.First(); await _fixture.Client.ResetAsync(name, userCredentials: TestCredentials.Root); var result = await _fixture.Client.GetStatusAsync(name, userCredentials: TestCredentials.Root); - + Assert.NotNull(result); Assert.Equal("Running", result!.Status); } diff --git a/test/EventStore.Client.ProjectionManagement.Tests/restart_subsystem.cs b/test/EventStore.Client.ProjectionManagement.Tests/restart_subsystem.cs index 0455e073b..ab17049b5 100644 --- a/test/EventStore.Client.ProjectionManagement.Tests/restart_subsystem.cs +++ b/test/EventStore.Client.ProjectionManagement.Tests/restart_subsystem.cs @@ -1,26 +1,19 @@ -namespace EventStore.Client; +namespace EventStore.Client; public class restart_subsystem : IClassFixture { - private readonly Fixture _fixture; + readonly Fixture _fixture; - public restart_subsystem(Fixture fixture) { - _fixture = fixture; - } + public restart_subsystem(Fixture fixture) => _fixture = fixture; [Fact] - public async Task does_not_throw() { - await _fixture.Client.RestartSubsystemAsync(userCredentials: TestCredentials.Root); - } + public async Task does_not_throw() => await _fixture.Client.RestartSubsystemAsync(userCredentials: TestCredentials.Root); [Fact] - public async Task throws_when_given_no_credentials() { - await Assert.ThrowsAsync(() => _fixture.Client.RestartSubsystemAsync()); - } + public async Task throws_when_given_no_credentials() => await Assert.ThrowsAsync(() => _fixture.Client.RestartSubsystemAsync()); public class Fixture : EventStoreClientFixture { - public Fixture () : base(noDefaultCredentials: true) { - } - + public Fixture() : base(noDefaultCredentials: true) { } + protected override Task Given() => Task.CompletedTask; protected override Task When() => Task.CompletedTask; } diff --git a/test/EventStore.Client.ProjectionManagement.Tests/update.cs b/test/EventStore.Client.ProjectionManagement.Tests/update.cs index 3e88c0c16..0e4b99bf9 100644 --- a/test/EventStore.Client.ProjectionManagement.Tests/update.cs +++ b/test/EventStore.Client.ProjectionManagement.Tests/update.cs @@ -1,4 +1,4 @@ -namespace EventStore.Client; +namespace EventStore.Client; public class @update : IClassFixture { private readonly Fixture _fixture; @@ -9,13 +9,21 @@ public update(Fixture fixture) { [Theory, InlineData(true), InlineData(false), InlineData(null)] public async Task returns_expected_result(bool? emitEnabled) { - await _fixture.Client.UpdateAsync(nameof(update), - "fromAll().when({$init: function (s, e) {return {};}});", emitEnabled, userCredentials: TestCredentials.Root); + await _fixture.Client.UpdateAsync( + nameof(update), + "fromAll().when({$init: function (s, e) {return {};}});", + emitEnabled, + userCredentials: TestCredentials.Root + ); } public class Fixture : EventStoreClientFixture { - protected override Task Given() => Client.CreateContinuousAsync(nameof(update), - "fromAll().when({$init: function (state, ev) {return {};}});", userCredentials: TestCredentials.Root); + protected override Task Given() => + Client.CreateContinuousAsync( + nameof(update), + "fromAll().when({$init: function (state, ev) {return {};}});", + userCredentials: TestCredentials.Root + ); protected override Task When() => Task.CompletedTask; } diff --git a/test/EventStore.Client.Streams.Tests/EventStore.Client.Streams.Tests.csproj b/test/EventStore.Client.Streams.Tests/EventStore.Client.Streams.Tests.csproj index a956c7979..e924bdc41 100644 --- a/test/EventStore.Client.Streams.Tests/EventStore.Client.Streams.Tests.csproj +++ b/test/EventStore.Client.Streams.Tests/EventStore.Client.Streams.Tests.csproj @@ -1,8 +1,6 @@  - - - + diff --git a/test/EventStore.Client.Tests.Common/EventStore.Client.Tests.Common.csproj b/test/EventStore.Client.Tests.Common/EventStore.Client.Tests.Common.csproj index 665d6aa4f..feb8caef2 100644 --- a/test/EventStore.Client.Tests.Common/EventStore.Client.Tests.Common.csproj +++ b/test/EventStore.Client.Tests.Common/EventStore.Client.Tests.Common.csproj @@ -11,7 +11,18 @@ - + + + + + + + + + + + + @@ -24,5 +35,8 @@ Always + + Always + diff --git a/test/EventStore.Client.Tests.Common/Extensions/EventStoreClientExtensions.cs b/test/EventStore.Client.Tests.Common/Extensions/EventStoreClientExtensions.cs index f5b02b82c..f6dbfe8c9 100644 --- a/test/EventStore.Client.Tests.Common/Extensions/EventStoreClientExtensions.cs +++ b/test/EventStore.Client.Tests.Common/Extensions/EventStoreClientExtensions.cs @@ -1,105 +1,9 @@ using Polly; -using Polly.Contrib.WaitAndRetry; using static System.TimeSpan; -namespace EventStore.Client.Tests; +namespace EventStore.Client.Tests; public static class EventStoreClientExtensions { - public static Task TryExecute(this EventStoreClientBase client, Func action) { - var delay = Backoff.DecorrelatedJitterBackoffV2(medianFirstRetryDelay: FromMilliseconds(100), retryCount: 100, fastFirst: true); - var retry = Policy.Handle().WaitAndRetryAsync(delay); - - var rediscoverTimeout = Policy.TimeoutAsync(FromSeconds(30), (_, __, ___) => client.RediscoverAsync()); - var executionTimeout = Policy.TimeoutAsync(FromSeconds(180)); - - var policy = executionTimeout - .WrapAsync(rediscoverTimeout.WrapAsync(retry)); - - return policy.ExecuteAsync(ct => Execute(ct), CancellationToken.None); - - async Task Execute(CancellationToken ct) { - try { - await action(ct); - } catch (Exception ex) when (ex is not OperationCanceledException) { - // grpc throws a rpcexception when you cancel the token (which we convert into - // invalid operation) - but polly expects operationcancelledexception or it wont - // call onTimeoutAsync. so raise that here. - ct.ThrowIfCancellationRequested(); - throw; - } - } - } - - public static Task WarmUp(this EventStoreClient client) => - client.TryExecute(async ct => { - // if we can read from $users then we know that - // 1. the users exist - // 2. we are connected to leader if we require it - var users = await client - .ReadStreamAsync( - direction: Direction.Forwards, - streamName: "$users", - revision: StreamPosition.Start, - maxCount: 1, - userCredentials: TestCredentials.Root, - cancellationToken: ct) - .ToArrayAsync(ct); - - if (users.Length == 0) - throw new ("System is not ready yet..."); - - // the read from leader above is not enough to guarantee the next write goes to leader - _ = await client.AppendToStreamAsync( - streamName: "warmup", - expectedState: StreamState.Any, - eventData: Enumerable.Empty(), - userCredentials: TestCredentials.Root, - cancellationToken: ct - ); - }); - - public static Task WarmUp(this EventStoreOperationsClient client) => - client.TryExecute( - ct => client.RestartPersistentSubscriptions( - userCredentials: TestCredentials.Root, - cancellationToken: ct - ) - ); - - public static Task WarmUp(this EventStorePersistentSubscriptionsClient client) => - client.TryExecute( - ct => { - var id = Guid.NewGuid(); - return client.CreateToStreamAsync( - streamName: $"warmup-stream-{id}", - groupName: $"warmup-group-{id}", - settings: new(), - userCredentials: TestCredentials.Root, - cancellationToken: ct - ); - } - ); - - public static Task WarmUp(this EventStoreProjectionManagementClient client) => - client.TryExecute( - async ct => await client - .ListAllAsync( - userCredentials: TestCredentials.Root, - cancellationToken: ct - ) - .ToArrayAsync(ct) - ); - - public static Task WarmUp(this EventStoreUserManagementClient client) => - client.TryExecute( - async ct => await client - .ListAllAsync( - userCredentials: TestCredentials.Root, - cancellationToken: ct - ) - .ToArrayAsync(ct) - ); - public static Task CreateUserWithRetry( this EventStoreUserManagementClient client, string loginName, string fullName, string[] groups, string password, UserCredentials? userCredentials = null, CancellationToken cancellationToken = default @@ -172,4 +76,4 @@ public static Task CreateUserWithRetry( // contextData: new Dictionary { { retryCountKey, 0 } }, // CancellationToken.None); // } -} +} \ No newline at end of file diff --git a/test/EventStore.Client.Tests.Common/Extensions/EventStoreClientWarmupExtensions.cs b/test/EventStore.Client.Tests.Common/Extensions/EventStoreClientWarmupExtensions.cs new file mode 100644 index 000000000..7bc1b26a3 --- /dev/null +++ b/test/EventStore.Client.Tests.Common/Extensions/EventStoreClientWarmupExtensions.cs @@ -0,0 +1,85 @@ +namespace EventStore.Client.Tests; + +public static class EventStoreClientWarmupExtensions { + public static Task WarmUp(this EventStoreClient client) => + DatabaseWarmup.TryExecuteOnce(client, async ct => { + // if we can read from $users then we know that + // 1. the users exist + // 2. we are connected to leader if we require it + var users = await client + .ReadStreamAsync( + direction: Direction.Forwards, + streamName: "$users", + revision: StreamPosition.Start, + maxCount: 1, + userCredentials: TestCredentials.Root, + cancellationToken: ct) + .ToArrayAsync(ct); + + if (users.Length == 0) + throw new ("System is not ready yet..."); + + // the read from leader above is not enough to guarantee the next write goes to leader + _ = await client.AppendToStreamAsync( + streamName: "warmup", + expectedState: StreamState.Any, + eventData: Enumerable.Empty(), + userCredentials: TestCredentials.Root, + cancellationToken: ct + ); + }); + + public static Task WarmUp(this EventStoreOperationsClient client) => + DatabaseWarmup.TryExecuteOnce( + client, + async ct => { + await client.RestartPersistentSubscriptions( + userCredentials: TestCredentials.Root, + cancellationToken: ct + ); + } + ); + + public static Task WarmUp(this EventStorePersistentSubscriptionsClient client) => + DatabaseWarmup.TryExecuteOnce( + client, + async ct => { + var id = Guid.NewGuid(); + await client.CreateToStreamAsync( + streamName: $"warmup-stream-{id}", + groupName: $"warmup-group-{id}", + settings: new(), + userCredentials: TestCredentials.Root, + cancellationToken: ct + ); + } + ); + + public static Task WarmUp(this EventStoreProjectionManagementClient client) => + DatabaseWarmup.TryExecuteOnce( + client, + async ct => { + _ = await client + .ListAllAsync( + userCredentials: TestCredentials.Root, + cancellationToken: ct + ) + .Take(1) + .ToArrayAsync(ct); + + // await client.RestartSubsystemAsync(userCredentials: TestCredentials.Root, cancellationToken: ct); + } + ); + + public static Task WarmUp(this EventStoreUserManagementClient client) => + DatabaseWarmup.TryExecuteOnce( + client, + async ct => _ = await client + .ListAllAsync( + userCredentials: TestCredentials.Root, + cancellationToken: ct + ) + .Take(1) + .ToArrayAsync(ct) + ); +} \ No newline at end of file diff --git a/test/EventStore.Client.Tests.Common/Extensions/OperatingSystemExtensions.cs b/test/EventStore.Client.Tests.Common/Extensions/OperatingSystemExtensions.cs index c854de407..a53237543 100644 --- a/test/EventStore.Client.Tests.Common/Extensions/OperatingSystemExtensions.cs +++ b/test/EventStore.Client.Tests.Common/Extensions/OperatingSystemExtensions.cs @@ -1,9 +1,7 @@ namespace EventStore.Client; -using System; - public static class OperatingSystemExtensions { public static bool IsWindows(this OperatingSystem operatingSystem) => - operatingSystem.Platform != PlatformID.Unix + operatingSystem.Platform != PlatformID.Unix && operatingSystem.Platform != PlatformID.MacOSX; } \ No newline at end of file diff --git a/test/EventStore.Client.Tests.Common/Fixtures/Base/EventStoreClientFixtureBase.cs b/test/EventStore.Client.Tests.Common/Fixtures/Base/EventStoreClientFixtureBase.cs index e6136b60c..547c54d6c 100644 --- a/test/EventStore.Client.Tests.Common/Fixtures/Base/EventStoreClientFixtureBase.cs +++ b/test/EventStore.Client.Tests.Common/Fixtures/Base/EventStoreClientFixtureBase.cs @@ -9,140 +9,140 @@ using Serilog.Extensions.Logging; using Serilog.Formatting.Display; -namespace EventStore.Client { - public abstract class EventStoreClientFixtureBase : IAsyncLifetime { - public const string TestEventType = "-"; +namespace EventStore.Client; - private const string ConnectionStringSingle = "esdb://admin:changeit@localhost:2113/?tlsVerifyCert=false"; - private const string ConnectionStringCluster = "esdb://admin:changeit@localhost:2113,localhost:2112,localhost:2111?tls=true&tlsVerifyCert=false"; +public abstract class EventStoreClientFixtureBase : IAsyncLifetime { + public const string TestEventType = "-"; - private static readonly Subject LogEventSubject = new Subject(); + private const string ConnectionStringSingle = "esdb://admin:changeit@localhost:2113/?tlsVerifyCert=false"; + private const string ConnectionStringCluster = "esdb://admin:changeit@localhost:2113,localhost:2112,localhost:2111?tls=true&tlsVerifyCert=false"; - private readonly IList _disposables; - public IEventStoreTestServer TestServer { get; } - protected EventStoreClientSettings Settings { get; } + private static readonly Subject LogEventSubject = new Subject(); - public Bogus.Faker Faker { get; } = new(); + private readonly IList _disposables; + public IEventStoreTestServer TestServer { get; } + protected EventStoreClientSettings Settings { get; } + + public Bogus.Faker Faker { get; } = new(); - static EventStoreClientFixtureBase() { - ConfigureLogging(); - } - - private static void ConfigureLogging() { - var loggerConfiguration = new LoggerConfiguration() - .Enrich.FromLogContext() - .MinimumLevel.Is(LogEventLevel.Verbose) - .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) - .MinimumLevel.Override("Grpc", LogEventLevel.Verbose) - .WriteTo.Observers(observable => observable.Subscribe(LogEventSubject.OnNext)) - .WriteTo.Seq("http://localhost:5341/", period: TimeSpan.FromMilliseconds(1)); - Log.Logger = loggerConfiguration.CreateLogger(); + static EventStoreClientFixtureBase() { + ConfigureLogging(); + } + + private static void ConfigureLogging() { + var loggerConfiguration = new LoggerConfiguration() + .Enrich.FromLogContext() + .MinimumLevel.Is(LogEventLevel.Verbose) + .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) + .MinimumLevel.Override("Grpc", LogEventLevel.Verbose) + .WriteTo.Observers(observable => observable.Subscribe(LogEventSubject.OnNext)) + .WriteTo.Seq("http://localhost:5341/", period: TimeSpan.FromMilliseconds(1)); + Log.Logger = loggerConfiguration.CreateLogger(); #if GRPC_CORE GrpcEnvironment.SetLogger(new GrpcCoreSerilogLogger(Log.Logger.ForContext())); #endif - AppDomain.CurrentDomain.DomainUnload += (_, e) => Log.CloseAndFlush(); - } + AppDomain.CurrentDomain.DomainUnload += (_, e) => Log.CloseAndFlush(); + } - protected EventStoreClientFixtureBase(EventStoreClientSettings? clientSettings, - IDictionary? env = null, bool noDefaultCredentials = false) { - _disposables = new List(); - ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; + protected EventStoreClientFixtureBase(EventStoreClientSettings? clientSettings, + IDictionary? env = null, bool noDefaultCredentials = false) { + _disposables = new List(); + ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; - var connectionString = GlobalEnvironment.UseCluster ? ConnectionStringCluster : ConnectionStringSingle; - Settings = clientSettings ?? EventStoreClientSettings.Create(connectionString); + var connectionString = GlobalEnvironment.UseCluster ? ConnectionStringCluster : ConnectionStringSingle; + Settings = clientSettings ?? EventStoreClientSettings.Create(connectionString); - if (noDefaultCredentials) { - Settings.DefaultCredentials = null; - } + if (noDefaultCredentials) { + Settings.DefaultCredentials = null; + } - Settings.DefaultDeadline = Debugger.IsAttached - ? new TimeSpan?() - : TimeSpan.FromSeconds(30); + Settings.DefaultDeadline = Debugger.IsAttached + ? new TimeSpan?() + : TimeSpan.FromSeconds(30); - var hostCertificatePath = Path.Combine(ProjectDir.Current, "..", "..", - GlobalEnvironment.UseCluster ? "certs-cluster" : "certs"); + var hostCertificatePath = Path.Combine(ProjectDir.Current, "..", "..", + GlobalEnvironment.UseCluster ? "certs-cluster" : "certs"); - Settings.LoggerFactory ??= new SerilogLoggerFactory(); + Settings.LoggerFactory ??= new SerilogLoggerFactory(); - Settings.ConnectivitySettings.MaxDiscoverAttempts = 20; - Settings.ConnectivitySettings.DiscoveryInterval = TimeSpan.FromSeconds(1); + Settings.ConnectivitySettings.MaxDiscoverAttempts = 20; + Settings.ConnectivitySettings.DiscoveryInterval = TimeSpan.FromSeconds(1); - if (GlobalEnvironment.UseExternalServer) { - TestServer = new EventStoreTestServerExternal(); - } else { - TestServer = GlobalEnvironment.UseCluster - ? new EventStoreTestServerCluster(hostCertificatePath, Settings.ConnectivitySettings.Address, env) - : new EventStoreTestServer(hostCertificatePath, Settings.ConnectivitySettings.Address, env); - } - } + if (GlobalEnvironment.UseExternalServer) { + TestServer = new EventStoreTestServerExternal(); + } else { + TestServer = GlobalEnvironment.UseCluster + ? new EventStoreTestServerCluster(hostCertificatePath, Settings.ConnectivitySettings.Address, env) + : new EventStoreTestServer(hostCertificatePath, Settings.ConnectivitySettings.Address, env); + } + } - protected abstract Task OnServerUpAsync(); - protected abstract Task Given(); - protected abstract Task When(); + protected abstract Task OnServerUpAsync(); + protected abstract Task Given(); + protected abstract Task When(); - public IEnumerable CreateTestEvents(int count = 1, string? type = null, int metadataSize = 1) - => Enumerable.Range(0, count).Select(index => CreateTestEvent(index, type ?? TestEventType, metadataSize)); + public IEnumerable CreateTestEvents(int count = 1, string? type = null, int metadataSize = 1) + => Enumerable.Range(0, count).Select(index => CreateTestEvent(index, type ?? TestEventType, metadataSize)); - protected static EventData CreateTestEvent(int index) => CreateTestEvent(index, TestEventType, 1); + protected static EventData CreateTestEvent(int index) => CreateTestEvent(index, TestEventType, 1); - protected static EventData CreateTestEvent(int index, string type, int metadataSize) - => new EventData( - eventId: Uuid.NewUuid(), - type: type, - data: Encoding.UTF8.GetBytes($@"{{""x"":{index}}}"), - metadata: Encoding.UTF8.GetBytes("\"" + new string('$', metadataSize) + "\"")); + protected static EventData CreateTestEvent(int index, string type, int metadataSize) + => new EventData( + eventId: Uuid.NewUuid(), + type: type, + data: Encoding.UTF8.GetBytes($@"{{""x"":{index}}}"), + metadata: Encoding.UTF8.GetBytes("\"" + new string('$', metadataSize) + "\"")); - public virtual async Task InitializeAsync() { - await TestServer.StartAsync().WithTimeout(TimeSpan.FromMinutes(5)); - await OnServerUpAsync().WithTimeout(TimeSpan.FromMinutes(5)); - await Given().WithTimeout(TimeSpan.FromMinutes(5)); - await When().WithTimeout(TimeSpan.FromMinutes(5)); - } + public virtual async Task InitializeAsync() { + await TestServer.StartAsync().WithTimeout(TimeSpan.FromMinutes(5)); + await OnServerUpAsync().WithTimeout(TimeSpan.FromMinutes(5)); + await Given().WithTimeout(TimeSpan.FromMinutes(5)); + await When().WithTimeout(TimeSpan.FromMinutes(5)); + } - public virtual Task DisposeAsync() { - foreach (var disposable in _disposables) { - disposable.Dispose(); - } + public virtual Task DisposeAsync() { + foreach (var disposable in _disposables) { + disposable.Dispose(); + } - return TestServer.DisposeAsync().AsTask().WithTimeout(TimeSpan.FromMinutes(5)); - } + return TestServer.DisposeAsync().AsTask().WithTimeout(TimeSpan.FromMinutes(5)); + } - public string GetStreamName([CallerMemberName] string? testMethod = null) { - var type = GetType(); + public string GetStreamName([CallerMemberName] string? testMethod = null) { + var type = GetType(); - return $"{type.DeclaringType?.Name}.{testMethod ?? "unknown"}"; - } + return $"{type.DeclaringType?.Name}.{testMethod ?? "unknown"}"; + } - public void CaptureLogs(ITestOutputHelper testOutputHelper) { - const string captureCorrelationId = nameof(captureCorrelationId); + public void CaptureLogs(ITestOutputHelper testOutputHelper) { + const string captureCorrelationId = nameof(captureCorrelationId); - var captureId = Guid.NewGuid(); + var captureId = Guid.NewGuid(); - var callContextData = new AsyncLocal<(string, Guid)> { - Value = (captureCorrelationId, captureId) - }; + var callContextData = new AsyncLocal<(string, Guid)> { + Value = (captureCorrelationId, captureId) + }; - bool Filter(LogEvent logEvent) => callContextData.Value.Item2.Equals(captureId); + bool Filter(LogEvent logEvent) => callContextData.Value.Item2.Equals(captureId); - MessageTemplateTextFormatter formatter = new MessageTemplateTextFormatter( - "{Timestamp:yyyy-MM-dd HH:mm:ss.fff} [{Level:u3}] [{SourceContext}] {Message}"); + MessageTemplateTextFormatter formatter = new MessageTemplateTextFormatter( + "{Timestamp:yyyy-MM-dd HH:mm:ss.fff} [{Level:u3}] [{SourceContext}] {Message}"); - MessageTemplateTextFormatter formatterWithException = - new MessageTemplateTextFormatter( - "{Timestamp:yyyy-MM-dd HH:mm:ss.fff} [{Level:u3}] [{SourceContext}] {Message}{NewLine}{Exception}"); + MessageTemplateTextFormatter formatterWithException = + new MessageTemplateTextFormatter( + "{Timestamp:yyyy-MM-dd HH:mm:ss.fff} [{Level:u3}] [{SourceContext}] {Message}{NewLine}{Exception}"); - var subscription = LogEventSubject.Where(Filter).Subscribe(logEvent => { - using var writer = new StringWriter(); - if (logEvent.Exception != null) { - formatterWithException.Format(logEvent, writer); - } else { - formatter.Format(logEvent, writer); - } + var subscription = LogEventSubject.Where(Filter).Subscribe(logEvent => { + using var writer = new StringWriter(); + if (logEvent.Exception != null) { + formatterWithException.Format(logEvent, writer); + } else { + formatter.Format(logEvent, writer); + } - testOutputHelper.WriteLine(writer.ToString()); - }); + testOutputHelper.WriteLine(writer.ToString()); + }); - _disposables.Add(subscription); - } - } -} + _disposables.Add(subscription); + } +} \ No newline at end of file diff --git a/test/EventStore.Client.Tests.Common/Fixtures/Base/EventStoreTestServer.cs b/test/EventStore.Client.Tests.Common/Fixtures/Base/EventStoreTestServer.cs index a90136df5..b198ea8ff 100644 --- a/test/EventStore.Client.Tests.Common/Fixtures/Base/EventStoreTestServer.cs +++ b/test/EventStore.Client.Tests.Common/Fixtures/Base/EventStoreTestServer.cs @@ -6,123 +6,123 @@ using Ductus.FluentDocker.Services.Extensions; using Polly; -namespace EventStore.Client { - public class EventStoreTestServer : IEventStoreTestServer { - private readonly string _hostCertificatePath; - private readonly IContainerService _eventStore; - private readonly HttpClient _httpClient; - private static readonly string ContainerName = "es-client-dotnet-test"; - - private static Version? _version; - public static Version Version => _version ??= GetVersion(); - - private static Version GetVersion() { - const string versionPrefix = "EventStoreDB version"; - - using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30)); - using var eventstore = new Builder().UseContainer() - .UseImage(GlobalEnvironment.DockerImage) - .Command("--version") - .Build() - .Start(); - using var log = eventstore.Logs(true, cts.Token); - foreach (var line in log.ReadToEnd()) { - if (line.StartsWith(versionPrefix) && - Version.TryParse(line[(versionPrefix.Length + 1)..].Split(' ')[0], out var version)) { - return version; - } - } - - throw new InvalidOperationException("Could not determine server version."); - } - - public EventStoreTestServer( - string hostCertificatePath, - Uri address, - IDictionary? envOverrides) { - - _hostCertificatePath = hostCertificatePath; - VerifyCertificatesExist(); - - _httpClient = new HttpClient(new SocketsHttpHandler { - SslOptions = {RemoteCertificateValidationCallback = delegate { return true; }} - }) { - BaseAddress = address, - }; - - var env = new Dictionary { - ["EVENTSTORE_DB_LOG_FORMAT"] = GlobalEnvironment.DbLogFormat, - ["EVENTSTORE_MEM_DB"] = "true", - ["EVENTSTORE_CHUNK_SIZE"] = (1024 * 1024).ToString(), - ["EVENTSTORE_CERTIFICATE_FILE"] = "/etc/eventstore/certs/node/node.crt", - ["EVENTSTORE_CERTIFICATE_PRIVATE_KEY_FILE"] = "/etc/eventstore/certs/node/node.key", - ["EVENTSTORE_TRUSTED_ROOT_CERTIFICATES_PATH"] = "/etc/eventstore/certs/ca", - ["EVENTSTORE_LOG_LEVEL"] = "Verbose", - ["EVENTSTORE_STREAM_EXISTENCE_FILTER_SIZE"] = "10000", - ["EVENTSTORE_STREAM_INFO_CACHE_CAPACITY"] = "10000", - ["EVENTSTORE_ENABLE_ATOM_PUB_OVER_HTTP"] = "True" - }; - foreach (var (key, value) in envOverrides ?? Enumerable.Empty>()) { - env[key] = value; - } - - _eventStore = new Builder() - .UseContainer() - .UseImage(GlobalEnvironment.DockerImage) - .WithEnvironment(env.Select(pair => $"{pair.Key}={pair.Value}").ToArray()) - .WithName(ContainerName) - .MountVolume(_hostCertificatePath, "/etc/eventstore/certs", MountType.ReadOnly) - .ExposePort(2113, 2113) - .WaitForHealthy(TimeSpan.FromSeconds(30)) - .ReuseIfExists() - //.KeepContainer() - //.KeepRunning() - .Build(); - } - - - private void VerifyCertificatesExist() { - var certificateFiles = new[] { - Path.Combine("ca", "ca.crt"), - Path.Combine("ca", "ca.key"), - Path.Combine("node", "node.crt"), - Path.Combine("node", "node.key") - }.Select(path => Path.Combine(_hostCertificatePath, path)); - - foreach (var file in certificateFiles) { - if (!File.Exists(file)) { - throw new InvalidOperationException( - $"Could not locate the certificates file {file} needed to run EventStoreDB. Please run the 'gencert' tool at the root of the repository."); - } - } - } - - public async Task StartAsync(CancellationToken cancellationToken = default) { - _eventStore.Start(); - try { - await Policy.Handle() - .WaitAndRetryAsync(200, retryCount => TimeSpan.FromMilliseconds(100)) - .ExecuteAsync(async () => { - using var response = await _httpClient.GetAsync("/health/live", cancellationToken); - if (response.StatusCode >= HttpStatusCode.BadRequest) { - throw new Exception($"Health check failed with status code: {response.StatusCode}."); - } - }); - } catch (Exception) { - _eventStore.Dispose(); - throw; - } - } - - public void Stop() { - _eventStore.Stop(); - } - - public ValueTask DisposeAsync() { - _httpClient?.Dispose(); - _eventStore?.Dispose(); - - return new ValueTask(Task.CompletedTask); - } - } -} +namespace EventStore.Client.Tests; + +public class EventStoreTestServer : IEventStoreTestServer { + private readonly string _hostCertificatePath; + private readonly IContainerService _eventStore; + private readonly HttpClient _httpClient; + private static readonly string ContainerName = "es-client-dotnet-test"; + + private static Version? _version; + public static Version Version => _version ??= GetVersion(); + + private static Version GetVersion() { + const string versionPrefix = "EventStoreDB version"; + + using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30)); + using var eventstore = new Builder().UseContainer() + .UseImage(GlobalEnvironment.DockerImage) + .Command("--version") + .Build() + .Start(); + using var log = eventstore.Logs(true, cts.Token); + foreach (var line in log.ReadToEnd()) { + if (line.StartsWith(versionPrefix) && + Version.TryParse(line[(versionPrefix.Length + 1)..].Split(' ')[0], out var version)) { + return version; + } + } + + throw new InvalidOperationException("Could not determine server version."); + } + + public EventStoreTestServer( + string hostCertificatePath, + Uri address, + IDictionary? envOverrides) { + + _hostCertificatePath = hostCertificatePath; + VerifyCertificatesExist(); + + _httpClient = new HttpClient(new SocketsHttpHandler { + SslOptions = {RemoteCertificateValidationCallback = delegate { return true; }} + }) { + BaseAddress = address, + }; + + var env = new Dictionary { + ["EVENTSTORE_DB_LOG_FORMAT"] = GlobalEnvironment.DbLogFormat, + ["EVENTSTORE_MEM_DB"] = "true", + ["EVENTSTORE_CHUNK_SIZE"] = (1024 * 1024).ToString(), + ["EVENTSTORE_CERTIFICATE_FILE"] = "/etc/eventstore/certs/node/node.crt", + ["EVENTSTORE_CERTIFICATE_PRIVATE_KEY_FILE"] = "/etc/eventstore/certs/node/node.key", + ["EVENTSTORE_TRUSTED_ROOT_CERTIFICATES_PATH"] = "/etc/eventstore/certs/ca", + ["EVENTSTORE_LOG_LEVEL"] = "Verbose", + ["EVENTSTORE_STREAM_EXISTENCE_FILTER_SIZE"] = "10000", + ["EVENTSTORE_STREAM_INFO_CACHE_CAPACITY"] = "10000", + ["EVENTSTORE_ENABLE_ATOM_PUB_OVER_HTTP"] = "True" + }; + foreach (var (key, value) in envOverrides ?? Enumerable.Empty>()) { + env[key] = value; + } + + _eventStore = new Builder() + .UseContainer() + .UseImage(GlobalEnvironment.DockerImage) + .WithEnvironment(env.Select(pair => $"{pair.Key}={pair.Value}").ToArray()) + .WithName(ContainerName) + .MountVolume(_hostCertificatePath, "/etc/eventstore/certs", MountType.ReadOnly) + .ExposePort(2113, 2113) + .WaitForHealthy(TimeSpan.FromSeconds(30)) + .ReuseIfExists() + //.KeepContainer() + //.KeepRunning() + .Build(); + } + + + private void VerifyCertificatesExist() { + var certificateFiles = new[] { + Path.Combine("ca", "ca.crt"), + Path.Combine("ca", "ca.key"), + Path.Combine("node", "node.crt"), + Path.Combine("node", "node.key") + }.Select(path => Path.Combine(_hostCertificatePath, path)); + + foreach (var file in certificateFiles) { + if (!File.Exists(file)) { + throw new InvalidOperationException( + $"Could not locate the certificates file {file} needed to run EventStoreDB. Please run the 'gencert' tool at the root of the repository."); + } + } + } + + public async Task StartAsync(CancellationToken cancellationToken = default) { + _eventStore.Start(); + try { + await Policy.Handle() + .WaitAndRetryAsync(200, retryCount => TimeSpan.FromMilliseconds(100)) + .ExecuteAsync(async () => { + using var response = await _httpClient.GetAsync("/health/live", cancellationToken); + if (response.StatusCode >= HttpStatusCode.BadRequest) { + throw new Exception($"Health check failed with status code: {response.StatusCode}."); + } + }); + } catch (Exception) { + _eventStore.Dispose(); + throw; + } + } + + public void Stop() { + _eventStore.Stop(); + } + + public ValueTask DisposeAsync() { + _httpClient?.Dispose(); + _eventStore?.Dispose(); + + return new ValueTask(Task.CompletedTask); + } +} \ No newline at end of file diff --git a/test/EventStore.Client.Tests.Common/Fixtures/Base/EventStoreTestServerCluster.cs b/test/EventStore.Client.Tests.Common/Fixtures/Base/EventStoreTestServerCluster.cs index 3fd2d397b..64ea33101 100644 --- a/test/EventStore.Client.Tests.Common/Fixtures/Base/EventStoreTestServerCluster.cs +++ b/test/EventStore.Client.Tests.Common/Fixtures/Base/EventStoreTestServerCluster.cs @@ -4,81 +4,81 @@ using Ductus.FluentDocker.Services; using Polly; -namespace EventStore.Client { - public class EventStoreTestServerCluster : IEventStoreTestServer { - private readonly ICompositeService _eventStoreCluster; - private readonly HttpClient _httpClient; +namespace EventStore.Client; - public EventStoreTestServerCluster( - string hostCertificatePath, - Uri address, - IDictionary? envOverrides) { +public class EventStoreTestServerCluster : IEventStoreTestServer { + private readonly ICompositeService _eventStoreCluster; + private readonly HttpClient _httpClient; - envOverrides ??= new Dictionary(); - envOverrides["ES_CERTS_CLUSTER"] = hostCertificatePath; + public EventStoreTestServerCluster( + string hostCertificatePath, + Uri address, + IDictionary? envOverrides) { - _eventStoreCluster = BuildCluster(envOverrides); + envOverrides ??= new Dictionary(); + envOverrides["ES_CERTS_CLUSTER"] = hostCertificatePath; - _httpClient = new HttpClient(new SocketsHttpHandler { - SslOptions = {RemoteCertificateValidationCallback = delegate { return true; }} - }) { - BaseAddress = address, - }; - } + _eventStoreCluster = BuildCluster(envOverrides); - private ICompositeService BuildCluster(IDictionary? envOverrides = null) { - var env = GlobalEnvironment - .GetEnvironmentVariables(envOverrides) - .Select(pair => $"{pair.Key}={pair.Value}") - .ToArray(); + _httpClient = new HttpClient(new SocketsHttpHandler { + SslOptions = {RemoteCertificateValidationCallback = delegate { return true; }} + }) { + BaseAddress = address, + }; + } + + private ICompositeService BuildCluster(IDictionary? envOverrides = null) { + var env = GlobalEnvironment + .GetEnvironmentVariables(envOverrides) + .Select(pair => $"{pair.Key}={pair.Value}") + .ToArray(); - return new Builder() - .UseContainer() - .UseCompose() - .WithEnvironment(env) - .FromFile("docker-compose.yml") - .ForceRecreate() - .RemoveOrphans() - .Build(); - } + return new Builder() + .UseContainer() + .UseCompose() + .WithEnvironment(env) + .FromFile("docker-compose.yml") + .ForceRecreate() + .RemoveOrphans() + .Build(); + } - public async Task StartAsync(CancellationToken cancellationToken = default) { - try { - // don't know why, sometimes the default network (e.g. net50_default) remains - // from previous cluster and prevents docker-compose up from executing successfully - Policy.Handle() - .WaitAndRetry( - retryCount: 10, - sleepDurationProvider: retryCount => TimeSpan.FromSeconds(2), - onRetry: (ex, _) => { - BuildCluster().Dispose(); - _eventStoreCluster.Start(); - }) - .Execute(() => { - _eventStoreCluster.Start(); - }); + public async Task StartAsync(CancellationToken cancellationToken = default) { + try { + // don't know why, sometimes the default network (e.g. net50_default) remains + // from previous cluster and prevents docker-compose up from executing successfully + Policy.Handle() + .WaitAndRetry( + retryCount: 10, + sleepDurationProvider: retryCount => TimeSpan.FromSeconds(2), + onRetry: (ex, _) => { + BuildCluster().Dispose(); + _eventStoreCluster.Start(); + }) + .Execute(() => { + _eventStoreCluster.Start(); + }); - await Policy.Handle() - .WaitAndRetryAsync(200, retryCount => TimeSpan.FromMilliseconds(100)) - .ExecuteAsync(async () => { - using var response = await _httpClient.GetAsync("/health/live", cancellationToken); - if (response.StatusCode >= HttpStatusCode.BadRequest) { - throw new Exception($"Health check failed with status code: {response.StatusCode}."); - } - }); - } catch (Exception) { - _eventStoreCluster.Dispose(); - throw; - } - } + await Policy.Handle() + .WaitAndRetryAsync(200, retryCount => TimeSpan.FromMilliseconds(100)) + .ExecuteAsync(async () => { + using var response = await _httpClient.GetAsync("/health/live", cancellationToken); + if (response.StatusCode >= HttpStatusCode.BadRequest) { + throw new Exception($"Health check failed with status code: {response.StatusCode}."); + } + }); + } catch (Exception) { + _eventStoreCluster.Dispose(); + throw; + } + } - public void Stop() { - _eventStoreCluster.Stop(); - } + public void Stop() { + _eventStoreCluster.Stop(); + } - public ValueTask DisposeAsync() { - _eventStoreCluster.Dispose(); - return new ValueTask(Task.CompletedTask); - } - } -} + public ValueTask DisposeAsync() { + _eventStoreCluster.Dispose(); + return new ValueTask(Task.CompletedTask); + } +} \ No newline at end of file diff --git a/test/EventStore.Client.Tests.Common/Fixtures/Base/EventStoreTestServerExternal.cs b/test/EventStore.Client.Tests.Common/Fixtures/Base/EventStoreTestServerExternal.cs index d21dffdbb..83a3ee47c 100644 --- a/test/EventStore.Client.Tests.Common/Fixtures/Base/EventStoreTestServerExternal.cs +++ b/test/EventStore.Client.Tests.Common/Fixtures/Base/EventStoreTestServerExternal.cs @@ -1,8 +1,8 @@ -namespace EventStore.Client { - public class EventStoreTestServerExternal : IEventStoreTestServer { - public Task StartAsync(CancellationToken cancellationToken = default) => Task.CompletedTask; - public void Stop() { } - - public ValueTask DisposeAsync() => ValueTask.CompletedTask; - } -} +namespace EventStore.Client; + +public class EventStoreTestServerExternal : IEventStoreTestServer { + public Task StartAsync(CancellationToken cancellationToken = default) => Task.CompletedTask; + public void Stop() { } + + public ValueTask DisposeAsync() => ValueTask.CompletedTask; +} \ No newline at end of file diff --git a/test/EventStore.Client.Tests.Common/Fixtures/Base/IEventStoreTestServer.cs b/test/EventStore.Client.Tests.Common/Fixtures/Base/IEventStoreTestServer.cs index e1a13474b..6218a0440 100644 --- a/test/EventStore.Client.Tests.Common/Fixtures/Base/IEventStoreTestServer.cs +++ b/test/EventStore.Client.Tests.Common/Fixtures/Base/IEventStoreTestServer.cs @@ -1,6 +1,6 @@ -namespace EventStore.Client { - public interface IEventStoreTestServer : IAsyncDisposable { - Task StartAsync(CancellationToken cancellationToken = default); - void Stop(); - } -} +namespace EventStore.Client; + +public interface IEventStoreTestServer : IAsyncDisposable { + Task StartAsync(CancellationToken cancellationToken = default); + void Stop(); +} \ No newline at end of file diff --git a/test/EventStore.Client.Tests.Common/Fixtures/CertificatesCommander.cs b/test/EventStore.Client.Tests.Common/Fixtures/CertificatesCommander.cs new file mode 100644 index 000000000..8a9d254b5 --- /dev/null +++ b/test/EventStore.Client.Tests.Common/Fixtures/CertificatesCommander.cs @@ -0,0 +1,76 @@ +using Ductus.FluentDocker.Builders; + +namespace EventStore.Client.Tests; + +static class CertificatesCommander { + public static async Task EnsureCertificatesExist(DirectoryInfo? certificateDirectory = null) { + //var hostCertificatePath = Path.Combine(ProjectDir.Current, "..", "..", GlobalEnvironment.UseCluster ? "certs-cluster" : "certs"); + //var directory = new DirectoryInfo(Path.Combine(Environment.CurrentDirectory, "certs")); + + certificateDirectory ??= GlobalEnvironment.CertificateDirectory; + + if (!certificateDirectory.Exists) + certificateDirectory.Create(); + + var caCertificatePath = Path.Combine(certificateDirectory.FullName, "ca"); + if (!Directory.Exists(caCertificatePath)) + await GenerateCertificates( + certificateDirectory.FullName, + "A CA certificate & key file have been generated in the '/tmp/ca/' directory", + "create-ca", + "-out", + "/tmp/ca" + ); + + var nodeCertificatePath = Path.Combine(certificateDirectory.FullName, "node"); + if (!Directory.Exists(nodeCertificatePath)) + await GenerateCertificates( + certificateDirectory.FullName, + "A node certificate & key file have been generated in the '/tmp/node' directory.", + "create-node", + "-ca-certificate", + "/tmp/ca/ca.crt", + "-ca-key", + "/tmp/ca/ca.key", + "-out", + "/tmp/node", + "-ip-addresses", + "127.0.0.1", + "-dns-names", + "localhost" + ); + + static Task GenerateCertificates(string sourceFolder, string expectedLogMessage, string command, params string[] commandArgs) { + using var container = new Builder() + .UseContainer() + .UseImage("eventstore/es-gencert-cli:1.0.1") + .MountVolume(sourceFolder, "/tmp", Ductus.FluentDocker.Model.Builders.MountType.ReadWrite) + .Command(command, commandArgs) + .WaitForMessageInLog(expectedLogMessage, TimeSpan.FromSeconds(5)) + .Build(); + + container.Start(); + + return Task.CompletedTask; + } + + VerifyCertificatesExist(certificateDirectory); + + return certificateDirectory; + } + + public static void VerifyCertificatesExist(DirectoryInfo certificateDirectory) { + var certificateFiles = new[] { + Path.Combine("ca", "ca.crt"), + Path.Combine("ca", "ca.key"), + Path.Combine("node", "node.crt"), + Path.Combine("node", "node.key") + }.Select(path => Path.Combine(certificateDirectory.FullName, path)); + + foreach (var file in certificateFiles) + if (!File.Exists(file)) + throw new InvalidOperationException( + $"Could not locate the certificates file {file} needed to run EventStoreDB. Please run the 'gencert' tool at the root of the repository." + ); + } +} \ No newline at end of file diff --git a/test/EventStore.Client.Tests.Common/Fixtures/DatabaseWarmup.cs b/test/EventStore.Client.Tests.Common/Fixtures/DatabaseWarmup.cs new file mode 100644 index 000000000..ce9febf9e --- /dev/null +++ b/test/EventStore.Client.Tests.Common/Fixtures/DatabaseWarmup.cs @@ -0,0 +1,69 @@ +// ReSharper disable StaticMemberInGenericType + +using Polly; +using Polly.Contrib.WaitAndRetry; +using Serilog; +using static System.TimeSpan; +using static Serilog.Core.Constants; + +namespace EventStore.Client.Tests; + +static class DatabaseWarmup where T : EventStoreClientBase { + static readonly InterlockedBoolean Completed = new InterlockedBoolean(); + static readonly SemaphoreSlim Semaphore = new(1, 1); + static readonly ILogger Logger = Log.ForContext(SourceContextPropertyName, typeof(T).Name); + + public static async Task TryExecuteOnce(T client, Func action, CancellationToken cancellationToken = default) { + if (!Completed.CurrentValue) { + Logger.Information("*** Warming up... ***"); + await Semaphore.WaitAsync(cancellationToken); + try { + await TryExecute(client, action, cancellationToken); + Completed.CompareExchange(true, false); + Logger.Information("*** Warmup completed ***"); + } + catch (Exception ex) { + Logger.Warning(ex, "*** Warmup failed :: {Error} ***", ex.Message); + } + finally { + Semaphore.Release(); + } + } + } + + static Task TryExecute(EventStoreClientBase client, Func action, CancellationToken cancellationToken) { + var delay = Backoff.DecorrelatedJitterBackoffV2( + medianFirstRetryDelay: FromMilliseconds(500), + retryCount: 1000, + fastFirst: false + ); + + var retry = Policy.Handle().WaitAndRetryAsync(delay); + + var rediscoverTimeout = Policy.TimeoutAsync( + FromSeconds(30), + async (_, _, _) => { + Logger.Warning("*** Triggering rediscovery... ***"); + await client.RediscoverAsync(); + } + ); + + var executionTimeout = Policy.TimeoutAsync(FromSeconds(180)); + + var policy = executionTimeout + .WrapAsync(rediscoverTimeout.WrapAsync(retry)); + + return policy.ExecuteAsync(async ct => { + try { + await action(ct); + } + catch (Exception ex) when (ex is not OperationCanceledException) { + // grpc throws a rpcexception when you cancel the token (which we convert into + // invalid operation) - but polly expects operationcancelledexception or it wont + // call onTimeoutAsync. so raise that here. + ct.ThrowIfCancellationRequested(); + throw; + } + }, cancellationToken); + } +} \ No newline at end of file diff --git a/test/EventStore.Client.Tests.Common/Fixtures/EventStoreClientsFixture.cs b/test/EventStore.Client.Tests.Common/Fixtures/EventStoreClientsFixture.cs deleted file mode 100644 index f736711e4..000000000 --- a/test/EventStore.Client.Tests.Common/Fixtures/EventStoreClientsFixture.cs +++ /dev/null @@ -1,93 +0,0 @@ -using System.Runtime.CompilerServices; -using System.Text; - -namespace EventStore.Client.Tests; - -public class EventStoreClientsFixture : EventStoreIntegrationFixture { - const string TestEventType = "-"; - - public EventStoreClient Client { get; private set; } = null!; - public EventStoreClient Streams { get; private set; } = null!; - public EventStoreOperationsClient Operations { get; private set; } = null!; - public EventStoreUserManagementClient Users { get; private set; } = null!; - public EventStoreProjectionManagementClient Projections { get; private set; } = null!; - public EventStorePersistentSubscriptionsClient PersistentSubscriptions { get; private set; } = null!; - - - static readonly InterlockedBoolean WarmUpCompleted = new InterlockedBoolean(); - - protected override async Task OnInitialized() { - Client = new(Options.ClientSettings); - Streams = Client; - Operations = new(Options.ClientSettings); - Users = new(Options.ClientSettings); - Projections = new(Options.ClientSettings); - PersistentSubscriptions = new(Options.ClientSettings); - - if (WarmUpCompleted.EnsureCalledOnce()) { - try { - await Task.WhenAll( - Streams.WarmUp(), - Operations.WarmUp(), - Users.WarmUp(), - Projections.WarmUp(), - PersistentSubscriptions.WarmUp() - ); - } - - catch (Exception) { - // ignored - } - } - - //TODO SS: in order to migrate/refactor code faster will keep Given() and When() apis for now - await Given().WithTimeout(TimeSpan.FromMinutes(5)); - await When().WithTimeout(TimeSpan.FromMinutes(5)); - } - - protected virtual Task Given() => Task.CompletedTask; - protected virtual Task When() => Task.CompletedTask; - - public string GetStreamName([CallerMemberName] string? testMethod = null) => - $"{GetType().DeclaringType?.Name}.{testMethod ?? "unknown"}"; - - public IEnumerable CreateTestEvents(int count = 1, string? type = null, int metadataSize = 1) => - Enumerable.Range(0, count).Select(index => CreateTestEvent(index, type ?? TestEventType, metadataSize)); - - protected static EventData CreateTestEvent(int index) => CreateTestEvent(index, TestEventType, 1); - - protected static EventData CreateTestEvent(int index, string type, int metadataSize) => - new( - Uuid.NewUuid(), - type, - Encoding.UTF8.GetBytes($$"""{"x":{{index}}}"""), - Encoding.UTF8.GetBytes($"\"{new string('$', metadataSize)}\"") - ); - - public async Task CreateTestUser(bool withoutGroups = true, bool useUserCredentials = false) { - var result = await CreateTestUsers(1, withoutGroups, useUserCredentials); - return result.First(); - } - - public Task CreateTestUsers(int count = 3, bool withoutGroups = true, bool useUserCredentials = false) => - Fakers.Users - .RuleFor(x => x.Groups, f => withoutGroups ? Array.Empty() : f.Lorem.Words()) - .Generate(count) - .Select( - async user => { - await Users.CreateUserAsync( - user.LoginName, user.FullName, user.Groups, user.Password, - userCredentials: useUserCredentials ? user.Credentials : TestCredentials.Root - ); - - return user; - } - ).WhenAll(); -} - -public class EventStoreInsecureClientsFixture : EventStoreClientsFixture { - protected override EventStoreTestServiceOptions Override(EventStoreTestServiceOptions options) { - options.ClientSettings.DefaultCredentials = null; - return options; - } -} \ No newline at end of file diff --git a/test/EventStore.Client.Tests.Common/Fixtures/EventStoreFixture.Helpers.cs b/test/EventStore.Client.Tests.Common/Fixtures/EventStoreFixture.Helpers.cs new file mode 100644 index 000000000..bf094d463 --- /dev/null +++ b/test/EventStore.Client.Tests.Common/Fixtures/EventStoreFixture.Helpers.cs @@ -0,0 +1,47 @@ +using System.Runtime.CompilerServices; +using System.Text; + +namespace EventStore.Client.Tests; + +public partial class EventStoreFixture { + const string TestEventType = "-"; + + public string GetStreamName([CallerMemberName] string? testMethod = null) => + $"{GetType().DeclaringType?.Name}.{testMethod ?? "unknown"}"; + + public IEnumerable CreateTestEvents(int count = 1, string? type = null, int metadataSize = 1) => + Enumerable.Range(0, count).Select(index => CreateTestEvent(index, type ?? TestEventType, metadataSize)); + + protected static EventData CreateTestEvent(int index) => CreateTestEvent(index, TestEventType, 1); + + protected static EventData CreateTestEvent(int index, string type, int metadataSize) => + new( + Uuid.NewUuid(), + type, + Encoding.UTF8.GetBytes($$"""{"x":{{index}}}"""), + Encoding.UTF8.GetBytes($"\"{new string('$', metadataSize)}\"") + ); + + public async Task CreateTestUser(bool withoutGroups = true, bool useUserCredentials = false) { + var result = await CreateTestUsers(1, withoutGroups, useUserCredentials); + return result.First(); + } + + public Task CreateTestUsers(int count = 3, bool withoutGroups = true, bool useUserCredentials = false) => + Fakers.Users + .RuleFor(x => x.Groups, f => withoutGroups ? Array.Empty() : f.Lorem.Words()) + .Generate(count) + .Select( + async user => { + await Users.CreateUserAsync( + user.LoginName, + user.FullName, + user.Groups, + user.Password, + userCredentials: useUserCredentials ? user.Credentials : TestCredentials.Root + ); + + return user; + } + ).WhenAll(); +} \ No newline at end of file diff --git a/test/EventStore.Client.Tests.Common/Fixtures/EventStoreFixture.cs b/test/EventStore.Client.Tests.Common/Fixtures/EventStoreFixture.cs new file mode 100644 index 000000000..89b6e5796 --- /dev/null +++ b/test/EventStore.Client.Tests.Common/Fixtures/EventStoreFixture.cs @@ -0,0 +1,194 @@ +using System.Net; +using EventStore.Client.Tests.FluentDocker; +using Serilog; + +namespace EventStore.Client.Tests; + +public delegate EventStoreFixtureOptions ConfigureFixture(EventStoreFixtureOptions options); + +public record EventStoreFixtureOptions(EventStoreClientSettings ClientSettings, IDictionary Environment, DirectoryInfo CertificateDirectory) { + public EventStoreFixtureOptions UseCluster(bool useCluster = true) { + Environment["ES_USE_CLUSTER"] = useCluster.ToString(); + return this; + } + + public EventStoreFixtureOptions RunInMemory(bool runInMemory = true) { + Environment["EVENTSTORE_MEM_DB"] = runInMemory.ToString(); + return this; + } + + public EventStoreFixtureOptions WithProjections(bool withProjections = true) { + Environment["EVENTSTORE_START_STANDARD_PROJECTIONS"] = withProjections.ToString(); + Environment["EVENTSTORE_RUN_PROJECTIONS"] = withProjections ? "All" :"None"; + return this; + } + + public EventStoreFixtureOptions WithoutDefaultCredentials(bool withoutCredentials = true) { + if (withoutCredentials) + ClientSettings.DefaultCredentials = null; + + return this; + } + + public EventStoreFixtureOptions WithRootCredentials(bool withRootCredentials = true) { + if (withRootCredentials) + ClientSettings.DefaultCredentials = TestCredentials.Root; + + return this; + } +} + +public partial class EventStoreFixture : IAsyncLifetime, IAsyncDisposable { + static readonly ILogger Logger = Log.ForContext(); + + static EventStoreFixture() { + ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; + } + + public EventStoreFixture(ITestOutputHelper outputHelper, ConfigureFixture? configure = null) { + TestRunId = Logging.CaptureLogs(outputHelper); + + if (GlobalEnvironment.UseExternalServer) { + Service = new TestBypassService(); + Options = new(new(), new Dictionary(), new("")); + } + + if (GlobalEnvironment.UseCluster) { + var options = EventStoreTestCluster.DefaultOptions() with { + CertificateDirectory = GlobalEnvironment.CertificateDirectory + }; + + options = configure?.Invoke(options) ?? options; + + Service = new EventStoreTestCluster(options); + Options = options; + } + else { + CertificatesCommander.VerifyCertificatesExist(GlobalEnvironment.CertificateDirectory); + + var options = EventStoreTestNode.DefaultOptions() with { + CertificateDirectory = GlobalEnvironment.CertificateDirectory + }; + + options = configure?.Invoke(options) ?? options; + + Service = new EventStoreTestNode(options); + Options = options; + } + + Streams = new(ClientSettings); + Users = new(ClientSettings); + Projections = new(ClientSettings); + PersistentSubscriptions = new(ClientSettings); + Operations = new(ClientSettings); + } + + public Guid TestRunId { get; } + public ITestService Service { get; } + public EventStoreFixtureOptions Options { get; } + + public EventStoreClient Streams { get; } + public EventStoreUserManagementClient Users { get; } + public EventStoreProjectionManagementClient Projections { get; } + public EventStorePersistentSubscriptionsClient PersistentSubscriptions { get; } + public EventStoreOperationsClient Operations { get; } + + // nice usability sugar + public EventStoreFixture Fixture => this; + + public Func OnSetUp { get; set; } = () => Task.CompletedTask; + public Func OnTearDown { get; set; } = () => Task.CompletedTask; + + /// + /// must test this + /// + public EventStoreClientSettings ClientSettings => + new EventStoreClientSettings { + Interceptors = Options.ClientSettings.Interceptors, + ConnectionName = Options.ClientSettings.ConnectionName, + CreateHttpMessageHandler = Options.ClientSettings.CreateHttpMessageHandler, + LoggerFactory = Options.ClientSettings.LoggerFactory, + ChannelCredentials = Options.ClientSettings.ChannelCredentials, + OperationOptions = Options.ClientSettings.OperationOptions, + ConnectivitySettings = Options.ClientSettings.ConnectivitySettings, + DefaultCredentials = Options.ClientSettings.DefaultCredentials, + DefaultDeadline = Options.ClientSettings.DefaultDeadline + }; + + public T Client(Action configure) where T : EventStoreClientBase, new() => + (T)Activator.CreateInstance(typeof(T), new object?[] { ClientSettings.With(configure) })!; + + public static EventStoreFixture Create(ITestOutputHelper outputHelper, ConfigureFixture? configure = null) => + new(outputHelper, configure); + + // public EventStoreFixture WithOnSetUp(Func onSetUp) { + // OnSetUp = onSetUp; + // return this; + // } + // + // public EventStoreFixture WithOnTearDown(Func onTearDown) { + // OnTearDown = onTearDown; + // return this; + // } + // + // public EventStoreFixture WithClientSettings(Func configure) { + // Options = Options with { ClientSettings = configure(Options.ClientSettings) }; + // return this; + // } + + public async Task SetUp() { + Logger.Information("Starting container service..."); + + await Service.Start(); + + // Logger.Information("Warming up database..."); + // + // await Streams.WarmUp(); + // await Users.WarmUp(); + // await Projections.WarmUp(); + // await PersistentSubscriptions.WarmUp(); + // await Operations.WarmUp(); + + Logger.Information("Fixture Initialized"); + } + + public async Task TearDown() { + Logger.Information("Stopping container service..."); + + await Service.DisposeAsync(); + + Logger.Information("Fixture Teardown"); + + Logging.ReleaseLogs(TestRunId); + } + + public static async Task Initialize(ITestOutputHelper outputHelper, ConfigureFixture? configure = null) { + var fixture = Create(outputHelper, configure); + await fixture.SetUp(); + return fixture; + } + + public async Task InitializeAsync() { + await Fixture.SetUp(); + + try { + await OnSetUp(); + } + catch (Exception ex) { + throw new("Failed to run OnSetUp!", ex); + } + } + + public async Task DisposeAsync() { + try { + await OnTearDown(); + } + catch { + // ignored + } + + await Fixture.TearDown(); + } + + async ValueTask IAsyncDisposable.DisposeAsync() => await TearDown(); +} \ No newline at end of file diff --git a/test/EventStore.Client.Tests.Common/Fixtures/EventStoreIntegrationFixture.cs b/test/EventStore.Client.Tests.Common/Fixtures/EventStoreIntegrationFixture.cs deleted file mode 100644 index 675dbffc6..000000000 --- a/test/EventStore.Client.Tests.Common/Fixtures/EventStoreIntegrationFixture.cs +++ /dev/null @@ -1,282 +0,0 @@ -using System.Net; -using System.Reactive.Linq; -using System.Reactive.Subjects; -using Ductus.FluentDocker.Builders; -using EventStore.Client.Tests.FluentDocker; -using Serilog; -using Serilog.Events; -using Serilog.Formatting.Display; - -namespace EventStore.Client.Tests; - -public abstract class EventStoreIntegrationFixture : IAsyncLifetime { - static readonly Subject LogEventSubject = new(); - - static EventStoreIntegrationFixture() { - ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; - - ConfigureLogging(); - - return; - - static void ConfigureLogging() { - - Ductus.FluentDocker.Services.Logging.Enabled(); - - var loggerConfiguration = new LoggerConfiguration() - .Enrich.FromLogContext() - .MinimumLevel.Is(LogEventLevel.Verbose) - .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) - .MinimumLevel.Override("Grpc", LogEventLevel.Verbose) - .WriteTo.Observers(observable => observable.Subscribe(LogEventSubject.OnNext)) - .WriteTo.Seq("http://localhost:5341/", period: TimeSpan.FromMilliseconds(1)); - - Log.Logger = loggerConfiguration.CreateLogger(); - -#if GRPC_CORE - GrpcEnvironment.SetLogger(new GrpcCoreSerilogLogger(Log.Logger.ForContext())); -#endif - - AppDomain.CurrentDomain.DomainUnload += (_, __) => Log.CloseAndFlush(); - } - } - - protected EventStoreIntegrationFixture() { - //VerifyCertificatesExist(GlobalEnvironment.CertificateDirectory.FullName); - // ReSharper disable once VirtualMemberCallInConstructor - Service = new EventStoreTestCluster( - Options = Override( - EventStoreTestCluster.DefaultOptions() with { - CertificateDirectory = GlobalEnvironment.CertificateDirectory - } - ) - ); - - // - // if (GlobalEnvironment.UseExternalServer) { - // Options = new(new(), new Dictionary(), new("")); - // Service = new EventStoreTestVoid(); - // } - // else if (GlobalEnvironment.UseCluster) { - // VerifyCertificatesExist(GlobalEnvironment.CertificateDirectory.FullName); - // // ReSharper disable once VirtualMemberCallInConstructor - // Service = new EventStoreTestCluster( - // Options = Override( - // EventStoreTestCluster.DefaultOptions() with { - // CertificateDirectory = GlobalEnvironment.CertificateDirectory - // } - // ) - // ); - // } - // else { - // VerifyCertificatesExist(GlobalEnvironment.CertificateDirectory.FullName); - // // ReSharper disable once VirtualMemberCallInConstructor - // Service = new EventStoreTestNode( - // Options = Override( - // EventStoreTestNode.DefaultOptions() with { - // CertificateDirectory = GlobalEnvironment.CertificateDirectory - // } - // ) - // ); - // } - } - - ITestService Service { get; } - IList Disposables { get; } = new List(); - - public ITestService TestServer => Service; - - protected EventStoreTestServiceOptions Options { get; } - - public EventStoreTestServiceOptions GetOptions() => Options with { }; - - public async Task InitializeAsync() { - await Service.Start(); - - try { - await OnInitialized(); - } - catch (Exception ex) { - throw new("Failed to run OnInitialized!", ex); - } - } - - public async Task DisposeAsync() { - try { - await OnTearDown(); - - foreach (var disposable in Disposables) - disposable.Dispose(); - } - catch { - // ignored - } - - await Service.DisposeAsync(); - } - - protected virtual EventStoreTestServiceOptions Override(EventStoreTestServiceOptions options) => options; - - static async Task EnsureCertificatesExist() { - //var hostCertificatePath = Path.Combine(ProjectDir.Current, "..", "..", GlobalEnvironment.UseCluster ? "certs-cluster" : "certs"); - //var directory = new DirectoryInfo(Path.Combine(Environment.CurrentDirectory, "certs")); - - var directory = GlobalEnvironment.CertificateDirectory; - - if (!directory.Exists) - directory.Create(); - - var caCertificatePath = Path.Combine(directory.FullName, "ca"); - if (!Directory.Exists(caCertificatePath)) - await GenerateCertificates( - directory.FullName, - "A CA certificate & key file have been generated in the '/tmp/ca/' directory", - "create-ca", "-out", "/tmp/ca" - ); - - var nodeCertificatePath = Path.Combine(directory.FullName, "node"); - if (!Directory.Exists(nodeCertificatePath)) - await GenerateCertificates( - directory.FullName, - "A node certificate & key file have been generated in the '/tmp/node' directory.", - "create-node", "-ca-certificate", "/tmp/ca/ca.crt", - "-ca-key", "/tmp/ca/ca.key", "-out", - "/tmp/node", "-ip-addresses", "127.0.0.1", - "-dns-names", "localhost" - ); - - static Task GenerateCertificates(string sourceFolder, string expectedLogMessage, string command, params string[] commandArgs) { - using var container = new Builder() - .UseContainer() - .UseImage("eventstore/es-gencert-cli:1.0.1") - .MountVolume(sourceFolder, "/tmp", Ductus.FluentDocker.Model.Builders.MountType.ReadWrite) - .Command(command, commandArgs) - .WaitForMessageInLog(expectedLogMessage, TimeSpan.FromSeconds(5)) - .Build(); - - try { - container.Start(); - } - catch { - container.Dispose(); - } - - return Task.CompletedTask; - } - - VerifyCertificatesExist(directory.FullName); - - return directory; - } - - static void VerifyCertificatesExist(string certificatePath) { - var certificateFiles = new[] { - Path.Combine("ca", "ca.crt"), - Path.Combine("ca", "ca.key"), - Path.Combine("node", "node.crt"), - Path.Combine("node", "node.key") - }.Select(path => Path.Combine(certificatePath, path)); - - foreach (var file in certificateFiles) - if (!File.Exists(file)) - throw new InvalidOperationException( - $"Could not locate the certificates file {file} needed to run EventStoreDB. Please run the 'gencert' tool at the root of the repository." - ); - } - - protected virtual Task OnInitialized() => Task.CompletedTask; - - protected virtual Task OnTearDown() => Task.CompletedTask; - - public void CaptureLogs(ITestOutputHelper outputHelper) { - const string captureCorrelationId = nameof(captureCorrelationId); - - var captureId = Guid.NewGuid(); - - var callContextData = new AsyncLocal<(string, Guid)> { - Value = (captureCorrelationId, captureId) - }; - - var formatter = new MessageTemplateTextFormatter( - "{Timestamp:yyyy-MM-dd HH:mm:ss.fff} [{Level:u3}] [{SourceContext}] {Message}" - ); - - var formatterWithException = new MessageTemplateTextFormatter( - "{Timestamp:yyyy-MM-dd HH:mm:ss.fff} [{Level:u3}] [{SourceContext}] {Message}{NewLine}{Exception}" - ); - - var subscription = LogEventSubject.Where(Filter).Subscribe( - logEvent => { - using var writer = new StringWriter(); - - if (logEvent.Exception != null) - formatterWithException.Format(logEvent, writer); - else - formatter.Format(logEvent, writer); - - outputHelper.WriteLine(writer.ToString()); - } - ); - - Disposables.Add(subscription); - - return; - - bool Filter(LogEvent logEvent) => callContextData.Value.Item2.Equals(captureId); - } -} - -// public abstract class EventStorePersistentIntegrationFixture { -// static readonly Subject LogEventSubject = new(); -// -// static EventStorePersistentIntegrationFixture() { -// ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; -// -// ConfigureLogging(); -// -// return; -// -// static void ConfigureLogging() { -// -// Ductus.FluentDocker.Services.Logging.Enabled(); -// -// var loggerConfiguration = new LoggerConfiguration() -// .Enrich.FromLogContext() -// .MinimumLevel.Is(LogEventLevel.Verbose) -// .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) -// .MinimumLevel.Override("Grpc", LogEventLevel.Verbose) -// .WriteTo.Observers(observable => observable.Subscribe(LogEventSubject.OnNext)) -// .WriteTo.Seq("http://localhost:5341/", period: TimeSpan.FromMilliseconds(1)); -// -// Log.Logger = loggerConfiguration.CreateLogger(); -// -// #if GRPC_CORE -// GrpcEnvironment.SetLogger(new GrpcCoreSerilogLogger(Log.Logger.ForContext())); -// #endif -// -// AppDomain.CurrentDomain.DomainUnload += (_, __) => Log.CloseAndFlush(); -// } -// } -// -// static ITestService Service { get; } = null!; -// static InterlockedBoolean Initialized { get; } = new(); -// -// public static async Task Initialize(Func configure) { -// var options = EventStoreTestCluster.DefaultOptions() with { -// CertificateDirectory = GlobalEnvironment.CertificateDirectory -// }; -// -// options = configure(options); -// -// Service = new EventStoreTestCluster( -// Options = Override( -// EventStoreTestCluster.DefaultOptions() with { -// CertificateDirectory = GlobalEnvironment.CertificateDirectory -// } -// ) -// ); -// -// -// Service.Start(); -// } -// } \ No newline at end of file diff --git a/test/EventStore.Client.Tests.Common/Fixtures/EventStoreTestCluster.cs b/test/EventStore.Client.Tests.Common/Fixtures/EventStoreTestCluster.cs index 29c69f577..660549ba3 100644 --- a/test/EventStore.Client.Tests.Common/Fixtures/EventStoreTestCluster.cs +++ b/test/EventStore.Client.Tests.Common/Fixtures/EventStoreTestCluster.cs @@ -1,4 +1,3 @@ -using System.Diagnostics; using Ductus.FluentDocker.Builders; using EventStore.Client.Tests.FluentDocker; using Serilog.Extensions.Logging; @@ -8,17 +7,18 @@ namespace EventStore.Client.Tests; public class EventStoreTestCluster : TestCompositeService { const string ConnectionString = "esdb://localhost:2113,localhost:2112,localhost:2111?tls=true&tlsVerifyCert=false"; - public EventStoreTestCluster(EventStoreTestServiceOptions? options = null) => Options = options ?? DefaultOptions(); + public EventStoreTestCluster(EventStoreFixtureOptions? options = null) => + Options = options ?? DefaultOptions(); - EventStoreTestServiceOptions Options { get; } + EventStoreFixtureOptions Options { get; } - public static EventStoreTestServiceOptions DefaultOptions() { + public static EventStoreFixtureOptions DefaultOptions() { var defaultSettings = EventStoreClientSettings.Create(ConnectionString); - defaultSettings.LoggerFactory = new SerilogLoggerFactory(); - defaultSettings.DefaultDeadline = Debugger.IsAttached ? new TimeSpan?() : TimeSpan.FromSeconds(30); + defaultSettings.LoggerFactory = new SerilogLoggerFactory(); + defaultSettings.DefaultDeadline = new TimeSpan?(); //Debugger.IsAttached ? new TimeSpan?() : TimeSpan.FromSeconds(180); defaultSettings.ConnectivitySettings.MaxDiscoverAttempts = 20; - defaultSettings.ConnectivitySettings.DiscoveryInterval = TimeSpan.FromSeconds(1); + defaultSettings.ConnectivitySettings.DiscoveryInterval = TimeSpan.FromSeconds(1); // ES_CERTS_CLUSTER = ./certs-cluster diff --git a/test/EventStore.Client.Tests.Common/Fixtures/EventStoreTestNode.cs b/test/EventStore.Client.Tests.Common/Fixtures/EventStoreTestNode.cs index 85d77da0e..8673412ca 100644 --- a/test/EventStore.Client.Tests.Common/Fixtures/EventStoreTestNode.cs +++ b/test/EventStore.Client.Tests.Common/Fixtures/EventStoreTestNode.cs @@ -1,37 +1,54 @@ -using System.Diagnostics; using Ductus.FluentDocker.Builders; using Ductus.FluentDocker.Model.Builders; using EventStore.Client.Tests.FluentDocker; +using Serilog; using Serilog.Extensions.Logging; namespace EventStore.Client.Tests; public class EventStoreTestNode : TestContainerService { - const string ConnectionString = "esdb://admin:changeit@localhost:2113/?tlsVerifyCert=false"; + const string ConnectionString = "esdb://admin:changeit@localhost:{port}/?tlsVerifyCert=false"; - public EventStoreTestNode(EventStoreTestServiceOptions? options = null) => Options = options ?? DefaultOptions(); + public EventStoreTestNode(EventStoreFixtureOptions? options = null) => + Options = options ?? DefaultOptions(); - EventStoreTestServiceOptions Options { get; } + EventStoreFixtureOptions Options { get; } - public static EventStoreTestServiceOptions DefaultOptions() { - var defaultSettings = EventStoreClientSettings.Create(ConnectionString); + static int _port = 2213; + + static int NextPort() => Interlocked.Increment(ref _port); + + public static EventStoreFixtureOptions DefaultOptions() { + var defaultSettings = EventStoreClientSettings.Create(ConnectionString.Replace("{port}", NextPort().ToString())); - defaultSettings.LoggerFactory = new SerilogLoggerFactory(); - defaultSettings.DefaultDeadline = Debugger.IsAttached ? new TimeSpan?() : TimeSpan.FromSeconds(30); - defaultSettings.ConnectivitySettings.MaxDiscoverAttempts = 20; - defaultSettings.ConnectivitySettings.DiscoveryInterval = TimeSpan.FromSeconds(1); + defaultSettings.LoggerFactory = new SerilogLoggerFactory(Log.Logger); + defaultSettings.DefaultDeadline = new TimeSpan?(); //Debugger.IsAttached ? new TimeSpan?() : TimeSpan.FromSeconds(30); + + defaultSettings.ConnectivitySettings.MaxDiscoverAttempts = 50; + defaultSettings.ConnectivitySettings.DiscoveryInterval = TimeSpan.FromSeconds(1); var defaultEnvironment = new Dictionary { - ["EVENTSTORE_DB_LOG_FORMAT"] = GlobalEnvironment.DbLogFormat, - ["EVENTSTORE_MEM_DB"] = "true", - ["EVENTSTORE_CHUNK_SIZE"] = (1024 * 1024).ToString(), - ["EVENTSTORE_CERTIFICATE_FILE"] = "/etc/eventstore/certs/node/node.crt", - ["EVENTSTORE_CERTIFICATE_PRIVATE_KEY_FILE"] = "/etc/eventstore/certs/node/node.key", + ["EVENTSTORE_DB_LOG_FORMAT"] = GlobalEnvironment.DbLogFormat, + ["EVENTSTORE_MEM_DB"] = "true", + ["EVENTSTORE_CHUNK_SIZE"] = (1024 * 1024).ToString(), + ["EVENTSTORE_CERTIFICATE_FILE"] = "/etc/eventstore/certs/node/node.crt", + ["EVENTSTORE_CERTIFICATE_PRIVATE_KEY_FILE"] = "/etc/eventstore/certs/node/node.key", ["EVENTSTORE_TRUSTED_ROOT_CERTIFICATES_PATH"] = "/etc/eventstore/certs/ca", - ["EVENTSTORE_LOG_LEVEL"] = "Verbose", - ["EVENTSTORE_STREAM_EXISTENCE_FILTER_SIZE"] = "10000", - ["EVENTSTORE_STREAM_INFO_CACHE_CAPACITY"] = "10000", - ["EVENTSTORE_ENABLE_ATOM_PUB_OVER_HTTP"] = "True" + ["EVENTSTORE_LOG_LEVEL"] = "Verbose", + ["EVENTSTORE_STREAM_EXISTENCE_FILTER_SIZE"] = "10000", + ["EVENTSTORE_STREAM_INFO_CACHE_CAPACITY"] = "10000", + ["EVENTSTORE_ENABLE_ATOM_PUB_OVER_HTTP"] = "True", + ["EVENTSTORE_RUN_PROJECTIONS"] = "ALL", + ["EVENTSTORE_START_STANDARD_PROJECTIONS"] = "True" + + // EVENTSTORE_CLUSTER_SIZE = 4 + // EVENTSTORE_INT_TCP_PORT = 1112 + // EVENTSTORE_HTTP_PORT = 2113 + // EVENTSTORE_TRUSTED_ROOT_CERTIFICATES_PATH = /etc/eventstore/certs/ca + // EVENTSTORE_DISCOVER_VIA_DNS = false + // EVENTSTORE_ENABLE_EXTERNAL_TCP = false + // EVENTSTORE_ENABLE_ATOM_PUB_OVER_HTTP = true + // EVENTSTORE_STREAM_EXISTENCE_FILTER_SIZE = 10000 }; return new(defaultSettings, defaultEnvironment, GlobalEnvironment.CertificateDirectory); @@ -40,14 +57,15 @@ public static EventStoreTestServiceOptions DefaultOptions() { protected override ContainerBuilder Configure() { var env = Options.Environment.Select(pair => $"{pair.Key}={pair.Value}").ToArray(); - return new Builder() - .UseContainer() - .UseImage(GlobalEnvironment.DockerImage) - .WithName("es-dotnet-test") - .WithEnvironment(env) - .MountVolume(Options.CertificateDirectory.FullName, "/etc/eventstore/certs", MountType.ReadOnly) - .ExposePort(2113, 2113) - .WaitForHealthy(TimeSpan.FromSeconds(30)) - .ReuseIfExists(); - } + var containerName = $"es-dotnet-test-{Guid.NewGuid().ToString()[30..]}"; + + return new Builder() + .UseContainer() + .UseImage(GlobalEnvironment.DockerImage) + .WithName(containerName) + .WithEnvironment(env) + .MountVolume(Options.CertificateDirectory.FullName, "/etc/eventstore/certs", MountType.ReadOnly) + .ExposePort(Options.ClientSettings.ConnectivitySettings.Address.Port, 2113) + .WaitForHealthy(TimeSpan.FromSeconds(60)); + } } \ No newline at end of file diff --git a/test/EventStore.Client.Tests.Common/Fixtures/EventStoreTestServiceOptions.cs b/test/EventStore.Client.Tests.Common/Fixtures/EventStoreTestServiceOptions.cs deleted file mode 100644 index 43c375984..000000000 --- a/test/EventStore.Client.Tests.Common/Fixtures/EventStoreTestServiceOptions.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace EventStore.Client.Tests; - -public record EventStoreTestServiceOptions( - EventStoreClientSettings ClientSettings, - IDictionary Environment, - DirectoryInfo CertificateDirectory -); \ No newline at end of file diff --git a/test/EventStore.Client.Tests.Common/Fixtures/EventStoreTestVoid.cs b/test/EventStore.Client.Tests.Common/Fixtures/EventStoreTestVoid.cs deleted file mode 100644 index 51962afc3..000000000 --- a/test/EventStore.Client.Tests.Common/Fixtures/EventStoreTestVoid.cs +++ /dev/null @@ -1,8 +0,0 @@ -using Ductus.FluentDocker.Builders; -using EventStore.Client.Tests.FluentDocker; - -namespace EventStore.Client.Tests; - -public class EventStoreTestVoid : TestContainerService { - protected override ContainerBuilder Configure() => new Builder().UseContainer(); -} \ No newline at end of file diff --git a/test/EventStore.Client.Tests.Common/Fixtures/Logging.cs b/test/EventStore.Client.Tests.Common/Fixtures/Logging.cs new file mode 100644 index 000000000..d0e92adf9 --- /dev/null +++ b/test/EventStore.Client.Tests.Common/Fixtures/Logging.cs @@ -0,0 +1,86 @@ +using System.Collections.Concurrent; +using System.Reactive.Linq; +using System.Reactive.Subjects; +using Serilog; +using Serilog.Events; +using Serilog.Formatting.Display; + +namespace EventStore.Client.Tests; + +static class Logging { + static readonly Subject LogEventSubject = new(); + + static readonly ConcurrentDictionary Subscriptions = new(); + + static Logging() { + var loggerConfiguration = new LoggerConfiguration() + .Enrich.FromLogContext() + .MinimumLevel.Is(LogEventLevel.Verbose) + .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) + .MinimumLevel.Override("Grpc", LogEventLevel.Information) + .WriteTo.Observers(x => x.Subscribe(LogEventSubject.OnNext)) + .WriteTo.Seq("http://localhost:5341/", period: TimeSpan.FromMilliseconds(1)); + + Log.Logger = loggerConfiguration.CreateLogger(); + + Ductus.FluentDocker.Services.Logging.Enabled(); + + #if GRPC_CORE + GrpcEnvironment.SetLogger(new GrpcCoreSerilogLogger(Log.Logger.ForContext())); + #endif + + AppDomain.CurrentDomain.DomainUnload += (_, _) => Log.CloseAndFlush(); + } + + public static Guid CaptureLogs(ITestOutputHelper outputHelper, Guid captureId = default) { + const string captureCorrelationId = nameof(captureCorrelationId); + + if (captureId == default) + captureId = Guid.NewGuid(); + + var callContextData = new AsyncLocal<(string CaptureCorrelationId, Guid CaptureId)> { + Value = (captureCorrelationId, captureId) + }; + + var formatter = new MessageTemplateTextFormatter("{Timestamp:HH:mm:ss.fff} [{Level:u3}] {SourceContext} {Message}"); + + var formatterWithException = new MessageTemplateTextFormatter( + "{Timestamp:HH:mm:ss.fff} [{Level:u3}] {SourceContext} {Message}{NewLine}{Exception}" + ); + + var subscription = LogEventSubject.Where(Filter).Subscribe( + logEvent => { + logEvent.AddOrUpdateProperty(new("CaptureId", new ScalarValue(captureId))); + + using var writer = new StringWriter(); + + if (logEvent.Exception != null) + formatterWithException.Format(logEvent, writer); + else + formatter.Format(logEvent, writer); + + outputHelper.WriteLine(writer.ToString()); + } + ); + + if (!Subscriptions.TryAdd(captureId, subscription)) { + throw new Exception("WTF ConcurrentDictionary?!?"); + } + + return captureId; + + bool Filter(LogEvent logEvent) => callContextData.Value.CaptureId.Equals(captureId); + } + + public static void ReleaseLogs(Guid captureId) { + if (!Subscriptions.TryRemove(captureId, out var subscription)) + return; + + try { + subscription.Dispose(); + } + catch { + // ignored + } + } +} \ No newline at end of file diff --git a/test/EventStore.Client.Tests.Common/FluentDocker/FluentDockerBuilderExtensions.cs b/test/EventStore.Client.Tests.Common/FluentDocker/FluentDockerBuilderExtensions.cs index 1423d38f5..e400cc0e2 100644 --- a/test/EventStore.Client.Tests.Common/FluentDocker/FluentDockerBuilderExtensions.cs +++ b/test/EventStore.Client.Tests.Common/FluentDocker/FluentDockerBuilderExtensions.cs @@ -1,54 +1,11 @@ using System.Reflection; using Ductus.FluentDocker.Builders; -using Ductus.FluentDocker.Common; using Ductus.FluentDocker.Model.Compose; -using Ductus.FluentDocker.Model.Containers; using Ductus.FluentDocker.Services; using Ductus.FluentDocker.Services.Impl; -using static System.TimeSpan; namespace EventStore.Client.Tests.FluentDocker; -public static class FluentDockerServiceExtensions { - static readonly TimeSpan DefaultRetryDelay = FromMilliseconds(100); - - public static async Task WaitUntilNodesAreHealthy(this IContainerService service, CancellationToken cancellationToken) { - while (true) { - var config = service.GetConfiguration(true); - var status = config?.State?.Health?.Status; - - if (status is HealthState.Healthy) return; - - if (cancellationToken.IsCancellationRequested) - throw new FluentDockerException($"Wait for healthy expired for container {service.Id}"); - - // ReSharper disable once MethodSupportsCancellation - await Task.Delay(DefaultRetryDelay); - } - } - - public static async ValueTask WaitUntilNodesAreHealthy(this IContainerService service, TimeSpan timeout) { - using var cts = new CancellationTokenSource(timeout); - await WaitUntilNodesAreHealthy(service, cts.Token); - } - - public static async Task WaitUntilNodesAreHealthy(this ICompositeService service, IEnumerable services, CancellationToken cancellationToken) { - var nodes = service.Containers.Where(x => services.Contains(x.Name)); - await Parallel.ForEachAsync(nodes, cancellationToken, async (node, ct) => await node.WaitUntilNodesAreHealthy(ct)); - } - - public static async Task WaitUntilNodesAreHealthy(this ICompositeService service, string serviceNamePrefix, CancellationToken cancellationToken) { - var nodes = service.Containers.Where(x => x.Name.StartsWith(serviceNamePrefix)); - await Parallel.ForEachAsync(nodes, cancellationToken, async (node, ct) => await node.WaitUntilNodesAreHealthy(ct)); - } - - public static async Task WaitUntilNodesAreHealthy(this ICompositeService service, string serviceNamePrefix, TimeSpan timeout) { - using var cts = new CancellationTokenSource(timeout); - await WaitUntilNodesAreHealthy(service, serviceNamePrefix, cts.Token); - } -} - - public static class FluentDockerBuilderExtensions { public static CompositeBuilder OverrideConfiguration(this CompositeBuilder compositeBuilder, Action configure) { configure(GetInternalConfig(compositeBuilder)); @@ -64,41 +21,4 @@ public static DockerComposeConfig Configuration(this ICompositeService service) (DockerComposeConfig)typeof(DockerComposeCompositeService) .GetProperty("Config", BindingFlags.NonPublic | BindingFlags.Instance)! .GetValue(service)!; - - // public static ICompositeService OverrideConfiguration(this ICompositeService service, Action configure) { - // configure(GetInternalConfig(service)); - // return service; - // - // static DockerComposeConfig GetInternalConfig(ICompositeService svc) => - // (DockerComposeConfig)typeof(DockerComposeCompositeService) - // .GetProperty("Config", BindingFlags.NonPublic | BindingFlags.Instance)! - // .GetValue(svc)!; - // } - // - // public static ICompositeService KeepAllContainersRunning(this ICompositeService service) { - // return OverrideConfiguration( - // service, config => { - // config.StopOnDispose = false; - // config.KeepContainers = true; - // } - // ); - // } - - // public static CompositeBuilder WaitForHealthy(this CompositeBuilder builder, TimeSpan timeout, params string[] services) { - // var timeoutMs = (long)timeout.TotalMilliseconds; - // - // foreach (var service in services) - // builder.WaitForHealthy(timeoutMs, service); - // - // return builder; - // } - // - // static CompositeBuilder WaitForHealthy(this CompositeBuilder builder, long timeoutMs, string service) { - // return builder.Wait( - // service, (svc, _) => { - // svc.WaitForHealthy(timeoutMs); - // return 0; - // } - // ); - // } } \ No newline at end of file diff --git a/test/EventStore.Client.Tests.Common/FluentDocker/FluentDockerServiceExtensions.cs b/test/EventStore.Client.Tests.Common/FluentDocker/FluentDockerServiceExtensions.cs new file mode 100644 index 000000000..7211af0ed --- /dev/null +++ b/test/EventStore.Client.Tests.Common/FluentDocker/FluentDockerServiceExtensions.cs @@ -0,0 +1,44 @@ +using Ductus.FluentDocker.Common; +using Ductus.FluentDocker.Model.Containers; +using Ductus.FluentDocker.Services; + +namespace EventStore.Client.Tests.FluentDocker; + +public static class FluentDockerServiceExtensions { + static readonly TimeSpan DefaultRetryDelay = TimeSpan.FromMilliseconds(100); + + public static async Task WaitUntilNodesAreHealthy(this IContainerService service, CancellationToken cancellationToken) { + while (true) { + var config = service.GetConfiguration(true); + var status = config?.State?.Health?.Status; + + if (status is HealthState.Healthy) return; + + if (cancellationToken.IsCancellationRequested) + throw new FluentDockerException($"Wait for healthy expired for container {service.Id}"); + + // ReSharper disable once MethodSupportsCancellation + await Task.Delay(DefaultRetryDelay); + } + } + + public static async ValueTask WaitUntilNodesAreHealthy(this IContainerService service, TimeSpan timeout) { + using var cts = new CancellationTokenSource(timeout); + await WaitUntilNodesAreHealthy(service, cts.Token); + } + + public static async Task WaitUntilNodesAreHealthy(this ICompositeService service, IEnumerable services, CancellationToken cancellationToken) { + var nodes = service.Containers.Where(x => services.Contains(x.Name)); + await Parallel.ForEachAsync(nodes, cancellationToken, async (node, ct) => await node.WaitUntilNodesAreHealthy(ct)); + } + + public static async Task WaitUntilNodesAreHealthy(this ICompositeService service, string serviceNamePrefix, CancellationToken cancellationToken) { + var nodes = service.Containers.Where(x => x.Name.StartsWith(serviceNamePrefix)); + await Parallel.ForEachAsync(nodes, cancellationToken, async (node, ct) => await node.WaitUntilNodesAreHealthy(ct)); + } + + public static async Task WaitUntilNodesAreHealthy(this ICompositeService service, string serviceNamePrefix, TimeSpan timeout) { + using var cts = new CancellationTokenSource(timeout); + await WaitUntilNodesAreHealthy(service, serviceNamePrefix, cts.Token); + } +} \ No newline at end of file diff --git a/test/EventStore.Client.Tests.Common/FluentDocker/TestBypassService.cs b/test/EventStore.Client.Tests.Common/FluentDocker/TestBypassService.cs new file mode 100644 index 000000000..924b890f1 --- /dev/null +++ b/test/EventStore.Client.Tests.Common/FluentDocker/TestBypassService.cs @@ -0,0 +1,61 @@ +using Ductus.FluentDocker.Builders; +using Ductus.FluentDocker.Common; +using Ductus.FluentDocker.Services; + +namespace EventStore.Client.Tests.FluentDocker; + +public class TestBypassService : TestService { + protected override BypassBuilder Configure() => throw new NotImplementedException(); + + public override async Task Start() { + try { + await OnServiceStarted(); + } + catch (Exception ex) { + throw new FluentDockerException($"{nameof(OnServiceStarted)} execution error", ex); + } + } + + public override async Task Stop() { + try { + await OnServiceStop(); + } + catch (Exception ex) { + throw new FluentDockerException($"{nameof(OnServiceStop)} execution error", ex); + } + } + + public override ValueTask DisposeAsync() => ValueTask.CompletedTask; +} + +public sealed class BypassService : IService { + public string Name { get; } = nameof(BypassService); + public ServiceRunningState State { get; } = ServiceRunningState.Unknown; + + public void Dispose() { } + + public void Start() { } + + public void Pause() { } + + public void Stop() { } + + public void Remove(bool force = false) { } + + public IService AddHook(ServiceRunningState state, Action hook, string? uniqueName = null) => this; + + public IService RemoveHook(string uniqueName) => this; + + public event ServiceDelegates.StateChange? StateChange; + + void OnStateChange(StateChangeEventArgs evt) => StateChange?.Invoke(this, evt); +} + +public sealed class BypassBuilder : BaseBuilder { + BypassBuilder(IBuilder? parent) : base(parent) { } + public BypassBuilder() : this(null) { } + + public override BypassService Build() => new BypassService(); + + protected override IBuilder InternalCreate() => this; +} \ No newline at end of file diff --git a/test/EventStore.Client.Tests.Common/FluentDocker/TestCompositeService.cs b/test/EventStore.Client.Tests.Common/FluentDocker/TestCompositeService.cs new file mode 100644 index 000000000..274791e0a --- /dev/null +++ b/test/EventStore.Client.Tests.Common/FluentDocker/TestCompositeService.cs @@ -0,0 +1,6 @@ +using Ductus.FluentDocker.Builders; +using Ductus.FluentDocker.Services; + +namespace EventStore.Client.Tests.FluentDocker; + +public abstract class TestCompositeService : TestService { } \ No newline at end of file diff --git a/test/EventStore.Client.Tests.Common/FluentDocker/TestContainerService.cs b/test/EventStore.Client.Tests.Common/FluentDocker/TestContainerService.cs new file mode 100644 index 000000000..01ab098af --- /dev/null +++ b/test/EventStore.Client.Tests.Common/FluentDocker/TestContainerService.cs @@ -0,0 +1,6 @@ +using Ductus.FluentDocker.Builders; +using Ductus.FluentDocker.Services; + +namespace EventStore.Client.Tests.FluentDocker; + +public abstract class TestContainerService : TestService { } \ No newline at end of file diff --git a/test/EventStore.Client.Tests.Common/FluentDocker/TestService.cs b/test/EventStore.Client.Tests.Common/FluentDocker/TestService.cs index 9d2af1806..3f3f6b9f5 100644 --- a/test/EventStore.Client.Tests.Common/FluentDocker/TestService.cs +++ b/test/EventStore.Client.Tests.Common/FluentDocker/TestService.cs @@ -1,104 +1,83 @@ +using Ductus.FluentDocker; using Ductus.FluentDocker.Builders; using Ductus.FluentDocker.Common; using Ductus.FluentDocker.Services; +using Serilog; namespace EventStore.Client.Tests.FluentDocker; -// public interface ITestService : IDisposable { -// void Start(); -// void Stop(); -// } -// -// public abstract class TestService : ITestService where TService : IService where TBuilder : BaseBuilder { -// protected TService Service { get; private set; } = default!; -// -// public void Start() { -// try { -// var builder = Configure(); -// Service = builder.Build(); -// Service.Start(); -// } -// catch(Exception ex) { -// throw new FluentDockerException($"Failed to start service {Service.Name}", ex); -// } -// -// try { -// OnServiceStarted(); -// } -// catch (Exception ex) { -// throw new($"{nameof(OnServiceStarted)} execution error", ex); -// } -// } -// -// public void Stop() { -// try { -// OnServiceStop(); -// } -// catch (Exception ex) { -// throw new($"{nameof(OnServiceStop)} execution error", ex); -// } -// -// try { -// Service.Stop(); -// } -// catch (Exception ex) { -// throw new FluentDockerException($"Failed to stop service {Service.Name}", ex); -// } -// } -// -// public void Dispose() { -// Stop(); -// -// try { -// if (Service.State != ServiceRunningState.Unknown) { -// Service.Dispose(); -// } -// } -// catch(Exception ex) { -// throw new FluentDockerException($"Failed to dispose of service {Service.Name}", ex); -// } -// } -// -// protected abstract TBuilder Configure(); -// -// protected virtual Task OnServiceStarted() => Task.CompletedTask; -// protected virtual Task OnServiceStop() => Task.CompletedTask; -// } - - public interface ITestService : IAsyncDisposable { Task Start(); Task Stop(); } +/// +/// Required to prevent multiple services from starting at the same time. +/// This avoids failures on creating the networks they are attached to. +/// +sealed class TestServiceGatekeeper { + static readonly SemaphoreSlim Semaphore = new(1, 1); + + public static Task Wait() => Semaphore.WaitAsync(); + public static void Next() => Semaphore.Release(); +} + public abstract class TestService : ITestService where TService : IService where TBuilder : BaseBuilder { - protected TService Service { get; private set; } = default!; + ILogger Logger { get; } - public async Task Start() { + public TestService() { + Logger = Log.ForContext(Serilog.Core.Constants.SourceContextPropertyName, GetType().Name); + } + + protected TService Service { get; private set; } = default!; + + INetworkService? Network { get; set; } = null!; + + public virtual async Task Start() { + Logger.Information("Starting container service..."); + + await TestServiceGatekeeper.Wait(); + try { var builder = Configure(); + Service = builder.Build(); - } - catch (Exception ex) { - throw new FluentDockerException($"Failed to configure service {Service.Name}", ex); - } - - try { - Service.Start(); - } - catch (Exception ex) { - throw new FluentDockerException($"Failed to start service {Service.Name}", ex); - } - try { - await OnServiceStarted(); + // for some reason fluent docker does not always create the network + // before the service is started, so we do it manually here + if (Service is IContainerService service) { + var cfg = service.GetConfiguration(true); + + Network = Fd + .UseNetwork(cfg.Name) + .IsInternal() + .Build() + .Attach(service, true); + + Logger.Information("Created network {Network}", Network.Name); + } + + try { + Service.Start(); + Logger.Information("Container service started"); + } + catch (Exception ex) { + throw new FluentDockerException("Failed to start service", ex); + } + + try { + await OnServiceStarted(); + } + catch (Exception ex) { + throw new FluentDockerException($"{nameof(OnServiceStarted)} execution error", ex); + } } - catch (Exception ex) { - throw new FluentDockerException($"{nameof(OnServiceStarted)} execution error", ex); + finally { + TestServiceGatekeeper.Next(); } } - public async Task Stop() { + public virtual async Task Stop() { try { await OnServiceStop(); } @@ -110,18 +89,20 @@ public async Task Stop() { Service.Stop(); } catch (Exception ex) { - throw new FluentDockerException($"Failed to stop service {Service.Name}", ex); + throw new FluentDockerException("Failed to stop service", ex); } } - public ValueTask DisposeAsync() { + public virtual ValueTask DisposeAsync() { try { + Network?.Dispose(); + if (Service.State != ServiceRunningState.Unknown) { Service.Dispose(); } } catch (Exception ex) { - throw new FluentDockerException($"Failed to dispose of service {Service.Name}", ex); + throw new FluentDockerException("Failed to dispose of service", ex); } return ValueTask.CompletedTask; @@ -131,10 +112,4 @@ public ValueTask DisposeAsync() { protected virtual Task OnServiceStarted() => Task.CompletedTask; protected virtual Task OnServiceStop() => Task.CompletedTask; -} - - -public abstract class TestCompositeService : TestService { } - -public abstract class TestContainerService : TestService { } - +} \ No newline at end of file diff --git a/test/EventStore.Client.Tests.Common/GlobalEnvironment.cs b/test/EventStore.Client.Tests.Common/GlobalEnvironment.cs index 682e20b15..f3170cde2 100644 --- a/test/EventStore.Client.Tests.Common/GlobalEnvironment.cs +++ b/test/EventStore.Client.Tests.Common/GlobalEnvironment.cs @@ -24,6 +24,8 @@ static GlobalEnvironment() { if (bool.TryParse(useClusterEnvVar, out var useCluster)) { UseCluster = useCluster; } + + //UseCluster = false; var useExternalServerEnvVar = Environment.GetEnvironmentVariable(UseExternalServerEnvKey); if (bool.TryParse(useExternalServerEnvVar, out var useExternalServer)) { @@ -63,9 +65,4 @@ public static IDictionary GetEnvironmentVariables(IDictionary? overrides = null) => - // GetEnvironmentVariables(overrides) - // .Select(pair => $"{pair.Key}={pair.Value}") - // .ToArray(); } \ No newline at end of file diff --git a/test/EventStore.Client.Tests.Common/TestCredentials.cs b/test/EventStore.Client.Tests.Common/TestCredentials.cs index 5006b0f2b..7530f124b 100644 --- a/test/EventStore.Client.Tests.Common/TestCredentials.cs +++ b/test/EventStore.Client.Tests.Common/TestCredentials.cs @@ -1,4 +1,4 @@ -namespace EventStore.Client; +namespace EventStore.Client.Tests; public static class TestCredentials { public static readonly UserCredentials Root = new("admin", "changeit"); diff --git a/test/EventStore.Client.Tests.Common/docker-compose.single.yml b/test/EventStore.Client.Tests.Common/docker-compose.single.yml new file mode 100644 index 000000000..28682a084 --- /dev/null +++ b/test/EventStore.Client.Tests.Common/docker-compose.single.yml @@ -0,0 +1,82 @@ +version: "3.5" + +services: + volumes-provisioner: + image: hasnat/volumes-provisioner + container_name: volumes-provisioner + environment: + PROVISION_DIRECTORIES: "1000:1000:0755:/tmp/certs" + volumes: + - "${ES_CERTS_CLUSTER}:/tmp/certs" + network_mode: none + + cert-gen: + image: eventstore/es-gencert-cli:1.0.2 + container_name: cert-gen + user: "1000:1000" + entrypoint: [ "/bin/sh","-c" ] + # rm -rf /tmp/certs/** + command: + - | + es-gencert-cli create-ca -out /tmp/certs/ca + es-gencert-cli create-node -ca-certificate /tmp/certs/ca/ca.crt -ca-key /tmp/certs/ca/ca.key -out /tmp/certs/node1 -ip-addresses 127.0.0.1,172.30.240.11 -dns-names localhost + es-gencert-cli create-node -ca-certificate /tmp/certs/ca/ca.crt -ca-key /tmp/certs/ca/ca.key -out /tmp/certs/node2 -ip-addresses 127.0.0.1,172.30.240.12 -dns-names localhost + es-gencert-cli create-node -ca-certificate /tmp/certs/ca/ca.crt -ca-key /tmp/certs/ca/ca.key -out /tmp/certs/node3 -ip-addresses 127.0.0.1,172.30.240.13 -dns-names localhost + es-gencert-cli create-node -ca-certificate /tmp/certs/ca/ca.crt -ca-key /tmp/certs/ca/ca.key -out /tmp/certs/node4 -ip-addresses 127.0.0.1,172.30.240.14 -dns-names localhost + volumes: + - "${ES_CERTS_CLUSTER}:/tmp/certs" + depends_on: + - volumes-provisioner + + seq: + image: datalust/seq:latest + container_name: seq + environment: + ACCEPT_EULA: Y + ports: + - "5341:80" + depends_on: + - volumes-provisioner + - cert-gen + + esdb-node0: + image: ghcr.io/eventstore/eventstore:${ES_DOCKER_TAG} + container_name: esdb-node + env_file: + - shared.env + environment: + - EVENTSTORE_GOSSIP_SEED=172.30.240.12:2113,172.30.240.13:2113 + - EVENTSTORE_INT_IP=172.30.240.11 + - EVENTSTORE_CERTIFICATE_FILE=/etc/eventstore/certs/node1/node.crt + - EVENTSTORE_CERTIFICATE_PRIVATE_KEY_FILE=/etc/eventstore/certs/node1/node.key + - EVENTSTORE_ADVERTISE_HOST_TO_CLIENT_AS=127.0.0.1 + - EVENTSTORE_ADVERTISE_HTTP_PORT_TO_CLIENT_AS=2111 + ports: + - "2111:2113" + networks: + clusternetwork: + ipv4_address: 172.30.240.11 + volumes: + - ${ES_CERTS_CLUSTER}:/etc/eventstore/certs + - type: volume + source: eventstore-volume-data1 + target: /var/lib/eventstore + - type: volume + source: eventstore-volume-logs1 + target: /var/log/eventstore + restart: unless-stopped + depends_on: + - cert-gen + +networks: + clusternetwork: + name: eventstoredb.local + driver: bridge + ipam: + driver: default + config: + - subnet: 172.30.240.0/24 + +volumes: + eventstore-volume-data1: + eventstore-volume-logs1: diff --git a/test/EventStore.Client.Tests.Common/docker-compose.yml b/test/EventStore.Client.Tests.Common/docker-compose.yml index 6bf66f074..610a27445 100644 --- a/test/EventStore.Client.Tests.Common/docker-compose.yml +++ b/test/EventStore.Client.Tests.Common/docker-compose.yml @@ -27,7 +27,18 @@ services: - "${ES_CERTS_CLUSTER}:/tmp/certs" depends_on: - volumes-provisioner - + + seq: + image: datalust/seq:latest + container_name: seq + environment: + ACCEPT_EULA: Y + ports: + - "5341:80" + depends_on: + - volumes-provisioner + - cert-gen + esdb-node1: image: ghcr.io/eventstore/eventstore:${ES_DOCKER_TAG} container_name: esdb-node1 diff --git a/test/EventStore.Client.Tests.Common/shared.env b/test/EventStore.Client.Tests.Common/shared.env index 697d7ab9c..67079d00c 100644 --- a/test/EventStore.Client.Tests.Common/shared.env +++ b/test/EventStore.Client.Tests.Common/shared.env @@ -8,9 +8,9 @@ EVENTSTORE_ENABLE_ATOM_PUB_OVER_HTTP=true EVENTSTORE_STREAM_EXISTENCE_FILTER_SIZE=10000 # pass through from environment -#EVENTSTORE_DB_LOG_FORMAT -#EVENTSTORE_LOG_LEVEL -#EVENTSTORE_MAX_APPEND_SIZE -#EVENTSTORE_MEM_DB -#EVENTSTORE_RUN_PROJECTIONS -#EVENTSTORE_START_STANDARD_PROJECTIONS +EVENTSTORE_DB_LOG_FORMAT +EVENTSTORE_LOG_LEVEL +EVENTSTORE_MAX_APPEND_SIZE +EVENTSTORE_MEM_DB +EVENTSTORE_RUN_PROJECTIONS +EVENTSTORE_START_STANDARD_PROJECTIONS diff --git a/test/EventStore.Client.Tests/Assertions/ComparableAssertion.cs b/test/EventStore.Client.Tests/Assertions/ComparableAssertion.cs index 72da22380..15a31b60b 100644 --- a/test/EventStore.Client.Tests/Assertions/ComparableAssertion.cs +++ b/test/EventStore.Client.Tests/Assertions/ComparableAssertion.cs @@ -3,67 +3,74 @@ using AutoFixture.Kernel; // ReSharper disable once CheckNamespace -namespace EventStore.Client; +namespace EventStore.Client; -internal class ComparableAssertion : CompositeIdiomaticAssertion { +class ComparableAssertion : CompositeIdiomaticAssertion { public ComparableAssertion(ISpecimenBuilder builder) : base(CreateChildrenAssertions(builder)) { } - private static IEnumerable CreateChildrenAssertions(ISpecimenBuilder builder) { + static IEnumerable CreateChildrenAssertions(ISpecimenBuilder builder) { yield return new ImplementsIComparableCorrectlyAssertion(); yield return new SameValueComparableAssertion(builder); yield return new DifferentValueComparableAssertion(builder); } - private class ImplementsIComparableCorrectlyAssertion : IdiomaticAssertion { + class ImplementsIComparableCorrectlyAssertion : IdiomaticAssertion { public override void Verify(Type type) => - Assert.False(type.ImplementsGenericIComparable() && !type.ImplementsIComparable(), - $"The type {type} implemented IComparable without implementing IComparable."); + Assert.False( + type.ImplementsGenericIComparable() && !type.ImplementsIComparable(), + $"The type {type} implemented IComparable without implementing IComparable." + ); } - private class SameValueComparableAssertion : IdiomaticAssertion { - private readonly ISpecimenBuilder _builder; + class SameValueComparableAssertion : IdiomaticAssertion { + readonly ISpecimenBuilder _builder; public SameValueComparableAssertion(ISpecimenBuilder builder) => _builder = builder; public override void Verify(Type type) { - if (!type.ImplementsGenericIComparable() || !type.ImplementsIComparable()) { + if (!type.ImplementsGenericIComparable() || !type.ImplementsIComparable()) return; - } var context = new SpecimenContext(_builder); var instance = context.Resolve(type); - Assert.True(type.InvokeGreaterThanOrEqualOperator(instance, instance), - $"The type {type} did not implement >= correctly, should be true for the same instance."); - Assert.False(type.InvokeGreaterThanOperator(instance, instance), - $"The type {type} did not implement > correctly, should be false for the same instance."); - Assert.True(type.InvokeLessThanOrEqualOperator(instance, instance), - $"The type {type} did not implement <= correctly, should be true for the same instance."); + Assert.True( + type.InvokeGreaterThanOrEqualOperator(instance, instance), + $"The type {type} did not implement >= correctly, should be true for the same instance." + ); + + Assert.False( + type.InvokeGreaterThanOperator(instance, instance), + $"The type {type} did not implement > correctly, should be false for the same instance." + ); + + Assert.True( + type.InvokeLessThanOrEqualOperator(instance, instance), + $"The type {type} did not implement <= correctly, should be true for the same instance." + ); - Assert.False(type.InvokeLessThanOperator(instance, instance), - $"The type {type} did not implement <= correctly, should be true for the same instance."); + Assert.False( + type.InvokeLessThanOperator(instance, instance), + $"The type {type} did not implement <= correctly, should be true for the same instance." + ); - if (type.ImplementsGenericIComparable()) { + if (type.ImplementsGenericIComparable()) Assert.Equal(0, type.InvokeGenericCompareTo(instance, instance)); - } - if (type.ImplementsIComparable()) { + if (type.ImplementsIComparable()) Assert.Equal(0, type.InvokeCompareTo(instance, instance)); - } } } - private class DifferentValueComparableAssertion : IdiomaticAssertion { - private readonly ISpecimenBuilder _builder; + class DifferentValueComparableAssertion : IdiomaticAssertion { + readonly ISpecimenBuilder _builder; - public DifferentValueComparableAssertion(ISpecimenBuilder builder) => - _builder = builder ?? throw new ArgumentNullException(nameof(builder)); + public DifferentValueComparableAssertion(ISpecimenBuilder builder) => _builder = builder ?? throw new ArgumentNullException(nameof(builder)); public override void Verify(Type type) { - if (!type.ImplementsGenericIComparable() || !type.ImplementsIComparable()) { + if (!type.ImplementsGenericIComparable() || !type.ImplementsIComparable()) return; - } var context = new SpecimenContext(_builder); @@ -75,36 +82,63 @@ public override void Verify(Type type) { var compareTo = type.InvokeCompareTo(instance, other); Assert.Equal(compareToGeneric, compareTo); - + Assert.Equal(1, type.InvokeCompareTo(instance, null)); - var ex = Assert.Throws(() => { - try { - type.InvokeCompareTo(instance, new object()); - } catch (TargetInvocationException ex) { - throw ex.InnerException!; - } - }); + var ex = Assert.Throws( + () => { + try { + type.InvokeCompareTo(instance, new()); + } + catch (TargetInvocationException ex) { + throw ex.InnerException!; + } + } + ); + Assert.Equal("Object is not a " + type.Name, ex.Message); if (compareToGeneric < 0) { - Assert.False(type.InvokeGreaterThanOrEqualOperator(instance, other), - $"The type {type} did not implement >= correctly, should be false for different instances."); - Assert.False(type.InvokeGreaterThanOperator(instance, other), - $"The type {type} did not implement > correctly, should be false for different instances."); - Assert.True(type.InvokeLessThanOrEqualOperator(instance, other), - $"The type {type} did not implement <= correctly, should be true for different instances."); - Assert.True(type.InvokeLessThanOperator(instance, other), - $"The type {type} did not implement <= correctly, should be true for different instances."); - } else { - Assert.True(type.InvokeGreaterThanOrEqualOperator(instance, other), - $"The type {type} did not implement >= correctly, should be true for different instances."); - Assert.True(type.InvokeGreaterThanOperator(instance, other), - $"The type {type} did not implement > correctly, should be true for different instances."); - Assert.False(type.InvokeLessThanOrEqualOperator(instance, other), - $"The type {type} did not implement <= correctly, should be false for different instances."); - Assert.False(type.InvokeLessThanOperator(instance, other), - $"The type {type} did not implement <= correctly, should be false for different instances."); + Assert.False( + type.InvokeGreaterThanOrEqualOperator(instance, other), + $"The type {type} did not implement >= correctly, should be false for different instances." + ); + + Assert.False( + type.InvokeGreaterThanOperator(instance, other), + $"The type {type} did not implement > correctly, should be false for different instances." + ); + + Assert.True( + type.InvokeLessThanOrEqualOperator(instance, other), + $"The type {type} did not implement <= correctly, should be true for different instances." + ); + + Assert.True( + type.InvokeLessThanOperator(instance, other), + $"The type {type} did not implement <= correctly, should be true for different instances." + ); + } + else { + Assert.True( + type.InvokeGreaterThanOrEqualOperator(instance, other), + $"The type {type} did not implement >= correctly, should be true for different instances." + ); + + Assert.True( + type.InvokeGreaterThanOperator(instance, other), + $"The type {type} did not implement > correctly, should be true for different instances." + ); + + Assert.False( + type.InvokeLessThanOrEqualOperator(instance, other), + $"The type {type} did not implement <= correctly, should be false for different instances." + ); + + Assert.False( + type.InvokeLessThanOperator(instance, other), + $"The type {type} did not implement <= correctly, should be false for different instances." + ); } } } diff --git a/test/EventStore.Client.Tests/Assertions/EqualityAssertion.cs b/test/EventStore.Client.Tests/Assertions/EqualityAssertion.cs index 8a4891663..45ac79f3e 100644 --- a/test/EventStore.Client.Tests/Assertions/EqualityAssertion.cs +++ b/test/EventStore.Client.Tests/Assertions/EqualityAssertion.cs @@ -2,12 +2,12 @@ using AutoFixture.Kernel; // ReSharper disable once CheckNamespace -namespace EventStore.Client; +namespace EventStore.Client; -internal class EqualityAssertion : CompositeIdiomaticAssertion { +class EqualityAssertion : CompositeIdiomaticAssertion { public EqualityAssertion(ISpecimenBuilder builder) : base(CreateChildrenAssertions(builder)) { } - private static IEnumerable CreateChildrenAssertions(ISpecimenBuilder builder) { + static IEnumerable CreateChildrenAssertions(ISpecimenBuilder builder) { yield return new EqualsNewObjectAssertion(builder); yield return new EqualsSelfAssertion(builder); yield return new EqualsSuccessiveAssertion(builder); @@ -16,42 +16,40 @@ private static IEnumerable CreateChildrenAssertions(ISpecim yield return new DifferentValuesEqualityOperatorsAssertion(builder); } - private class SameValueEqualityOperatorsAssertion : IdiomaticAssertion { - private readonly ISpecimenBuilder _builder; + class SameValueEqualityOperatorsAssertion : IdiomaticAssertion { + readonly ISpecimenBuilder _builder; - public SameValueEqualityOperatorsAssertion(ISpecimenBuilder builder) => - _builder = builder ?? throw new ArgumentNullException(nameof(builder)); + public SameValueEqualityOperatorsAssertion(ISpecimenBuilder builder) => _builder = builder ?? throw new ArgumentNullException(nameof(builder)); public override void Verify(Type type) { - if (type == null) throw new ArgumentNullException(nameof(type)); + if (type == null) + throw new ArgumentNullException(nameof(type)); + var instance = new SpecimenContext(_builder).Resolve(type); var equals = type.InvokeEqualityOperator(instance, instance); var notEquals = type.InvokeInequalityOperator(instance, instance); - if (equals == notEquals) { - throw new Exception( - $"The type '{type}' returned {equals} for both equality (==) and inequality (!=)."); - } + if (equals == notEquals) + throw new($"The type '{type}' returned {equals} for both equality (==) and inequality (!=)."); - if (!equals) { - throw new Exception($"The type '{type}' did not implement the equality (==) operator correctly."); - } + if (!equals) + throw new($"The type '{type}' did not implement the equality (==) operator correctly."); - if (notEquals) { - throw new Exception($"The type '{type}' did not implement the inequality (!=) operator correctly."); - } + if (notEquals) + throw new($"The type '{type}' did not implement the inequality (!=) operator correctly."); } } - private class DifferentValuesEqualityOperatorsAssertion : IdiomaticAssertion { - private readonly ISpecimenBuilder _builder; + class DifferentValuesEqualityOperatorsAssertion : IdiomaticAssertion { + readonly ISpecimenBuilder _builder; - public DifferentValuesEqualityOperatorsAssertion(ISpecimenBuilder builder) => - _builder = builder ?? throw new ArgumentNullException(nameof(builder)); + public DifferentValuesEqualityOperatorsAssertion(ISpecimenBuilder builder) => _builder = builder ?? throw new ArgumentNullException(nameof(builder)); public override void Verify(Type type) { - if (type == null) throw new ArgumentNullException(nameof(type)); + if (type == null) + throw new ArgumentNullException(nameof(type)); + var context = new SpecimenContext(_builder); var instance = context.Resolve(type); var other = context.Resolve(type); @@ -59,19 +57,14 @@ public override void Verify(Type type) { var equals = type.InvokeEqualityOperator(instance, other); var notEquals = type.InvokeInequalityOperator(instance, other); - if (equals == notEquals) { - throw new Exception( - $"The type '{type}' returned {equals} for both equality (==) and inequality (!=)."); - } - - if (equals) { - throw new Exception($"The type '{type}' did not implement the equality (==) operator correctly."); - } + if (equals == notEquals) + throw new($"The type '{type}' returned {equals} for both equality (==) and inequality (!=)."); - if (!notEquals) { - throw new Exception($"The type '{type}' did not implement the inequality (!=) operator correctly."); - } + if (equals) + throw new($"The type '{type}' did not implement the equality (==) operator correctly."); + if (!notEquals) + throw new($"The type '{type}' did not implement the inequality (!=) operator correctly."); } } } \ No newline at end of file diff --git a/test/EventStore.Client.Tests/Assertions/NullArgumentAssertion.cs b/test/EventStore.Client.Tests/Assertions/NullArgumentAssertion.cs index 3b9fad6a7..6d6656e9f 100644 --- a/test/EventStore.Client.Tests/Assertions/NullArgumentAssertion.cs +++ b/test/EventStore.Client.Tests/Assertions/NullArgumentAssertion.cs @@ -3,41 +3,51 @@ using AutoFixture.Kernel; // ReSharper disable once CheckNamespace -namespace EventStore.Client; +namespace EventStore.Client; -internal class NullArgumentAssertion : IdiomaticAssertion { - private readonly ISpecimenBuilder _builder; +class NullArgumentAssertion : IdiomaticAssertion { + readonly ISpecimenBuilder _builder; public NullArgumentAssertion(ISpecimenBuilder builder) => _builder = builder; public override void Verify(Type type) { var context = new SpecimenContext(_builder); - Assert.All(type.GetConstructors(), constructor => { - var parameters = constructor.GetParameters(); - - Assert.All(parameters.Where(p => p.ParameterType.IsClass || - p.ParameterType == typeof(string) || - p.ParameterType.IsGenericType && - p.ParameterType.GetGenericArguments().FirstOrDefault() == - typeof(Nullable<>)), p => { - var args = new object[parameters.Length]; - - for (var i = 0; i < args.Length; i++) { - if (i != p.Position) { - args[i] = context.Resolve(p.ParameterType); - } - } - - var ex = Assert.Throws(() => { - try { - constructor.Invoke(args); - } catch (TargetInvocationException ex) { - throw ex.InnerException!; + Assert.All( + type.GetConstructors(), + constructor => { + var parameters = constructor.GetParameters(); + + Assert.All( + parameters.Where( + p => p.ParameterType.IsClass || + p.ParameterType == typeof(string) || + (p.ParameterType.IsGenericType && + p.ParameterType.GetGenericArguments().FirstOrDefault() == + typeof(Nullable<>)) + ), + p => { + var args = new object[parameters.Length]; + + for (var i = 0; i < args.Length; i++) + if (i != p.Position) + args[i] = context.Resolve(p.ParameterType); + + var ex = Assert.Throws( + () => { + try { + constructor.Invoke(args); + } + catch (TargetInvocationException ex) { + throw ex.InnerException!; + } + } + ); + + Assert.Equal(p.Name, ex.ParamName); } - }); - Assert.Equal(p.Name, ex.ParamName); - }); - }); + ); + } + ); } } \ No newline at end of file diff --git a/test/EventStore.Client.Tests/Assertions/StringConversionAssertion.cs b/test/EventStore.Client.Tests/Assertions/StringConversionAssertion.cs index 08e0b624d..8113250d9 100644 --- a/test/EventStore.Client.Tests/Assertions/StringConversionAssertion.cs +++ b/test/EventStore.Client.Tests/Assertions/StringConversionAssertion.cs @@ -3,45 +3,44 @@ using AutoFixture.Kernel; // ReSharper disable once CheckNamespace -namespace EventStore.Client; +namespace EventStore.Client; -internal class StringConversionAssertion : IdiomaticAssertion { - private readonly ISpecimenBuilder _builder; +class StringConversionAssertion : IdiomaticAssertion { + readonly ISpecimenBuilder _builder; public StringConversionAssertion(ISpecimenBuilder builder) => _builder = builder; public override void Verify(Type type) { var context = new SpecimenContext(_builder); - var constructor = type.GetConstructor(new[] {typeof(string)}); + var constructor = type.GetConstructor(new[] { typeof(string) }); - if (constructor is null) { + if (constructor is null) return; - } var value = (string)context.Resolve(typeof(string)); - var instance = constructor.Invoke(new object[] {value}); - var args =new[]{instance}; + var instance = constructor.Invoke(new object[] { value }); + var args = new[] { instance }; var @explicit = type .GetMethods(BindingFlags.Public | BindingFlags.Static) .FirstOrDefault(m => m.Name == "op_Explicit" && m.ReturnType == typeof(string)); - if (@explicit is not null) { + + if (@explicit is not null) Assert.Equal(value, @explicit.Invoke(null, args)); - } var @implicit = type .GetMethods(BindingFlags.Public | BindingFlags.Static) .FirstOrDefault(m => m.Name == "op_Implicit" && m.ReturnType == typeof(string)); - if (@implicit is not null) { + + if (@implicit is not null) Assert.Equal(value, @implicit.Invoke(null, args)); - } var toString = type .GetMethods(BindingFlags.Public | BindingFlags.Public) .FirstOrDefault(m => m.Name == "ToString" && m.ReturnType == typeof(string)); - if (toString is not null) { + + if (toString is not null) Assert.Equal(value, toString.Invoke(instance, null)); - } } } \ No newline at end of file diff --git a/test/EventStore.Client.Tests/Assertions/ValueObjectAssertion.cs b/test/EventStore.Client.Tests/Assertions/ValueObjectAssertion.cs index 812bf8f7d..953fd0c75 100644 --- a/test/EventStore.Client.Tests/Assertions/ValueObjectAssertion.cs +++ b/test/EventStore.Client.Tests/Assertions/ValueObjectAssertion.cs @@ -2,12 +2,12 @@ using AutoFixture.Kernel; // ReSharper disable once CheckNamespace -namespace EventStore.Client; +namespace EventStore.Client; -internal class ValueObjectAssertion : CompositeIdiomaticAssertion { +class ValueObjectAssertion : CompositeIdiomaticAssertion { public ValueObjectAssertion(ISpecimenBuilder builder) : base(CreateChildrenAssertions(builder)) { } - private static IEnumerable CreateChildrenAssertions(ISpecimenBuilder builder) { + static IEnumerable CreateChildrenAssertions(ISpecimenBuilder builder) { yield return new EqualityAssertion(builder); yield return new ComparableAssertion(builder); yield return new StringConversionAssertion(builder); diff --git a/test/EventStore.Client.Tests/AutoScenarioDataAttribute.cs b/test/EventStore.Client.Tests/AutoScenarioDataAttribute.cs index 68d47ba0c..e917b6e16 100644 --- a/test/EventStore.Client.Tests/AutoScenarioDataAttribute.cs +++ b/test/EventStore.Client.Tests/AutoScenarioDataAttribute.cs @@ -3,26 +3,26 @@ using AutoFixture.Xunit2; using Xunit.Sdk; -namespace EventStore.Client; +namespace EventStore.Client; [DataDiscoverer("AutoFixture.Xunit2.NoPreDiscoveryDataDiscoverer", "AutoFixture.Xunit2")] public class AutoScenarioDataAttribute : DataAttribute { - private readonly Type _fixtureType; - public int Iterations { get; } + readonly Type _fixtureType; public AutoScenarioDataAttribute(Type fixtureType, int iterations = 3) { _fixtureType = fixtureType; Iterations = iterations; } + public int Iterations { get; } + public override IEnumerable GetData(MethodInfo testMethod) { var customAutoData = new CustomAutoData(_fixtureType); return Enumerable.Range(0, Iterations).SelectMany(_ => customAutoData.GetData(testMethod)); } - private class CustomAutoData : AutoDataAttribute { - public CustomAutoData(Type fixtureType) : base(() => (IFixture)Activator.CreateInstance(fixtureType)!) { - } + class CustomAutoData : AutoDataAttribute { + public CustomAutoData(Type fixtureType) : base(() => (IFixture)Activator.CreateInstance(fixtureType)!) { } } } \ No newline at end of file diff --git a/test/EventStore.Client.Tests/ConnectionStringTests.cs b/test/EventStore.Client.Tests/ConnectionStringTests.cs index d7d093635..e452a5962 100644 --- a/test/EventStore.Client.Tests/ConnectionStringTests.cs +++ b/test/EventStore.Client.Tests/ConnectionStringTests.cs @@ -119,14 +119,15 @@ public void tls_verify_cert(bool tlsVerifyCert) { [Fact] public void infinite_grpc_timeouts() { - var result = - EventStoreClientSettings.Create("esdb://localhost:2113?keepAliveInterval=-1&keepAliveTimeout=-1"); + var result = EventStoreClientSettings.Create("esdb://localhost:2113?keepAliveInterval=-1&keepAliveTimeout=-1"); Assert.Equal(System.Threading.Timeout.InfiniteTimeSpan, result.ConnectivitySettings.KeepAliveInterval); Assert.Equal(System.Threading.Timeout.InfiniteTimeSpan, result.ConnectivitySettings.KeepAliveTimeout); - using var handler = result.CreateHttpMessageHandler?.Invoke(); - var socketsHandler = Assert.IsType(handler); + using var handler = result.CreateHttpMessageHandler?.Invoke(); + + var socketsHandler = Assert.IsType(handler); + Assert.Equal(System.Threading.Timeout.InfiniteTimeSpan, socketsHandler.KeepAlivePingTimeout); Assert.Equal(System.Threading.Timeout.InfiniteTimeSpan, socketsHandler.KeepAlivePingDelay); } @@ -218,28 +219,54 @@ public void with_default_settings() { var settings = EventStoreClientSettings.Create("esdb://hostname:4321/"); Assert.Null(settings.ConnectionName); - Assert.Equal(EventStoreClientConnectivitySettings.Default.Address.Scheme, - settings.ConnectivitySettings.Address.Scheme); - Assert.Equal(EventStoreClientConnectivitySettings.Default.DiscoveryInterval.TotalMilliseconds, - settings.ConnectivitySettings.DiscoveryInterval.TotalMilliseconds); + Assert.Equal( + EventStoreClientConnectivitySettings.Default.Address.Scheme, + settings.ConnectivitySettings.Address.Scheme + ); + + Assert.Equal( + EventStoreClientConnectivitySettings.Default.DiscoveryInterval.TotalMilliseconds, + settings.ConnectivitySettings.DiscoveryInterval.TotalMilliseconds + ); + Assert.Null(EventStoreClientConnectivitySettings.Default.DnsGossipSeeds); Assert.Empty(EventStoreClientConnectivitySettings.Default.GossipSeeds); - Assert.Equal(EventStoreClientConnectivitySettings.Default.GossipTimeout.TotalMilliseconds, - settings.ConnectivitySettings.GossipTimeout.TotalMilliseconds); + Assert.Equal( + EventStoreClientConnectivitySettings.Default.GossipTimeout.TotalMilliseconds, + settings.ConnectivitySettings.GossipTimeout.TotalMilliseconds + ); + Assert.Null(EventStoreClientConnectivitySettings.Default.IpGossipSeeds); - Assert.Equal(EventStoreClientConnectivitySettings.Default.MaxDiscoverAttempts, - settings.ConnectivitySettings.MaxDiscoverAttempts); - Assert.Equal(EventStoreClientConnectivitySettings.Default.NodePreference, - settings.ConnectivitySettings.NodePreference); - Assert.Equal(EventStoreClientConnectivitySettings.Default.Insecure, - settings.ConnectivitySettings.Insecure); + Assert.Equal( + EventStoreClientConnectivitySettings.Default.MaxDiscoverAttempts, + settings.ConnectivitySettings.MaxDiscoverAttempts + ); + + Assert.Equal( + EventStoreClientConnectivitySettings.Default.NodePreference, + settings.ConnectivitySettings.NodePreference + ); + + Assert.Equal( + EventStoreClientConnectivitySettings.Default.Insecure, + settings.ConnectivitySettings.Insecure + ); + Assert.Equal(TimeSpan.FromSeconds(10), settings.DefaultDeadline); - Assert.Equal(EventStoreClientOperationOptions.Default.ThrowOnAppendFailure, - settings.OperationOptions.ThrowOnAppendFailure); - Assert.Equal(EventStoreClientConnectivitySettings.Default.KeepAliveInterval, - settings.ConnectivitySettings.KeepAliveInterval); - Assert.Equal(EventStoreClientConnectivitySettings.Default.KeepAliveTimeout, - settings.ConnectivitySettings.KeepAliveTimeout); + Assert.Equal( + EventStoreClientOperationOptions.Default.ThrowOnAppendFailure, + settings.OperationOptions.ThrowOnAppendFailure + ); + + Assert.Equal( + EventStoreClientConnectivitySettings.Default.KeepAliveInterval, + settings.ConnectivitySettings.KeepAliveInterval + ); + + Assert.Equal( + EventStoreClientConnectivitySettings.Default.KeepAliveTimeout, + settings.ConnectivitySettings.KeepAliveTimeout + ); } [Theory, @@ -291,22 +318,22 @@ public void allow_tls_override_for_single_node(string connectionString, bool? in Assert.Equal(expectedScheme, result.ConnectivitySettings.Address.Scheme); } - private static string GetConnectionString(EventStoreClientSettings settings, - Func? getKey = default) + static string GetConnectionString(EventStoreClientSettings settings, + Func? getKey = default) => $"{GetScheme(settings)}{GetAuthority(settings)}?{GetKeyValuePairs(settings, getKey)}"; - private static string GetScheme(EventStoreClientSettings settings) => settings.ConnectivitySettings.IsSingleNode + static string GetScheme(EventStoreClientSettings settings) => settings.ConnectivitySettings.IsSingleNode ? "esdb://" : "esdb+discover://"; - private static string GetAuthority(EventStoreClientSettings settings) => + static string GetAuthority(EventStoreClientSettings settings) => settings.ConnectivitySettings.IsSingleNode ? $"{settings.ConnectivitySettings.Address.Host}:{settings.ConnectivitySettings.Address.Port}" : string.Join(",", settings.ConnectivitySettings.GossipSeeds.Select(x => $"{x.GetHost()}:{x.GetPort()}")); - private static string GetKeyValuePairs(EventStoreClientSettings settings, - Func? getKey = default) { + static string GetKeyValuePairs(EventStoreClientSettings settings, + Func? getKey = default) { var pairs = new Dictionary { ["tls"] = (!settings.ConnectivitySettings.Insecure).ToString(), ["connectionName"] = settings.ConnectionName, @@ -337,7 +364,7 @@ private static string GetKeyValuePairs(EventStoreClientSettings settings, return string.Join("&", pairs.Select(pair => $"{getKey?.Invoke(pair.Key) ?? pair.Key}={pair.Value}")); } - private class EventStoreClientSettingsEqualityComparer : IEqualityComparer { + class EventStoreClientSettingsEqualityComparer : IEqualityComparer { public static readonly EventStoreClientSettingsEqualityComparer Instance = new EventStoreClientSettingsEqualityComparer(); @@ -361,7 +388,7 @@ public int GetHashCode(EventStoreClientSettings obj) => HashCode.Hash .Combine(EventStoreClientOperationOptionsEqualityComparer.Instance.GetHashCode(obj.OperationOptions)); } - private class EventStoreClientConnectivitySettingsEqualityComparer + class EventStoreClientConnectivitySettingsEqualityComparer : IEqualityComparer { public static readonly EventStoreClientConnectivitySettingsEqualityComparer Instance = new(); @@ -394,7 +421,7 @@ public int GetHashCode(EventStoreClientConnectivitySettings obj) => .Combine(obj.Insecure), (hashcode, endpoint) => hashcode.Combine(endpoint.GetHashCode())); } - private class EventStoreClientOperationOptionsEqualityComparer + class EventStoreClientOperationOptionsEqualityComparer : IEqualityComparer { public static readonly EventStoreClientOperationOptionsEqualityComparer Instance = new(); diff --git a/test/EventStore.Client.Tests/EventStore.Client.Tests.csproj b/test/EventStore.Client.Tests/EventStore.Client.Tests.csproj index 8ea2bd1a0..5e372bf6c 100644 --- a/test/EventStore.Client.Tests/EventStore.Client.Tests.csproj +++ b/test/EventStore.Client.Tests/EventStore.Client.Tests.csproj @@ -1,12 +1,8 @@  - - + - - - @@ -23,6 +19,8 @@ + + all diff --git a/test/EventStore.Client.Tests/EventStoreClientOperationOptionsTests.cs b/test/EventStore.Client.Tests/EventStoreClientOperationOptionsTests.cs index f7805b6d2..836051ef3 100644 --- a/test/EventStore.Client.Tests/EventStoreClientOperationOptionsTests.cs +++ b/test/EventStore.Client.Tests/EventStoreClientOperationOptionsTests.cs @@ -1,13 +1,13 @@ -namespace EventStore.Client; +namespace EventStore.Client; public class EventStoreClientOperationOptionsTests { [Fact] public void setting_options_on_clone_should_not_modify_original() { - EventStoreClientOperationOptions options = EventStoreClientOperationOptions.Default; - + var options = EventStoreClientOperationOptions.Default; + var clonedOptions = options.Clone(); clonedOptions.BatchAppendSize = int.MaxValue; - + Assert.Equal(options.BatchAppendSize, EventStoreClientOperationOptions.Default.BatchAppendSize); Assert.Equal(int.MaxValue, clonedOptions.BatchAppendSize); } diff --git a/test/EventStore.Client.Tests/FromAllTests.cs b/test/EventStore.Client.Tests/FromAllTests.cs index 45411928c..d960597aa 100644 --- a/test/EventStore.Client.Tests/FromAllTests.cs +++ b/test/EventStore.Client.Tests/FromAllTests.cs @@ -3,8 +3,7 @@ namespace EventStore.Client; public class FromAllTests : ValueObjectTests { - public FromAllTests() : base(new ScenarioFixture()) { - } + public FromAllTests() : base(new ScenarioFixture()) { } [Fact] public void IsComparable() => @@ -35,15 +34,16 @@ public void AfterLiveThrows() => [Fact] public void ToUInt64ReturnsExpectedResults() { var position = _fixture.Create(); - Assert.Equal((position.CommitPosition, position.PreparePosition), - FromAll.After(position).ToUInt64()); + Assert.Equal( + (position.CommitPosition, position.PreparePosition), + FromAll.After(position).ToUInt64() + ); } - private class ScenarioFixture : Fixture { + class ScenarioFixture : Fixture { public ScenarioFixture() { Customize(composer => composer.FromFactory(value => new Position(value, value))); - Customize(composter => - composter.FromFactory(FromAll.After)); + Customize(composter => composter.FromFactory(FromAll.After)); } } } \ No newline at end of file diff --git a/test/EventStore.Client.Tests/FromStreamTests.cs b/test/EventStore.Client.Tests/FromStreamTests.cs index 89ec570a2..f82a3a79f 100644 --- a/test/EventStore.Client.Tests/FromStreamTests.cs +++ b/test/EventStore.Client.Tests/FromStreamTests.cs @@ -1,39 +1,35 @@ using AutoFixture; -namespace EventStore.Client; +namespace EventStore.Client; public class FromStreamTests : ValueObjectTests { - public FromStreamTests() : base(new ScenarioFixture()) { - } + public FromStreamTests() : base(new ScenarioFixture()) { } [Fact] - public void IsComparable() => - Assert.IsAssignableFrom>( - _fixture.Create()); + public void IsComparable() => Assert.IsAssignableFrom>(_fixture.Create()); - [Theory, AutoScenarioData(typeof(ScenarioFixture))] - public void StartIsLessThanAll(FromStream other) => - Assert.True(FromStream.Start < other); + [Theory] + [AutoScenarioData(typeof(ScenarioFixture))] + public void StartIsLessThanAll(FromStream other) => Assert.True(FromStream.Start < other); - [Theory, AutoScenarioData(typeof(ScenarioFixture))] - public void LiveIsGreaterThanAll(FromStream other) => - Assert.True(FromStream.End > other); + [Theory] + [AutoScenarioData(typeof(ScenarioFixture))] + public void LiveIsGreaterThanAll(FromStream other) => Assert.True(FromStream.End > other); public static IEnumerable ToStringCases() { var fixture = new ScenarioFixture(); var position = fixture.Create(); - yield return new object?[] {FromStream.After(position), position.ToString()}; - yield return new object?[] {FromStream.Start, "Start"}; - yield return new object?[] {FromStream.End, "Live"}; + yield return new object?[] { FromStream.After(position), position.ToString() }; + yield return new object?[] { FromStream.Start, "Start" }; + yield return new object?[] { FromStream.End, "Live" }; } - [Theory, MemberData(nameof(ToStringCases))] - public void ToStringReturnsExpectedResult(FromStream sut, string expected) => - Assert.Equal(expected, sut.ToString()); + [Theory] + [MemberData(nameof(ToStringCases))] + public void ToStringReturnsExpectedResult(FromStream sut, string expected) => Assert.Equal(expected, sut.ToString()); [Fact] - public void AfterLiveThrows() => - Assert.Throws(() => FromStream.After(StreamPosition.End)); + public void AfterLiveThrows() => Assert.Throws(() => FromStream.After(StreamPosition.End)); [Fact] public void ToUInt64ReturnsExpectedResults() { @@ -41,11 +37,10 @@ public void ToUInt64ReturnsExpectedResults() { Assert.Equal(position.ToUInt64(), FromStream.After(position).ToUInt64()); } - private class ScenarioFixture : Fixture { + class ScenarioFixture : Fixture { public ScenarioFixture() { - Customize(composer => composer.FromFactory(value => new StreamPosition(value))); - Customize(composter => - composter.FromFactory(FromStream.After)); + Customize(composer => composer.FromFactory(value => new(value))); + Customize(composter => composter.FromFactory(FromStream.After)); } } } \ No newline at end of file diff --git a/test/EventStore.Client.Tests/GossipChannelSelectorTests.cs b/test/EventStore.Client.Tests/GossipChannelSelectorTests.cs index a74b74b2b..76d8b8c8f 100644 --- a/test/EventStore.Client.Tests/GossipChannelSelectorTests.cs +++ b/test/EventStore.Client.Tests/GossipChannelSelectorTests.cs @@ -1,7 +1,7 @@ using System.Net; using Grpc.Core; -namespace EventStore.Client; +namespace EventStore.Client; public class GossipChannelSelectorTests { [Fact] @@ -14,18 +14,37 @@ public async Task ExplicitlySettingEndPointChangesChannels() { var settings = new EventStoreClientSettings { ConnectivitySettings = { - DnsGossipSeeds = new[] {firstSelection, secondSelection}, - Insecure = true + DnsGossipSeeds = new[] { + firstSelection, + secondSelection + }, + Insecure = true } }; await using var channelCache = new ChannelCache(settings); - var sut = new GossipChannelSelector(settings, channelCache, new FakeGossipClient( - new ClusterMessages.ClusterInfo( - new ClusterMessages.MemberInfo[] { - new(firstId, ClusterMessages.VNodeState.Leader, true, firstSelection), - new(secondId, ClusterMessages.VNodeState.Follower, true, secondSelection), - }))); + var sut = new GossipChannelSelector( + settings, + channelCache, + new FakeGossipClient( + new ClusterMessages.ClusterInfo( + new ClusterMessages.MemberInfo[] { + new( + firstId, + ClusterMessages.VNodeState.Leader, + true, + firstSelection + ), + new( + secondId, + ClusterMessages.VNodeState.Follower, + true, + secondSelection + ), + } + ) + ) + ); var channel = await sut.SelectChannelAsync(cancellationToken: default); Assert.Equal($"{firstSelection.Host}:{firstSelection.Port}", channel.Target); @@ -38,17 +57,21 @@ public async Task ExplicitlySettingEndPointChangesChannels() { public async Task ThrowsWhenDiscoveryFails() { var settings = new EventStoreClientSettings { ConnectivitySettings = { - IpGossipSeeds = new[] {new IPEndPoint(IPAddress.Loopback, 2113)}, + IpGossipSeeds = new[] { + new IPEndPoint(IPAddress.Loopback, 2113) + }, Insecure = true, MaxDiscoverAttempts = 3 } }; await using var channelCache = new ChannelCache(settings); - var sut = new GossipChannelSelector(settings, channelCache, new BadGossipClient()); - var ex = await Assert.ThrowsAsync(async () => - await sut.SelectChannelAsync(cancellationToken: default).ConfigureAwait(false)); + var sut = new GossipChannelSelector(settings, channelCache, new BadGossipClient()); + + var ex = await Assert.ThrowsAsync( + async () => await sut.SelectChannelAsync(cancellationToken: default).ConfigureAwait(false) + ); Assert.Equal(3, ex.MaxDiscoverAttempts); } @@ -60,13 +83,18 @@ public FakeGossipClient(ClusterMessages.ClusterInfo clusterInfo) { _clusterInfo = clusterInfo; } - public ValueTask GetAsync(ChannelBase channel, - CancellationToken cancellationToken) => new(_clusterInfo); + public ValueTask GetAsync( + ChannelBase channel, + CancellationToken cancellationToken + ) => + new(_clusterInfo); } private class BadGossipClient : IGossipClient { - public ValueTask GetAsync(ChannelBase channel, - CancellationToken cancellationToken) { + public ValueTask GetAsync( + ChannelBase channel, + CancellationToken cancellationToken + ) { throw new NotSupportedException(); } } diff --git a/test/EventStore.Client.Tests/GrpcServerCapabilitiesClientTests.cs b/test/EventStore.Client.Tests/GrpcServerCapabilitiesClientTests.cs index e989d41eb..a032686e8 100644 --- a/test/EventStore.Client.Tests/GrpcServerCapabilitiesClientTests.cs +++ b/test/EventStore.Client.Tests/GrpcServerCapabilitiesClientTests.cs @@ -6,11 +6,11 @@ using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; -namespace EventStore.Client; +namespace EventStore.Client; public class GrpcServerCapabilitiesClientTests { public static IEnumerable ExpectedResultsCases() { - yield return new object?[] {new SupportedMethods(), new ServerCapabilities()}; + yield return new object?[] { new SupportedMethods(), new ServerCapabilities() }; yield return new object?[] { new SupportedMethods { Methods = { @@ -20,20 +20,24 @@ public class GrpcServerCapabilitiesClientTests { } } }, - new ServerCapabilities(SupportsBatchAppend: true) + new ServerCapabilities(true) }; + yield return new object?[] { new SupportedMethods { Methods = { new SupportedMethod { ServiceName = "event_store.client.persistent_subscriptions.persistentsubscriptions", MethodName = "read", - Features = { "all" } + Features = { + "all" + } } } }, new ServerCapabilities(SupportsPersistentSubscriptionsToAll: true) }; + yield return new object?[] { new SupportedMethods { Methods = { @@ -47,41 +51,50 @@ public class GrpcServerCapabilitiesClientTests { }; } - [Theory, MemberData(nameof(ExpectedResultsCases))] - internal async Task GetAsyncReturnsExpectedResults(SupportedMethods supportedMethods, - ServerCapabilities expected) { - using var kestrel = new TestServer(new WebHostBuilder() - .ConfigureServices(services => services - .AddRouting() - .AddGrpc().Services - .AddSingleton(new FakeServerFeatures(supportedMethods))) - .Configure(app => app - .UseRouting() - .UseEndpoints(ep => ep.MapGrpcService()))); - var sut = new GrpcServerCapabilitiesClient(new EventStoreClientSettings()); + [Theory] + [MemberData(nameof(ExpectedResultsCases))] + internal async Task GetAsyncReturnsExpectedResults( + SupportedMethods supportedMethods, + ServerCapabilities expected + ) { + using var kestrel = new TestServer( + new WebHostBuilder() + .ConfigureServices( + services => services + .AddRouting() + .AddGrpc().Services + .AddSingleton(new FakeServerFeatures(supportedMethods)) + ) + .Configure( + app => app + .UseRouting() + .UseEndpoints(ep => ep.MapGrpcService()) + ) + ); + + var sut = new GrpcServerCapabilitiesClient(new()); var actual = await sut.GetAsync( ChannelFactory .CreateChannel( - new EventStoreClientSettings { + new() { CreateHttpMessageHandler = kestrel.CreateHandler }, - new DnsEndPoint("localhost", 80)) + new DnsEndPoint("localhost", 80) + ) .CreateCallInvoker(), - cancellationToken: default); + default + ); Assert.Equal(expected, actual); } - private class FakeServerFeatures : ServerFeatures.ServerFeatures.ServerFeaturesBase { - private readonly SupportedMethods _supportedMethods; + class FakeServerFeatures : ServerFeatures.ServerFeatures.ServerFeaturesBase { + readonly SupportedMethods _supportedMethods; - public FakeServerFeatures(SupportedMethods supportedMethods) { - _supportedMethods = supportedMethods; - } + public FakeServerFeatures(SupportedMethods supportedMethods) => _supportedMethods = supportedMethods; - public override Task GetSupportedMethods(Empty request, ServerCallContext context) => - Task.FromResult(_supportedMethods); + public override Task GetSupportedMethods(Empty request, ServerCallContext context) => Task.FromResult(_supportedMethods); } } \ No newline at end of file diff --git a/test/EventStore.Client.Tests/Interceptors/ReportLeaderInterceptorTests.cs b/test/EventStore.Client.Tests/Interceptors/ReportLeaderInterceptorTests.cs index f260dc1f3..899d818ac 100644 --- a/test/EventStore.Client.Tests/Interceptors/ReportLeaderInterceptorTests.cs +++ b/test/EventStore.Client.Tests/Interceptors/ReportLeaderInterceptorTests.cs @@ -1,19 +1,20 @@ +using EventStore.Client.Interceptors; using Grpc.Core; using Grpc.Core.Interceptors; -namespace EventStore.Client.Interceptors; +namespace EventStore.Client.Tests.Interceptors; public class ReportLeaderInterceptorTests { public delegate Task GrpcCall(Interceptor interceptor, Task? response = null); - private static readonly Marshaller _marshaller = new(_ => Array.Empty(), _ => new object()); + static readonly Marshaller Marshaller = new(_ => Array.Empty(), _ => new()); - private static readonly StatusCode[] ForcesRediscoveryStatusCodes = { + static readonly StatusCode[] ForcesRediscoveryStatusCodes = { //StatusCode.Unknown, TODO: use RPC exceptions on server StatusCode.Unavailable }; - private static IEnumerable GrpcCalls() { + static IEnumerable GrpcCalls() { yield return MakeUnaryCall; yield return MakeClientStreamingCall; yield return MakeDuplexStreamingCall; @@ -22,142 +23,197 @@ private static IEnumerable GrpcCalls() { yield return MakeDuplexStreamingCallForWriting; } - public static IEnumerable ReportsNewLeaderCases() => GrpcCalls().Select(call => new object[] {call}); + public static IEnumerable ReportsNewLeaderCases() => GrpcCalls().Select(call => new object[] { call }); - [Theory, MemberData(nameof(ReportsNewLeaderCases))] + [Theory] + [MemberData(nameof(ReportsNewLeaderCases))] public async Task ReportsNewLeader(GrpcCall call) { ReconnectionRequired? actual = default; - var sut = new ReportLeaderInterceptor(result => actual = result); - var result = await Assert.ThrowsAsync(() => - call(sut, Task.FromException(new NotLeaderException("a.host", 2112)))); + var sut = new ReportLeaderInterceptor(result => actual = result); + + var result = await Assert.ThrowsAsync( + () => call(sut, Task.FromException(new NotLeaderException("a.host", 2112))) + ); + Assert.Equal(new ReconnectionRequired.NewLeader(result.LeaderEndpoint), actual); } public static IEnumerable ForcesRediscoveryCases() => from call in GrpcCalls() from statusCode in ForcesRediscoveryStatusCodes - select new object[] {call, statusCode}; + select new object[] { call, statusCode }; - [Theory, MemberData(nameof(ForcesRediscoveryCases))] + [Theory] + [MemberData(nameof(ForcesRediscoveryCases))] public async Task ForcesRediscovery(GrpcCall call, StatusCode statusCode) { ReconnectionRequired? actual = default; - var sut = new ReportLeaderInterceptor(result => actual = result); - await Assert.ThrowsAsync(() => call(sut, - Task.FromException(new RpcException(new Status(statusCode, "oops"))))); + var sut = new ReportLeaderInterceptor(result => actual = result); + + await Assert.ThrowsAsync( + () => call(sut, Task.FromException(new RpcException(new(statusCode, "oops")))) + ); + Assert.Equal(ReconnectionRequired.Rediscover.Instance, actual); } - + public static IEnumerable DoesNotForceRediscoveryCases() => from call in GrpcCalls() from statusCode in Enum.GetValues(typeof(StatusCode)) .OfType() .Except(ForcesRediscoveryStatusCodes) - select new object[] {call, statusCode}; + select new object[] { call, statusCode }; - [Theory, MemberData(nameof(DoesNotForceRediscoveryCases))] + [Theory] + [MemberData(nameof(DoesNotForceRediscoveryCases))] public async Task DoesNotForceRediscovery(GrpcCall call, StatusCode statusCode) { ReconnectionRequired actual = ReconnectionRequired.None.Instance; - var sut = new ReportLeaderInterceptor(result => actual = result); - await Assert.ThrowsAsync(() => call(sut, - Task.FromException(new RpcException(new Status(statusCode, "oops"))))); + var sut = new ReportLeaderInterceptor(result => actual = result); + + await Assert.ThrowsAsync( + () => call(sut, Task.FromException(new RpcException(new(statusCode, "oops")))) + ); + Assert.Equal(ReconnectionRequired.None.Instance, actual); } - - private static async Task MakeUnaryCall(Interceptor interceptor, Task? response = null) { - using var call = interceptor.AsyncUnaryCall(new object(), - CreateClientInterceptorContext(MethodType.Unary), - (_, context) => new AsyncUnaryCall(response ?? Task.FromResult(new object()), - Task.FromResult(context.Options.Headers!), GetSuccess, GetTrailers, OnDispose)); + static async Task MakeUnaryCall(Interceptor interceptor, Task? response = null) { + using var call = interceptor.AsyncUnaryCall( + new(), + CreateClientInterceptorContext(MethodType.Unary), + (_, context) => new( + response ?? Task.FromResult(new object()), + Task.FromResult(context.Options.Headers!), + GetSuccess, + GetTrailers, + OnDispose + ) + ); + await call.ResponseAsync; } - private static async Task MakeClientStreamingCall(Interceptor interceptor, Task? response = null) { + static async Task MakeClientStreamingCall(Interceptor interceptor, Task? response = null) { using var call = interceptor.AsyncClientStreamingCall( CreateClientInterceptorContext(MethodType.ClientStreaming), - context => new AsyncClientStreamingCall(null!, response ?? Task.FromResult(new object()), - Task.FromResult(context.Options.Headers!), GetSuccess, GetTrailers, OnDispose)); + context => new( + null!, + response ?? Task.FromResult(new object()), + Task.FromResult(context.Options.Headers!), + GetSuccess, + GetTrailers, + OnDispose + ) + ); + await call.ResponseAsync; } - private static async Task MakeServerStreamingCall(Interceptor interceptor, Task? response = null) { - using var call = interceptor.AsyncServerStreamingCall(new object(), - CreateClientInterceptorContext(MethodType.ServerStreaming), - (_, context) => new AsyncServerStreamingCall(new TestAsyncStreamReader(response), - Task.FromResult(context.Options.Headers!), GetSuccess, GetTrailers, OnDispose)); + static async Task MakeServerStreamingCall(Interceptor interceptor, Task? response = null) { + using var call = interceptor.AsyncServerStreamingCall( + new(), + CreateClientInterceptorContext(MethodType.ServerStreaming), + (_, context) => new( + new TestAsyncStreamReader(response), + Task.FromResult(context.Options.Headers!), + GetSuccess, + GetTrailers, + OnDispose + ) + ); + await call.ResponseStream.ReadAllAsync().ToArrayAsync(); } - private static async Task MakeDuplexStreamingCall(Interceptor interceptor, Task? response = null) { + static async Task MakeDuplexStreamingCall(Interceptor interceptor, Task? response = null) { using var call = interceptor.AsyncDuplexStreamingCall( CreateClientInterceptorContext(MethodType.ServerStreaming), - context => new AsyncDuplexStreamingCall(null!, new TestAsyncStreamReader(response), - Task.FromResult(context.Options.Headers!), GetSuccess, GetTrailers, OnDispose)); + context => new( + null!, + new TestAsyncStreamReader(response), + Task.FromResult(context.Options.Headers!), + GetSuccess, + GetTrailers, + OnDispose + ) + ); + await call.ResponseStream.ReadAllAsync().ToArrayAsync(); } // we might write to the server before listening to its response. if that write fails because // the server is down then we will never listen to its response, so the failed write should // trigger rediscovery itself - private static async Task MakeClientStreamingCallForWriting(Interceptor interceptor, Task? response = null) { + static async Task MakeClientStreamingCallForWriting(Interceptor interceptor, Task? response = null) { using var call = interceptor.AsyncClientStreamingCall( - context: CreateClientInterceptorContext(MethodType.ClientStreaming), - continuation: context => new AsyncClientStreamingCall( - requestStream: new TestAsyncStreamWriter(response), - responseAsync: Task.FromResult(new object()), - responseHeadersAsync: Task.FromResult(context.Options.Headers!), - getStatusFunc: GetSuccess, - getTrailersFunc: GetTrailers, - disposeAction: OnDispose)); - await call.RequestStream.WriteAsync(new object()); + CreateClientInterceptorContext(MethodType.ClientStreaming), + context => new( + new TestAsyncStreamWriter(response), + Task.FromResult(new object()), + Task.FromResult(context.Options.Headers!), + GetSuccess, + GetTrailers, + OnDispose + ) + ); + + await call.RequestStream.WriteAsync(new()); } - private static async Task MakeDuplexStreamingCallForWriting(Interceptor interceptor, Task? response = null) { + static async Task MakeDuplexStreamingCallForWriting(Interceptor interceptor, Task? response = null) { using var call = interceptor.AsyncDuplexStreamingCall( - context: CreateClientInterceptorContext(MethodType.ServerStreaming), - continuation: context => new AsyncDuplexStreamingCall( - requestStream: new TestAsyncStreamWriter(response), - responseStream: null!, - responseHeadersAsync: null!, - getStatusFunc: GetSuccess, - getTrailersFunc: GetTrailers, - disposeAction: OnDispose)); - await call.RequestStream.WriteAsync(new object()); + CreateClientInterceptorContext(MethodType.ServerStreaming), + _ => new( + new TestAsyncStreamWriter(response), + null!, + null!, + GetSuccess, + GetTrailers, + OnDispose + ) + ); + + await call.RequestStream.WriteAsync(new()); } - private static Status GetSuccess() => Status.DefaultSuccess; + static Status GetSuccess() => Status.DefaultSuccess; - private static Metadata GetTrailers() => Metadata.Empty; + static Metadata GetTrailers() => Metadata.Empty; - private static void OnDispose() { } + static void OnDispose() { } - private static ClientInterceptorContext CreateClientInterceptorContext(MethodType methodType) => - new(new Method(methodType, string.Empty, string.Empty, _marshaller, _marshaller), - null, new CallOptions(new Metadata())); + static ClientInterceptorContext CreateClientInterceptorContext(MethodType methodType) => + new( + new( + methodType, + string.Empty, + string.Empty, + Marshaller, + Marshaller + ), + null, + new(new()) + ); - private class TestAsyncStreamReader : IAsyncStreamReader { - private readonly Task _response; + class TestAsyncStreamReader : IAsyncStreamReader { + readonly Task _response; - public Task MoveNext(CancellationToken cancellationToken) => _response.IsFaulted - ? Task.FromException(_response.Exception!.GetBaseException()) - : Task.FromResult(false); + public TestAsyncStreamReader(Task? response = null) => _response = response ?? Task.FromResult(new object()); - public object Current => _response.Result; + public Task MoveNext(CancellationToken cancellationToken) => + _response.IsFaulted + ? Task.FromException(_response.Exception!.GetBaseException()) + : Task.FromResult(false); - public TestAsyncStreamReader(Task? response = null) { - _response = response ?? Task.FromResult(new object()); - } + public object Current => _response.Result; } - private class TestAsyncStreamWriter : IClientStreamWriter { - private readonly Task _response; + class TestAsyncStreamWriter : IClientStreamWriter { + readonly Task _response; - public TestAsyncStreamWriter(Task? response = null) { - _response = response ?? Task.FromResult(new object()); - } + public TestAsyncStreamWriter(Task? response = null) => _response = response ?? Task.FromResult(new object()); public WriteOptions? WriteOptions { get => throw new NotImplementedException(); @@ -166,8 +222,9 @@ public WriteOptions? WriteOptions { public Task CompleteAsync() => throw new NotImplementedException(); - public Task WriteAsync(object message) => _response.IsFaulted - ? Task.FromException(_response.Exception!.GetBaseException()) - : Task.FromResult(false); + public Task WriteAsync(object message) => + _response.IsFaulted + ? Task.FromException(_response.Exception!.GetBaseException()) + : Task.FromResult(false); } } \ No newline at end of file diff --git a/test/EventStore.Client.Tests/NodePreferenceComparerTests.cs b/test/EventStore.Client.Tests/NodePreferenceComparerTests.cs index fb86ec641..67f7218c5 100644 --- a/test/EventStore.Client.Tests/NodePreferenceComparerTests.cs +++ b/test/EventStore.Client.Tests/NodePreferenceComparerTests.cs @@ -1,24 +1,24 @@ using static EventStore.Client.ClusterMessages.VNodeState; -namespace EventStore.Client; +namespace EventStore.Client; public class NodePreferenceComparerTests { - private static ClusterMessages.VNodeState RunTest(IComparer sut, - params ClusterMessages.VNodeState[] states) => + static ClusterMessages.VNodeState RunTest(IComparer sut, params ClusterMessages.VNodeState[] states) => states .OrderBy(state => state, sut) .ThenBy(_ => Guid.NewGuid()) .First(); public static IEnumerable LeaderTestCases() { - yield return new object?[] {Leader, Leader, Follower, Follower, ReadOnlyReplica}; - yield return new object?[] {Follower, Follower, Follower, ReadOnlyReplica}; - yield return new object?[] {ReadOnlyReplica, ReadOnlyReplica, PreReadOnlyReplica, ReadOnlyLeaderless}; - yield return new object?[] {PreReadOnlyReplica, PreReadOnlyReplica, ReadOnlyLeaderless}; - yield return new object?[] {ReadOnlyLeaderless, ReadOnlyLeaderless, DiscoverLeader}; + yield return new object?[] { Leader, Leader, Follower, Follower, ReadOnlyReplica }; + yield return new object?[] { Follower, Follower, Follower, ReadOnlyReplica }; + yield return new object?[] { ReadOnlyReplica, ReadOnlyReplica, PreReadOnlyReplica, ReadOnlyLeaderless }; + yield return new object?[] { PreReadOnlyReplica, PreReadOnlyReplica, ReadOnlyLeaderless }; + yield return new object?[] { ReadOnlyLeaderless, ReadOnlyLeaderless, DiscoverLeader }; } - [Theory, MemberData(nameof(LeaderTestCases))] + [Theory] + [MemberData(nameof(LeaderTestCases))] internal void LeaderTests(ClusterMessages.VNodeState expected, params ClusterMessages.VNodeState[] states) { var actual = RunTest(NodePreferenceComparers.Leader, states); @@ -26,14 +26,15 @@ internal void LeaderTests(ClusterMessages.VNodeState expected, params ClusterMes } public static IEnumerable FollowerTestCases() { - yield return new object?[] {Follower, Leader, Follower, Follower, ReadOnlyReplica}; - yield return new object?[] {Leader, Leader, ReadOnlyReplica, ReadOnlyReplica}; - yield return new object?[] {ReadOnlyReplica, ReadOnlyReplica, PreReadOnlyReplica, ReadOnlyLeaderless}; - yield return new object?[] {PreReadOnlyReplica, PreReadOnlyReplica, ReadOnlyLeaderless}; - yield return new object?[] {ReadOnlyLeaderless, ReadOnlyLeaderless, DiscoverLeader}; + yield return new object?[] { Follower, Leader, Follower, Follower, ReadOnlyReplica }; + yield return new object?[] { Leader, Leader, ReadOnlyReplica, ReadOnlyReplica }; + yield return new object?[] { ReadOnlyReplica, ReadOnlyReplica, PreReadOnlyReplica, ReadOnlyLeaderless }; + yield return new object?[] { PreReadOnlyReplica, PreReadOnlyReplica, ReadOnlyLeaderless }; + yield return new object?[] { ReadOnlyLeaderless, ReadOnlyLeaderless, DiscoverLeader }; } - [Theory, MemberData(nameof(FollowerTestCases))] + [Theory] + [MemberData(nameof(FollowerTestCases))] internal void FollowerTests(ClusterMessages.VNodeState expected, params ClusterMessages.VNodeState[] states) { var actual = RunTest(NodePreferenceComparers.Follower, states); @@ -41,16 +42,16 @@ internal void FollowerTests(ClusterMessages.VNodeState expected, params ClusterM } public static IEnumerable ReadOnlyReplicaTestCases() { - yield return new object?[] {ReadOnlyReplica, Leader, Follower, Follower, ReadOnlyReplica}; - yield return new object?[] {PreReadOnlyReplica, Leader, Follower, Follower, PreReadOnlyReplica}; - yield return new object?[] {ReadOnlyLeaderless, Leader, Follower, Follower, ReadOnlyLeaderless}; - yield return new object?[] {Leader, Leader, Follower, Follower}; - yield return new object?[] {Follower, DiscoverLeader, Follower, Follower}; + yield return new object?[] { ReadOnlyReplica, Leader, Follower, Follower, ReadOnlyReplica }; + yield return new object?[] { PreReadOnlyReplica, Leader, Follower, Follower, PreReadOnlyReplica }; + yield return new object?[] { ReadOnlyLeaderless, Leader, Follower, Follower, ReadOnlyLeaderless }; + yield return new object?[] { Leader, Leader, Follower, Follower }; + yield return new object?[] { Follower, DiscoverLeader, Follower, Follower }; } - [Theory, MemberData(nameof(ReadOnlyReplicaTestCases))] - internal void ReadOnlyReplicaTests(ClusterMessages.VNodeState expected, - params ClusterMessages.VNodeState[] states) { + [Theory] + [MemberData(nameof(ReadOnlyReplicaTestCases))] + internal void ReadOnlyReplicaTests(ClusterMessages.VNodeState expected, params ClusterMessages.VNodeState[] states) { var actual = RunTest(NodePreferenceComparers.ReadOnlyReplica, states); Assert.Equal(expected, actual); diff --git a/test/EventStore.Client.Tests/NodeSelectorTests.cs b/test/EventStore.Client.Tests/NodeSelectorTests.cs index baefea92a..2e9a409e4 100644 --- a/test/EventStore.Client.Tests/NodeSelectorTests.cs +++ b/test/EventStore.Client.Tests/NodeSelectorTests.cs @@ -3,7 +3,7 @@ namespace EventStore.Client; public class NodeSelectorTests { - private static readonly ClusterMessages.VNodeState[] _notAllowedStates = { + static readonly ClusterMessages.VNodeState[] NotAllowedStates = { ClusterMessages.VNodeState.Manager, ClusterMessages.VNodeState.ShuttingDown, ClusterMessages.VNodeState.Shutdown, @@ -19,7 +19,7 @@ public class NodeSelectorTests { }; public static IEnumerable InvalidStatesCases() { - foreach (var state in _notAllowedStates) { + foreach (var state in NotAllowedStates) { var allowedNodeId = Uuid.NewUuid(); var allowedNode = new DnsEndPoint(allowedNodeId.ToString(), 2113); @@ -73,11 +73,11 @@ public void DeadNodesAreNotConsidered() { }; var sut = new NodeSelector(settings); - var selectedNode = sut.SelectNode(new ClusterMessages.ClusterInfo( - new ClusterMessages.MemberInfo[] { - new(allowedNodeId, ClusterMessages.VNodeState.Follower, true, allowedNode), - new(notAllowedNodeId, ClusterMessages.VNodeState.Leader, false, notAllowedNode), - })); + + var selectedNode = sut.SelectNode(new ClusterMessages.ClusterInfo(new ClusterMessages.MemberInfo[] { + new(allowedNodeId, ClusterMessages.VNodeState.Follower, true, allowedNode), + new(notAllowedNodeId, ClusterMessages.VNodeState.Leader, false, notAllowedNode), + })); Assert.Equal(allowedNode.Host, selectedNode.Host); Assert.Equal(allowedNode.Port, selectedNode.Port); @@ -97,12 +97,12 @@ public void CanPrefer(NodePreference nodePreference, string expectedHost) { var sut = new NodeSelector(settings); var selectedNode = sut.SelectNode(new ClusterMessages.ClusterInfo( - new ClusterMessages.MemberInfo[] { - new(Uuid.NewUuid(), ClusterMessages.VNodeState.Follower, false, new DnsEndPoint("follower1", 2113)), - new(Uuid.NewUuid(), ClusterMessages.VNodeState.Leader, true, new DnsEndPoint("leader", 2113)), - new(Uuid.NewUuid(), ClusterMessages.VNodeState.Follower, true, new DnsEndPoint("follower2", 2113)), - new(Uuid.NewUuid(), ClusterMessages.VNodeState.ReadOnlyReplica, true, new DnsEndPoint("readOnlyReplica", 2113)), - })); + new ClusterMessages.MemberInfo[] { + new(Uuid.NewUuid(), ClusterMessages.VNodeState.Follower, false, new DnsEndPoint("follower1", 2113)), + new(Uuid.NewUuid(), ClusterMessages.VNodeState.Leader, true, new DnsEndPoint("leader", 2113)), + new(Uuid.NewUuid(), ClusterMessages.VNodeState.Follower, true, new DnsEndPoint("follower2", 2113)), + new(Uuid.NewUuid(), ClusterMessages.VNodeState.ReadOnlyReplica, true, new DnsEndPoint("readOnlyReplica", 2113)), + })); if (expectedHost == "any") return; diff --git a/test/EventStore.Client.Tests/PositionTests.cs b/test/EventStore.Client.Tests/PositionTests.cs index e90bcc982..b84cc0a98 100644 --- a/test/EventStore.Client.Tests/PositionTests.cs +++ b/test/EventStore.Client.Tests/PositionTests.cs @@ -1,19 +1,19 @@ using AutoFixture; -namespace EventStore.Client; +namespace EventStore.Client; public class PositionTests : ValueObjectTests { - public PositionTests() : base(new ScenarioFixture()) { - } + public PositionTests() : base(new ScenarioFixture()) { } [Fact] - public void IsComparable() => - Assert.IsAssignableFrom>(_fixture.Create()); + public void IsComparable() => Assert.IsAssignableFrom>(_fixture.Create()); - [Theory, AutoScenarioData(typeof(ScenarioFixture))] + [Theory] + [AutoScenarioData(typeof(ScenarioFixture))] public void StartIsLessThanAll(Position other) => Assert.True(Position.Start < other); - [Theory, AutoScenarioData(typeof(ScenarioFixture))] + [Theory] + [AutoScenarioData(typeof(ScenarioFixture))] public void LiveIsGreaterThanAll(Position other) => Assert.True(Position.End > other); [Fact] @@ -26,38 +26,38 @@ public void ToStringReturnsExpectedResult() { const string commitPosition = nameof(commitPosition); const string preparePosition = nameof(preparePosition); - yield return new object?[] {5, 6, commitPosition}; - yield return new object?[] {ulong.MaxValue - 1, 6, commitPosition}; - yield return new object?[] {ulong.MaxValue, ulong.MaxValue - 1, preparePosition}; - yield return new object?[] {(ulong)long.MaxValue + 1, long.MaxValue, commitPosition}; + yield return new object?[] { 5, 6, commitPosition }; + yield return new object?[] { ulong.MaxValue - 1, 6, commitPosition }; + yield return new object?[] { ulong.MaxValue, ulong.MaxValue - 1, preparePosition }; + yield return new object?[] { (ulong)long.MaxValue + 1, long.MaxValue, commitPosition }; } - [Theory, MemberData(nameof(ArgumentOutOfRangeTestCases))] + [Theory] + [MemberData(nameof(ArgumentOutOfRangeTestCases))] public void ArgumentOutOfRange(ulong commitPosition, ulong preparePosition, string name) { var ex = Assert.Throws(() => new Position(commitPosition, preparePosition)); Assert.Equal(name, ex.ParamName); } - private class ScenarioFixture : Fixture { - public ScenarioFixture() { - Customize(composer => composer.FromFactory(value => new Position(value, value))); - } - } - - [Theory, MemberData(nameof(ParseTestCases))] + [Theory] + [MemberData(nameof(ParseTestCases))] public void TryParse(string s, bool success, Position? expected) { Position? p; Assert.Equal(success, Position.TryParse(s, out p)); Assert.Equal(expected, p); } - + public static IEnumerable ParseTestCases() { - yield return new object?[] {"", false, null}; - yield return new object?[] {"CP", false, null}; - yield return new object?[] {"C:6\\P:5", false, null}; - yield return new object[] {Position.Start.ToString(), true, Position.Start}; - yield return new object[] {Position.End.ToString(), true, Position.End}; - yield return new object[] {"C:6/P:5", true, new Position(6, 5)}; - yield return new object[] {"C: 6/P:5", true, new Position(6, 5)}; + yield return new object?[] { "", false, null }; + yield return new object?[] { "CP", false, null }; + yield return new object?[] { "C:6\\P:5", false, null }; + yield return new object[] { Position.Start.ToString(), true, Position.Start }; + yield return new object[] { Position.End.ToString(), true, Position.End }; + yield return new object[] { "C:6/P:5", true, new Position(6, 5) }; + yield return new object[] { "C: 6/P:5", true, new Position(6, 5) }; + } + + class ScenarioFixture : Fixture { + public ScenarioFixture() => Customize(composer => composer.FromFactory(value => new(value, value))); } } \ No newline at end of file diff --git a/test/EventStore.Client.Tests/PrefixFilterExpressionTests.cs b/test/EventStore.Client.Tests/PrefixFilterExpressionTests.cs index 5aea2a088..cd7dfa538 100644 --- a/test/EventStore.Client.Tests/PrefixFilterExpressionTests.cs +++ b/test/EventStore.Client.Tests/PrefixFilterExpressionTests.cs @@ -1,14 +1,12 @@ using AutoFixture; -namespace EventStore.Client; +namespace EventStore.Client; public class PrefixFilterExpressionTests : ValueObjectTests { public PrefixFilterExpressionTests() : base(new ScenarioFixture()) { } - private class ScenarioFixture : Fixture { - public ScenarioFixture() { - Customize(composer => - composer.FromFactory(value => new PrefixFilterExpression(value))); - } + class ScenarioFixture : Fixture { + public ScenarioFixture() => + Customize(composer => composer.FromFactory(value => new(value))); } } \ No newline at end of file diff --git a/test/EventStore.Client.Tests/RegularFilterExpressionTests.cs b/test/EventStore.Client.Tests/RegularFilterExpressionTests.cs index a84c1cb2c..6c2a8e47b 100644 --- a/test/EventStore.Client.Tests/RegularFilterExpressionTests.cs +++ b/test/EventStore.Client.Tests/RegularFilterExpressionTests.cs @@ -6,11 +6,7 @@ namespace EventStore.Client; public class RegularFilterExpressionTests : ValueObjectTests { public RegularFilterExpressionTests() : base(new ScenarioFixture()) { } - private class ScenarioFixture : Fixture { - public ScenarioFixture() { - Customize( - composer => composer.FromFactory(value => new RegularFilterExpression(value)) - ); - } + class ScenarioFixture : Fixture { + public ScenarioFixture() => Customize(composer => composer.FromFactory(value => new(value))); } } \ No newline at end of file diff --git a/test/EventStore.Client.Tests/SharingProviderTests.cs b/test/EventStore.Client.Tests/SharingProviderTests.cs index 804ccf5a5..bcbb87374 100644 --- a/test/EventStore.Client.Tests/SharingProviderTests.cs +++ b/test/EventStore.Client.Tests/SharingProviderTests.cs @@ -1,13 +1,16 @@ #pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously -namespace EventStore.Client; + +namespace EventStore.Client; public class SharingProviderTests { [Fact] public async Task CanGetCurrent() { using var sut = new SharingProvider( - factory: async (x, _) => x + 1, - factoryRetryDelay: TimeSpan.FromSeconds(0), - initialInput: 5); + async (x, _) => x + 1, + TimeSpan.FromSeconds(0), + 5 + ); + Assert.Equal(6, await sut.CurrentAsync); } @@ -15,26 +18,28 @@ public async Task CanGetCurrent() { public async Task CanReset() { var count = 0; using var sut = new SharingProvider( - factory: async (_, _) => count++, - factoryRetryDelay: TimeSpan.FromSeconds(0), - initialInput: true); + async (_, _) => count++, + TimeSpan.FromSeconds(0), + true + ); Assert.Equal(0, await sut.CurrentAsync); sut.Reset(); Assert.Equal(1, await sut.CurrentAsync); } - + [Fact] public async Task CanReturnBroken() { Action? onBroken = null; var count = 0; using var sut = new SharingProvider( - factory: async (_, f) => { + async (_, f) => { onBroken = f; return count++; }, - factoryRetryDelay: TimeSpan.FromSeconds(0), - initialInput: true); + TimeSpan.FromSeconds(0), + true + ); Assert.Equal(0, await sut.CurrentAsync); @@ -50,12 +55,13 @@ public async Task CanReturnSameBoxTwice() { Action? onBroken = null; var count = 0; using var sut = new SharingProvider( - factory: async (_, f) => { + async (_, f) => { onBroken = f; return count++; }, - factoryRetryDelay: TimeSpan.FromSeconds(0), - initialInput: true); + TimeSpan.FromSeconds(0), + true + ); Assert.Equal(0, await sut.CurrentAsync); @@ -74,15 +80,15 @@ public async Task CanReturnPendingBox() { Action? onBroken = null; var count = 0; using var sut = new SharingProvider( - factory: async (_, f) => { + async (_, f) => { onBroken = f; count++; await trigger.WaitAsync(); return count; }, - factoryRetryDelay: TimeSpan.FromSeconds(0), - initialInput: true); - + TimeSpan.FromSeconds(0), + true + ); var currentTask = sut.CurrentAsync; @@ -110,14 +116,13 @@ public async Task CanReturnPendingBox() { [Fact] public async Task FactoryCanThrow() { using var sut = new SharingProvider( - factory: (x, _) => throw new Exception($"input {x}"), - factoryRetryDelay: TimeSpan.FromSeconds(0), - initialInput: 0); + (x, _) => throw new($"input {x}"), + TimeSpan.FromSeconds(0), + 0 + ); // exception propagated to consumer - var ex = await Assert.ThrowsAsync(async () => { - await sut.CurrentAsync; - }); + var ex = await Assert.ThrowsAsync(async () => { await sut.CurrentAsync; }); Assert.Equal("input 0", ex.Message); } @@ -128,13 +133,15 @@ public async Task FactoryCanThrow() { [Fact] public async Task FactoryCanCallOnBrokenSynchronously() { using var sut = new SharingProvider( - factory: async (x, onBroken) => { + async (x, onBroken) => { if (x == 0) onBroken(5); + return x; }, - factoryRetryDelay: TimeSpan.FromSeconds(0), - initialInput: 0); + TimeSpan.FromSeconds(0), + 0 + ); // onBroken was called but it didn't do anything Assert.Equal(0, await sut.CurrentAsync); @@ -143,34 +150,35 @@ public async Task FactoryCanCallOnBrokenSynchronously() { [Fact] public async Task FactoryCanCallOnBrokenSynchronouslyAndThrow() { using var sut = new SharingProvider( - factory: async (x, onBroken) => { + async (x, onBroken) => { if (x == 0) { onBroken(5); - throw new Exception($"input {x}"); + throw new($"input {x}"); } + return x; }, - factoryRetryDelay: TimeSpan.FromSeconds(0), - initialInput: 0); + TimeSpan.FromSeconds(0), + 0 + ); - var ex = await Assert.ThrowsAsync(async () => { - await sut.CurrentAsync; - }); + var ex = await Assert.ThrowsAsync(async () => { await sut.CurrentAsync; }); Assert.Equal("input 0", ex.Message); } - + [Fact] public async Task StopsAfterBeingDisposed() { Action? onBroken = null; var count = 0; using var sut = new SharingProvider( - factory: async (_, f) => { + async (_, f) => { onBroken = f; return count++; }, - factoryRetryDelay: TimeSpan.FromSeconds(0), - initialInput: true); + TimeSpan.FromSeconds(0), + true + ); Assert.Equal(0, await sut.CurrentAsync); Assert.Equal(1, count); @@ -200,15 +208,20 @@ async Task Factory(int input, Action onBroken) { await completeConstruction.WaitAsync(); try { if (input == 2) { - throw new Exception($"fail to create {input} in factory"); - } else { - _ = triggerFailure.WaitAsync().ContinueWith(t => { - onBroken(input + 1); - failed.Release(); - }); + throw new($"fail to create {input} in factory"); + } + else { + _ = triggerFailure.WaitAsync().ContinueWith( + t => { + onBroken(input + 1); + failed.Release(); + } + ); + return input; } - } finally { + } + finally { constructionCompleted.Release(); } } @@ -236,9 +249,7 @@ async Task Factory(int input, Action onBroken) { var t = sut.CurrentAsync; await constructionCompleted.WaitAsync(); completeConstruction.Release(); - var ex = await Assert.ThrowsAsync(async () => { - await t; - }); + var ex = await Assert.ThrowsAsync(async () => { await t; }); Assert.Equal("fail to create 2 in factory", ex.Message); // when the factory is allowed to produce another item (0), it does: diff --git a/test/EventStore.Client.Tests/StreamPositionTests.cs b/test/EventStore.Client.Tests/StreamPositionTests.cs index d12b4b533..9f0e08db2 100644 --- a/test/EventStore.Client.Tests/StreamPositionTests.cs +++ b/test/EventStore.Client.Tests/StreamPositionTests.cs @@ -1,20 +1,18 @@ using AutoFixture; -namespace EventStore.Client; +namespace EventStore.Client; public class StreamPositionTests : ValueObjectTests { - public StreamPositionTests() : base(new ScenarioFixture()) { - } + public StreamPositionTests() : base(new ScenarioFixture()) { } [Fact] - public void IsComparable() => - Assert.IsAssignableFrom>(_fixture.Create()); + public void IsComparable() => Assert.IsAssignableFrom>(_fixture.Create()); [Fact] public void AdditionOperator() { var sut = StreamPosition.Start; - Assert.Equal(new StreamPosition(1), sut + 1); - Assert.Equal(new StreamPosition(1), 1 + sut); + Assert.Equal(new(1), sut + 1); + Assert.Equal(new(1), 1 + sut); } [Fact] @@ -24,11 +22,12 @@ public void NextReturnsExpectedResult() { } public static IEnumerable AdditionOutOfBoundsCases() { - yield return new object?[] {StreamPosition.End, 1}; - yield return new object?[] {new StreamPosition(long.MaxValue), long.MaxValue + 2UL}; + yield return new object?[] { StreamPosition.End, 1 }; + yield return new object?[] { new StreamPosition(long.MaxValue), long.MaxValue + 2UL }; } - [Theory, MemberData(nameof(AdditionOutOfBoundsCases))] + [Theory] + [MemberData(nameof(AdditionOutOfBoundsCases))] public void AdditionOutOfBoundsThrows(StreamPosition StreamPosition, ulong operand) { Assert.Throws(() => StreamPosition + operand); Assert.Throws(() => operand + StreamPosition); @@ -37,71 +36,77 @@ public void AdditionOutOfBoundsThrows(StreamPosition StreamPosition, ulong opera [Fact] public void SubtractionOperator() { var sut = new StreamPosition(1); - Assert.Equal(new StreamPosition(0), sut - 1); - Assert.Equal(new StreamPosition(0), 1 - sut); + Assert.Equal(new(0), sut - 1); + Assert.Equal(new(0), 1 - sut); } public static IEnumerable SubtractionOutOfBoundsCases() { - yield return new object?[] {new StreamPosition(1), 2}; - yield return new object?[] {StreamPosition.Start, 1}; + yield return new object?[] { new StreamPosition(1), 2 }; + yield return new object?[] { StreamPosition.Start, 1 }; } - [Theory, MemberData(nameof(SubtractionOutOfBoundsCases))] + [Theory] + [MemberData(nameof(SubtractionOutOfBoundsCases))] public void SubtractionOutOfBoundsThrows(StreamPosition streamPosition, ulong operand) { Assert.Throws(() => streamPosition - operand); Assert.Throws(() => (ulong)streamPosition - new StreamPosition(operand)); } public static IEnumerable ArgumentOutOfRangeTestCases() { - yield return new object?[] {long.MaxValue + 1UL}; - yield return new object?[] {ulong.MaxValue - 1UL}; + yield return new object?[] { long.MaxValue + 1UL }; + yield return new object?[] { ulong.MaxValue - 1UL }; } - [Theory, MemberData(nameof(ArgumentOutOfRangeTestCases))] + [Theory] + [MemberData(nameof(ArgumentOutOfRangeTestCases))] public void ArgumentOutOfRange(ulong value) { var ex = Assert.Throws(() => new StreamPosition(value)); Assert.Equal(nameof(value), ex.ParamName); } [Fact] - public void FromStreamPositionEndThrows() { + public void FromStreamPositionEndThrows() => Assert.Throws(() => StreamRevision.FromStreamPosition(StreamPosition.End)); - } [Fact] public void FromStreamPositionReturnsExpectedResult() { - var result = StreamPosition.FromStreamRevision(new StreamRevision(0)); + var result = StreamPosition.FromStreamRevision(new(0)); - Assert.Equal(new StreamPosition(0), result); + Assert.Equal(new(0), result); } [Fact] public void ExplicitConversionToUInt64ReturnsExpectedResult() { - const ulong value = 0UL; - var actual = (ulong)new StreamPosition(value); + const ulong value = 0UL; + + var actual = (ulong)new StreamPosition(value); Assert.Equal(value, actual); } [Fact] public void ImplicitConversionToUInt64ReturnsExpectedResult() { - const ulong value = 0UL; - ulong actual = new StreamPosition(value); + const ulong value = 0UL; + + ulong actual = new StreamPosition(value); Assert.Equal(value, actual); } [Fact] public void ExplicitConversionToStreamPositionReturnsExpectedResult() { - const ulong value = 0UL; - var expected = new StreamPosition(value); - var actual = (StreamPosition)value; + const ulong value = 0UL; + + var expected = new StreamPosition(value); + var actual = (StreamPosition)value; Assert.Equal(expected, actual); } [Fact] public void ImplicitConversionToStreamPositionReturnsExpectedResult() { - const ulong value = 0UL; - var expected = new StreamPosition(value); - StreamPosition actual = value; + const ulong value = 0UL; + + var expected = new StreamPosition(value); + + StreamPosition actual = value; Assert.Equal(expected, actual); } @@ -119,10 +124,7 @@ public void ToUInt64ExpectedResult() { Assert.Equal(expected, new StreamPosition(expected).ToUInt64()); } - private class ScenarioFixture : Fixture { - public ScenarioFixture() { - Customize(composer => composer.FromFactory(value => new StreamPosition(value))); - } + class ScenarioFixture : Fixture { + public ScenarioFixture() => Customize(composer => composer.FromFactory(value => new(value))); } - } \ No newline at end of file diff --git a/test/EventStore.Client.Tests/StreamRevisionTests.cs b/test/EventStore.Client.Tests/StreamRevisionTests.cs index 8233bbec8..de1eace70 100644 --- a/test/EventStore.Client.Tests/StreamRevisionTests.cs +++ b/test/EventStore.Client.Tests/StreamRevisionTests.cs @@ -1,19 +1,18 @@ using AutoFixture; -namespace EventStore.Client; +namespace EventStore.Client; public class StreamRevisionTests : ValueObjectTests { public StreamRevisionTests() : base(new ScenarioFixture()) { } [Fact] - public void IsComparable() => - Assert.IsAssignableFrom>(_fixture.Create()); + public void IsComparable() => Assert.IsAssignableFrom>(_fixture.Create()); [Fact] public void AdditionOperator() { var sut = new StreamRevision(0); - Assert.Equal(new StreamRevision(1), sut + 1); - Assert.Equal(new StreamRevision(1), 1 + sut); + Assert.Equal(new(1), sut + 1); + Assert.Equal(new(1), 1 + sut); } [Fact] @@ -23,10 +22,11 @@ public void NextReturnsExpectedResult() { } public static IEnumerable AdditionOutOfBoundsCases() { - yield return new object?[] {new StreamRevision(long.MaxValue), long.MaxValue + 2UL}; + yield return new object?[] { new StreamRevision(long.MaxValue), long.MaxValue + 2UL }; } - [Theory, MemberData(nameof(AdditionOutOfBoundsCases))] + [Theory] + [MemberData(nameof(AdditionOutOfBoundsCases))] public void AdditionOutOfBoundsThrows(StreamRevision streamRevision, ulong operand) { Assert.Throws(() => streamRevision + operand); Assert.Throws(() => operand + streamRevision); @@ -35,71 +35,80 @@ public void AdditionOutOfBoundsThrows(StreamRevision streamRevision, ulong opera [Fact] public void SubtractionOperator() { var sut = new StreamRevision(1); - Assert.Equal(new StreamRevision(0), sut - 1); - Assert.Equal(new StreamRevision(0), 1 - sut); + Assert.Equal(new(0), sut - 1); + Assert.Equal(new(0), 1 - sut); } public static IEnumerable SubtractionOutOfBoundsCases() { - yield return new object?[] {new StreamRevision(1), 2}; - yield return new object?[] {new StreamRevision(0), 1}; + yield return new object?[] { new StreamRevision(1), 2 }; + yield return new object?[] { new StreamRevision(0), 1 }; } - [Theory, MemberData(nameof(SubtractionOutOfBoundsCases))] + [Theory] + [MemberData(nameof(SubtractionOutOfBoundsCases))] public void SubtractionOutOfBoundsThrows(StreamRevision streamRevision, ulong operand) { Assert.Throws(() => streamRevision - operand); Assert.Throws(() => (ulong)streamRevision - new StreamRevision(operand)); } public static IEnumerable ArgumentOutOfRangeTestCases() { - yield return new object?[] {long.MaxValue + 1UL}; - yield return new object?[] {ulong.MaxValue - 1UL}; + yield return new object?[] { long.MaxValue + 1UL }; + yield return new object?[] { ulong.MaxValue - 1UL }; } - [Theory, MemberData(nameof(ArgumentOutOfRangeTestCases))] + [Theory] + [MemberData(nameof(ArgumentOutOfRangeTestCases))] public void ArgumentOutOfRange(ulong value) { var ex = Assert.Throws(() => new StreamRevision(value)); Assert.Equal(nameof(value), ex.ParamName); } [Fact] - public void FromStreamPositionEndThrows() { + public void FromStreamPositionEndThrows() => Assert.Throws(() => StreamRevision.FromStreamPosition(StreamPosition.End)); - } [Fact] public void FromStreamPositionReturnsExpectedResult() { var result = StreamRevision.FromStreamPosition(StreamPosition.Start); - Assert.Equal(new StreamRevision(0), result); + Assert.Equal(new(0), result); } [Fact] public void ExplicitConversionToUInt64ReturnsExpectedResult() { - const ulong value = 0UL; - var actual = (ulong)new StreamRevision(value); + const ulong value = 0UL; + + var actual = (ulong)new StreamRevision(value); + Assert.Equal(value, actual); } [Fact] public void ImplicitConversionToUInt64ReturnsExpectedResult() { - const ulong value = 0UL; - ulong actual = new StreamRevision(value); + const ulong value = 0UL; + + ulong actual = new StreamRevision(value); + Assert.Equal(value, actual); } [Fact] public void ExplicitConversionToStreamRevisionReturnsExpectedResult() { - const ulong value = 0UL; - var expected = new StreamRevision(value); - var actual = (StreamRevision)value; + const ulong value = 0UL; + + var expected = new StreamRevision(value); + var actual = (StreamRevision)value; + Assert.Equal(expected, actual); } [Fact] public void ImplicitConversionToStreamRevisionReturnsExpectedResult() { - const ulong value = 0UL; - var expected = new StreamRevision(value); - StreamRevision actual = value; + const ulong value = 0UL; + + var expected = new StreamRevision(value); + + StreamRevision actual = value; Assert.Equal(expected, actual); } @@ -117,9 +126,7 @@ public void ToUInt64ExpectedResult() { Assert.Equal(expected, new StreamRevision(expected).ToUInt64()); } - private class ScenarioFixture : Fixture { - public ScenarioFixture() { - Customize(composer => composer.FromFactory(value => new StreamRevision(value))); - } + class ScenarioFixture : Fixture { + public ScenarioFixture() => Customize(composer => composer.FromFactory(value => new(value))); } } \ No newline at end of file diff --git a/test/EventStore.Client.Tests/StreamStateTests.cs b/test/EventStore.Client.Tests/StreamStateTests.cs index 7eebbf9bc..72947c569 100644 --- a/test/EventStore.Client.Tests/StreamStateTests.cs +++ b/test/EventStore.Client.Tests/StreamStateTests.cs @@ -1,19 +1,19 @@ using System.Reflection; using AutoFixture; -namespace EventStore.Client; +namespace EventStore.Client; public class StreamStateTests : ValueObjectTests { - public StreamStateTests() : base(new ScenarioFixture()) { - } + public StreamStateTests() : base(new ScenarioFixture()) { } public static IEnumerable ArgumentOutOfRangeTestCases() { - yield return new object?[] {0}; - yield return new object?[] {int.MaxValue}; - yield return new object?[] {-3}; + yield return new object?[] { 0 }; + yield return new object?[] { int.MaxValue }; + yield return new object?[] { -3 }; } - [Theory, MemberData(nameof(ArgumentOutOfRangeTestCases))] + [Theory] + [MemberData(nameof(ArgumentOutOfRangeTestCases))] public void ArgumentOutOfRange(int value) { var ex = Assert.Throws(() => new StreamState(value)); Assert.Equal(nameof(value), ex.ParamName); @@ -33,23 +33,27 @@ public void ImplicitConversionExpectedResult() { } public static IEnumerable ToStringTestCases() { - yield return new object?[] {StreamState.Any, nameof(StreamState.Any)}; - yield return new object?[] {StreamState.NoStream, nameof(StreamState.NoStream)}; - yield return new object?[] {StreamState.StreamExists, nameof(StreamState.StreamExists)}; + yield return new object?[] { StreamState.Any, nameof(StreamState.Any) }; + yield return new object?[] { StreamState.NoStream, nameof(StreamState.NoStream) }; + yield return new object?[] { StreamState.StreamExists, nameof(StreamState.StreamExists) }; } - [Theory, MemberData(nameof(ToStringTestCases))] - public void ToStringExpectedResult(StreamState sut, string expected) { - Assert.Equal(expected, sut.ToString()); - } + [Theory] + [MemberData(nameof(ToStringTestCases))] + public void ToStringExpectedResult(StreamState sut, string expected) => Assert.Equal(expected, sut.ToString()); - private class ScenarioFixture : Fixture { - private static int RefCount; + class ScenarioFixture : Fixture { + static int RefCount; - private static readonly StreamState[] Instances = Array.ConvertAll(typeof(StreamState) - .GetFields(BindingFlags.Public | BindingFlags.Static), fi => (StreamState)fi.GetValue(null)!); + static readonly StreamState[] Instances = Array.ConvertAll( + typeof(StreamState) + .GetFields(BindingFlags.Public | BindingFlags.Static), + fi => (StreamState)fi.GetValue(null)! + ); - public ScenarioFixture() => Customize(composer => - composer.FromFactory(() => Instances[Interlocked.Increment(ref RefCount) % Instances.Length])); + public ScenarioFixture() => + Customize( + composer => composer.FromFactory(() => Instances[Interlocked.Increment(ref RefCount) % Instances.Length]) + ); } } \ No newline at end of file diff --git a/test/EventStore.Client.Tests/TypeExtensions.cs b/test/EventStore.Client.Tests/TypeExtensions.cs index 67e4d34ef..6c78c064b 100644 --- a/test/EventStore.Client.Tests/TypeExtensions.cs +++ b/test/EventStore.Client.Tests/TypeExtensions.cs @@ -1,8 +1,8 @@ using System.Reflection; -namespace EventStore.Client; +namespace EventStore.Client; -internal static class TypeExtensions { +static class TypeExtensions { public static bool InvokeEqualityOperator(this Type type, object? left, object? right) => type.InvokeOperator("Equality", left, right); @@ -37,7 +37,7 @@ public static bool ImplementsGenericIComparable(this Type type) => public static bool ImplementsIComparable(this Type type) => type.GetInterfaces().Length > 0 && type.GetInterfaces().Any(t => t == typeof(IComparable)); - private static bool InvokeOperator(this Type type, string name, object? left, object? right) { + static bool InvokeOperator(this Type type, string name, object? left, object? right) { var op = type.GetMethod($"op_{name}", BindingFlags.Public | BindingFlags.Static); if (op == null) { throw new Exception($"The type {type} did not implement op_{name}."); diff --git a/test/EventStore.Client.Tests/UuidTests.cs b/test/EventStore.Client.Tests/UuidTests.cs index ba0dd2e9f..170c8ccce 100644 --- a/test/EventStore.Client.Tests/UuidTests.cs +++ b/test/EventStore.Client.Tests/UuidTests.cs @@ -1,6 +1,6 @@ using AutoFixture; -namespace EventStore.Client; +namespace EventStore.Client; public class UuidTests : ValueObjectTests { public UuidTests() : base(new ScenarioFixture()) { } @@ -59,7 +59,7 @@ public void FromInt64ReturnsExpectedResult() { Assert.Equal(expected, sut); } - private static long GetRandomInt64() { + static long GetRandomInt64() { var buffer = new byte[sizeof(long)]; new Random().NextBytes(buffer); @@ -67,7 +67,7 @@ private static long GetRandomInt64() { return BitConverter.ToInt64(buffer, 0); } - private class ScenarioFixture : Fixture { + class ScenarioFixture : Fixture { public ScenarioFixture() => Customize(composer => composer.FromFactory(Uuid.FromGuid)); } } \ No newline at end of file diff --git a/test/EventStore.Client.Tests/ValueObjectTests.cs b/test/EventStore.Client.Tests/ValueObjectTests.cs index b83fa8c81..e1b6cc79b 100644 --- a/test/EventStore.Client.Tests/ValueObjectTests.cs +++ b/test/EventStore.Client.Tests/ValueObjectTests.cs @@ -1,6 +1,6 @@ using AutoFixture; -namespace EventStore.Client; +namespace EventStore.Client; public abstract class ValueObjectTests { protected readonly Fixture _fixture; diff --git a/test/EventStore.Client.UserManagement.Tests/EventStore.Client.UserManagement.Tests.csproj b/test/EventStore.Client.UserManagement.Tests/EventStore.Client.UserManagement.Tests.csproj index 644743455..2f52b0da1 100644 --- a/test/EventStore.Client.UserManagement.Tests/EventStore.Client.UserManagement.Tests.csproj +++ b/test/EventStore.Client.UserManagement.Tests/EventStore.Client.UserManagement.Tests.csproj @@ -4,9 +4,7 @@ EventStore.Client.Tests - - - + diff --git a/test/EventStore.Client.UserManagement.Tests/InvalidCredentialsCases.cs b/test/EventStore.Client.UserManagement.Tests/InvalidCredentialsCases.cs index 0a7ae8a97..ed05d6044 100644 --- a/test/EventStore.Client.UserManagement.Tests/InvalidCredentialsCases.cs +++ b/test/EventStore.Client.UserManagement.Tests/InvalidCredentialsCases.cs @@ -1,11 +1,11 @@ using System.Collections; -namespace EventStore.Client.Tests; +namespace EventStore.Client.Tests; public class InvalidCredentialsCases : IEnumerable { public IEnumerator GetEnumerator() { yield return Fakers.Users.WithNoCredentials().WithResult(user => new object?[] { user, typeof(AccessDeniedException) }); - yield return Fakers.Users.WithInvalidCredentials(wrongLoginName: false).WithResult(user => new object?[] { user, typeof(NotAuthenticatedException) }); + yield return Fakers.Users.WithInvalidCredentials(false).WithResult(user => new object?[] { user, typeof(NotAuthenticatedException) }); yield return Fakers.Users.WithInvalidCredentials(wrongPassword: false).WithResult(user => new object?[] { user, typeof(NotAuthenticatedException) }); } diff --git a/test/EventStore.Client.UserManagement.Tests/changing_user_password.cs b/test/EventStore.Client.UserManagement.Tests/changing_user_password.cs index 9b76ea2c8..12cad9dad 100644 --- a/test/EventStore.Client.UserManagement.Tests/changing_user_password.cs +++ b/test/EventStore.Client.UserManagement.Tests/changing_user_password.cs @@ -1,14 +1,8 @@ -using System.Net.Http.Headers; -using System.Text; - namespace EventStore.Client.Tests; -public class changing_user_password : IClassFixture { - public changing_user_password(EventStoreInsecureClientsFixture fixture, ITestOutputHelper output) => - Fixture = fixture.With(f => f.CaptureLogs(output)); +public class changing_user_password : EventStoreFixture { + public changing_user_password(ITestOutputHelper output) : base(output) { } - EventStoreInsecureClientsFixture Fixture { get; } - public static IEnumerable NullInputCases() { yield return Fakers.Users.Generate().WithResult(x => new object?[] { null, x.Password, x.Password, "loginName" }); yield return Fakers.Users.Generate().WithResult(x => new object?[] { x.LoginName, null, x.Password, "currentPassword" }); @@ -71,73 +65,4 @@ await Fixture.Users .ChangePasswordAsync(user.LoginName, user.Password, "new-password", userCredentials: user.Credentials) .ShouldNotThrowAsync(); } - - static readonly UTF8Encoding UTF8NoBom = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); - // static readonly UTF8Encoding UTF8Normal = new UTF8Encoding(); - - [Fact] - public async Task with_own_credentials_wtf() { - var user = Fakers.Users.Generate(); - - // var encodedNoBomBytes = UTF8NoBom.GetBytes($"{user.LoginName}:{user.Password}"); - // var encodedNoBom = Convert.ToBase64String(encodedNoBomBytes); - // var decodedNoBomBytes = Convert.FromBase64String(encodedNoBom); - // var decodedNoBom = UTF8NoBom.GetString(decodedNoBomBytes); - // - // var encodedBytes = UTF8Normal.GetBytes($"{user.LoginName}:{user.Password}"); - // var encoded = Convert.ToBase64String(encodedBytes); - // var decodedBytes = Convert.FromBase64String(encoded); - // var decoded = UTF8Normal.GetString(decodedBytes); - // - // - //var loginName = Guid.NewGuid().ToString(); - - await Fixture.Users.CreateUserAsync( - user.LoginName, "Full Name", Array.Empty(), - user.Password, userCredentials: TestCredentials.Root - ); - // - // await Fixture.Users.ChangePasswordAsync( - // user.LoginName, user.Password, "newPassword", - // userCredentials: new UserCredentials(user.LoginName, user.Password) - // ); - - var Authorization = new AuthenticationHeaderValue( - Constants.Headers.BasicScheme, - Convert.ToBase64String(UTF8NoBom.GetBytes($"{user.LoginName}:{user.Password}")) - ); - - var creds = GetBasicAuth(Authorization); - - return; - - static (string? Username, string? Password) GetBasicAuth(AuthenticationHeaderValue header) { - if (header.Parameter == null || header.Scheme != Constants.Headers.BasicScheme) { - return (null, null); - } - - var credentials = UTF8NoBom.GetString(Convert.FromBase64String(header.Parameter)).AsSpan(); - - var passwordStart = credentials.IndexOf(':') + 1; - - var password = credentials[passwordStart..].ToString(); - var username = credentials[..password.Length].ToString(); - - return (username, password); - } - } - - [Fact] - public async Task with_own_credentials_old() { - var loginName = Guid.NewGuid().ToString(); - await Fixture.Users.CreateUserAsync( - loginName, "Full Name", Array.Empty(), - "password", userCredentials: TestCredentials.Root - ); - - await Fixture.Users.ChangePasswordAsync( - loginName, "password", "newPassword", - userCredentials: new UserCredentials(loginName, "password") - ); - } } diff --git a/test/EventStore.Client.UserManagement.Tests/creating_a_user.cs b/test/EventStore.Client.UserManagement.Tests/creating_a_user.cs index 6a8f0802a..751752913 100644 --- a/test/EventStore.Client.UserManagement.Tests/creating_a_user.cs +++ b/test/EventStore.Client.UserManagement.Tests/creating_a_user.cs @@ -1,10 +1,7 @@ namespace EventStore.Client.Tests; -public class creating_a_user : IClassFixture { - public creating_a_user(EventStoreInsecureClientsFixture fixture, ITestOutputHelper output) => - Fixture = fixture.With(f => f.CaptureLogs(output)); - - EventStoreInsecureClientsFixture Fixture { get; } +public class creating_a_user : EventStoreFixture { + public creating_a_user(ITestOutputHelper output) : base(output) { } public static IEnumerable NullInputCases() { yield return Fakers.Users.Generate().WithResult(x => new object?[] { null, x.FullName, x.Groups, x.Password, "loginName" }); diff --git a/test/EventStore.Client.UserManagement.Tests/deleting_a_user.cs b/test/EventStore.Client.UserManagement.Tests/deleting_a_user.cs index 425dce5c5..61e2ff363 100644 --- a/test/EventStore.Client.UserManagement.Tests/deleting_a_user.cs +++ b/test/EventStore.Client.UserManagement.Tests/deleting_a_user.cs @@ -1,10 +1,8 @@ namespace EventStore.Client.Tests; -public class deleting_a_user : IClassFixture { - public deleting_a_user(EventStoreInsecureClientsFixture fixture, ITestOutputHelper output) => - Fixture = fixture.With(f => f.CaptureLogs(output)); - - EventStoreInsecureClientsFixture Fixture { get; } +public class deleting_a_user : EventStoreFixture { + public deleting_a_user(ITestOutputHelper output) + : base(output, x => x.WithoutDefaultCredentials()) { } [Fact] public async Task with_null_input_throws() { diff --git a/test/EventStore.Client.UserManagement.Tests/disabling_a_user.cs b/test/EventStore.Client.UserManagement.Tests/disabling_a_user.cs index eadab360c..6e614b09a 100644 --- a/test/EventStore.Client.UserManagement.Tests/disabling_a_user.cs +++ b/test/EventStore.Client.UserManagement.Tests/disabling_a_user.cs @@ -1,10 +1,7 @@ namespace EventStore.Client.Tests; -public class disabling_a_user : IClassFixture { - public disabling_a_user(EventStoreInsecureClientsFixture fixture, ITestOutputHelper output) => - Fixture = fixture.With(f => f.CaptureLogs(output)); - - EventStoreInsecureClientsFixture Fixture { get; } +public class disabling_a_user : EventStoreFixture { + public disabling_a_user(ITestOutputHelper output) : base(output) { } [Fact] public async Task with_null_input_throws() { diff --git a/test/EventStore.Client.UserManagement.Tests/enabling_a_user.cs b/test/EventStore.Client.UserManagement.Tests/enabling_a_user.cs index 9c79624fe..399713d6e 100644 --- a/test/EventStore.Client.UserManagement.Tests/enabling_a_user.cs +++ b/test/EventStore.Client.UserManagement.Tests/enabling_a_user.cs @@ -1,10 +1,7 @@ namespace EventStore.Client.Tests; -public class enabling_a_user : IClassFixture { - public enabling_a_user(EventStoreInsecureClientsFixture fixture, ITestOutputHelper output) => - Fixture = fixture.With(f => f.CaptureLogs(output)); - - EventStoreInsecureClientsFixture Fixture { get; } +public class enabling_a_user : EventStoreFixture { + public enabling_a_user(ITestOutputHelper output) : base(output) { } [Fact] public async Task with_null_input_throws() { diff --git a/test/EventStore.Client.UserManagement.Tests/getting_current_user.cs b/test/EventStore.Client.UserManagement.Tests/getting_current_user.cs index 297fec610..1a481a0ed 100644 --- a/test/EventStore.Client.UserManagement.Tests/getting_current_user.cs +++ b/test/EventStore.Client.UserManagement.Tests/getting_current_user.cs @@ -1,10 +1,7 @@ namespace EventStore.Client.Tests; -public class getting_current_user : IClassFixture { - public getting_current_user(EventStoreClientsFixture fixture, ITestOutputHelper output) => - Fixture = fixture.With(f => f.CaptureLogs(output)); - - EventStoreClientsFixture Fixture { get; } +public class getting_current_user : EventStoreFixture { + public getting_current_user(ITestOutputHelper output) : base(output) { } [Fact] public async Task returns_the_current_user() { diff --git a/test/EventStore.Client.UserManagement.Tests/listing_users.cs b/test/EventStore.Client.UserManagement.Tests/listing_users.cs index f8257f1d3..d0560bef4 100644 --- a/test/EventStore.Client.UserManagement.Tests/listing_users.cs +++ b/test/EventStore.Client.UserManagement.Tests/listing_users.cs @@ -1,10 +1,7 @@ namespace EventStore.Client.Tests; -public class listing_users : IClassFixture { - public listing_users(EventStoreInsecureClientsFixture fixture, ITestOutputHelper output) => - Fixture = fixture.With(f => f.CaptureLogs(output)); - - EventStoreInsecureClientsFixture Fixture { get; } +public class listing_users : EventStoreFixture { + public listing_users(ITestOutputHelper output) : base(output) { } [Fact] public async Task returns_all_created_users() { diff --git a/test/EventStore.Client.UserManagement.Tests/reset_user_password.cs b/test/EventStore.Client.UserManagement.Tests/resetting_user_password.cs similarity index 89% rename from test/EventStore.Client.UserManagement.Tests/reset_user_password.cs rename to test/EventStore.Client.UserManagement.Tests/resetting_user_password.cs index 981a1ab63..7c4c60747 100644 --- a/test/EventStore.Client.UserManagement.Tests/reset_user_password.cs +++ b/test/EventStore.Client.UserManagement.Tests/resetting_user_password.cs @@ -1,10 +1,7 @@ namespace EventStore.Client.Tests; -public class resetting_user_password : IClassFixture { - public resetting_user_password(EventStoreInsecureClientsFixture fixture, ITestOutputHelper output) => - Fixture = fixture.With(f => f.CaptureLogs(output)); - - EventStoreInsecureClientsFixture Fixture { get; } +public class resetting_user_password : EventStoreFixture { + public resetting_user_password(ITestOutputHelper output) : base(output) { } public static IEnumerable NullInputCases() { var loginName = "ouro";