From dee61ecd3dc2b6842ba3e6b38a65cdad7bf4af87 Mon Sep 17 00:00:00 2001 From: "Jeremy D. Miller" Date: Wed, 29 Jul 2026 14:17:01 -0500 Subject: [PATCH 1/2] test: reinstate the xUnit1051 analyzer across 71 of 73 xUnit projects (GH-3702) xUnit1051 ("use TestContext.Current.CancellationToken") was suppressed repo-wide in Directory.Build.props during the v3 migration, because TreatWarningsAsErrors turned it into a hard build break across 2,264 call sites (8,140 raw warnings once multi-targeting is counted). The fix is applied by xUnit's OWN code fix, not by hand and not by a regex. `dotnet format analyzers` cannot drive it -- Xunit.Analyzers.Fixes.UseCancellationTokenFixer returns null from GetFixAllProvider(), and dotnet format only applies fixers that support FixAll -- so a small Roslyn driver loads the analyzer and invokes the CodeFixProvider directly, one compilation per pass, merging the disjoint TextChanges per file. Three things that driver had to account for, each of which a blind sweep gets wrong: - The tool's own diagnostic count cannot be trusted. An MSBuildWorkspace load on a cold project can return an incomplete compilation and report ZERO diagnostics -- CoreTests first reported 0, then 472 on retry. The build, with xUnit1051 back at error severity, is the gate; the driver re-runs the fixer while anything is still reported. - The fixer sometimes binds to the wrong named parameter. On `InvokeAsync(object, CancellationToken, TimeSpan?)` it emitted `timeout: TestContext.Current.CancellationToken`. CS1503 caught both occurrences. - It declines some shapes outright: `Task.Run(() => ...)` and `Task.WhenAny(tcs.Task, Task.Delay(...))`. Twelve sites threaded by hand. Separately, the analyzer fires inside NSubstitute verifications, where taking its advice is actively wrong: `channel.Received().QueueDeclareAsync(..., cancellationToken: TestContext .Current.CancellationToken)` narrows the verification to that exact token, which production code does not pass. Those 25 sites use `Arg.Any()` instead, which the analyzer accepts. Rather than a global flag flip, Directory.Build.targets carries a conditional NoWarn so each project opts in with true It has to live in .targets because the property is set by the project file, which is evaluated after Directory.Build.props. Delete the block once the last two projects are in. 71 of 73 xUnit projects are converted. The two left out are SampleTests and TracingTests, which do not compile at all on main -- that is GH-3704. Verified: `dotnet build wolverine.slnx -c Release` succeeds. CoreTests runs 2104 total / 2101 passed / 1 failed, the same single pre-existing failure main has (GH-3703, fixed separately in #3717) -- i.e. no movement from this change. Remaining suites are compile-verified only and rely on CI; anything that misbehaves will do so at runtime, not at build time. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01JMNKwGVHnyaBjiheC5k8KX --- Directory.Build.props | 6 +- Directory.Build.targets | 19 +++++ .../Samples.cs | 4 +- ...ine.DataAnnotationsValidation.Tests.csproj | 2 + .../configuration_specs.cs | 4 +- .../end_to_end.cs | 16 ++-- .../Samples.cs | 6 +- .../Wolverine.FluentValidation.Tests.csproj | 2 + .../configuration_specs.cs | 18 ++--- .../end_to_end.cs | 24 +++--- .../internals_tests.cs | 2 +- .../Wolverine.MemoryPack.Tests.csproj | 2 + .../serialization_configuration.cs | 4 +- .../Wolverine.MessagePack.Tests.csproj | 2 + .../serialization_configuration.cs | 4 +- .../Wolverine.Protobuf.Tests.csproj | 2 + .../Wolverine.Http.AspVersioning.Tests.csproj | 2 + ...dler_should_not_try_to_use_query_string.cs | 2 +- .../Bugs/Bug_2205_multiple_document_args.cs | 8 +- .../Bugs/Bug_281_erroneous_215.cs | 2 +- ...ariables_in_middleware_without_argument.cs | 2 +- ...g_using_fromquery_with_aggregatehandler.cs | 2 +- .../Bugs/Bug_using_host_stop.cs | 2 +- .../Marten/compiled_query_writer.cs | 6 +- .../Marten/document_attribute_usage.cs | 14 ++-- ..._publishing_with_entity_attribute_usage.cs | 2 +- ...anted_session_factory_without_wolverine.cs | 8 +- .../Marten/soft_deleted_attribute_usage.cs | 2 +- .../Marten/streaming_endpoints.cs | 18 ++--- .../Marten/strong_typed_identifiers.cs | 18 ++--- .../using_aggregate_handler_workflow.cs | 16 ++-- .../Marten/using_ancillary_stores.cs | 2 +- .../Marten/using_version_source_override.cs | 4 +- .../write_aggregate_with_asparameters.cs | 2 +- ...multi_tenancy_detection_and_integration.cs | 2 +- .../Transport/HttpScheduledMessageTests.cs | 2 +- .../HttpTransportConfigurationTests.cs | 14 ++-- .../Transport/inline_request_reply_sender.cs | 6 +- .../Wolverine.Http.Tests.csproj | 2 + ...ccepts_content_type_negative_cases_3649.cs | 2 +- .../api_explorer_before_host_start.cs | 10 +-- ...shing_other_messages_from_http_endpoint.cs | 4 +- .../from_form_file_binding.cs | 24 +++--- .../query_verb_support.cs | 4 +- .../todo_endpoint_specs.cs | 8 +- ...and_metadata_derived_from_response_type.cs | 4 +- src/Http/Wolverine.Http.Tests/using_efcore.cs | 8 +- src/Http/Wolverine.Http.Tests/using_marten.cs | 4 +- .../CosmosDbTests/CosmosDbTests.csproj | 2 + src/Persistence/CosmosDbTests/end_to_end.cs | 2 +- .../saga_optimistic_concurrency.cs | 12 +-- .../CosmosDbTests/saga_partitioning.cs | 16 ++-- ...rage_return_types_and_entity_attributes.cs | 2 +- ...9_host_build_with_managed_multi_tenancy.cs | 2 +- ...del_cache_key_includes_wolverine_schema.cs | 4 +- .../ConjoinedPartitioningCompliance.cs | 64 ++++++++-------- .../ConjoinedTenancyCompliance.cs | 22 +++--- .../EfCoreTests.MultiTenancy.csproj | 2 + .../MultiTenancyCompliance.cs | 74 +++++++++---------- .../EfCoreTests/Bug_252_codegen_issue.cs | 12 +-- .../Bug_661_postgresql_with_ef_core.cs | 2 +- ...6_duplicate_execution_of_scheduled_jobs.cs | 2 +- ...parated_behavior_and_scheduled_messages.cs | 2 +- ...Bug_3342_saga_entity_and_storage_action.cs | 2 +- ...rableLocalQueue_ancillary_store_routing.cs | 6 +- .../DomainEventScraperStateFilterTests.cs | 6 +- ...configuration_of_domain_events_scrapers.cs | 4 +- .../EfCoreTests/EfCoreCompilationScenarios.cs | 8 +- .../EfCoreTests/EfCoreTests.csproj | 2 + .../Migrations/with_one_postgresql_context.cs | 4 +- .../Migrations/with_one_sqlserver_context.cs | 4 +- .../Optimistic_concurrency_with_ef_core.cs | 6 +- .../QueryPlans/QueryPlan_end_to_end.cs | 6 +- .../EfCoreTests/QueryPlans/QueryPlan_specs.cs | 10 +-- .../auto_database_cleaner_tests.cs | 6 +- .../EfCoreTests/batch_query_tests.cs | 10 +-- .../EfCoreTests/database_cleaner_tests.cs | 10 +-- .../dbContext_abstraction_scenarios.cs | 18 ++--- ...xt_transactions_with_abstractions_tests.cs | 6 +- ...cy_with_non_wolverine_mapped_db_context.cs | 10 +-- .../end_to_end_efcore_persistence.cs | 50 ++++++------- ...inline_or_buffered_endpoints_end_to_end.cs | 6 +- .../persisting_envelopes_with_sqlserver.cs | 4 +- .../storage_dbcontext_selection_tests.cs | 10 +-- .../transaction_middleware_mode_tests.cs | 16 ++-- ...transactional_dbcontext_selection_tests.cs | 20 ++--- ...dd_dbcontext_with_wolverine_integration.cs | 8 +- .../CosmosDbTests.LeaderElection.csproj | 2 + .../MySqlTests.LeaderElection.csproj | 2 + .../OracleTests.LeaderElection.csproj | 2 + .../PostgresqlTests.LeaderElection.csproj | 2 + .../RavenDbTests.LeaderElection.csproj | 2 + .../SqlServerTests.LeaderElection.csproj | 2 + .../MartenSubscriptionTests.csproj | 2 + .../subscriptions_end_to_end.cs | 50 ++++++------- .../aggregate_handler_workflow.cs | 12 +-- .../aggregate_handler_workflow_with_ievent.cs | 10 +-- ...aggregate_handler_with_multiple_streams.cs | 4 +- .../natural_key_aggregate_handler_workflow.cs | 12 +-- .../override_of_event_metadata.cs | 6 +- .../strong_named_identifiers.cs | 20 ++--- ...nt_partitioned_aggregate_matrix_phase1b.cs | 2 +- ...t_partitioned_events_aggregate_workflow.cs | 2 +- ..._ancillary_marten_stores_with_wolverine.cs | 2 +- ...torage_attribute_routes_to_marten_store.cs | 2 +- .../tenant_partitioned_ancillary_store.cs | 6 +- .../Bugs/Bug_1175_schema_name_with_queues.cs | 4 +- ...dler_command_should_not_require_version.cs | 2 +- ...oneous_failure_ack_on_invoke_async_of_t.cs | 6 +- ...n_session_is_dependency_of_a_dependency.cs | 4 +- ...pound_handlers_and_marten_event_streams.cs | 4 +- .../Bugs/Bug_226_disambiguate_loggers.cs | 2 +- .../Bugs/Bug_2318_ancillary_dlq_replay.cs | 4 +- .../Bugs/Bug_2382_ancillary_store_inbox.cs | 12 +-- ...write_aggregate_throw_exception_codegen.cs | 2 +- ...ise_side_effects_with_metadata_override.cs | 4 +- ...illary_scheduled_message_stuck_incoming.cs | 2 +- ...icit_delivery_options_sagaid_should_win.cs | 2 +- ..._does_not_complete_with_timeout_message.cs | 4 +- ...ten_store_local_message_from_main_store.cs | 2 +- ..._not_publishing_with_tuple_return_value.cs | 4 +- ...es_should_be_deep_on_injected_arguments.cs | 4 +- ..._saga_handler_that_returns_another_saga.cs | 4 +- ...ph_transactional_middleware_application.cs | 2 +- .../Bugs/Bug_756_composite_handler_on_saga.cs | 2 +- .../Bug_778_multiple_marten_ops_in_tuple.cs | 6 +- .../Bug_826_issue_with_paused_listener.cs | 2 +- ...play_dead_letter_queue_of_event_wrapper.cs | 4 +- ...y_to_local_message_tries_to_be_Outgoing.cs | 2 +- .../MartenTests/Bugs/event_forwarding_bug.cs | 2 +- .../Bugs/event_forwarding_routing_bug.cs | 4 +- .../Dcb/boundary_model_workflow_tests.cs | 11 ++- .../Dcb/dedup_load_boundary_frame_tests.cs | 5 +- ...preserves_per_tenant_progression_floors.cs | 4 +- ...ind_agent_uri_for_registered_projection.cs | 4 +- .../find_agent_uri_per_tenant_database.cs | 6 +- .../Distribution/inline_projection_rebuild.cs | 12 +-- ...tenant_churn_under_managed_distribution.cs | 2 +- .../store_scoped_find_agent_uri_3647.cs | 20 ++--- .../store_scoped_transient_rebuild_3618.cs | 2 +- .../subscription_descriptor_agent_uris.cs | 4 +- ...nant_partitioned_distribution_multinode.cs | 2 +- .../MartenTests/MartenOutbox_end_to_end.cs | 4 +- .../MartenTests/MartenTests.csproj | 2 + .../MultiTenancy/agent_mechanics.cs | 4 +- ...ootstrapping_and_database_configuration.cs | 12 +-- .../MultiTenancy/conjoined_tenancy.cs | 6 +- ...ability_agents_for_new_tenant_databases.cs | 6 +- ...up_new_tenant_databases_with_autocreate.cs | 6 +- .../MartenTests/MultiTenancy/end_to_end.cs | 4 +- .../MultiTenancy/multi_tenancy_queue_usage.cs | 4 +- ...enant_specific_queues_and_subscriptions.cs | 2 +- .../end_to_end_with_persistence.cs | 6 +- .../Requirements/using_data_requirements.cs | 24 +++--- .../MartenTests/Saga/RevisionedSaga.cs | 4 +- .../Saga/When_handling_messages_in_saga.cs | 8 +- .../Saga/multiple_sagas_for_same_message.cs | 14 ++-- .../MartenTests/Saga/not_found_usage.cs | 2 +- .../Saga/soft_deleted_saga_experiment.cs | 10 +-- ...rting_saga_by_returning_it_from_handler.cs | 8 +- .../MartenTests/Saga/strong_typed_id_saga.cs | 10 +-- .../MartenTests/Sample/SampleApp.cs | 4 +- .../catch_up_and_then_do_nothing.cs | 12 +-- .../TestHelpers/catch_up_then_restart.cs | 12 +-- ...ch_up_when_using_wolverine_distribution.cs | 12 +-- ...ch_up_with_second_subscription_consumer.cs | 4 +- ...ld_catch_up_with_wolverine_distribution.cs | 4 +- .../TestHelpers/reset_data_first.cs | 12 +-- .../TestHelpers/second_stage_waiting.cs | 12 +-- .../wait_for_non_stale_data_after.cs | 12 +-- .../MartenTests/basic_marten_integration.cs | 4 +- .../MartenTests/batch_processing.cs | 14 ++-- .../MartenTests/batch_querying_support.cs | 4 +- ...oncurrency_resilient_sharded_processing.cs | 8 +- ...sh_messages_through_marten_to_wolverine.cs | 14 ++-- .../event_stream_append_persists.cs | 2 +- .../MartenTests/event_streaming.cs | 4 +- .../MartenTests/global_entity_defaults.cs | 2 +- ..._actions_with_implied_marten_operations.cs | 48 ++++++------ ...ndler_actions_with_returned_StartStream.cs | 4 +- ...cy_check_in_marten_envelope_transaction.cs | 4 +- .../marten_tracking_diagnostics.cs | 4 +- ...ng_data_handling_with_entity_attributes.cs | 4 +- .../non_transactional_attribute_opt_out.cs | 6 +- .../read_aggregate_attribute_usage.cs | 8 +- .../service_location_document_session.cs | 2 +- .../single_marten_op_side_effect_persists.cs | 4 +- .../MartenTests/strong_typed_identifiers.cs | 4 +- .../transactional_frame_end_to_end.cs | 4 +- .../MySqlTests/Agents/control_queue_tests.cs | 6 +- .../MySql/MySqlTests/MySqlTests.csproj | 2 + .../Sagas/configuring_saga_table_storage.cs | 10 +-- .../Sagas/saga_storage_operations.cs | 46 ++++++------ .../MySql/MySqlTests/SchemaTests.cs | 28 +++---- .../Transport/basic_functionality.cs | 6 +- .../health_check_timestamp_round_trip.cs | 6 +- .../Oracle/OracleTests/OracleTests.csproj | 2 + .../Sagas/saga_storage_operations.cs | 46 ++++++------ ...handled_in_transaction_binds_raw16_guid.cs | 8 +- ...e_must_not_start_the_agent_being_paused.cs | 10 +-- ...le_execution_outside_of_message_handler.cs | 4 +- .../PersistenceTests/DurableFixture.cs | 2 +- .../modular_monolith_usage.cs | 8 +- .../PersistenceTests/PersistenceTests.csproj | 2 + ...stence_provider_precedence_permutations.cs | 4 +- .../PolecatIncidentService.Tests.csproj | 2 + .../aggregate_handler_workflow.cs | 12 +-- ...aggregate_handler_with_multiple_streams.cs | 6 +- .../strong_named_identifiers.cs | 20 ++--- ...ancillary_polecat_stores_with_wolverine.cs | 2 +- ...orage_attribute_routes_to_polecat_store.cs | 2 +- ...g_191_aggregate_handler_without_version.cs | 2 +- ...oneous_failure_ack_on_invoke_async_of_t.cs | 8 +- ...ound_handlers_and_polecat_event_streams.cs | 6 +- ...xed_session_listener_null_message_store.cs | 2 +- ..._not_publishing_with_tuple_return_value.cs | 8 +- ..._saga_handler_that_returns_another_saga.cs | 4 +- .../Bugs/Bug_756_composite_handler_on_saga.cs | 4 +- .../Bug_778_multiple_polecat_ops_in_tuple.cs | 8 +- .../Dcb/boundary_model_workflow_tests.cs | 11 ++- ...managed_event_subscription_distribution.cs | 2 +- .../subscription_descriptor_agent_uris.cs | 4 +- .../PolecatTests/PolecatTests.csproj | 2 + ...olecat_to_wolverine_outbox_registration.cs | 6 +- .../Requirements/using_data_requirements.cs | 26 +++---- .../PolecatTests/Sagas/RevisionedSaga.cs | 4 +- .../Sagas/When_handling_messages_in_saga.cs | 12 +-- .../Sagas/multiple_sagas_for_same_message.cs | 14 ++-- .../PolecatTests/Sagas/not_found_usage.cs | 2 +- ...rting_saga_by_returning_it_from_handler.cs | 10 +-- .../Sagas/strong_typed_id_saga.cs | 10 +-- .../Subscriptions/subscriptions_end_to_end.cs | 64 ++++++++-------- ...actions_with_implied_polecat_operations.cs | 40 +++++----- ...ndler_actions_with_returned_StartStream.cs | 2 +- ...ng_data_handling_with_entity_attributes.cs | 4 +- .../natural_key_aggregate_handler_workflow.cs | 12 +-- .../non_transactional_attribute_opt_out.cs | 6 +- .../read_aggregate_attribute_usage.cs | 8 +- .../PolecatTests/strong_typed_identifiers.cs | 4 +- .../transactional_frame_end_to_end.cs | 12 +-- .../Agents/control_queue_tests.cs | 4 +- .../Bug_1516_get_the_schema_names_right.cs | 2 +- ...g_1942_replay_dlq_to_buffered_or_inline.cs | 4 +- ...2518_concurrent_migration_advisory_lock.cs | 14 ++-- .../Bugs/Bug_GH3166_dlq_null_received_at.cs | 4 +- .../DeadLetterTable_index_creation.cs | 12 +-- .../multi_node_tenant_database_connections.cs | 2 +- .../MultiTenancy/static_multi_tenancy.cs | 4 +- .../PostgresqlMessageStoreTests.cs | 8 +- .../PostgresqlMessageStore_DQL_expiration.cs | 12 +-- ...ageStore_with_IdAndDestination_Identity.cs | 6 +- .../PostgresqlTests/PostgresqlTests.csproj | 2 + .../Sagas/configuring_saga_table_storage.cs | 8 +- .../Sagas/order_saga_example.cs | 2 +- .../Sagas/saga_storage_operations.cs | 46 ++++++------ .../Transport/basic_functionality.cs | 4 +- .../Transport/external_message_tables.cs | 22 +++--- ...source_setup_against_a_missing_database.cs | 6 +- .../Transport/sticky_listener_health_tests.cs | 4 +- .../Transport/transport_perf_benchmark.cs | 4 +- .../advisory_lock_session_hygiene.cs | 4 +- .../bumping_stale_inbox_messages.cs | 12 +-- .../bumping_stale_outbox_messages.cs | 12 +-- .../compliance_using_table_partitioning.cs | 8 +- ...it_resource_setup_with_auto_create_none.cs | 6 +- .../master_table_tenancy_di_registration.cs | 4 +- ..._store_initialization_and_configuration.cs | 6 +- ...waysMakeScheduledMessagesDurable_is_set.cs | 6 +- .../using_default_message_schema_name.cs | 6 +- .../RavenDbTests/RavenDbTests.csproj | 2 + .../durability_recovery_orphaned_listener.cs | 4 +- .../RavenDbTests/leadership_locking.cs | 58 +++++---------- .../RavenDbTests/message_store_compliance.cs | 5 +- ...ssage_identity_using_id_and_destination.cs | 2 +- .../RavenDbTests/transactional_middleware.cs | 4 +- .../Agents/control_queue_tests.cs | 4 +- .../DeadLetterTable_index_creation.cs | 12 +-- .../MultiTenancy/static_multi_tenancy.cs | 4 +- .../Persistence/SqlServerMessageStoreTests.cs | 13 ++-- .../SqlServerMessageStore_DQL_expiration.cs | 12 +-- ...ageStore_with_IdAndDestination_Identity.cs | 11 +-- .../Sagas/configuring_saga_table_storage.cs | 8 +- .../Sagas/order_saga_example.cs | 2 +- .../Sagas/saga_storage_operations.cs | 38 +++++----- .../string_identity_schema_configuration.cs | 14 ++-- .../SqlServerTests/SqlServerTests.csproj | 2 + .../nsb_dedicated_database_multitenancy.cs | 2 +- .../Transport/external_message_tables.cs | 18 ++--- .../stateful_resource_smoke_tests.cs | 4 +- .../Transport/transport_perf_benchmark.cs | 12 +-- .../bumping_stale_inbox_messages.cs | 12 +-- .../bumping_stale_outbox_messages.cs | 12 +-- .../master_table_tenancy_dynamic_lifecycle.cs | 2 +- ..._store_initialization_and_configuration.cs | 6 +- .../SqlServerTests/rate_limiting_storage.cs | 6 +- .../using_default_message_schema_name.cs | 4 +- ...ty_id_and_destination_emits_invalid_ddl.cs | 10 +-- ...e_dlq_expiration_creates_expires_column.cs | 10 +-- .../DeadLetterTable_index_creation.cs | 8 +- .../Sagas/saga_storage_operations.cs | 44 +++++------ .../SqliteTests/SqliteMessageStoreTests.cs | 4 +- .../SqliteTests/SqliteTests.csproj | 2 + .../Transport/basic_functionality.cs | 8 +- .../Transport/sqlite_advisory_lock.cs | 30 ++++---- .../Transport/sqlite_migration_lock.cs | 8 +- .../Transport/transport_workflow.cs | 10 +-- .../configuration_extension_methods.cs | 4 +- .../SqliteTests/extension_registrations.cs | 4 +- ..._store_initialization_and_configuration.cs | 6 +- .../SqliteTests/message_workflow.cs | 6 +- ...Wolverine.ClaimCheck.AmazonS3.Tests.csproj | 2 + ...e.ClaimCheck.AzureBlobStorage.Tests.csproj | 2 + ...ClaimCheck.GoogleCloudStorage.Tests.csproj | 2 + .../Wolverine.ClaimCheck.Nats.Tests.csproj | 2 + .../PostgresqlClaimCheckStoreTests.cs | 16 ++-- ...lverine.ClaimCheck.Postgresql.Tests.csproj | 2 + .../TeleHealth.Tests/GettingStarted.cs | 11 ++- .../TeleHealth.Tests/TeleHealth.Tests.csproj | 2 + .../DiagnosticsTests/DiagnosticsTests.csproj | 2 + .../ItemService.Tests.csproj | 2 + .../ItemService.Tests/end_to_end.cs | 8 +- ...or_dbcontext_not_integrated_with_outbox.cs | 2 +- .../IncidentService.Tests.csproj | 2 + .../when_logging_an_incident.cs | 2 +- .../AppWithMiddleware.Tests.csproj | 2 + .../try_out_the_middleware.cs | 8 +- .../MultiTenantedTodoWebService.Tests.csproj | 2 + .../when_cancelling_a_fulfillment.cs | 8 +- .../when_completing_a_fulfillment.cs | 10 +-- .../when_payment_times_out.cs | 10 +-- .../when_starting_a_fulfillment.cs | 6 +- .../ProcessManagerViaHandlers.Tests.csproj | 2 + .../BankingService.Tests.csproj | 2 + .../TodoWebServiceTests.csproj | 2 + .../BackPressureTests.csproj | 2 + .../Acceptance/batch_coalesce_poison.cs | 4 +- .../batch_handler_conflict_diagnostic.cs | 6 +- .../Acceptance/batch_isolate_members.cs | 6 +- .../Acceptance/batch_item_isolation.cs | 8 +- .../batch_probe_individually_after.cs | 4 +- .../batching_with_separated_handlers.cs | 6 +- .../CoreTests/Acceptance/compound_handlers.cs | 14 ++-- .../Acceptance/configuring_local_queues.cs | 2 +- .../Acceptance/encryption_acceptance.cs | 38 +++++----- .../execution_finished_logs_duration_3063.cs | 2 +- .../indefinite_scheduled_retries.cs | 8 +- .../Acceptance/invoke_tracing_mode.cs | 16 ++-- ...nvoke_does_not_publish_the_return_value.cs | 2 +- .../CoreTests/Acceptance/missing_handlers.cs | 2 +- .../Acceptance/on_exception_convention.cs | 32 ++++---- .../CoreTests/Acceptance/remote_invocation.cs | 2 +- .../requirement_result_validation_handlers.cs | 10 +-- .../Acceptance/result_types_end_to_end.cs | 24 +++--- .../saga_store_diagnostics_tests.cs | 14 ++-- .../CoreTests/Acceptance/service_tags_3240.cs | 4 +- .../Acceptance/simple_validation_handlers.cs | 24 +++--- .../Acceptance/sticky_message_handlers.cs | 4 +- .../Acceptance/streaming_handler_support.cs | 20 ++--- .../Acceptance/streaming_request_support.cs | 28 +++---- .../system_message_type_filtering.cs | 4 +- .../Acceptance/using_async_extensions.cs | 4 +- .../Acceptance/using_custom_side_effect.cs | 2 +- .../using_side_effect_as_return_values.cs | 2 +- .../Acceptance/wolverine_as_command_bus.cs | 14 ++-- .../Bugs/Bug_1182_infinite_loop_codegen.cs | 2 +- .../Bug_143_disambiguate_logger_variables.cs | 2 +- ...iguate_variables_from_multiple_handlers.cs | 2 +- .../Bugs/Bug_2004_separated_handler_stuff.cs | 2 +- ...2023_invoke_with_discard_error_handling.cs | 2 +- ...ng_generic_types_with_local_queue_names.cs | 2 +- ...going_messages_from_multiple_middleware.cs | 2 +- .../Bug_2471_codegen_without_connectivity.cs | 2 +- .../Bug_263_return_string_from_load_async.cs | 2 +- ...returning_string_from_middleware_method.cs | 2 +- ...scriptive_message_on_multiple_variables.cs | 2 +- ...96_mixed_lifetime_enumerable_dependency.cs | 4 +- ...with_same_name_bug_different_namespaces.cs | 2 +- .../Bug_3263_wire_tap_on_scheduled_send.cs | 4 +- .../Bug_3343_separated_handlers_no_loop.cs | 2 +- ...tched_message_separated_handler_codegen.cs | 4 +- ...concurrent_creation_of_command_handlers.cs | 2 +- .../Bugs/Bug_559_erroneous_failure_ack.cs | 2 +- ...isposing_disposable_or_async_disposable.cs | 2 +- .../Compilation/enumerable_dependencies.cs | 2 +- .../Compilation/handler_that_uses_ilogger.cs | 2 +- .../handler_with_optional_side_effect.cs | 4 +- .../Configuration/bootstrapping_specs.cs | 2 +- .../configuring_deliver_within_rules.cs | 4 +- .../configuring_idempotency_style.cs | 6 +- .../Configuration/configuring_middleware.cs | 2 +- .../disabling_all_external_transports.cs | 2 +- ...nt_health_connection_state_default_3231.cs | 2 +- .../environment_sensitive_configuration.cs | 8 +- ...enerated_code_output_path_configuration.cs | 4 +- .../handler_chain_customization_ordering.cs | 6 +- .../Configuration/missing_handler_behavior.cs | 8 +- .../receive_loop_health_default_3236.cs | 2 +- ...ered_application_assembly_reuse_warning.cs | 2 +- .../runtime_compilation_extension.cs | 4 +- .../using_solo_mode_as_override.cs | 2 +- .../Configuration/wire_tap_configuration.cs | 10 +-- src/Testing/CoreTests/CoreTests.csproj | 2 + .../WolverineDiagnosticsCommandTests.cs | 6 +- .../FaultPublishingPolicyResolveTests.cs | 2 +- .../Integration/FaultBypassTracingTests.cs | 8 +- .../FaultCryptoExceptionGuardTests.cs | 6 +- .../FaultEncryptionRoundTripTests.cs | 2 +- .../FaultRedactionIntegrationTests.cs | 4 +- .../PublishFaultEventsIntegrationTests.cs | 24 +++--- .../CoreTests/OutgoingMessagesTests.cs | 2 +- .../FileSystemClaimCheckStoreTests.cs | 12 +-- .../DynamicListenersDefaultsTests.cs | 6 +- ..._cascading_messages_with_separated_mode.cs | 4 +- ...ing_a_saga_with_separated_behavior_mode.cs | 2 +- ...ll_wolverine_storage_on_storeless_hosts.cs | 4 +- ...WolverineRuntimeListenerExtensionsTests.cs | 6 +- ...lth_check_uses_tenant_scoped_high_water.cs | 14 ++-- ...rtbeat_decoupled_from_command_execution.cs | 4 +- .../leader_election_self_visibility_tests.cs | 4 +- .../Runtime/Agents/parallel_drain_on_stop.cs | 6 +- .../Agents/pending_assignment_ledger.cs | 2 +- .../Runtime/Agents/scale_safe_batch_starts.cs | 4 +- .../Agents/solo_mode_health_check_tracing.cs | 4 +- .../Runtime/Handlers/HandlerGraphTests.cs | 8 +- .../concurrent_saga_chain_compilation.cs | 2 +- .../HeartbeatBackgroundServiceTests.cs | 6 +- .../Heartbeat/solo_storeless_node_identity.cs | 8 +- ...en_reading_and_writing_CloudEvents_data.cs | 2 +- .../ShardedExecutionBlockSmokeTests.cs | 2 +- ...al_partitioning_with_separated_handlers.cs | 2 +- ...ticky_handlers_with_global_partitioning.cs | 4 +- .../description_mode_routes_are_not_cached.cs | 2 +- .../Runtime/Routing/explain_routing.cs | 14 ++-- ...ssage_routed_skipped_during_description.cs | 2 +- .../Runtime/Routing/routing_rules.cs | 30 ++++---- .../Routing/separated_batch_routing.cs | 6 +- .../Encryption/CachingKeyProviderTests.cs | 52 ++++++------- .../Encryption/InMemoryKeyProviderTests.cs | 2 +- ...ageTypePoliciesEncryptFaultPairingTests.cs | 2 +- .../WolverineOptionsEncryptionTests.cs | 18 ++--- .../Runtime/Stubs/using_stubs_end_to_end.cs | 14 ++-- ...fered_receiver_null_listener_guard_3013.cs | 2 +- .../inline_receiver_drain_and_latch.cs | 42 +++++------ .../CoreTests/Runtime/envelope_pool_tests.cs | 2 +- .../Runtime/handler_type_activity_tagging.cs | 6 +- .../histogram_bucket_boundaries_3224.cs | 2 +- ...ource_migration_failure_mode_on_startup.cs | 2 +- .../service_location_message_context.cs | 8 +- .../Runtime/tracking_diagnostics_opt_in.cs | 32 ++++---- .../Runtime/using_wolverine_activators.cs | 2 +- .../WolverineRuntimeLimitsWireupTests.cs | 6 +- .../serialization_configuration.cs | 16 ++-- src/Testing/CoreTests/Shims/mediatr_usage.cs | 9 +-- .../CoreTests/TestMessageContextTests.cs | 66 +++++++---------- ...d_for_published_message_without_handler.cs | 2 +- .../Transports/Sending/BatchedSenderTests.cs | 2 +- .../Sending/SendingAgentDisposalTests.cs | 8 +- .../shared_memory_envelope_pooling_3015.cs | 4 +- .../background_receive_loop_3236.cs | 8 +- .../CoreTests/WolverineOptionsTests.cs | 2 +- .../CoreTests/critterstack_defaults_usage.cs | 10 +-- .../CoreTests/envelope_id_generation.cs | 7 +- .../respecting_jasper_fx_defaults.cs | 4 +- .../MessageRoutingTests.csproj | 2 + src/Testing/MetricsTests/MetricsTests.csproj | 2 + src/Testing/PolicyTests/PolicyTests.csproj | 2 + ...ant_partitioning_with_inferred_grouping.cs | 4 +- ...ug_concurrency_with_global_partitioning.cs | 14 ++-- src/Testing/SlowTests/RetryBlockTests.cs | 2 +- ...nvelope_is_stamped_before_serialization.cs | 2 +- src/Testing/SlowTests/SlowTests.csproj | 5 ++ .../SlowTests/delayed_message_end_to_end.cs | 2 +- .../dropped_messages_on_full_local_queue.cs | 2 +- .../SlowTests/in_memory_scheduled_messages.cs | 2 +- .../intrinsic_serialization_end_to_end.cs | 4 +- .../invoke_async_with_delivery_options.cs | 8 +- .../SlowTests/tracked_session_mechanics.cs | 12 +-- .../BehaviouralRunStep.cs | 4 +- .../CodegenWriteFSharpCli.cs | 6 +- .../Wolverine.Behavioural.FSharpTests.csproj | 2 + .../Wolverine.ComplianceTests.csproj | 2 + .../Wolverine.Core.FSharpTests.csproj | 2 + .../Wolverine.Cosmos.FSharpTests.csproj | 2 + .../Wolverine.EfCore.FSharpTests.csproj | 2 + .../Wolverine.Http.FSharpTests.csproj | 2 + .../Wolverine.Marten.FSharpTests.csproj | 2 + ...lverine.MartenAggregate.FSharpTests.csproj | 2 + .../Internal/AmazonSnsTopicTests.cs | 5 +- .../Wolverine.AmazonSns.Tests.csproj | 2 + .../bootstrapping.cs | 12 +-- .../end_to_end_with_named_broker.cs | 2 +- .../AmazonSqsPerTenantConnectionTests.cs | 4 +- .../BufferedSendingAndReceivingCompliance.cs | 2 +- .../Bugs/disabling_dead_letter_queue.cs | 6 +- .../DurableSendingAndReceivingCompliance.cs | 2 +- .../InlineSendingAndReceivingCompliance.cs | 2 +- .../Internal/AmazonSqsQueueTests.cs | 15 ++-- .../Samples/Bootstrapping.cs | 2 +- .../Wolverine.AmazonSqs.Tests.csproj | 2 + .../bootstrapping.cs | 18 ++--- ...oncurrency_resilient_sharded_processing.cs | 2 +- .../dead_letter_queue_recovery.cs | 2 +- .../default_dead_letter_queue_name.cs | 18 ++--- .../end_to_end_with_named_broker.cs | 2 +- .../global_partitioned_sharded_processing.cs | 2 +- .../BufferedSendingAndReceivingCompliance.cs | 2 +- ...rated_handlers_and_conventional_routing.cs | 2 +- ..._1933_multi_tenant_conventional_routing.cs | 4 +- .../Bug_2283_purge_session_subscription.cs | 4 +- .../AzureServiceBusSubscriptionTests.cs | 12 +-- .../Internal/AzureServiceBusTopicTests.cs | 4 +- .../Wolverine.AzureServiceBus.Tests.csproj | 2 + .../connection_state_3237.cs | 2 +- .../dead_letter_queue_recovery.cs | 2 +- .../end_to_end.cs | 2 +- .../end_to_end_with_named_broker.cs | 2 +- .../session_id_pinning.cs | 6 +- .../using_native_scheduling.cs | 20 ++--- .../PubsubPerTenantBrokerTests.cs | 6 +- .../Wolverine.Pubsub.Tests.csproj | 2 + .../connection_state_3237.cs | 4 +- .../send_and_receive.cs | 2 +- ...37_autoprovision_creates_missing_topics.cs | 2 +- .../KafkaPerTenantConfigurationTests.cs | 2 +- .../KafkaPerTenantConnectionTests.cs | 2 +- .../Wolverine.Kafka.Tests.csproj | 2 + .../cold_start_and_hot_tail.cs | 2 +- .../commit_strategy_end_to_end.cs | 4 +- .../configuration_precedence.cs | 2 +- .../connection_state_3454.cs | 6 +- .../disable_requeueing.cs | 2 +- ...te_message_handling_with_postgres_inbox.cs | 4 +- ...lobal_partitioned_aggregate_concurrency.cs | 8 +- .../global_partitioned_sharded_processing.cs | 2 +- .../Wolverine.Kafka.Tests/kafka_replay.cs | 10 +-- .../moving_unknown_cloudevents_type_to_dlq.cs | 6 +- .../next_generation_rebalance_protocol.cs | 4 +- .../publish_and_receive_raw_json.cs | 6 +- .../publish_raw_json_wire_format.cs | 8 +- .../raw_json_serializer_options.cs | 8 +- .../send_kafka_tombstone.cs | 2 +- ...ticky_handlers_with_global_partitioning.cs | 8 +- ..._not_using_default_serializer_correctly.cs | 2 +- .../Bug_mapper_exception_routes_to_dlq.cs | 6 +- .../Wolverine.MQTT.Tests.csproj | 2 + .../Wolverine.MQTT.Tests/ack_smoke_tests.cs | 4 +- .../MQTT/Wolverine.MQTT.Tests/connectivity.cs | 4 +- .../mqtt_per_tenant_broker_tests.cs | 2 +- .../named_broker_tests.cs | 4 +- ..._not_using_default_serializer_correctly.cs | 2 +- .../Bug_mapper_exception_routes_to_dlq.cs | 6 +- .../Wolverine.Mqtt5.Tests.csproj | 2 + .../Wolverine.Mqtt5.Tests/ack_smoke_tests.cs | 4 +- .../Wolverine.Mqtt5.Tests/connectivity.cs | 6 +- .../mqtt_per_tenant_broker_tests.cs | 2 +- .../named_broker_tests.cs | 4 +- .../NatsDynamicSubjectTenancyTests.cs | 2 +- .../NatsDynamicSubjectTests.cs | 8 +- .../NatsJetStreamConsumerFilterTests.cs | 12 +-- .../NatsJetStreamDedupTests.cs | 6 +- .../NatsNamedBrokerTests.cs | 4 +- .../NatsPerTenantConnectionTests.cs | 6 +- .../NatsTransportIntegrationTests.cs | 2 +- .../Wolverine.Nats.Tests/RequestReplyTests.cs | 6 +- .../Wolverine.Nats.Tests.csproj | 2 + .../connection_state_3231.cs | 2 +- .../PulsarListenerTests.cs | 8 +- .../PulsarNamedBrokerIntegrationTests.cs | 2 +- .../PulsarPerTenantConfigurationTests.cs | 2 +- .../PulsarPerTenantConnectionTests.cs | 2 +- .../Wolverine.Pulsar.Tests.csproj | 2 + .../acknowledgment_strategy.cs | 2 +- .../connection_state_3231.cs | 2 +- .../Wolverine.Pulsar.Tests/pulsar_hot_tail.cs | 2 +- .../Wolverine.Pulsar.Tests/pulsar_replay.cs | 10 +-- .../subscription_initial_position.cs | 2 +- .../RabbitMQ/ChaosTesting/ChaosTesting.csproj | 2 + .../CircuitBreakerIntegrationContext.cs | 2 +- .../CircuitBreakingTests.csproj | 2 + .../RabbitMq/back_pressure_tripping_off.cs | 2 +- .../stopping_and_starting_listeners.cs | 2 +- .../Bugs/Bug_1594_ReplayDeadLetterQueue.cs | 8 +- ...rated_handlers_and_conventional_routing.cs | 2 +- .../Bug_1716_weird_serialization_issue.cs | 4 +- ...Bug_1801_not_acking_on_consumer_failure.cs | 2 +- ...e_are_many_messages_in_queue_on_startup.cs | 8 +- .../Bugs/Bug_1921_order_of_operations.cs | 2 +- ..._2155_ancillary_store_inbox_persistence.cs | 2 +- .../Bug_2360_publish_with_require_response.cs | 10 +-- ..._2361_outbox_stuck_with_tenanted_broker.cs | 10 +-- .../Bugs/Bug_2944_interop_ancillary_inbox.cs | 2 +- ...Bug_3171_channel_only_shutdown_recovery.cs | 2 +- .../Bug_3391_callback_exception_restart.cs | 2 +- ...settling_a_delivery_from_a_dead_channel.cs | 2 +- ...475_durable_outbox_sending_out_of_order.cs | 4 +- ...nge_errorneously_used_for_system_queues.cs | 2 +- .../Bugs/Bug_DLQ_NotSavedToDatabase.cs | 20 ++--- .../Bug_mapper_exception_routes_to_dlq.cs | 4 +- .../Internals/RabbitMqExchangeTests.cs | 6 +- .../Internals/RabbitMqQueueTests.cs | 46 +++++------- .../RabbitMqBrokerHealthProbe_tests.cs | 2 +- .../RabbitMqExchangeBindingTests.cs | 9 +-- .../Wolverine.RabbitMQ.Tests.csproj | 2 + ...without_rabbit_mq_transport_initialized.cs | 2 +- .../cluster_endpoints.cs | 2 +- .../dead_letter_queue_recovery_listener.cs | 6 +- .../disable_external_listeners.cs | 2 +- ...ports_does_not_try_to_connect_to_rabbit.cs | 2 +- .../Wolverine.RabbitMQ.Tests/end_to_end.cs | 26 +++---- .../end_to_end_with_named_broker.cs | 4 +- .../endpoint_health_connection_state_3231.cs | 2 +- .../exclusive_listeners.cs | 2 +- ...om_external_to_separated_local_handlers.cs | 2 +- .../global_partitioned_sharded_processing.cs | 2 +- ...op_friendly_dead_letter_queue_mechanics.cs | 2 +- .../leader_pinned_listener.cs | 2 +- .../masstransit_interop_map_tenant_id.cs | 2 +- ...masstransit_interop_serializer_on_retry.cs | 2 +- .../multi_node_exclusive_listener_recovery.cs | 2 +- .../native_dead_letter_queue_mechanics.cs | 22 +++--- .../rate_limiting_end_to_end.cs | 24 +++--- ...scheduled_saga_timeout_preserves_tenant.cs | 6 +- .../sending_raw_messages.cs | 6 +- .../Wolverine.Redis.Tests/BasicPubSubTests.cs | 4 +- .../Bugs/Bug_1970_issue_with_scheduling.cs | 2 +- .../DatabaseBackedEndpointTests.cs | 16 ++-- .../DeadLetterQueueTests.cs | 6 +- .../NativeSchedulingRetryTests.cs | 4 +- .../NonDefaultDatabaseTests.cs | 4 +- .../RedisAutoClaimIntegrationTests.cs | 10 +-- .../RedisClaimingTests.cs | 6 +- .../RedisNamedBrokerTests.cs | 2 +- .../RedisPerTenantConnectionTests.cs | 2 +- .../Wolverine.Redis.Tests/RetryLimitTests.cs | 10 +-- .../ScheduledMessageIntegrationTests.cs | 16 ++-- .../ScheduledMessageTests.cs | 12 +-- .../StartFromBehaviorTests.cs | 20 ++--- .../Wolverine.Redis.Tests.csproj | 2 + .../connection_state_3231.cs | 2 +- .../redis_connection_source_configuration.cs | 10 +-- .../Wolverine.SignalR.Tests.csproj | 2 + .../Client/registration_tests.cs | 2 +- .../grpc_bidi_streaming_tests.cs | 28 +++---- .../grpc_client_streaming_tests.cs | 12 +-- .../middleware_scoping_fixture_smoke_tests.cs | 6 +- .../middleware_weaving_execution_tests.cs | 26 +++---- .../policy_leak_tests.cs | 10 +-- .../type_name_disambiguation_tests.cs | 6 +- .../grpc_validate_convention_tests.cs | 4 +- .../ProtoFirst/proto_first_grpc_tests.cs | 18 ++--- .../Wolverine.Grpc.Tests.csproj | 2 + .../code_first_grpc_tests.cs | 4 +- .../codegen_preview_grpc_tests.cs | 4 +- .../grpc_and_http_coexistence_3591.cs | 8 +- .../grpc_and_http_coexistence_3630.cs | 8 +- ...rpc_capabilities_descriptor_source_3267.cs | 2 +- .../grpc_endpoint_manifest_3235.cs | 4 +- .../grpc_service_manifest.cs | 2 +- .../inline_request_reply_grpc.cs | 2 +- .../EndToEndIntegrationTests.cs | 12 +-- .../Wolverine.HealthChecks.Tests.csproj | 2 + .../WolverineBusHealthCheckTests.cs | 8 +- .../WolverineListenerHealthCheckTests.cs | 14 ++-- 663 files changed, 2446 insertions(+), 2354 deletions(-) diff --git a/Directory.Build.props b/Directory.Build.props index 4ebe0a388..21736dd43 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -10,11 +10,7 @@ http://github.com/jasperfx/wolverine MIT net9.0;net10.0 - - 1570;1571;1572;1573;1574;1587;1591;1701;1702;1711;1735;0618;VSTHRD200;xUnit1051 + 1570;1571;1572;1573;1574;1587;1591;1701;1702;1711;1735;0618;VSTHRD200 true true enable diff --git a/Directory.Build.targets b/Directory.Build.targets index c442ae210..835073ce4 100644 --- a/Directory.Build.targets +++ b/Directory.Build.targets @@ -1,6 +1,25 @@ + + + $(NoWarn);xUnit1051 + + + true Exe false diff --git a/src/Extensions/Wolverine.DataAnnotationsValidation.Tests/configuration_specs.cs b/src/Extensions/Wolverine.DataAnnotationsValidation.Tests/configuration_specs.cs index 316113b9a..ea50afd72 100644 --- a/src/Extensions/Wolverine.DataAnnotationsValidation.Tests/configuration_specs.cs +++ b/src/Extensions/Wolverine.DataAnnotationsValidation.Tests/configuration_specs.cs @@ -19,7 +19,7 @@ public async Task add_the_default_services() .UseWolverine(opts => { opts.UseDataAnnotationsValidation(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); host.Services.GetRequiredService>() .ShouldBeOfType>(); @@ -32,7 +32,7 @@ public async Task place_or_not_place_the_middleware_correctly() .UseWolverine(opts => { opts.UseDataAnnotationsValidation(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var wolverineOptions = host.Services.GetRequiredService() .As().Options; diff --git a/src/Extensions/Wolverine.DataAnnotationsValidation.Tests/end_to_end.cs b/src/Extensions/Wolverine.DataAnnotationsValidation.Tests/end_to_end.cs index 0c5c1c8e3..351690316 100644 --- a/src/Extensions/Wolverine.DataAnnotationsValidation.Tests/end_to_end.cs +++ b/src/Extensions/Wolverine.DataAnnotationsValidation.Tests/end_to_end.cs @@ -13,7 +13,7 @@ public async Task invoke_happy_path_with_multiple_validators() .UseWolverine(opts => { opts.UseDataAnnotationsValidation(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var command = new Command1 { @@ -31,7 +31,7 @@ public async Task invoke_sad_path_with_multiple_validators() .UseWolverine(opts => { opts.UseDataAnnotationsValidation(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var command = new Command1 { @@ -48,7 +48,7 @@ public async Task invoke_happy_path_with_single_validator() .UseWolverine(opts => { opts.UseDataAnnotationsValidation(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var command = new Command2 { @@ -66,7 +66,7 @@ public async Task invoke_sad_path_with_single_validator() .UseWolverine(opts => { opts.UseDataAnnotationsValidation(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var command = new Command2 { @@ -83,7 +83,7 @@ public async Task invoke_sad_path_validator_with_async_rule() .UseWolverine(opts => { opts.UseDataAnnotationsValidation(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var command = new Command4 { @@ -91,7 +91,7 @@ public async Task invoke_sad_path_validator_with_async_rule() }; await Should.ThrowAsync(() => host.InvokeAsync(command)); - await host.StopAsync(); + await host.StopAsync(TestContext.Current.CancellationToken); } [Fact] @@ -101,7 +101,7 @@ public async Task invoke_happy_path_validator_with_async_rule() .UseWolverine(opts => { opts.UseDataAnnotationsValidation(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var command = new Command4 { @@ -109,6 +109,6 @@ public async Task invoke_happy_path_validator_with_async_rule() }; await Should.NotThrowAsync(() => host.InvokeAsync(command)); - await host.StopAsync(); + await host.StopAsync(TestContext.Current.CancellationToken); } } \ No newline at end of file diff --git a/src/Extensions/Wolverine.FluentValidation.Tests/Samples.cs b/src/Extensions/Wolverine.FluentValidation.Tests/Samples.cs index a8264d45f..a027a38d5 100644 --- a/src/Extensions/Wolverine.FluentValidation.Tests/Samples.cs +++ b/src/Extensions/Wolverine.FluentValidation.Tests/Samples.cs @@ -24,7 +24,7 @@ public async Task register_the_middleware() // Just a prerequisite for some of the test validators opts.Services.AddSingleton(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); #endregion } @@ -49,7 +49,7 @@ public async Task register_the_middleware_with_validator_options() // Just a prerequisite for some of the test validators opts.Services.AddSingleton(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); #endregion } @@ -70,7 +70,7 @@ public async Task register_the_middleware_with_override_failure_condition() // Just a prerequisite for some of the test validators opts.Services.AddSingleton(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); #endregion } diff --git a/src/Extensions/Wolverine.FluentValidation.Tests/Wolverine.FluentValidation.Tests.csproj b/src/Extensions/Wolverine.FluentValidation.Tests/Wolverine.FluentValidation.Tests.csproj index 9d01fae69..6368a5917 100644 --- a/src/Extensions/Wolverine.FluentValidation.Tests/Wolverine.FluentValidation.Tests.csproj +++ b/src/Extensions/Wolverine.FluentValidation.Tests/Wolverine.FluentValidation.Tests.csproj @@ -1,6 +1,8 @@ + + true Exe false diff --git a/src/Extensions/Wolverine.FluentValidation.Tests/configuration_specs.cs b/src/Extensions/Wolverine.FluentValidation.Tests/configuration_specs.cs index 5da268ef5..b04d075e2 100644 --- a/src/Extensions/Wolverine.FluentValidation.Tests/configuration_specs.cs +++ b/src/Extensions/Wolverine.FluentValidation.Tests/configuration_specs.cs @@ -34,7 +34,7 @@ public async Task register_validators_in_application_assembly() opts.UseFluentValidation(); opts.Services.AddScoped(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var container = host.Services.GetRequiredService(); @@ -55,7 +55,7 @@ public async Task add_the_default_services() opts.UseFluentValidation(); opts.Services.AddScoped(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); host.Services.GetRequiredService>() .ShouldBeOfType>(); @@ -70,7 +70,7 @@ public async Task place_or_not_place_the_middleware_correctly() opts.UseFluentValidation(); opts.Services.AddScoped(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var wolverineOptions = host.Services.GetRequiredService() .As().Options; @@ -110,7 +110,7 @@ public async Task configure_validator_options_via_action_overload() }); opts.Services.AddScoped(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); ValidatorOptions.Global.DefaultRuleLevelCascadeMode.ShouldBe(CascadeMode.Stop); ValidatorOptions.Global.DefaultClassLevelCascadeMode.ShouldBe(CascadeMode.Stop); @@ -129,7 +129,7 @@ public async Task configure_registration_behavior_via_action_overload() { fv.RegistrationBehavior = RegistrationBehavior.ExplicitRegistration; }); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var container = host.Services.GetRequiredService(); @@ -150,7 +150,7 @@ public async Task action_overload_still_applies_middleware() }); opts.Services.AddScoped(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var wolverineOptions = host.Services.GetRequiredService() .As().Options; @@ -177,7 +177,7 @@ public async Task discover_internal_validators_when_include_internal_types_is_tr }); opts.Services.AddScoped(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var container = host.Services.GetRequiredService(); @@ -196,7 +196,7 @@ public async Task do_not_discover_internal_validators_by_default() opts.UseFluentValidation(); opts.Services.AddScoped(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var container = host.Services.GetRequiredService(); @@ -216,7 +216,7 @@ public async Task discover_internal_validator_with_dependencies_as_scoped() }); opts.Services.AddScoped(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var container = host.Services.GetRequiredService(); diff --git a/src/Extensions/Wolverine.FluentValidation.Tests/end_to_end.cs b/src/Extensions/Wolverine.FluentValidation.Tests/end_to_end.cs index ebba5c5ba..941250c47 100644 --- a/src/Extensions/Wolverine.FluentValidation.Tests/end_to_end.cs +++ b/src/Extensions/Wolverine.FluentValidation.Tests/end_to_end.cs @@ -16,7 +16,7 @@ public async Task invoke_happy_path_with_multiple_validators() opts.UseFluentValidation(); opts.Services.AddScoped(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var command = new Command1 { @@ -36,7 +36,7 @@ public async Task invoke_sad_path_with_multiple_validators() opts.UseFluentValidation(); opts.Services.AddScoped(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var command = new Command1 { @@ -55,7 +55,7 @@ public async Task invoke_happy_path_with_single_validator() opts.UseFluentValidation(); opts.Services.AddScoped(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var command = new Command2 { @@ -75,7 +75,7 @@ public async Task invoke_sad_path_with_single_validator() opts.UseFluentValidation(); opts.Services.AddScoped(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var command = new Command2 { @@ -94,7 +94,7 @@ public async Task invoke_sad_path_validator_with_async_rule() opts.UseFluentValidation(); opts.Services.AddScoped(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var command = new Command4 { @@ -102,7 +102,7 @@ public async Task invoke_sad_path_validator_with_async_rule() }; await Should.ThrowAsync(() => host.InvokeAsync(command)); - await host.StopAsync(); + await host.StopAsync(TestContext.Current.CancellationToken); } [Fact] @@ -114,7 +114,7 @@ public async Task invoke_happy_path_validator_with_async_rule() opts.UseFluentValidation(); opts.Services.AddScoped(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var command = new Command4 { @@ -122,7 +122,7 @@ public async Task invoke_happy_path_validator_with_async_rule() }; await Should.NotThrowAsync(() => host.InvokeAsync(command)); - await host.StopAsync(); + await host.StopAsync(TestContext.Current.CancellationToken); } [Fact] @@ -134,7 +134,7 @@ public async Task invoke_sad_path_multiple_validators_with_async_rule() opts.UseFluentValidation(); opts.Services.AddScoped(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var command = new Command5 { @@ -143,7 +143,7 @@ public async Task invoke_sad_path_multiple_validators_with_async_rule() }; await Should.ThrowAsync(() => host.InvokeAsync(command)); - await host.StopAsync(); + await host.StopAsync(TestContext.Current.CancellationToken); } [Fact] @@ -155,7 +155,7 @@ public async Task invoke_happy_path_multiple_validators_with_async_rule() opts.UseFluentValidation(); opts.Services.AddScoped(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var command = new Command5 { @@ -164,6 +164,6 @@ public async Task invoke_happy_path_multiple_validators_with_async_rule() }; await Should.NotThrowAsync(() => host.InvokeAsync(command)); - await host.StopAsync(); + await host.StopAsync(TestContext.Current.CancellationToken); } } \ No newline at end of file diff --git a/src/Extensions/Wolverine.FluentValidation.Tests/internals_tests.cs b/src/Extensions/Wolverine.FluentValidation.Tests/internals_tests.cs index 68160cb55..64bc068b5 100644 --- a/src/Extensions/Wolverine.FluentValidation.Tests/internals_tests.cs +++ b/src/Extensions/Wolverine.FluentValidation.Tests/internals_tests.cs @@ -11,7 +11,7 @@ public async Task default_validation_action_throws_exception() var validator = new Command1Validator(); var command = new Command1(); - var result = await validator.ValidateAsync(command); + var result = await validator.ValidateAsync(command, TestContext.Current.CancellationToken); var ex = Should.Throw(() => { diff --git a/src/Extensions/Wolverine.MemoryPack.Tests/Wolverine.MemoryPack.Tests.csproj b/src/Extensions/Wolverine.MemoryPack.Tests/Wolverine.MemoryPack.Tests.csproj index 789abc94e..f2ebb91f4 100644 --- a/src/Extensions/Wolverine.MemoryPack.Tests/Wolverine.MemoryPack.Tests.csproj +++ b/src/Extensions/Wolverine.MemoryPack.Tests/Wolverine.MemoryPack.Tests.csproj @@ -1,6 +1,8 @@ + + true Exe false diff --git a/src/Extensions/Wolverine.MemoryPack.Tests/serialization_configuration.cs b/src/Extensions/Wolverine.MemoryPack.Tests/serialization_configuration.cs index d898ec265..eb91bab47 100644 --- a/src/Extensions/Wolverine.MemoryPack.Tests/serialization_configuration.cs +++ b/src/Extensions/Wolverine.MemoryPack.Tests/serialization_configuration.cs @@ -18,7 +18,7 @@ public async Task can_override_the_default_app_wide() opts.UseMemoryPackSerialization(); opts.PublishAllMessages().To("stub://one"); opts.ListenForMessagesFrom("stub://two"); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var root = host.Services.GetRequiredService(); root.Endpoints.EndpointFor("stub://one".ToUri()) @@ -36,7 +36,7 @@ public async Task can_override_the_serialization_on_just_one_endpoint() opts.PublishAllMessages().To("stub://one").UseMemoryPackSerialization(); opts.ListenForMessagesFrom("stub://two").UseMemoryPackSerialization(); opts.ListenForMessagesFrom("stub://three"); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var root = host.Services.GetRequiredService(); root.Endpoints.EndpointFor("stub://one".ToUri()) diff --git a/src/Extensions/Wolverine.MessagePack.Tests/Wolverine.MessagePack.Tests.csproj b/src/Extensions/Wolverine.MessagePack.Tests/Wolverine.MessagePack.Tests.csproj index 1cbc36506..90b9c4dda 100644 --- a/src/Extensions/Wolverine.MessagePack.Tests/Wolverine.MessagePack.Tests.csproj +++ b/src/Extensions/Wolverine.MessagePack.Tests/Wolverine.MessagePack.Tests.csproj @@ -1,6 +1,8 @@ + + true Exe false diff --git a/src/Extensions/Wolverine.MessagePack.Tests/serialization_configuration.cs b/src/Extensions/Wolverine.MessagePack.Tests/serialization_configuration.cs index b5f5b0f7f..d97907854 100644 --- a/src/Extensions/Wolverine.MessagePack.Tests/serialization_configuration.cs +++ b/src/Extensions/Wolverine.MessagePack.Tests/serialization_configuration.cs @@ -19,7 +19,7 @@ public async Task can_override_the_default_app_wide() opts.UseMessagePackSerialization(); opts.PublishAllMessages().To("stub://one"); opts.ListenForMessagesFrom("stub://two"); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var root = host.Services.GetRequiredService(); root.Endpoints.EndpointFor("stub://one".ToUri()) @@ -37,7 +37,7 @@ public async Task can_override_the_serialization_on_just_one_endpoint() opts.PublishAllMessages().To("stub://one").UseMessagePackSerialization(); opts.ListenForMessagesFrom("stub://two").UseMessagePackSerialization(); opts.ListenForMessagesFrom("stub://three"); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var root = host.Services.GetRequiredService(); root.Endpoints.EndpointFor("stub://one".ToUri()) diff --git a/src/Extensions/Wolverine.Protobuf.Tests/Wolverine.Protobuf.Tests.csproj b/src/Extensions/Wolverine.Protobuf.Tests/Wolverine.Protobuf.Tests.csproj index b8f92baf0..e001c967c 100644 --- a/src/Extensions/Wolverine.Protobuf.Tests/Wolverine.Protobuf.Tests.csproj +++ b/src/Extensions/Wolverine.Protobuf.Tests/Wolverine.Protobuf.Tests.csproj @@ -1,6 +1,8 @@ + + true Exe false diff --git a/src/Http/Wolverine.Http.AspVersioning.Tests/Wolverine.Http.AspVersioning.Tests.csproj b/src/Http/Wolverine.Http.AspVersioning.Tests/Wolverine.Http.AspVersioning.Tests.csproj index a6eb9f1dd..d09e78946 100644 --- a/src/Http/Wolverine.Http.AspVersioning.Tests/Wolverine.Http.AspVersioning.Tests.csproj +++ b/src/Http/Wolverine.Http.AspVersioning.Tests/Wolverine.Http.AspVersioning.Tests.csproj @@ -1,6 +1,8 @@  + + true Exe net10.0 false diff --git a/src/Http/Wolverine.Http.Tests/Bugs/Bug_1295_aggregate_handler_should_not_try_to_use_query_string.cs b/src/Http/Wolverine.Http.Tests/Bugs/Bug_1295_aggregate_handler_should_not_try_to_use_query_string.cs index 9db094915..eed9b238b 100644 --- a/src/Http/Wolverine.Http.Tests/Bugs/Bug_1295_aggregate_handler_should_not_try_to_use_query_string.cs +++ b/src/Http/Wolverine.Http.Tests/Bugs/Bug_1295_aggregate_handler_should_not_try_to_use_query_string.cs @@ -46,7 +46,7 @@ public async Task run_end_to_end() await using var session = host.DocumentStore().LightweightSession(); var streamKey = Guid.NewGuid().ToString(); session.Events.StartStream(streamKey, new TestEvent()); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await host.Scenario(x => { diff --git a/src/Http/Wolverine.Http.Tests/Bugs/Bug_2205_multiple_document_args.cs b/src/Http/Wolverine.Http.Tests/Bugs/Bug_2205_multiple_document_args.cs index 4752da3aa..baaf70e04 100644 --- a/src/Http/Wolverine.Http.Tests/Bugs/Bug_2205_multiple_document_args.cs +++ b/src/Http/Wolverine.Http.Tests/Bugs/Bug_2205_multiple_document_args.cs @@ -17,7 +17,7 @@ public async Task multiple_documents_should_return_both() await using var session = Store.LightweightSession(); session.Store(new Invoice { Id = invoiceId }); session.Store(new Receipt { Id = receiptId }); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); var result = await Scenario(x => { @@ -37,7 +37,7 @@ public async Task multiple_documents_returns_404_when_first_missing() await using var session = Store.LightweightSession(); session.Store(new Receipt { Id = receiptId }); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await Scenario(x => { @@ -53,7 +53,7 @@ public async Task multiple_documents_returns_404_when_second_missing() await using var session = Store.LightweightSession(); session.Store(new Invoice { Id = invoiceId }); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await Scenario(x => { @@ -71,7 +71,7 @@ public async Task document_and_aggregate_should_return_both() await using var session = Store.LightweightSession(); session.Store(new Invoice { Id = invoiceId }); session.Events.StartStream(orderId, new OrderCreated([new Item { Name = "Widget" }])); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); var result = await Scenario(x => { diff --git a/src/Http/Wolverine.Http.Tests/Bugs/Bug_281_erroneous_215.cs b/src/Http/Wolverine.Http.Tests/Bugs/Bug_281_erroneous_215.cs index fbce99c60..cd0c0e5b4 100644 --- a/src/Http/Wolverine.Http.Tests/Bugs/Bug_281_erroneous_215.cs +++ b/src/Http/Wolverine.Http.Tests/Bugs/Bug_281_erroneous_215.cs @@ -23,7 +23,7 @@ await Scenario(x => }); var client = Host.Server.CreateClient(); - var response = await client.PostAsJsonAsync("/users/sign-up", signUpRequest); + var response = await client.PostAsJsonAsync("/users/sign-up", signUpRequest, cancellationToken: TestContext.Current.CancellationToken); response.StatusCode.As().ShouldBe(204); } } \ No newline at end of file diff --git a/src/Http/Wolverine.Http.Tests/Bugs/Bug_608_using_route_variables_in_middleware_without_argument.cs b/src/Http/Wolverine.Http.Tests/Bugs/Bug_608_using_route_variables_in_middleware_without_argument.cs index 0d93e30d1..bfb2f9720 100644 --- a/src/Http/Wolverine.Http.Tests/Bugs/Bug_608_using_route_variables_in_middleware_without_argument.cs +++ b/src/Http/Wolverine.Http.Tests/Bugs/Bug_608_using_route_variables_in_middleware_without_argument.cs @@ -13,7 +13,7 @@ public async Task can_use_route_argument_in_middleware() { using var session = Store.LightweightSession(); session.Store(new SomeDocument{Id = "ball"}); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await Scenario(x => { diff --git a/src/Http/Wolverine.Http.Tests/Bugs/Bug_using_fromquery_with_aggregatehandler.cs b/src/Http/Wolverine.Http.Tests/Bugs/Bug_using_fromquery_with_aggregatehandler.cs index 2af5d5891..5d52e83d9 100644 --- a/src/Http/Wolverine.Http.Tests/Bugs/Bug_using_fromquery_with_aggregatehandler.cs +++ b/src/Http/Wolverine.Http.Tests/Bugs/Bug_using_fromquery_with_aggregatehandler.cs @@ -70,7 +70,7 @@ public async Task run_end_to_end() await using var session = host.DocumentStore().LightweightSession(); var aggregateId = Guid.NewGuid(); session.Events.StartStream(aggregateId, new FromQueryAggregateHandlerEvent(Guid.NewGuid(), "Something1")); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); var body = await host.Scenario(x => x.Get.Url("/getusingfromqueryandaggregatehandler?id=" + aggregateId +"&something=Something2")); diff --git a/src/Http/Wolverine.Http.Tests/Bugs/Bug_using_host_stop.cs b/src/Http/Wolverine.Http.Tests/Bugs/Bug_using_host_stop.cs index ff0cdf696..d1b96e5b1 100644 --- a/src/Http/Wolverine.Http.Tests/Bugs/Bug_using_host_stop.cs +++ b/src/Http/Wolverine.Http.Tests/Bugs/Bug_using_host_stop.cs @@ -33,7 +33,7 @@ public async Task wolverine_runtime_stops_when_host_is_stopped(HostType type) var checkPoints = new bool[2]; checkPoints[0] = IsRunning(wolverineRuntime); - await host.StopAsync(); + await host.StopAsync(TestContext.Current.CancellationToken); checkPoints[1] = IsRunning(wolverineRuntime); checkPoints.ShouldBe([true, false]); diff --git a/src/Http/Wolverine.Http.Tests/Marten/compiled_query_writer.cs b/src/Http/Wolverine.Http.Tests/Marten/compiled_query_writer.cs index f069ec4aa..91ee131ff 100644 --- a/src/Http/Wolverine.Http.Tests/Marten/compiled_query_writer.cs +++ b/src/Http/Wolverine.Http.Tests/Marten/compiled_query_writer.cs @@ -120,7 +120,7 @@ public async Task endpoint_returning_compiled_list_query_should_return_query_res session.Store(invoice); } - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); var approvedInvoiceList = await Host.GetAsJson>("/invoices/approved"); approvedInvoiceList.ShouldNotBeNull(); @@ -141,7 +141,7 @@ public async Task endpoint_returning_compiled_primitive_query_should_return_quer session.Store(invoice); } - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); var invoiceCountString = await Host.GetAsText("/invoices/compiled/count"); invoiceCountString.ShouldNotBeNull(); @@ -224,7 +224,7 @@ public async Task endpoint_returning_compiled_query_should_return_query_result() }; using var session = Store.LightweightSession(); session.Store(invoice); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); var invoiceCompiled = await Host.GetAsJson($"/invoices/compiled/{invoice.Id}"); diff --git a/src/Http/Wolverine.Http.Tests/Marten/document_attribute_usage.cs b/src/Http/Wolverine.Http.Tests/Marten/document_attribute_usage.cs index 205941cb3..bbb089cdf 100644 --- a/src/Http/Wolverine.Http.Tests/Marten/document_attribute_usage.cs +++ b/src/Http/Wolverine.Http.Tests/Marten/document_attribute_usage.cs @@ -28,10 +28,10 @@ public async Task returns_404_when_soft_deleted() var invoice = new Invoice(); using var session = Store.LightweightSession(); session.Store(invoice); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); session.Delete(invoice); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await Scenario(x => { @@ -46,7 +46,7 @@ public async Task default_to_id_route() var invoice = new Invoice(); using var session = Store.LightweightSession(); session.Store(invoice); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); var invoice2 = await Host.GetAsJson("/invoices/" + invoice.Id); @@ -59,7 +59,7 @@ public async Task try_to_use_document_name_id_naming_convention() var invoice = new Invoice(); using var session = Store.LightweightSession(); session.Store(invoice); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await Host.Scenario(x => { @@ -67,7 +67,7 @@ await Host.Scenario(x => x.StatusCodeShouldBe(204); }); - var loaded = await session.LoadAsync(invoice.Id); + var loaded = await session.LoadAsync(invoice.Id, TestContext.Current.CancellationToken); loaded!.Paid.ShouldBeTrue(); } @@ -77,7 +77,7 @@ public async Task use_explicit_path_argument() var invoice = new Invoice(); await using var session = Store.LightweightSession(); session.Store(invoice); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await Host.Scenario(x => { @@ -85,7 +85,7 @@ await Host.Scenario(x => x.StatusCodeShouldBe(204); }); - var loaded = await session.LoadAsync(invoice.Id); + var loaded = await session.LoadAsync(invoice.Id, TestContext.Current.CancellationToken); loaded!.Approved.ShouldBeTrue(); } } \ No newline at end of file diff --git a/src/Http/Wolverine.Http.Tests/Marten/message_publishing_with_entity_attribute_usage.cs b/src/Http/Wolverine.Http.Tests/Marten/message_publishing_with_entity_attribute_usage.cs index 30a9d1bd9..25cd6ba6d 100644 --- a/src/Http/Wolverine.Http.Tests/Marten/message_publishing_with_entity_attribute_usage.cs +++ b/src/Http/Wolverine.Http.Tests/Marten/message_publishing_with_entity_attribute_usage.cs @@ -17,7 +17,7 @@ public async Task call_with_completed_todo() var todo = new Todo2 { Id = Guid.NewGuid().ToString(), IsComplete = true}; using var session = Host.DocumentStore().LightweightSession(); session.Store(todo); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); var (tracked, response) = await TrackedHttpCall(x => { diff --git a/src/Http/Wolverine.Http.Tests/Marten/multi_tenanted_session_factory_without_wolverine.cs b/src/Http/Wolverine.Http.Tests/Marten/multi_tenanted_session_factory_without_wolverine.cs index 87cbec7fb..a3864b961 100644 --- a/src/Http/Wolverine.Http.Tests/Marten/multi_tenanted_session_factory_without_wolverine.cs +++ b/src/Http/Wolverine.Http.Tests/Marten/multi_tenanted_session_factory_without_wolverine.cs @@ -52,7 +52,7 @@ public async Task can_do_the_tenancy_detection() Number = 1 }); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); } // Store the green doc @@ -64,7 +64,7 @@ public async Task can_do_the_tenancy_detection() Number = 2 }); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); } var blueDoc = await host.GetAsJson("/color?tenant=blue"); @@ -117,7 +117,7 @@ public async Task can_do_the_tenancy_detection_with_custom_metadata() Number = 1 }); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); } // Store the green doc @@ -129,7 +129,7 @@ public async Task can_do_the_tenancy_detection_with_custom_metadata() Number = 2 }); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); } var blueDoc = await host.GetAsJson("/color?tenant=blue"); diff --git a/src/Http/Wolverine.Http.Tests/Marten/soft_deleted_attribute_usage.cs b/src/Http/Wolverine.Http.Tests/Marten/soft_deleted_attribute_usage.cs index 14fe44ced..76ba87063 100644 --- a/src/Http/Wolverine.Http.Tests/Marten/soft_deleted_attribute_usage.cs +++ b/src/Http/Wolverine.Http.Tests/Marten/soft_deleted_attribute_usage.cs @@ -23,7 +23,7 @@ await Scenario(x => using var session = Host.DocumentStore().LightweightSession(); var invoice = new Invoice(); session.Store(invoice); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); // second, a hit var response = await Scenario(x => diff --git a/src/Http/Wolverine.Http.Tests/Marten/streaming_endpoints.cs b/src/Http/Wolverine.Http.Tests/Marten/streaming_endpoints.cs index 9b2511cc7..c06dc654f 100644 --- a/src/Http/Wolverine.Http.Tests/Marten/streaming_endpoints.cs +++ b/src/Http/Wolverine.Http.Tests/Marten/streaming_endpoints.cs @@ -27,7 +27,7 @@ public async Task stream_one_returns_matching_document_as_json() await using (var session = Store.LightweightSession()) { session.Store(invoice); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); } var body = await Host.GetAsJson($"/streaming/invoice/{invoice.Id}"); @@ -44,7 +44,7 @@ public async Task stream_one_sets_content_type_and_status_on_hit() await using (var session = Store.LightweightSession()) { session.Store(invoice); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); } var result = await Host.Scenario(x => @@ -75,7 +75,7 @@ public async Task stream_one_respects_custom_on_found_status() await using (var session = Store.LightweightSession()) { session.Store(invoice); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); } await Host.Scenario(x => @@ -92,7 +92,7 @@ public async Task stream_one_respects_custom_content_type() await using (var session = Store.LightweightSession()) { session.Store(invoice); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); } await Host.Scenario(x => @@ -110,7 +110,7 @@ public async Task stream_one_emits_etag_header_by_default() await using (var session = Store.LightweightSession()) { session.Store(invoice); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); } var result = await Host.Scenario(x => @@ -129,7 +129,7 @@ public async Task stream_one_omits_etag_header_when_disabled() await using (var session = Store.LightweightSession()) { session.Store(invoice); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); } var result = await Host.Scenario(x => @@ -152,7 +152,7 @@ public async Task stream_many_returns_json_array() await using (var session = Store.LightweightSession()) { foreach (var id in ids) session.Store(new Invoice { Id = id, Approved = true }); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); } var body = await Host.GetAsJson>("/streaming/invoices/approved"); @@ -215,7 +215,7 @@ public async Task stream_paged_returns_paged_envelope() await using (var session = Store.LightweightSession()) { foreach (var id in ids) session.Store(new Invoice { Id = id }); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); } var result = await Host.Scenario(x => @@ -242,7 +242,7 @@ public async Task stream_paged_by_cursor_returns_items_and_next_cursor() await using (var session = Store.LightweightSession()) { foreach (var id in ids) session.Store(new Invoice { Id = id }); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); } var result = await Host.Scenario(x => diff --git a/src/Http/Wolverine.Http.Tests/Marten/strong_typed_identifiers.cs b/src/Http/Wolverine.Http.Tests/Marten/strong_typed_identifiers.cs index 9b797a95e..d77a7c95a 100644 --- a/src/Http/Wolverine.Http.Tests/Marten/strong_typed_identifiers.cs +++ b/src/Http/Wolverine.Http.Tests/Marten/strong_typed_identifiers.cs @@ -18,7 +18,7 @@ public async Task use_read_aggregate_by_itself() using var session = Host.DocumentStore().LightweightSession(); session.Events.StartStream(streamId, new AEvent(), new BEvent(), new CEvent(), new CEvent()); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); var result = await Scenario(x => { @@ -39,7 +39,7 @@ public async Task single_usage_of_write_aggregate() using var session = Host.DocumentStore().LightweightSession(); session.Events.StartStream(streamId, new AEvent(), new BEvent(), new CEvent(), new CEvent()); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await Scenario(x => { @@ -70,7 +70,7 @@ public async Task batch_query_usage_of_write_aggregate() session.Events.StartStream(stream2Id, new AEvent(), new BEvent(), new BEvent(), new AEvent()); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await Scenario(x => { @@ -78,10 +78,10 @@ await Scenario(x => x.StatusCodeShouldBe(204); }); - var aggregate1 = await session.Events.FetchLatest(stream1Id); + var aggregate1 = await session.Events.FetchLatest(stream1Id, TestContext.Current.CancellationToken); aggregate1!.BCount.ShouldBe(2); - var aggregate2 = await session.Events.FetchLatest(stream2Id); + var aggregate2 = await session.Events.FetchLatest(stream2Id, TestContext.Current.CancellationToken); aggregate2!.BCount.ShouldBe(3); } @@ -97,7 +97,7 @@ public async Task batch_query_with_both_read_and_write_aggregate() session.Events.StartStream(stream2Id, new AEvent(), new BEvent(), new BEvent(), new AEvent(), new DEvent()); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await Host.Scenario(x => { @@ -106,12 +106,12 @@ await Host.Scenario(x => x.StatusCodeShouldBe(204); }); - var aggregate1 = await session.Events.FetchLatest(stream1Id); + var aggregate1 = await session.Events.FetchLatest(stream1Id, TestContext.Current.CancellationToken); aggregate1!.BCount.ShouldBe(3); aggregate1.ACount.ShouldBe(3); aggregate1.DCount.ShouldBe(1); - var aggregate2 = await session.Events.FetchLatest(stream2Id); + var aggregate2 = await session.Events.FetchLatest(stream2Id, TestContext.Current.CancellationToken); aggregate2!.BCount.ShouldBe(2); } @@ -121,7 +121,7 @@ public async Task use_entity_or_document_attribute() var toy = new Toy { Id = ToyId.New(), Name = "My toy" }; using var session = Host.DocumentStore().LightweightSession(); session.Store(toy); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); var result = await Scenario(x => x.Get.Url("/toys/" + toy.Id.Value)); diff --git a/src/Http/Wolverine.Http.Tests/Marten/using_aggregate_handler_workflow.cs b/src/Http/Wolverine.Http.Tests/Marten/using_aggregate_handler_workflow.cs index ffc78d0c0..84d89fb1d 100644 --- a/src/Http/Wolverine.Http.Tests/Marten/using_aggregate_handler_workflow.cs +++ b/src/Http/Wolverine.Http.Tests/Marten/using_aggregate_handler_workflow.cs @@ -30,7 +30,7 @@ await Scenario(x => await using var session = Store.LightweightSession(); - var order = await session.Events.AggregateStreamAsync(status1.OrderId); + var order = await session.Events.AggregateStreamAsync(status1.OrderId, token: TestContext.Current.CancellationToken); order.ShouldNotBeNull(); order.Items["Socks"].Ready.ShouldBeTrue(); @@ -105,7 +105,7 @@ await Scenario(x => await using var session = Store.LightweightSession(); - var order = await session.Events.AggregateStreamAsync(id); + var order = await session.Events.AggregateStreamAsync(id, token: TestContext.Current.CancellationToken); order.ShouldNotBeNull(); order.Items["Socks"].Ready.ShouldBeTrue(); @@ -130,7 +130,7 @@ await Scenario(x => await using var session = Store.LightweightSession(); - var order = await session.Events.AggregateStreamAsync(status1.OrderId); + var order = await session.Events.AggregateStreamAsync(status1.OrderId, token: TestContext.Current.CancellationToken); order.ShouldNotBeNull(); order.Shipped.HasValue.ShouldBeTrue(); @@ -156,7 +156,7 @@ await Scenario(x => await using var session = Store.LightweightSession(); - var order = await session.Events.AggregateStreamAsync(status1.OrderId); + var order = await session.Events.AggregateStreamAsync(status1.OrderId, token: TestContext.Current.CancellationToken); order.ShouldNotBeNull(); order.Shipped.HasValue.ShouldBeTrue(); @@ -182,7 +182,7 @@ await Scenario(x => await using var session = Store.LightweightSession(); - var order = await session.Events.AggregateStreamAsync(status1.OrderId); + var order = await session.Events.AggregateStreamAsync(status1.OrderId, token: TestContext.Current.CancellationToken); order.ShouldNotBeNull(); order.Shipped.HasValue.ShouldBeTrue(); @@ -219,7 +219,7 @@ await Scenario(x => await using var session = Store.LightweightSession(); - var order = await session.Events.AggregateStreamAsync(status1.OrderId); + var order = await session.Events.AggregateStreamAsync(status1.OrderId, token: TestContext.Current.CancellationToken); order.ShouldNotBeNull(); order.Shipped.HasValue.ShouldBeTrue(); @@ -245,7 +245,7 @@ await Scenario(x => await using var session = Store.LightweightSession(); - var order = await session.Events.AggregateStreamAsync(status1.OrderId); + var order = await session.Events.AggregateStreamAsync(status1.OrderId, token: TestContext.Current.CancellationToken); order.ShouldNotBeNull(); order.Shipped.HasValue.ShouldBeTrue(); @@ -348,7 +348,7 @@ public async Task return_updated_aggregate_in_tuple() order.IsConfirmed.ShouldBeTrue(); using var session = Host.DocumentStore().LightweightSession(); - var stream = await session.Events.FetchStreamAsync(status.OrderId); + var stream = await session.Events.FetchStreamAsync(status.OrderId, token: TestContext.Current.CancellationToken); stream.Select(x => x.Data).OfType().Any().ShouldBeFalse(); } diff --git a/src/Http/Wolverine.Http.Tests/Marten/using_ancillary_stores.cs b/src/Http/Wolverine.Http.Tests/Marten/using_ancillary_stores.cs index ac43d094a..dc43c59a2 100644 --- a/src/Http/Wolverine.Http.Tests/Marten/using_ancillary_stores.cs +++ b/src/Http/Wolverine.Http.Tests/Marten/using_ancillary_stores.cs @@ -26,7 +26,7 @@ public async Task create_new_thing_with_different_identity() var store = Host.DocumentStore(); using var session = store.LightweightSession(); - var thing = await session.Events.FetchLatest(response.Id); + var thing = await session.Events.FetchLatest(response.Id, TestContext.Current.CancellationToken); thing.ShouldNotBeNull(); } } \ No newline at end of file diff --git a/src/Http/Wolverine.Http.Tests/Marten/using_version_source_override.cs b/src/Http/Wolverine.Http.Tests/Marten/using_version_source_override.cs index 7ae0b44a9..230731bf5 100644 --- a/src/Http/Wolverine.Http.Tests/Marten/using_version_source_override.cs +++ b/src/Http/Wolverine.Http.Tests/Marten/using_version_source_override.cs @@ -32,7 +32,7 @@ await Scenario(x => }); await using var session = Store.LightweightSession(); - var order = await session.Events.AggregateStreamAsync(orderId); + var order = await session.Events.AggregateStreamAsync(orderId, token: TestContext.Current.CancellationToken); order.ShouldNotBeNull(); order.Shipped.HasValue.ShouldBeTrue(); } @@ -64,7 +64,7 @@ await Scenario(x => }); await using var session = Store.LightweightSession(); - var order = await session.Events.AggregateStreamAsync(orderId); + var order = await session.Events.AggregateStreamAsync(orderId, token: TestContext.Current.CancellationToken); order.ShouldNotBeNull(); order.Shipped.HasValue.ShouldBeTrue(); } diff --git a/src/Http/Wolverine.Http.Tests/Marten/write_aggregate_with_asparameters.cs b/src/Http/Wolverine.Http.Tests/Marten/write_aggregate_with_asparameters.cs index cfe4c7238..f00bc023b 100644 --- a/src/Http/Wolverine.Http.Tests/Marten/write_aggregate_with_asparameters.cs +++ b/src/Http/Wolverine.Http.Tests/Marten/write_aggregate_with_asparameters.cs @@ -32,7 +32,7 @@ await Scenario(x => // The OrderShipped event was appended to the resolved stream using var session = Store.LightweightSession(); - var order = await session.Events.AggregateStreamAsync(id); + var order = await session.Events.AggregateStreamAsync(id, token: TestContext.Current.CancellationToken); order!.IsShipped().ShouldBeTrue(); } } diff --git a/src/Http/Wolverine.Http.Tests/MultiTenancy/multi_tenancy_detection_and_integration.cs b/src/Http/Wolverine.Http.Tests/MultiTenancy/multi_tenancy_detection_and_integration.cs index af607a48c..57ac254bd 100644 --- a/src/Http/Wolverine.Http.Tests/MultiTenancy/multi_tenancy_detection_and_integration.cs +++ b/src/Http/Wolverine.Http.Tests/MultiTenancy/multi_tenancy_detection_and_integration.cs @@ -300,7 +300,7 @@ await configure(opts => await theHost.Services.GetRequiredService().Advanced.Clean - .DeleteDocumentsByTypeAsync(typeof(TenantTodo)); + .DeleteDocumentsByTypeAsync(typeof(TenantTodo), TestContext.Current.CancellationToken); // Create todo to "red" await theHost.Scenario(x => diff --git a/src/Http/Wolverine.Http.Tests/Transport/HttpScheduledMessageTests.cs b/src/Http/Wolverine.Http.Tests/Transport/HttpScheduledMessageTests.cs index a8c4ccdda..8bbb409a9 100644 --- a/src/Http/Wolverine.Http.Tests/Transport/HttpScheduledMessageTests.cs +++ b/src/Http/Wolverine.Http.Tests/Transport/HttpScheduledMessageTests.cs @@ -63,7 +63,7 @@ public async Task should_delay_execution_of_scheduled_message() await bus.ScheduleAsync(command, scheduledTime); } - await Task.Delay(500); // some delay for batching + await Task.Delay(500, TestContext.Current.CancellationToken); // some delay for batching tracker.ReceivedMessages.Count.ShouldBe(count); } } diff --git a/src/Http/Wolverine.Http.Tests/Transport/HttpTransportConfigurationTests.cs b/src/Http/Wolverine.Http.Tests/Transport/HttpTransportConfigurationTests.cs index 65afad9cf..f973bb9ee 100644 --- a/src/Http/Wolverine.Http.Tests/Transport/HttpTransportConfigurationTests.cs +++ b/src/Http/Wolverine.Http.Tests/Transport/HttpTransportConfigurationTests.cs @@ -20,7 +20,7 @@ public async Task to_http_endpoint_creates_endpoint_with_correct_uri() opts.PublishAllMessages() .ToHttpEndpoint("https://external-service.com/api"); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.GetRuntime(); var transport = runtime.Options.Transports.GetOrCreate(); @@ -39,7 +39,7 @@ public async Task to_http_endpoint_with_native_scheduled_send_sets_flag() opts.PublishAllMessages() .ToHttpEndpoint("https://scheduler.com/api", supportsNativeScheduledSend: true); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.GetRuntime(); var transport = runtime.Options.Transports.GetOrCreate(); @@ -57,7 +57,7 @@ public async Task to_http_endpoint_without_native_scheduled_send_defaults_to_fal opts.PublishAllMessages() .ToHttpEndpoint("https://regular.com/api"); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.GetRuntime(); var transport = runtime.Options.Transports.GetOrCreate(); @@ -83,7 +83,7 @@ public async Task to_http_endpoint_with_cloud_events_sets_serializer_options() useCloudEvents: true, options: customOptions); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.GetRuntime(); var transport = runtime.Options.Transports.GetOrCreate(); @@ -104,7 +104,7 @@ public async Task to_http_endpoint_without_cloud_events_keeps_default_options() opts.PublishAllMessages() .ToHttpEndpoint("https://binary.com/api"); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); #endregion @@ -128,7 +128,7 @@ public async Task to_http_endpoint_returns_subscriber_configuration() config.ShouldBeOfType(); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); } [Fact] @@ -142,7 +142,7 @@ public async Task can_chain_subscriber_configuration_methods() .SendInline() .CustomizeOutgoing(e => e.CorrelationId = "test-correlation"); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.GetRuntime(); var transport = runtime.Options.Transports.GetOrCreate(); diff --git a/src/Http/Wolverine.Http.Tests/Transport/inline_request_reply_sender.cs b/src/Http/Wolverine.Http.Tests/Transport/inline_request_reply_sender.cs index 197d84834..faf44953e 100644 --- a/src/Http/Wolverine.Http.Tests/Transport/inline_request_reply_sender.cs +++ b/src/Http/Wolverine.Http.Tests/Transport/inline_request_reply_sender.cs @@ -35,9 +35,9 @@ private static IHostBuilder ConfigureSender(IWolverineHttpTransportClient client [Fact] public async Task invoke_reads_reply_from_the_http_response_slot() { - using var host = await ConfigureSender(new EchoingInlineClient()).StartAsync(); + using var host = await ConfigureSender(new EchoingInlineClient()).StartAsync(cancellationToken: TestContext.Current.CancellationToken); - var response = await host.MessageBus().InvokeAsync(new InlineProbeRequest("Egwene")); + var response = await host.MessageBus().InvokeAsync(new InlineProbeRequest("Egwene"), TestContext.Current.CancellationToken); response.ShouldNotBeNull(); response.Name.ShouldBe("Egwene"); @@ -46,7 +46,7 @@ public async Task invoke_reads_reply_from_the_http_response_slot() [Fact] public async Task handler_failure_surfaces_as_request_reply_exception() { - using var host = await ConfigureSender(new FailingInlineClient()).StartAsync(); + using var host = await ConfigureSender(new FailingInlineClient()).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var ex = await Should.ThrowAsync(async () => await host.MessageBus().InvokeAsync(new InlineProbeRequest("Nynaeve"))); diff --git a/src/Http/Wolverine.Http.Tests/Wolverine.Http.Tests.csproj b/src/Http/Wolverine.Http.Tests/Wolverine.Http.Tests.csproj index dea0721a5..57862e216 100644 --- a/src/Http/Wolverine.Http.Tests/Wolverine.Http.Tests.csproj +++ b/src/Http/Wolverine.Http.Tests/Wolverine.Http.Tests.csproj @@ -1,6 +1,8 @@ + + true Exe false net9.0 diff --git a/src/Http/Wolverine.Http.Tests/accepts_content_type_negative_cases_3649.cs b/src/Http/Wolverine.Http.Tests/accepts_content_type_negative_cases_3649.cs index f4481fe9e..dffa2797b 100644 --- a/src/Http/Wolverine.Http.Tests/accepts_content_type_negative_cases_3649.cs +++ b/src/Http/Wolverine.Http.Tests/accepts_content_type_negative_cases_3649.cs @@ -145,7 +145,7 @@ public async Task a_method_mismatch_is_still_405_not_415() // GET /content-negotiation/items carries no Content-Type, so the 415 substitution must not swallow the // 405 that HttpMethodMatcherPolicy (Order 0) has already decided on. The policy only records candidates // that were valid when it saw them, which is what keeps these two apart. - var response = await Host.Server.CreateClient().GetAsync("/content-negotiation/items"); + var response = await Host.Server.CreateClient().GetAsync("/content-negotiation/items", TestContext.Current.CancellationToken); response.StatusCode.ShouldBe(HttpStatusCode.MethodNotAllowed); } diff --git a/src/Http/Wolverine.Http.Tests/api_explorer_before_host_start.cs b/src/Http/Wolverine.Http.Tests/api_explorer_before_host_start.cs index bc1fc382b..c7132c205 100644 --- a/src/Http/Wolverine.Http.Tests/api_explorer_before_host_start.cs +++ b/src/Http/Wolverine.Http.Tests/api_explorer_before_host_start.cs @@ -72,7 +72,7 @@ public async Task publishing_endpoints_early_does_not_duplicate_them_when_the_ho // Forces the early publish, exactly as a build-time OpenAPI read or a monitoring snapshot would readDescriptions(app).ShouldNotBeEmpty(); - await app.StartAsync(); + await app.StartAsync(TestContext.Current.CancellationToken); var routes = app.Services.GetRequiredService().Endpoints .OfType() @@ -84,9 +84,9 @@ public async Task publishing_endpoints_early_does_not_duplicate_them_when_the_ho // The proof that matters: an ambiguous match would throw here rather than answer var client = app.GetTestServer().CreateClient(); - (await client.GetAsync("/minimal/hello")).EnsureSuccessStatusCode(); + (await client.GetAsync("/minimal/hello", TestContext.Current.CancellationToken)).EnsureSuccessStatusCode(); - await app.StopAsync(); + await app.StopAsync(TestContext.Current.CancellationToken); } // Endpoints are only ever published from the application's root route builder. MapWolverineEndpoints() @@ -103,7 +103,7 @@ public async Task wolverine_endpoints_mapped_into_a_route_group_are_registered_e // Forces the publish, exactly as a build-time OpenAPI read or a monitoring snapshot would readDescriptions(app).ShouldNotBeEmpty(); - await app.StartAsync(); + await app.StartAsync(TestContext.Current.CancellationToken); var routes = app.Services.GetRequiredService().Endpoints .OfType() @@ -113,7 +113,7 @@ public async Task wolverine_endpoints_mapped_into_a_route_group_are_registered_e routes.Count(x => x == "/api/validate2/customer").ShouldBe(1); routes.ShouldNotContain("/validate2/customer"); - await app.StopAsync(); + await app.StopAsync(TestContext.Current.CancellationToken); } // Wolverine reaches RouteOptions.EndpointDataSources — internal to Microsoft.AspNetCore.Routing — diff --git a/src/Http/Wolverine.Http.Tests/building_a_saga_and_publishing_other_messages_from_http_endpoint.cs b/src/Http/Wolverine.Http.Tests/building_a_saga_and_publishing_other_messages_from_http_endpoint.cs index ae3675416..8d7bbc42b 100644 --- a/src/Http/Wolverine.Http.Tests/building_a_saga_and_publishing_other_messages_from_http_endpoint.cs +++ b/src/Http/Wolverine.Http.Tests/building_a_saga_and_publishing_other_messages_from_http_endpoint.cs @@ -15,7 +15,7 @@ public building_a_saga_and_publishing_other_messages_from_http_endpoint(AppFixtu public async Task can_create_saga_and_publish_message() { await Host.GetRuntime().Storage.Admin.ClearAllAsync(); - await Store.Advanced.Clean.DeleteDocumentsByTypeAsync(typeof(Reservation)); + await Store.Advanced.Clean.DeleteDocumentsByTypeAsync(typeof(Reservation), TestContext.Current.CancellationToken); IScenarioResult result = null!; @@ -34,7 +34,7 @@ await Host .ExecuteAndWaitAsync(action); using var session = Store.LightweightSession(); - var reservation = await session.LoadAsync("dinner"); + var reservation = await session.LoadAsync("dinner", TestContext.Current.CancellationToken); reservation.ShouldNotBeNull(); var @event = await result.ReadAsJsonAsync(); diff --git a/src/Http/Wolverine.Http.Tests/from_form_file_binding.cs b/src/Http/Wolverine.Http.Tests/from_form_file_binding.cs index f699b6895..a58abee90 100644 --- a/src/Http/Wolverine.Http.Tests/from_form_file_binding.cs +++ b/src/Http/Wolverine.Http.Tests/from_form_file_binding.cs @@ -16,8 +16,8 @@ public async Task bind_single_file_on_complex_model() content.Add(new StringContent("test-name"), "Name"); content.Add(new ByteArrayContent(new byte[] { 1, 2, 3 }), "File", "test.txt"); - var response = await Host.Server.CreateClient().PostAsync("/api/fromform-file", content); - var text = await response.Content.ReadAsStringAsync(); + var response = await Host.Server.CreateClient().PostAsync("/api/fromform-file", content, TestContext.Current.CancellationToken); + var text = await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken); response.EnsureSuccessStatusCode(); text.ShouldBe("test-name|test.txt|3"); } @@ -30,9 +30,9 @@ public async Task bind_file_collection_on_complex_model() content.Add(new ByteArrayContent(new byte[] { 1, 2, 3 }), "Files", "file1.txt"); content.Add(new ByteArrayContent(new byte[] { 4, 5 }), "Files", "file2.txt"); - var response = await Host.Server.CreateClient().PostAsync("/api/fromform-files", content); + var response = await Host.Server.CreateClient().PostAsync("/api/fromform-files", content, TestContext.Current.CancellationToken); response.EnsureSuccessStatusCode(); - var text = await response.Content.ReadAsStringAsync(); + var text = await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken); text.ShouldBe("test-name|2"); } @@ -42,9 +42,9 @@ public async Task bind_file_on_complex_model_when_no_file_sent() var content = new MultipartFormDataContent(); content.Add(new StringContent("test-name"), "Name"); - var response = await Host.Server.CreateClient().PostAsync("/api/fromform-file", content); + var response = await Host.Server.CreateClient().PostAsync("/api/fromform-file", content, TestContext.Current.CancellationToken); response.EnsureSuccessStatusCode(); - var text = await response.Content.ReadAsStringAsync(); + var text = await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken); text.ShouldBe("test-name||"); } @@ -55,9 +55,9 @@ public async Task bind_multiple_named_files() content.Add(new ByteArrayContent(new byte[] { 1, 2, 3 }), "document", "doc.pdf"); content.Add(new ByteArrayContent(new byte[] { 4, 5 }), "thumbnail", "thumb.jpg"); - var response = await Host.Server.CreateClient().PostAsync("/upload/named-files", content); + var response = await Host.Server.CreateClient().PostAsync("/upload/named-files", content, TestContext.Current.CancellationToken); response.EnsureSuccessStatusCode(); - var text = await response.Content.ReadAsStringAsync(); + var text = await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken); text.ShouldBe("doc.pdf|3|thumb.jpg|2"); } @@ -69,9 +69,9 @@ public async Task bind_fromform_complex_type_with_separate_file() content.Add(new StringContent("A description"), "Description"); content.Add(new ByteArrayContent(new byte[] { 1, 2, 3 }), "file", "test.pdf"); - var response = await Host.Server.CreateClient().PostAsync("/upload/mixed", content); + var response = await Host.Server.CreateClient().PostAsync("/upload/mixed", content, TestContext.Current.CancellationToken); response.EnsureSuccessStatusCode(); - var text = await response.Content.ReadAsStringAsync(); + var text = await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken); text.ShouldBe("My Document|A description|test.pdf|3"); } @@ -83,9 +83,9 @@ public async Task bind_iform_collection() content.Add(new StringContent("value2"), "key2"); content.Add(new ByteArrayContent(new byte[] { 1 }), "file", "test.txt"); - var response = await Host.Server.CreateClient().PostAsync("/upload/form-collection", content); + var response = await Host.Server.CreateClient().PostAsync("/upload/form-collection", content, TestContext.Current.CancellationToken); response.EnsureSuccessStatusCode(); - var text = await response.Content.ReadAsStringAsync(); + var text = await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken); text.ShouldBe("keys:key1,key2|files:1"); } } diff --git a/src/Http/Wolverine.Http.Tests/query_verb_support.cs b/src/Http/Wolverine.Http.Tests/query_verb_support.cs index e5150da11..b0bb9f191 100644 --- a/src/Http/Wolverine.Http.Tests/query_verb_support.cs +++ b/src/Http/Wolverine.Http.Tests/query_verb_support.cs @@ -28,10 +28,10 @@ public async Task query_endpoint_reads_request_body_and_returns_result() Content = JsonContent.Create(new SearchRequest("widget", 3)) }; - var response = await client.SendAsync(request); + var response = await client.SendAsync(request, TestContext.Current.CancellationToken); response.StatusCode.ShouldBe(HttpStatusCode.OK); - var results = await response.Content.ReadFromJsonAsync(); + var results = await response.Content.ReadFromJsonAsync(cancellationToken: TestContext.Current.CancellationToken); results.ShouldNotBeNull(); results.Term.ShouldBe("widget"); results.Page.ShouldBe(3); diff --git a/src/Http/Wolverine.Http.Tests/todo_endpoint_specs.cs b/src/Http/Wolverine.Http.Tests/todo_endpoint_specs.cs index 93c2f30b8..caf850018 100644 --- a/src/Http/Wolverine.Http.Tests/todo_endpoint_specs.cs +++ b/src/Http/Wolverine.Http.Tests/todo_endpoint_specs.cs @@ -22,7 +22,7 @@ public async Task wolverine_can_handle_route_constraints(string baseUrl) await using var session = Store.LightweightSession(); var todo = new Todo { Name = "First", IsComplete = false }; session.Store(todo); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await Scenario(opts => { @@ -30,7 +30,7 @@ await Scenario(opts => opts.StatusCodeShouldBe(204); }); - var changes = await session.LoadAsync(todo.Id); + var changes = await session.LoadAsync(todo.Id, TestContext.Current.CancellationToken); changes!.IsComplete.ShouldBeTrue(); changes.Name.ShouldBe("Second"); } @@ -41,14 +41,14 @@ public async Task bug_466_codegen_error() await using var session = Store.LightweightSession(); var todo = new Todo { Name = "First", IsComplete = false }; session.Store(todo); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await Scenario(opts => { opts.Put.Json(new UpdateRequest("Second", true)).ToUrl("/todos2/" + todo.Id); }); - var changes = await session.LoadAsync(todo.Id); + var changes = await session.LoadAsync(todo.Id, TestContext.Current.CancellationToken); changes!.IsComplete.ShouldBeTrue(); changes.Name.ShouldBe("Second"); } diff --git a/src/Http/Wolverine.Http.Tests/using_create_response_and_metadata_derived_from_response_type.cs b/src/Http/Wolverine.Http.Tests/using_create_response_and_metadata_derived_from_response_type.cs index 76e5b63ed..17410c9db 100644 --- a/src/Http/Wolverine.Http.Tests/using_create_response_and_metadata_derived_from_response_type.cs +++ b/src/Http/Wolverine.Http.Tests/using_create_response_and_metadata_derived_from_response_type.cs @@ -36,7 +36,7 @@ public void read_metadata_from_IEndpointMetadataProvider() [Fact] public async Task make_the_request() { - await Store.Advanced.Clean.DeleteDocumentsByTypeAsync(typeof(Issue)); + await Store.Advanced.Clean.DeleteDocumentsByTypeAsync(typeof(Issue), TestContext.Current.CancellationToken); var result = await Scenario(x => { @@ -48,7 +48,7 @@ public async Task make_the_request() created.ShouldNotBeNull(); using var session = Store.LightweightSession(); - var issue = await session.LoadAsync(created.Id); + var issue = await session.LoadAsync(created.Id, TestContext.Current.CancellationToken); issue.ShouldNotBeNull(); issue.Title.ShouldBe("It's bad"); diff --git a/src/Http/Wolverine.Http.Tests/using_efcore.cs b/src/Http/Wolverine.Http.Tests/using_efcore.cs index 53c70c7b9..f3566774e 100644 --- a/src/Http/Wolverine.Http.Tests/using_efcore.cs +++ b/src/Http/Wolverine.Http.Tests/using_efcore.cs @@ -35,7 +35,7 @@ await Scenario(x => using var nested = Host.Services.CreateScope(); var context = nested.ServiceProvider.GetRequiredService(); - var item = await context.Items.Where(x => x.Name == command.Name).FirstOrDefaultAsync(); + var item = await context.Items.Where(x => x.Name == command.Name).FirstOrDefaultAsync(cancellationToken: TestContext.Current.CancellationToken); item.ShouldNotBeNull(); } @@ -55,7 +55,7 @@ public async Task using_db_context_with_outbox() using var nested = Host.Services.CreateScope(); var context = nested.ServiceProvider.GetRequiredService(); - var item = await context.Items.Where(x => x.Name == command.Name).FirstOrDefaultAsync(); + var item = await context.Items.Where(x => x.Name == command.Name).FirstOrDefaultAsync(cancellationToken: TestContext.Current.CancellationToken); item.ShouldNotBeNull(); tracked.Sent.SingleMessage() @@ -100,7 +100,7 @@ public async Task using_db_context_with_outbox_schedule() using var nested = Host.Services.CreateScope(); var context = nested.ServiceProvider.GetRequiredService(); - var item = await context.Items.Where(x => x.Name == command.Name).FirstOrDefaultAsync(); + var item = await context.Items.Where(x => x.Name == command.Name).FirstOrDefaultAsync(cancellationToken: TestContext.Current.CancellationToken); item.ShouldBeNull(); var records = tracked.AllRecordsInOrder().ToArray(); @@ -126,7 +126,7 @@ public async Task using_db_context_with_outbox_schedule2() using var nested = Host.Services.CreateScope(); var context = nested.ServiceProvider.GetRequiredService(); - var item = await context.Items.Where(x => x.Name == command.Name).FirstOrDefaultAsync(); + var item = await context.Items.Where(x => x.Name == command.Name).FirstOrDefaultAsync(cancellationToken: TestContext.Current.CancellationToken); item.ShouldBeNull(); var scheduledMessage = tracked.Scheduled.SingleEnvelope(); diff --git a/src/Http/Wolverine.Http.Tests/using_marten.cs b/src/Http/Wolverine.Http.Tests/using_marten.cs index e2ed47ec7..bc1fd3224 100644 --- a/src/Http/Wolverine.Http.Tests/using_marten.cs +++ b/src/Http/Wolverine.Http.Tests/using_marten.cs @@ -18,7 +18,7 @@ public async Task use_marten_document_session_without_outbox() using (var session = Store.LightweightSession()) { session.Store(data); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); } var result = await Host.GetAsJson($"/data/{data.Id}"); @@ -42,7 +42,7 @@ public async Task use_marten_document_session_with_outbox() published.Name.ShouldBe(input.Name); using var session = Store.LightweightSession(); - var loaded = await session.LoadAsync(input.Id); + var loaded = await session.LoadAsync(input.Id, TestContext.Current.CancellationToken); loaded.ShouldNotBeNull(); } diff --git a/src/Persistence/CosmosDbTests/CosmosDbTests.csproj b/src/Persistence/CosmosDbTests/CosmosDbTests.csproj index 883522e96..85cc1c48b 100644 --- a/src/Persistence/CosmosDbTests/CosmosDbTests.csproj +++ b/src/Persistence/CosmosDbTests/CosmosDbTests.csproj @@ -1,6 +1,8 @@ + + true Exe net9.0 enable diff --git a/src/Persistence/CosmosDbTests/end_to_end.cs b/src/Persistence/CosmosDbTests/end_to_end.cs index 8dddea92b..b0361842c 100644 --- a/src/Persistence/CosmosDbTests/end_to_end.cs +++ b/src/Persistence/CosmosDbTests/end_to_end.cs @@ -29,7 +29,7 @@ public async Task can_send_and_receive_messages() opts.UseCosmosDbPersistence(AppFixture.DatabaseName); opts.Services.AddSingleton(_fixture.Client); opts.Discovery.IncludeAssembly(GetType().Assembly); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var tracked = await host.InvokeMessageAndWaitAsync(new SmokeTestMessage("Hello, CosmosDb!")); diff --git a/src/Persistence/CosmosDbTests/saga_optimistic_concurrency.cs b/src/Persistence/CosmosDbTests/saga_optimistic_concurrency.cs index 66b8228e0..5e33369b6 100644 --- a/src/Persistence/CosmosDbTests/saga_optimistic_concurrency.cs +++ b/src/Persistence/CosmosDbTests/saga_optimistic_concurrency.cs @@ -51,7 +51,7 @@ public async Task stale_write_is_surfaced_as_SagaConcurrencyException() var bus = host.MessageBus(); var id = Guid.NewGuid().ToString(); - await bus.InvokeAsync(new StartCounter(id)); + await bus.InvokeAsync(new StartCounter(id), TestContext.Current.CancellationToken); // Interfere exactly the way a second node would: the handler reads the saga, then another writer // commits a new revision of the same document before this message gets to write. Without the @@ -73,7 +73,7 @@ public async Task concurrent_messages_against_one_saga_both_get_applied() opts.Policies.OnException().RetryTimes(5)); var id = Guid.NewGuid().ToString(); - await host.MessageBus().InvokeAsync(new StartCounter(id)); + await host.MessageBus().InvokeAsync(new StartCounter(id), TestContext.Current.CancellationToken); // Both handlers pause between the saga read and the saga write, so both genuinely read Count = 0. // Pre-fix, the loser's blind upsert overwrote the winner and Count ended at 1 with no error at all. @@ -81,8 +81,10 @@ public async Task concurrent_messages_against_one_saga_both_get_applied() // driven concurrently. var pause = TimeSpan.FromMilliseconds(500); await Task.WhenAll( - host.MessageBus().InvokeAsync(new IncrementCounter(id) { Delay = pause }), - host.MessageBus().InvokeAsync(new IncrementCounter(id) { Delay = pause })); + host.MessageBus().InvokeAsync(new IncrementCounter(id) { Delay = pause }, + TestContext.Current.CancellationToken), + host.MessageBus().InvokeAsync(new IncrementCounter(id) { Delay = pause }, + TestContext.Current.CancellationToken)); var saga = await loadAsync(id); saga!.Count.ShouldBe(2); @@ -97,7 +99,7 @@ public async Task stale_delete_of_a_completed_saga_is_surfaced_as_SagaConcurrenc var bus = host.MessageBus(); var id = Guid.NewGuid().ToString(); - await bus.InvokeAsync(new StartCounter(id)); + await bus.InvokeAsync(new StartCounter(id), TestContext.Current.CancellationToken); // Completing a saga deletes the document. A blind delete would drop the interfering writer's // revision just as silently as a blind upsert would. diff --git a/src/Persistence/CosmosDbTests/saga_partitioning.cs b/src/Persistence/CosmosDbTests/saga_partitioning.cs index 6c10d938d..d2b5bb8fd 100644 --- a/src/Persistence/CosmosDbTests/saga_partitioning.cs +++ b/src/Persistence/CosmosDbTests/saga_partitioning.cs @@ -37,7 +37,7 @@ public async Task partitioned_saga_lives_in_the_partition_keyed_by_its_own_id() using var host = await buildHostAsync(partitionById: true); var id = Guid.NewGuid().ToString(); - await host.MessageBus().InvokeAsync(new StartPartitioned(id)); + await host.MessageBus().InvokeAsync(new StartPartitioned(id), TestContext.Current.CancellationToken); // The point read CosmosDB is at its best on: id and partition key are the same value var saga = await loadAsync(id, new PartitionKey(id)); @@ -61,7 +61,7 @@ public async Task saga_stays_in_the_undefined_partition_by_default() using var host = await buildHostAsync(partitionById: false); var id = Guid.NewGuid().ToString(); - await host.MessageBus().InvokeAsync(new StartPartitioned(id)); + await host.MessageBus().InvokeAsync(new StartPartitioned(id), TestContext.Current.CancellationToken); (await loadAsync(id, PartitionKey.None)).ShouldNotBeNull(); (await loadAsync(id, new PartitionKey(id))).ShouldBeNull(); @@ -77,14 +77,14 @@ public async Task partitioned_saga_can_be_updated_and_completed() using var host = await buildHostAsync(partitionById: true); var id = Guid.NewGuid().ToString(); - await host.MessageBus().InvokeAsync(new StartPartitioned(id)); - await host.MessageBus().InvokeAsync(new IncrementPartitioned(id)); - await host.MessageBus().InvokeAsync(new IncrementPartitioned(id)); + await host.MessageBus().InvokeAsync(new StartPartitioned(id), TestContext.Current.CancellationToken); + await host.MessageBus().InvokeAsync(new IncrementPartitioned(id), TestContext.Current.CancellationToken); + await host.MessageBus().InvokeAsync(new IncrementPartitioned(id), TestContext.Current.CancellationToken); var saga = await loadAsync(id, new PartitionKey(id)); saga!.Count.ShouldBe(2); - await host.MessageBus().InvokeAsync(new CompletePartitioned(id)); + await host.MessageBus().InvokeAsync(new CompletePartitioned(id), TestContext.Current.CancellationToken); (await loadAsync(id, new PartitionKey(id))).ShouldBeNull(); } @@ -100,7 +100,7 @@ public async Task optimistic_concurrency_still_holds_for_a_partitioned_saga() var bus = host.MessageBus(); var id = Guid.NewGuid().ToString(); - await bus.InvokeAsync(new StartPartitioned(id)); + await bus.InvokeAsync(new StartPartitioned(id), TestContext.Current.CancellationToken); // Commit a competing revision of the document between this message's read and its write, exactly as a // second node handling another message for this saga would @@ -122,7 +122,7 @@ public async Task saga_stored_through_a_storage_action_lands_in_its_own_partitio using var host = await buildHostAsync(partitionById: true); var id = Guid.NewGuid().ToString(); - await host.MessageBus().InvokeAsync(new StorePartitionedDirectly(id)); + await host.MessageBus().InvokeAsync(new StorePartitionedDirectly(id), TestContext.Current.CancellationToken); var saga = await loadAsync(id, new PartitionKey(id)); saga!.Count.ShouldBe(StorePartitionedDirectlyHandler.StoredCount); diff --git a/src/Persistence/CosmosDbTests/using_storage_return_types_and_entity_attributes.cs b/src/Persistence/CosmosDbTests/using_storage_return_types_and_entity_attributes.cs index 67dffb4b2..87fc7dc07 100644 --- a/src/Persistence/CosmosDbTests/using_storage_return_types_and_entity_attributes.cs +++ b/src/Persistence/CosmosDbTests/using_storage_return_types_and_entity_attributes.cs @@ -29,7 +29,7 @@ public async Task can_use_cosmosdb_ops_as_side_effects() opts.UseCosmosDbPersistence(AppFixture.DatabaseName); opts.Services.AddSingleton(_fixture.Client); opts.Discovery.IncludeAssembly(GetType().Assembly); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var tracked = await host.InvokeMessageAndWaitAsync(new CreateDocument("doc1", "Test Document")); tracked.Executed.MessagesOf().Any().ShouldBeTrue(); diff --git a/src/Persistence/EfCoreTests.MultiTenancy/Bug_2739_host_build_with_managed_multi_tenancy.cs b/src/Persistence/EfCoreTests.MultiTenancy/Bug_2739_host_build_with_managed_multi_tenancy.cs index 57d64bc2c..b2f3319ac 100644 --- a/src/Persistence/EfCoreTests.MultiTenancy/Bug_2739_host_build_with_managed_multi_tenancy.cs +++ b/src/Persistence/EfCoreTests.MultiTenancy/Bug_2739_host_build_with_managed_multi_tenancy.cs @@ -88,7 +88,7 @@ public async Task host_build_does_not_throw_with_AddDbContextWithWolverineManage }); using var host = builder.Build(); - await host.StartAsync(); + await host.StartAsync(TestContext.Current.CancellationToken); // Force WolverineOptions singleton resolution. The bug from #2739 // fires inside the WolverineOptions factory lambda in diff --git a/src/Persistence/EfCoreTests.MultiTenancy/Bug_3497_model_cache_key_includes_wolverine_schema.cs b/src/Persistence/EfCoreTests.MultiTenancy/Bug_3497_model_cache_key_includes_wolverine_schema.cs index 26f7b0eee..e6e6d92a6 100644 --- a/src/Persistence/EfCoreTests.MultiTenancy/Bug_3497_model_cache_key_includes_wolverine_schema.cs +++ b/src/Persistence/EfCoreTests.MultiTenancy/Bug_3497_model_cache_key_includes_wolverine_schema.cs @@ -31,7 +31,7 @@ public async Task two_hosts_with_different_wolverine_schemas_get_distinct_envelo opts.PersistMessagesWithPostgresql(Servers.PostgresConnectionString, "bug3497_a"); opts.Services.AddDbContextWithWolverineIntegration( x => x.UseNpgsql(Servers.PostgresConnectionString)); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); using var hostB = await Host.CreateDefaultBuilder() .UseWolverine(opts => @@ -41,7 +41,7 @@ public async Task two_hosts_with_different_wolverine_schemas_get_distinct_envelo opts.PersistMessagesWithPostgresql(Servers.PostgresConnectionString, "bug3497_b"); opts.Services.AddDbContextWithWolverineIntegration( x => x.UseNpgsql(Servers.PostgresConnectionString)); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); using var scopeA = hostA.Services.CreateScope(); using var scopeB = hostB.Services.CreateScope(); diff --git a/src/Persistence/EfCoreTests.MultiTenancy/ConjoinedTenancy/ConjoinedPartitioningCompliance.cs b/src/Persistence/EfCoreTests.MultiTenancy/ConjoinedTenancy/ConjoinedPartitioningCompliance.cs index 8026d659f..0f502d960 100644 --- a/src/Persistence/EfCoreTests.MultiTenancy/ConjoinedTenancy/ConjoinedPartitioningCompliance.cs +++ b/src/Persistence/EfCoreTests.MultiTenancy/ConjoinedTenancy/ConjoinedPartitioningCompliance.cs @@ -196,8 +196,8 @@ public async Task ef_model_keys_stay_single_and_sqlserver_maps_the_ordinal_colum [Fact] public async Task add_tenants_then_write_and_read_per_tenant() { - await thePartitions.AddTenantAsync("green"); - await thePartitions.AddTenantAsync("blue"); + await thePartitions.AddTenantAsync("green", TestContext.Current.CancellationToken); + await thePartitions.AddTenantAsync("blue", TestContext.Current.CancellationToken); var greenId = Guid.NewGuid(); var blueId = Guid.NewGuid(); @@ -205,17 +205,17 @@ public async Task add_tenants_then_write_and_read_per_tenant() await theHost.ExecuteAndWaitAsync(c => c.InvokeForTenantAsync("blue", new CreatePartitionedItem(blueId, "b"))); var green = await theBuilder.BuildAsync("green", CancellationToken.None); - (await green.Items.ToListAsync()).Single().Id.ShouldBe(greenId); + (await green.Items.ToListAsync(cancellationToken: TestContext.Current.CancellationToken)).Single().Id.ShouldBe(greenId); var blue = await theBuilder.BuildAsync("blue", CancellationToken.None); - (await blue.Items.ToListAsync()).Single().Id.ShouldBe(blueId); + (await blue.Items.ToListAsync(cancellationToken: TestContext.Current.CancellationToken)).Single().Id.ShouldBe(blueId); } [Fact] public async Task adding_the_same_tenant_twice_is_idempotent() { - await thePartitions.AddTenantAsync("green"); - await thePartitions.AddTenantAsync("green"); + await thePartitions.AddTenantAsync("green", TestContext.Current.CancellationToken); + await thePartitions.AddTenantAsync("green", TestContext.Current.CancellationToken); } [Fact] @@ -238,7 +238,7 @@ public async Task add_tenants_reports_the_outcome_for_every_managed_table() { ["green"] = null, ["blue"] = null - }); + }, TestContext.Current.CancellationToken); result.Succeeded.ShouldBeTrue(); result.Failures.ShouldBeEmpty(); @@ -264,15 +264,15 @@ public async Task add_tenants_reports_the_outcome_for_every_managed_table() [Fact] public async Task back_fill_reconciles_every_managed_table_and_is_idempotent() { - await thePartitions.AddTenantAsync("green"); - await thePartitions.AddTenantAsync("blue"); + await thePartitions.AddTenantAsync("green", TestContext.Current.CancellationToken); + await thePartitions.AddTenantAsync("blue", TestContext.Current.CancellationToken); - var first = await thePartitions.MigrateTenantPartitionsAsync(); + var first = await thePartitions.MigrateTenantPartitionsAsync(TestContext.Current.CancellationToken); first.Succeeded.ShouldBeTrue(); first.Tables.ShouldContain(x => x.TableName.Contains("partitioned_items")); // Back-fill is a reconcile, not a one-shot -- re-running it changes nothing - var second = await thePartitions.MigrateTenantPartitionsAsync(); + var second = await thePartitions.MigrateTenantPartitionsAsync(TestContext.Current.CancellationToken); second.Succeeded.ShouldBeTrue(); // and the tenants registered before the back-fill still write and read @@ -281,7 +281,7 @@ await theHost.ExecuteAndWaitAsync(c => c.InvokeForTenantAsync("green", new CreatePartitionedItem(id, "g"))); var green = await theBuilder.BuildAsync("green", CancellationToken.None); - (await green.Items.ToListAsync()).Single().Id.ShouldBe(id); + (await green.Items.ToListAsync(cancellationToken: TestContext.Current.CancellationToken)).Single().Id.ShouldBe(id); } [Fact] @@ -292,8 +292,8 @@ public async Task bucketed_tenants_registered_separately_share_one_partition() // second member was swallowed by CREATE TABLE IF NOT EXISTS so its first write failed with 23514; // SQL Server's registry had no bucket key, so each call quietly allocated a separate ordinal and // the tenants never actually shared the partition that bucketing exists to give them. - await thePartitions.AddTenantAsync("smalla", "shared_bucket"); - await thePartitions.AddTenantAsync("smallb", "shared_bucket"); + await thePartitions.AddTenantAsync("smalla", "shared_bucket", TestContext.Current.CancellationToken); + await thePartitions.AddTenantAsync("smallb", "shared_bucket", TestContext.Current.CancellationToken); // Both members read and write... var aId = Guid.NewGuid(); @@ -304,10 +304,10 @@ await theHost.ExecuteAndWaitAsync(c => c.InvokeForTenantAsync("smallb", new CreatePartitionedItem(bId, "b"))); var a = await theBuilder.BuildAsync("smalla", CancellationToken.None); - (await a.Items.ToListAsync()).Single().Id.ShouldBe(aId); + (await a.Items.ToListAsync(cancellationToken: TestContext.Current.CancellationToken)).Single().Id.ShouldBe(aId); var b = await theBuilder.BuildAsync("smallb", CancellationToken.None); - (await b.Items.ToListAsync()).Single().Id.ShouldBe(bId); + (await b.Items.ToListAsync(cancellationToken: TestContext.Current.CancellationToken)).Single().Id.ShouldBe(bId); // ...and they genuinely share ONE physical partition, which is the entire point (await distinctPartitionCountAsync(["smalla", "smallb"])).ShouldBe(1); @@ -320,7 +320,7 @@ await thePartitions.AddTenantsAsync(new Dictionary { ["smalla"] = "shared_bucket", ["smallb"] = "shared_bucket" - }); + }, TestContext.Current.CancellationToken); (await distinctPartitionCountAsync(["smalla", "smallb"])).ShouldBe(1); } @@ -330,8 +330,8 @@ public async Task dropping_one_bucket_member_leaves_the_others_working() { // The co-tenant data-loss defect found alongside GH-3683: on PostgreSQL the by-value drop resolved // the tenant to its suffix and dropped BY SUFFIX, taking every co-tenant's rows with it. - await thePartitions.AddTenantAsync("smalla", "shared_bucket"); - await thePartitions.AddTenantAsync("smallb", "shared_bucket"); + await thePartitions.AddTenantAsync("smalla", "shared_bucket", TestContext.Current.CancellationToken); + await thePartitions.AddTenantAsync("smallb", "shared_bucket", TestContext.Current.CancellationToken); var survivorId = Guid.NewGuid(); await theHost.ExecuteAndWaitAsync(c => @@ -339,11 +339,11 @@ await theHost.ExecuteAndWaitAsync(c => await theHost.ExecuteAndWaitAsync(c => c.InvokeForTenantAsync("smallb", new CreatePartitionedItem(survivorId, "survivor"))); - await thePartitions.DropTenantAsync("smalla", deleteData: true); + await thePartitions.DropTenantAsync("smalla", deleteData: true, cancellationToken: TestContext.Current.CancellationToken); // The survivor keeps its rows... var b = await theBuilder.BuildAsync("smallb", CancellationToken.None); - (await b.Items.ToListAsync()).Single().Id.ShouldBe(survivorId); + (await b.Items.ToListAsync(cancellationToken: TestContext.Current.CancellationToken)).Single().Id.ShouldBe(survivorId); // ...and can still write var moreId = Guid.NewGuid(); @@ -351,7 +351,7 @@ await theHost.ExecuteAndWaitAsync(c => c.InvokeForTenantAsync("smallb", new CreatePartitionedItem(moreId, "more"))); b = await theBuilder.BuildAsync("smallb", CancellationToken.None); - (await b.Items.ToListAsync()).Select(x => x.Id).OrderBy(x => x) + (await b.Items.ToListAsync(cancellationToken: TestContext.Current.CancellationToken)).Select(x => x.Id).OrderBy(x => x) .ShouldBe(new[] { survivorId, moreId }.OrderBy(x => x)); } @@ -399,29 +399,29 @@ from pg_class c [Fact] public async Task physical_partition_exists_per_tenant() { - await thePartitions.AddTenantAsync("green"); + await thePartitions.AddTenantAsync("green", TestContext.Current.CancellationToken); if (_engine == DatabaseEngine.PostgreSQL) { await using var conn = new NpgsqlConnection(Servers.PostgresConnectionString); - await conn.OpenAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); await using var cmd = conn.CreateCommand(); cmd.CommandText = @" select count(*) from pg_inherits join pg_class parent on pg_inherits.inhparent = parent.oid join pg_namespace ns on parent.relnamespace = ns.oid where ns.nspname = 'conjoined_part' and parent.relname = 'partitioned_items'"; - var partitionCount = (long)(await cmd.ExecuteScalarAsync())!; + var partitionCount = (long)(await cmd.ExecuteScalarAsync(TestContext.Current.CancellationToken))!; partitionCount.ShouldBeGreaterThanOrEqualTo(1); } else { await using var conn = new SqlConnection(Servers.SqlServerConnectionString); - await conn.OpenAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); await using var cmd = conn.CreateCommand(); cmd.CommandText = "SELECT COUNT(*) FROM conjoined_part_wolverine.wolverine_tenant_partitions WHERE tenant_id = 'green'"; - ((int)(await cmd.ExecuteScalarAsync())!).ShouldBe(1); + ((int)(await cmd.ExecuteScalarAsync(TestContext.Current.CancellationToken))!).ShouldBe(1); } } } @@ -442,14 +442,14 @@ public conjoined_partitioning_with_postgresql() : base(DatabaseEngine.PostgreSQL [Fact] public async Task back_fill_recreates_a_partition_missing_for_a_registered_tenant() { - await thePartitions.AddTenantAsync("green"); + await thePartitions.AddTenantAsync("green", TestContext.Current.CancellationToken); await using (var conn = new NpgsqlConnection(Servers.PostgresConnectionString)) { - await conn.OpenAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); await using var drop = conn.CreateCommand(); drop.CommandText = "DROP TABLE conjoined_part.partitioned_items_green;"; - await drop.ExecuteNonQueryAsync(); + await drop.ExecuteNonQueryAsync(TestContext.Current.CancellationToken); } // Without its partition, the tenant's writes have nowhere to land @@ -460,7 +460,7 @@ await theHost.TrackActivity().DoNotAssertOnExceptionsDetected() c.InvokeForTenantAsync("green", new CreatePartitionedItem(Guid.NewGuid(), "before"))); }); - var result = await thePartitions.MigrateTenantPartitionsAsync(); + var result = await thePartitions.MigrateTenantPartitionsAsync(TestContext.Current.CancellationToken); result.Succeeded.ShouldBeTrue(); var id = Guid.NewGuid(); @@ -468,7 +468,7 @@ await theHost.ExecuteAndWaitAsync(c => c.InvokeForTenantAsync("green", new CreatePartitionedItem(id, "after"))); var green = await theBuilder.BuildAsync("green", CancellationToken.None); - (await green.Items.ToListAsync()).Single().Id.ShouldBe(id); + (await green.Items.ToListAsync(cancellationToken: TestContext.Current.CancellationToken)).Single().Id.ShouldBe(id); } } diff --git a/src/Persistence/EfCoreTests.MultiTenancy/ConjoinedTenancy/ConjoinedTenancyCompliance.cs b/src/Persistence/EfCoreTests.MultiTenancy/ConjoinedTenancy/ConjoinedTenancyCompliance.cs index 099bede7b..cea1cdc91 100644 --- a/src/Persistence/EfCoreTests.MultiTenancy/ConjoinedTenancy/ConjoinedTenancyCompliance.cs +++ b/src/Persistence/EfCoreTests.MultiTenancy/ConjoinedTenancy/ConjoinedTenancyCompliance.cs @@ -110,7 +110,7 @@ public async Task handler_insert_stamps_the_ambient_tenant_id() await theHost.ExecuteAndWaitAsync(c => c.InvokeForTenantAsync("green", new CreateConjoinedItem(id, "one"))); var context = await theBuilder.BuildAsync("green", CancellationToken.None); - var item = await context.Items.FindAsync(id); + var item = await context.Items.FindAsync(new object?[] { id }, TestContext.Current.CancellationToken); item.ShouldNotBeNull(); item.TenantId.ShouldBe("green"); @@ -123,7 +123,7 @@ public async Task insert_without_a_tenant_gets_the_default_tenant_sentinel() await theHost.InvokeMessageAndWaitAsync(new CreateConjoinedItem(id, "plain")); var context = await theBuilder.BuildAsync(CancellationToken.None); - var item = await context.Items.FindAsync(id); + var item = await context.Items.FindAsync(new object?[] { id }, TestContext.Current.CancellationToken); item.ShouldNotBeNull(); item.TenantId.ShouldBe(StorageConstants.DefaultTenantId); @@ -143,9 +143,9 @@ public async Task queries_are_bound_to_the_tenant_of_each_context_instance() var blue = await theBuilder.BuildAsync("blue", CancellationToken.None); var greenAgain = await theBuilder.BuildAsync("green", CancellationToken.None); - (await green.Items.Where(x => x.Name == "same").ToListAsync()).Single().Id.ShouldBe(greenId); - (await blue.Items.Where(x => x.Name == "same").ToListAsync()).Single().Id.ShouldBe(blueId); - (await greenAgain.Items.Where(x => x.Name == "same").ToListAsync()).Single().Id.ShouldBe(greenId); + (await green.Items.Where(x => x.Name == "same").ToListAsync(cancellationToken: TestContext.Current.CancellationToken)).Single().Id.ShouldBe(greenId); + (await blue.Items.Where(x => x.Name == "same").ToListAsync(cancellationToken: TestContext.Current.CancellationToken)).Single().Id.ShouldBe(blueId); + (await greenAgain.Items.Where(x => x.Name == "same").ToListAsync(cancellationToken: TestContext.Current.CancellationToken)).Single().Id.ShouldBe(greenId); } [Fact] @@ -157,10 +157,10 @@ public async Task find_async_respects_the_tenant_filter() await theHost.ExecuteAndWaitAsync(c => c.InvokeForTenantAsync("green", new CreateConjoinedItem(greenId, "mine"))); var blue = await theBuilder.BuildAsync("blue", CancellationToken.None); - (await blue.Items.FindAsync(greenId)).ShouldBeNull(); + (await blue.Items.FindAsync(new object?[] { greenId }, TestContext.Current.CancellationToken)).ShouldBeNull(); var green = await theBuilder.BuildAsync("green", CancellationToken.None); - (await green.Items.FindAsync(greenId)).ShouldNotBeNull(); + (await green.Items.FindAsync(new object?[] { greenId }, TestContext.Current.CancellationToken)).ShouldNotBeNull(); } [Fact] @@ -170,7 +170,7 @@ public async Task cross_tenant_update_is_rejected() await theHost.ExecuteAndWaitAsync(c => c.InvokeForTenantAsync("green", new CreateConjoinedItem(id, "guarded"))); var blue = await theBuilder.BuildAsync("blue", CancellationToken.None); - var smuggled = await blue.Items.IgnoreQueryFilters().SingleAsync(x => x.Id == id); + var smuggled = await blue.Items.IgnoreQueryFilters().SingleAsync(x => x.Id == id, cancellationToken: TestContext.Current.CancellationToken); smuggled.Name = "hijacked"; var ex = await Should.ThrowAsync(() => blue.SaveChangesAsync()); @@ -185,7 +185,7 @@ public async Task cross_tenant_delete_is_rejected() await theHost.ExecuteAndWaitAsync(c => c.InvokeForTenantAsync("green", new CreateConjoinedItem(id, "keeper"))); var blue = await theBuilder.BuildAsync("blue", CancellationToken.None); - var smuggled = await blue.Items.IgnoreQueryFilters().SingleAsync(x => x.Id == id); + var smuggled = await blue.Items.IgnoreQueryFilters().SingleAsync(x => x.Id == id, cancellationToken: TestContext.Current.CancellationToken); blue.Items.Remove(smuggled); await Should.ThrowAsync(() => blue.SaveChangesAsync()); @@ -213,12 +213,12 @@ await Should.ThrowAsync(() => theHost.TrackActivity() .ExecuteAndWaitAsync(c => c.InvokeForTenantAsync("blue", new IncrementCounter(id)))); var green = await theBuilder.BuildAsync("green", CancellationToken.None); - var saga = await green.Counters.SingleAsync(x => x.Id == id); + var saga = await green.Counters.SingleAsync(x => x.Id == id, cancellationToken: TestContext.Current.CancellationToken); saga.Count.ShouldBe(1); saga.TenantId.ShouldBe("green"); var blue = await theBuilder.BuildAsync("blue", CancellationToken.None); - (await blue.Counters.FindAsync(id)).ShouldBeNull(); + (await blue.Counters.FindAsync(new object?[] { id }, TestContext.Current.CancellationToken)).ShouldBeNull(); } } diff --git a/src/Persistence/EfCoreTests.MultiTenancy/EfCoreTests.MultiTenancy.csproj b/src/Persistence/EfCoreTests.MultiTenancy/EfCoreTests.MultiTenancy.csproj index b09ce498b..2620632c9 100644 --- a/src/Persistence/EfCoreTests.MultiTenancy/EfCoreTests.MultiTenancy.csproj +++ b/src/Persistence/EfCoreTests.MultiTenancy/EfCoreTests.MultiTenancy.csproj @@ -1,6 +1,8 @@ + + true Exe false true diff --git a/src/Persistence/EfCoreTests.MultiTenancy/MultiTenancyCompliance.cs b/src/Persistence/EfCoreTests.MultiTenancy/MultiTenancyCompliance.cs index edf632ab9..29167c687 100644 --- a/src/Persistence/EfCoreTests.MultiTenancy/MultiTenancyCompliance.cs +++ b/src/Persistence/EfCoreTests.MultiTenancy/MultiTenancyCompliance.cs @@ -162,17 +162,17 @@ public async Task end_to_end_with_commands() var greenDbContext = await theBuilder.BuildAsync("green", CancellationToken.None); var redDbContext = await theBuilder.BuildAsync("red", CancellationToken.None); - (await blueDbContext.Items.FindAsync(blueId))!.Name.ShouldBe("Blue!"); - (await greenDbContext.Items.FindAsync(blueId)).ShouldBeNull(); - (await redDbContext.Items.FindAsync(blueId)).ShouldBeNull(); + (await blueDbContext.Items.FindAsync(new object?[] { blueId }, TestContext.Current.CancellationToken))!.Name.ShouldBe("Blue!"); + (await greenDbContext.Items.FindAsync(new object?[] { blueId }, TestContext.Current.CancellationToken)).ShouldBeNull(); + (await redDbContext.Items.FindAsync(new object?[] { blueId }, TestContext.Current.CancellationToken)).ShouldBeNull(); - (await blueDbContext.Items.FindAsync(redId)).ShouldBeNull(); - (await greenDbContext.Items.FindAsync(redId)).ShouldBeNull(); - (await redDbContext.Items.FindAsync(redId))!.Name.ShouldBe("Red!"); + (await blueDbContext.Items.FindAsync(new object?[] { redId }, TestContext.Current.CancellationToken)).ShouldBeNull(); + (await greenDbContext.Items.FindAsync(new object?[] { redId }, TestContext.Current.CancellationToken)).ShouldBeNull(); + (await redDbContext.Items.FindAsync(new object?[] { redId }, TestContext.Current.CancellationToken))!.Name.ShouldBe("Red!"); - (await blueDbContext.Items.FindAsync(greenId)).ShouldBeNull(); - (await greenDbContext.Items.FindAsync(greenId))!.Name.ShouldBe("Green!"); - (await redDbContext.Items.FindAsync(greenId)).ShouldBeNull(); + (await blueDbContext.Items.FindAsync(new object?[] { greenId }, TestContext.Current.CancellationToken)).ShouldBeNull(); + (await greenDbContext.Items.FindAsync(new object?[] { greenId }, TestContext.Current.CancellationToken))!.Name.ShouldBe("Green!"); + (await redDbContext.Items.FindAsync(new object?[] { greenId }, TestContext.Current.CancellationToken)).ShouldBeNull(); } [Fact] @@ -189,7 +189,7 @@ public async Task end_to_end_with_default_database() var greenDbContext = await theBuilder.BuildAsync("green", CancellationToken.None); var redDbContext = await theBuilder.BuildAsync("red", CancellationToken.None); - (await defaultDbContext.FindAsync(defaultId))!.Name.ShouldBe("The Default!"); + (await defaultDbContext.FindAsync(new object?[] { defaultId }, TestContext.Current.CancellationToken))!.Name.ShouldBe("The Default!"); } catch (DefaultTenantUsageDisabledException) { @@ -212,23 +212,23 @@ public async Task end_to_end_with_cascading_messages() var greenDbContext = await theBuilder.BuildAsync("green", CancellationToken.None); var redDbContext = await theBuilder.BuildAsync("red", CancellationToken.None); - var blue = (await blueDbContext.Items.FindAsync(blueId))!; + var blue = (await blueDbContext.Items.FindAsync(new object?[] { blueId }, TestContext.Current.CancellationToken))!; blue.Name.ShouldBe("Blue!"); blue.Approved.ShouldBeTrue(); - (await greenDbContext.Items.FindAsync(blueId)).ShouldBeNull(); - (await redDbContext.Items.FindAsync(blueId)).ShouldBeNull(); + (await greenDbContext.Items.FindAsync(new object?[] { blueId }, TestContext.Current.CancellationToken)).ShouldBeNull(); + (await redDbContext.Items.FindAsync(new object?[] { blueId }, TestContext.Current.CancellationToken)).ShouldBeNull(); - (await blueDbContext.Items.FindAsync(redId)).ShouldBeNull(); - (await greenDbContext.Items.FindAsync(redId)).ShouldBeNull(); - var red = (await redDbContext.Items.FindAsync(redId))!; + (await blueDbContext.Items.FindAsync(new object?[] { redId }, TestContext.Current.CancellationToken)).ShouldBeNull(); + (await greenDbContext.Items.FindAsync(new object?[] { redId }, TestContext.Current.CancellationToken)).ShouldBeNull(); + var red = (await redDbContext.Items.FindAsync(new object?[] { redId }, TestContext.Current.CancellationToken))!; red.Name.ShouldBe("Red!"); red.Approved.ShouldBeTrue(); - (await blueDbContext.Items.FindAsync(greenId)).ShouldBeNull(); - var green = (await greenDbContext.Items.FindAsync(greenId))!; + (await blueDbContext.Items.FindAsync(new object?[] { greenId }, TestContext.Current.CancellationToken)).ShouldBeNull(); + var green = (await greenDbContext.Items.FindAsync(new object?[] { greenId }, TestContext.Current.CancellationToken))!; green.Name.ShouldBe("Green!"); green.Approved.ShouldBeTrue(); - (await redDbContext.Items.FindAsync(greenId)).ShouldBeNull(); + (await redDbContext.Items.FindAsync(new object?[] { greenId }, TestContext.Current.CancellationToken)).ShouldBeNull(); } [Fact] @@ -248,11 +248,11 @@ await theHost.Scenario(x => var redDbContext = await theBuilder.BuildAsync("red", CancellationToken.None); - (await defaultDbContext.FindAsync(command.Id)).ShouldBeNull(); - (await redDbContext.FindAsync(command.Id)).ShouldBeNull(); - (await greenDbContext.FindAsync(command.Id)).ShouldBeNull(); + (await defaultDbContext.FindAsync(new object?[] { command.Id }, TestContext.Current.CancellationToken)).ShouldBeNull(); + (await redDbContext.FindAsync(new object?[] { command.Id }, TestContext.Current.CancellationToken)).ShouldBeNull(); + (await greenDbContext.FindAsync(new object?[] { command.Id }, TestContext.Current.CancellationToken)).ShouldBeNull(); - (await blueDbContext.FindAsync(command.Id))!.Name.ShouldBe(command.Name); + (await blueDbContext.FindAsync(new object?[] { command.Id }, TestContext.Current.CancellationToken))!.Name.ShouldBe(command.Name); } [Fact] @@ -271,11 +271,11 @@ await theHost.Scenario(x => var greenDbContext = await theBuilder.BuildAsync("green", CancellationToken.None); var redDbContext = await theBuilder.BuildAsync("red", CancellationToken.None); - (await blueDbContext.FindAsync(command.Id)).ShouldBeNull(); - (await redDbContext.FindAsync(command.Id)).ShouldBeNull(); - (await greenDbContext.FindAsync(command.Id)).ShouldBeNull(); + (await blueDbContext.FindAsync(new object?[] { command.Id }, TestContext.Current.CancellationToken)).ShouldBeNull(); + (await redDbContext.FindAsync(new object?[] { command.Id }, TestContext.Current.CancellationToken)).ShouldBeNull(); + (await greenDbContext.FindAsync(new object?[] { command.Id }, TestContext.Current.CancellationToken)).ShouldBeNull(); - (await defaultDbContext.FindAsync(command.Id))!.Name.ShouldBe(command.Name); + (await defaultDbContext.FindAsync(new object?[] { command.Id }, TestContext.Current.CancellationToken))!.Name.ShouldBe(command.Name); } [Fact] @@ -373,11 +373,11 @@ await theHost.Scenario(x => var greenDbContext = await theBuilder.BuildAsync("green", CancellationToken.None); var redDbContext = await theBuilder.BuildAsync("red", CancellationToken.None); - (await blueDbContext.FindAsync(command.Id))!.Approved.ShouldBeFalse(); - (await redDbContext.FindAsync(command.Id))!.Approved.ShouldBeFalse(); + (await blueDbContext.FindAsync(new object?[] { command.Id }, TestContext.Current.CancellationToken))!.Approved.ShouldBeFalse(); + (await redDbContext.FindAsync(new object?[] { command.Id }, TestContext.Current.CancellationToken))!.Approved.ShouldBeFalse(); // Only approved this one - (await greenDbContext.FindAsync(command.Id))!.Approved.ShouldBeTrue(); + (await greenDbContext.FindAsync(new object?[] { command.Id }, TestContext.Current.CancellationToken))!.Approved.ShouldBeTrue(); } [Fact] @@ -403,11 +403,11 @@ await theHost.Scenario(x => var greenDbContext = await theBuilder.BuildAsync("green", CancellationToken.None); var redDbContext = await theBuilder.BuildAsync("red", CancellationToken.None); - (await blueDbContext.FindAsync(command.Id))!.Approved.ShouldBeFalse(); - (await redDbContext.FindAsync(command.Id))!.Approved.ShouldBeFalse(); + (await blueDbContext.FindAsync(new object?[] { command.Id }, TestContext.Current.CancellationToken))!.Approved.ShouldBeFalse(); + (await redDbContext.FindAsync(new object?[] { command.Id }, TestContext.Current.CancellationToken))!.Approved.ShouldBeFalse(); // Only approved this one - (await greenDbContext.FindAsync(command.Id))!.Approved.ShouldBeTrue(); + (await greenDbContext.FindAsync(new object?[] { command.Id }, TestContext.Current.CancellationToken))!.Approved.ShouldBeTrue(); } [Fact] @@ -433,11 +433,11 @@ await theHost.Scenario(x => var greenDbContext = await theBuilder.BuildAsync("green", CancellationToken.None); var redDbContext = await theBuilder.BuildAsync("red", CancellationToken.None); - (await blueDbContext.FindAsync(command.Id))!.Approved.ShouldBeFalse(); - (await redDbContext.FindAsync(command.Id))!.Approved.ShouldBeFalse(); + (await blueDbContext.FindAsync(new object?[] { command.Id }, TestContext.Current.CancellationToken))!.Approved.ShouldBeFalse(); + (await redDbContext.FindAsync(new object?[] { command.Id }, TestContext.Current.CancellationToken))!.Approved.ShouldBeFalse(); // Only approved this one - (await greenDbContext.FindAsync(command.Id))!.Approved.ShouldBeTrue(); + (await greenDbContext.FindAsync(new object?[] { command.Id }, TestContext.Current.CancellationToken))!.Approved.ShouldBeTrue(); } [Fact] @@ -494,7 +494,7 @@ await theHost.ExecuteAndWaitAsync(async _ => var builder = theHost.Services.GetRequiredService>(); var dbContext = await builder.BuildAsync("blue", CancellationToken.None); - var item2 = await dbContext.Items.FindAsync(id); + var item2 = await dbContext.Items.FindAsync(new object?[] { id }, TestContext.Current.CancellationToken); item2!.Approved.ShouldBeTrue(); } diff --git a/src/Persistence/EfCoreTests/Bug_252_codegen_issue.cs b/src/Persistence/EfCoreTests/Bug_252_codegen_issue.cs index 45dcb954e..e08c883a0 100644 --- a/src/Persistence/EfCoreTests/Bug_252_codegen_issue.cs +++ b/src/Persistence/EfCoreTests/Bug_252_codegen_issue.cs @@ -33,8 +33,8 @@ public Bug_252_codegen_issue(ITestOutputHelper output) public async Task use_the_saga_type_to_determine_the_correct_DbContext_type() { await using var conn = new SqlConnection(Servers.SqlServerConnectionString); - await conn.OpenAsync(); - await conn.DropSchemaAsync("mt_items"); + await conn.OpenAsync(TestContext.Current.CancellationToken); + await conn.DropSchemaAsync("mt_items", ct: TestContext.Current.CancellationToken); await conn.CloseAsync(); using var host = await Host.CreateDefaultBuilder() @@ -58,7 +58,7 @@ public async Task use_the_saga_type_to_determine_the_correct_DbContext_type() opt.Services.AddResourceSetupOnStartup(StartupAction.ResetState); opt.Policies.UseDurableLocalQueues(); opt.Policies.AutoApplyTransactions(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); await host.InvokeMessageAndWaitAsync(new OrderCreated(Guid.NewGuid())); } @@ -67,8 +67,8 @@ public async Task use_the_saga_type_to_determine_the_correct_DbContext_type() public async Task bug_256_message_bus_should_be_in_outbox_transaction() { await using var conn = new SqlConnection(Servers.SqlServerConnectionString); - await conn.OpenAsync(); - await conn.DropSchemaAsync("mt_items"); + await conn.OpenAsync(TestContext.Current.CancellationToken); + await conn.DropSchemaAsync("mt_items", ct: TestContext.Current.CancellationToken); await conn.CloseAsync(); using var host = await Host.CreateDefaultBuilder() @@ -92,7 +92,7 @@ public async Task bug_256_message_bus_should_be_in_outbox_transaction() opt.Services.AddResourceSetupOnStartup(StartupAction.ResetState); opt.Policies.UseDurableLocalQueues(); opt.Policies.AutoApplyTransactions(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var chain = host.Services.GetRequiredService().HandlerFor()!.As()!.Chain!; diff --git a/src/Persistence/EfCoreTests/Bug_661_postgresql_with_ef_core.cs b/src/Persistence/EfCoreTests/Bug_661_postgresql_with_ef_core.cs index 1cfd5b3f5..c99e13b7a 100644 --- a/src/Persistence/EfCoreTests/Bug_661_postgresql_with_ef_core.cs +++ b/src/Persistence/EfCoreTests/Bug_661_postgresql_with_ef_core.cs @@ -26,6 +26,6 @@ public async Task can_set_up_with_default_schema_name() opts.PersistMessagesWithPostgresql(Servers.PostgresConnectionString); opts.Services.AddResourceSetupOnStartup(); opts.Services.AddDbContext(opt => opt.UseNpgsql(Servers.PostgresConnectionString)); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); } } \ No newline at end of file diff --git a/src/Persistence/EfCoreTests/Bugs/Bug_1846_duplicate_execution_of_scheduled_jobs.cs b/src/Persistence/EfCoreTests/Bugs/Bug_1846_duplicate_execution_of_scheduled_jobs.cs index 845565061..02aed7ae3 100644 --- a/src/Persistence/EfCoreTests/Bugs/Bug_1846_duplicate_execution_of_scheduled_jobs.cs +++ b/src/Persistence/EfCoreTests/Bugs/Bug_1846_duplicate_execution_of_scheduled_jobs.cs @@ -43,7 +43,7 @@ public async Task should_not_double_execute() opts.Services.AddDbContextWithWolverineIntegration(x => x.UseSqlServer(Servers.SqlServerConnectionString)); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var session = await host.TrackActivity() .WaitForMessageToBeReceivedAt(host) diff --git a/src/Persistence/EfCoreTests/Bugs/Bug_2075_separated_behavior_and_scheduled_messages.cs b/src/Persistence/EfCoreTests/Bugs/Bug_2075_separated_behavior_and_scheduled_messages.cs index 58bd38994..9768ef6b1 100644 --- a/src/Persistence/EfCoreTests/Bugs/Bug_2075_separated_behavior_and_scheduled_messages.cs +++ b/src/Persistence/EfCoreTests/Bugs/Bug_2075_separated_behavior_and_scheduled_messages.cs @@ -39,7 +39,7 @@ public async Task MyBug() opts.MultipleHandlerBehavior = MultipleHandlerBehavior.Separated; GlobalErrorHandlingPolicy.Invoke(opts); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var session = await host.TrackActivity().DoNotAssertOnExceptionsDetected().WaitForMessageToBeReceivedAt(host).Timeout(30.Seconds()) .SendMessageAndWaitAsync(new SayStuffy0()); diff --git a/src/Persistence/EfCoreTests/Bugs/Bug_3342_saga_entity_and_storage_action.cs b/src/Persistence/EfCoreTests/Bugs/Bug_3342_saga_entity_and_storage_action.cs index 3b6c87fe9..1313b10ba 100644 --- a/src/Persistence/EfCoreTests/Bugs/Bug_3342_saga_entity_and_storage_action.cs +++ b/src/Persistence/EfCoreTests/Bugs/Bug_3342_saga_entity_and_storage_action.cs @@ -81,7 +81,7 @@ public async Task cascaded_handler_sees_the_persisted_entity() // And the record persisted by the Update in the ProcessOrder handler must be up to date. using var scope = _host.Services.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); - var record = await db.OrderProcessRecords.FirstOrDefaultAsync(x => x.Id == TheOrderId); + var record = await db.OrderProcessRecords.FirstOrDefaultAsync(x => x.Id == TheOrderId, cancellationToken: TestContext.Current.CancellationToken); record.ShouldNotBeNull("Start's Storage.Insert must be persisted"); record.StockChecked.ShouldBeTrue("the ProcessOrder handler's Storage.Update must be persisted"); } diff --git a/src/Persistence/EfCoreTests/Bugs/Bug_DurableLocalQueue_ancillary_store_routing.cs b/src/Persistence/EfCoreTests/Bugs/Bug_DurableLocalQueue_ancillary_store_routing.cs index 3250ba81e..9e1718ac4 100644 --- a/src/Persistence/EfCoreTests/Bugs/Bug_DurableLocalQueue_ancillary_store_routing.cs +++ b/src/Persistence/EfCoreTests/Bugs/Bug_DurableLocalQueue_ancillary_store_routing.cs @@ -214,7 +214,7 @@ await _host .SendMessageAndWaitAsync(message); // Give a moment for post-processing - await Task.Delay(500); + await Task.Delay(500, TestContext.Current.CancellationToken); var runtime = _host.Services.GetRequiredService(); @@ -240,7 +240,7 @@ await _host .TrackActivity() .SendMessageAndWaitAsync(message); - await Task.Delay(500); + await Task.Delay(500, TestContext.Current.CancellationToken); var runtime = _host.Services.GetRequiredService(); @@ -264,7 +264,7 @@ await _host // Verify the entity was actually saved in the ancillary DbContext using var scope = _host.Services.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); - var doc = await db.Docs.FindAsync(message.Id); + var doc = await db.Docs.FindAsync(new object?[] { message.Id }, TestContext.Current.CancellationToken); doc.ShouldNotBeNull(); doc.Name.ShouldBe("test-entity"); } diff --git a/src/Persistence/EfCoreTests/DomainEvents/DomainEventScraperStateFilterTests.cs b/src/Persistence/EfCoreTests/DomainEvents/DomainEventScraperStateFilterTests.cs index 6657db24d..2e2487820 100644 --- a/src/Persistence/EfCoreTests/DomainEvents/DomainEventScraperStateFilterTests.cs +++ b/src/Persistence/EfCoreTests/DomainEvents/DomainEventScraperStateFilterTests.cs @@ -58,7 +58,7 @@ public async Task domain_event_scraper_collects_events_from_added_and_modified_b { seed.Items.Add(new Item { Id = Guid.Parse("00000000-0000-0000-0000-000000000001"), Name = "WillBeUnchanged" }); seed.Items.Add(new Item { Id = Guid.Parse("00000000-0000-0000-0000-000000000002"), Name = "WillBeDeleted" }); - await seed.SaveChangesAsync(); + await seed.SaveChangesAsync(TestContext.Current.CancellationToken); } using var ctx = new ScraperTestDbContext(options); @@ -69,12 +69,12 @@ public async Task domain_event_scraper_collects_events_from_added_and_modified_b addedItem.Approve(); // raises ItemApproved event // Modified – load, change, and let EF detect it - var modifiedItem = await ctx.Items.FindAsync(Guid.Parse("00000000-0000-0000-0000-000000000001")); + var modifiedItem = await ctx.Items.FindAsync(new object?[] { Guid.Parse("00000000-0000-0000-0000-000000000001") }, TestContext.Current.CancellationToken); modifiedItem!.Approve(); // raises event AND sets Approved=true → Modified state // Unchanged – load but do not touch // (we manually add an event to the unchanged item to prove the scraper skips it) - var unchangedItem = await ctx.Items.FindAsync(Guid.Parse("00000000-0000-0000-0000-000000000002")); + var unchangedItem = await ctx.Items.FindAsync(new object?[] { Guid.Parse("00000000-0000-0000-0000-000000000002") }, TestContext.Current.CancellationToken); unchangedItem!.Publish(new ItemApproved(unchangedItem.Id)); // event added, but state stays Unchanged // Verify states are as expected diff --git a/src/Persistence/EfCoreTests/DomainEvents/configuration_of_domain_events_scrapers.cs b/src/Persistence/EfCoreTests/DomainEvents/configuration_of_domain_events_scrapers.cs index ef8271d1d..446b66de0 100644 --- a/src/Persistence/EfCoreTests/DomainEvents/configuration_of_domain_events_scrapers.cs +++ b/src/Persistence/EfCoreTests/DomainEvents/configuration_of_domain_events_scrapers.cs @@ -187,7 +187,7 @@ public async Task publish_through_db_context_scraping1() var item = new Item { Id = itemId, Name = "Latte"}; dbContext.Items.Add(item); - await dbContext.SaveChangesAsync(); + await dbContext.SaveChangesAsync(TestContext.Current.CancellationToken); } var tracked = await theHost.InvokeMessageAndWaitAsync(new ApproveItem(itemId)); @@ -208,7 +208,7 @@ public async Task publish_through_db_context_scraping2() var item = new Item { Id = itemId, Name = "Smoothie"}; dbContext.Items.Add(item); - await dbContext.SaveChangesAsync(); + await dbContext.SaveChangesAsync(TestContext.Current.CancellationToken); } var tracked = await theHost.InvokeMessageAndWaitAsync(new ApproveItem(itemId)); diff --git a/src/Persistence/EfCoreTests/EfCoreCompilationScenarios.cs b/src/Persistence/EfCoreTests/EfCoreCompilationScenarios.cs index 90c07ba26..d7cf2e583 100644 --- a/src/Persistence/EfCoreTests/EfCoreCompilationScenarios.cs +++ b/src/Persistence/EfCoreTests/EfCoreCompilationScenarios.cs @@ -24,7 +24,7 @@ public async Task ef_context_is_scoped_and_options_are_scoped() opts.UseEntityFrameworkCoreTransactions(); }); - await host.MessageBus().InvokeAsync(new CreateItem { Name = "foo" }); + await host.MessageBus().InvokeAsync(new CreateItem { Name = "foo" }, TestContext.Current.CancellationToken); } [Fact] @@ -39,8 +39,8 @@ public async Task ef_context_is_scoped_and_options_are_singleton() opts.UseEntityFrameworkCoreTransactions(); }); - await host.MessageBus().InvokeAsync(new CreateItem { Name = "foo" }); - await host.StopAsync(); + await host.MessageBus().InvokeAsync(new CreateItem { Name = "foo" }, TestContext.Current.CancellationToken); + await host.StopAsync(TestContext.Current.CancellationToken); host.Dispose(); } @@ -57,7 +57,7 @@ public async Task ef_context_is_singleton_and_options_are_singleton() opts.UseEntityFrameworkCoreTransactions(); }); - await host.MessageBus().InvokeAsync(new CreateItem { Name = "foo" }); + await host.MessageBus().InvokeAsync(new CreateItem { Name = "foo" }, TestContext.Current.CancellationToken); } } diff --git a/src/Persistence/EfCoreTests/EfCoreTests.csproj b/src/Persistence/EfCoreTests/EfCoreTests.csproj index 8d4b5feb6..1e51faf3c 100644 --- a/src/Persistence/EfCoreTests/EfCoreTests.csproj +++ b/src/Persistence/EfCoreTests/EfCoreTests.csproj @@ -1,6 +1,8 @@ + + true Exe false true diff --git a/src/Persistence/EfCoreTests/Migrations/with_one_postgresql_context.cs b/src/Persistence/EfCoreTests/Migrations/with_one_postgresql_context.cs index a5548d3bd..acdf13a1a 100644 --- a/src/Persistence/EfCoreTests/Migrations/with_one_postgresql_context.cs +++ b/src/Persistence/EfCoreTests/Migrations/with_one_postgresql_context.cs @@ -74,8 +74,8 @@ await context.Blogs.AddAsync(new Blog() { BlogId = 1, Url = "http://codebetter.com" - }); - await context.SaveChangesAsync(); + }, TestContext.Current.CancellationToken); + await context.SaveChangesAsync(TestContext.Current.CancellationToken); } [Fact] diff --git a/src/Persistence/EfCoreTests/Migrations/with_one_sqlserver_context.cs b/src/Persistence/EfCoreTests/Migrations/with_one_sqlserver_context.cs index bc4f07bdf..a9b6301ce 100644 --- a/src/Persistence/EfCoreTests/Migrations/with_one_sqlserver_context.cs +++ b/src/Persistence/EfCoreTests/Migrations/with_one_sqlserver_context.cs @@ -73,8 +73,8 @@ await context.Blogs.AddAsync(new Blog() { BlogId = 1, Url = "http://codebetter.com" - }); - await context.SaveChangesAsync(); + }, TestContext.Current.CancellationToken); + await context.SaveChangesAsync(TestContext.Current.CancellationToken); } [Fact] diff --git a/src/Persistence/EfCoreTests/Optimistic_concurrency_with_ef_core.cs b/src/Persistence/EfCoreTests/Optimistic_concurrency_with_ef_core.cs index f068d6ac2..348ffe109 100644 --- a/src/Persistence/EfCoreTests/Optimistic_concurrency_with_ef_core.cs +++ b/src/Persistence/EfCoreTests/Optimistic_concurrency_with_ef_core.cs @@ -49,7 +49,7 @@ public async Task detect_concurrency_exception_as_SagaConcurrencyException() opt.Services.AddResourceSetupOnStartup(StartupAction.ResetState); opt.Policies.UseDurableLocalQueues(); opt.Policies.AutoApplyTransactions(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); using var scope = host.Services.CreateScope(); var dbContext = scope.ServiceProvider.GetRequiredService(); @@ -70,8 +70,8 @@ await dbContext.ConcurrencyTestSagas.AddAsync(new() Id = sagaId, Value = "initial value", Version = 0, - }); - await dbContext.SaveChangesAsync(); + }, TestContext.Current.CancellationToken); + await dbContext.SaveChangesAsync(TestContext.Current.CancellationToken); await Should.ThrowAsync(() => host.InvokeMessageAndWaitAsync(new UpdateConcurrencyTestSaga(sagaId, "updated value"))); diff --git a/src/Persistence/EfCoreTests/QueryPlans/QueryPlan_end_to_end.cs b/src/Persistence/EfCoreTests/QueryPlans/QueryPlan_end_to_end.cs index 8d4335103..1b9860d24 100644 --- a/src/Persistence/EfCoreTests/QueryPlans/QueryPlan_end_to_end.cs +++ b/src/Persistence/EfCoreTests/QueryPlans/QueryPlan_end_to_end.cs @@ -58,7 +58,7 @@ public async Task handler_uses_query_plan_to_approve_matching_items() db.Items.Add(new Item { Id = Guid.NewGuid(), Name = $"{prefix}_a", Approved = false }); db.Items.Add(new Item { Id = Guid.NewGuid(), Name = $"{prefix}_b", Approved = false }); db.Items.Add(new Item { Id = Guid.NewGuid(), Name = "untouched", Approved = false }); - await db.SaveChangesAsync(); + await db.SaveChangesAsync(TestContext.Current.CancellationToken); } await _host.InvokeMessageAndWaitAsync(new ApproveItemsByPrefix(prefix)); @@ -68,10 +68,10 @@ public async Task handler_uses_query_plan_to_approve_matching_items() var approved = await verifyDb.Items .Where(x => x.Name.StartsWith(prefix) && x.Approved) - .CountAsync(); + .CountAsync(cancellationToken: TestContext.Current.CancellationToken); approved.ShouldBe(2); - var untouched = await verifyDb.Items.SingleAsync(x => x.Name == "untouched"); + var untouched = await verifyDb.Items.SingleAsync(x => x.Name == "untouched", cancellationToken: TestContext.Current.CancellationToken); untouched.Approved.ShouldBeFalse(); } } diff --git a/src/Persistence/EfCoreTests/QueryPlans/QueryPlan_specs.cs b/src/Persistence/EfCoreTests/QueryPlans/QueryPlan_specs.cs index 3367fb246..4846dbd88 100644 --- a/src/Persistence/EfCoreTests/QueryPlans/QueryPlan_specs.cs +++ b/src/Persistence/EfCoreTests/QueryPlans/QueryPlan_specs.cs @@ -73,7 +73,7 @@ public async Task query_plan_returns_null_when_no_match() { // Delete everything, then run the plan _db.Items.RemoveRange(_db.Items); - await _db.SaveChangesAsync(); + await _db.SaveChangesAsync(TestContext.Current.CancellationToken); var plan = new FirstApprovedItem(); var result = await plan.FetchAsync(_db, CancellationToken.None); @@ -84,7 +84,7 @@ public async Task query_plan_returns_null_when_no_match() [Fact] public async Task QueryByPlanAsync_extension_routes_to_the_plan() { - var result = await _db.QueryByPlanAsync(new FirstApprovedItem()); + var result = await _db.QueryByPlanAsync(new FirstApprovedItem(), cancellation: TestContext.Current.CancellationToken); result.ShouldNotBeNull(); result.Approved.ShouldBeTrue(); @@ -93,7 +93,7 @@ public async Task QueryByPlanAsync_extension_routes_to_the_plan() [Fact] public async Task QueryByPlanAsync_extension_works_with_list_plan() { - var results = await _db.QueryByPlanAsync(new ItemsByNamePrefix("Red")); + var results = await _db.QueryByPlanAsync(new ItemsByNamePrefix("Red"), cancellation: TestContext.Current.CancellationToken); results.Count.ShouldBe(2); } @@ -123,8 +123,8 @@ public async Task plan_parameters_via_constructor_flow_through_to_query() { // Verify that distinct parameter values yield distinct results — the // core claim of the specification pattern - var red = await _db.QueryByPlanAsync(new ItemsByNamePrefix("Red")); - var blue = await _db.QueryByPlanAsync(new ItemsByNamePrefix("Blue")); + var red = await _db.QueryByPlanAsync(new ItemsByNamePrefix("Red"), cancellation: TestContext.Current.CancellationToken); + var blue = await _db.QueryByPlanAsync(new ItemsByNamePrefix("Blue"), cancellation: TestContext.Current.CancellationToken); red.Count.ShouldBe(2); blue.Count.ShouldBe(1); diff --git a/src/Persistence/EfCoreTests/auto_database_cleaner_tests.cs b/src/Persistence/EfCoreTests/auto_database_cleaner_tests.cs index 3d6bf2a4d..267ba0503 100644 --- a/src/Persistence/EfCoreTests/auto_database_cleaner_tests.cs +++ b/src/Persistence/EfCoreTests/auto_database_cleaner_tests.cs @@ -99,15 +99,15 @@ public async Task host_ResetAllDataAsync_deletes_then_reseeds() { var db = scope.ServiceProvider.GetRequiredService(); db.Items.Add(new Item { Id = Guid.NewGuid(), Name = "Noise" }); - await db.SaveChangesAsync(); + await db.SaveChangesAsync(TestContext.Current.CancellationToken); } // Act: the new one-liner for test teardown. - await _ctx.Host.ResetAllDataAsync(); + await _ctx.Host.ResetAllDataAsync(ct: TestContext.Current.CancellationToken); using var check = _ctx.Host.Services.CreateScope(); var checkDb = check.ServiceProvider.GetRequiredService(); - var items = await checkDb.Items.OrderBy(x => x.Name).ToListAsync(); + var items = await checkDb.Items.OrderBy(x => x.Name).ToListAsync(cancellationToken: TestContext.Current.CancellationToken); items.Select(x => x.Name).ShouldBe( SeedItemsForTests.Items.Select(x => x.Name).OrderBy(n => n)); diff --git a/src/Persistence/EfCoreTests/batch_query_tests.cs b/src/Persistence/EfCoreTests/batch_query_tests.cs index a87c2a477..8db2c9f3d 100644 --- a/src/Persistence/EfCoreTests/batch_query_tests.cs +++ b/src/Persistence/EfCoreTests/batch_query_tests.cs @@ -54,7 +54,7 @@ public async Task load_two_entities_in_single_round_trip() var batch = db.CreateBatchQuery(); var item1Task = batch.QuerySingle(db.Items.Where(x => x.Id == id1)); var item2Task = batch.QuerySingle(db.Items.Where(x => x.Id == id2)); - await batch.ExecuteAsync(); + await batch.ExecuteAsync(TestContext.Current.CancellationToken); var item1 = await item1Task; var item2 = await item2Task; @@ -80,7 +80,7 @@ public async Task load_list_of_entities_via_batch() new Item { Id = Guid.NewGuid(), Name = $"{prefix}_list_2" }); #pragma warning restore VSTHRD103 // Call async methods when in an async method - await db.SaveChangesAsync(); + await db.SaveChangesAsync(TestContext.Current.CancellationToken); } using (var scope = _host.Services.CreateScope()) @@ -88,7 +88,7 @@ public async Task load_list_of_entities_via_batch() var db = scope.ServiceProvider.GetRequiredService(); var batch = db.CreateBatchQuery(); var listTask = batch.Query(db.Items.Where(x => x.Name.StartsWith(prefix))); - await batch.ExecuteAsync(); + await batch.ExecuteAsync(TestContext.Current.CancellationToken); var items = await listTask; items.Count.ShouldBe(3); @@ -112,7 +112,7 @@ public async Task mix_single_and_list_queries_in_same_batch() new Item { Id = Guid.NewGuid(), Name = $"{prefix}_b" }); #pragma warning restore VSTHRD103 // Call async methods when in an async method - await db.SaveChangesAsync(); + await db.SaveChangesAsync(TestContext.Current.CancellationToken); } using (var scope = _host.Services.CreateScope()) @@ -122,7 +122,7 @@ public async Task mix_single_and_list_queries_in_same_batch() var batch = db.CreateBatchQuery(); var singleTask = batch.QuerySingle(db.Items.Where(x => x.Id == id1)); var listTask = batch.Query(db.Items.Where(x => x.Name.StartsWith(prefix))); - await batch.ExecuteAsync(); + await batch.ExecuteAsync(TestContext.Current.CancellationToken); var single = await singleTask; var list = await listTask; diff --git a/src/Persistence/EfCoreTests/database_cleaner_tests.cs b/src/Persistence/EfCoreTests/database_cleaner_tests.cs index c3df8f23a..1671b45a5 100644 --- a/src/Persistence/EfCoreTests/database_cleaner_tests.cs +++ b/src/Persistence/EfCoreTests/database_cleaner_tests.cs @@ -110,11 +110,11 @@ public async Task delete_all_data_removes_every_row() { var db = scope.ServiceProvider.GetRequiredService(); db.Items.Add(new Item { Id = Guid.NewGuid(), Name = "Temp Item" }); - await db.SaveChangesAsync(); + await db.SaveChangesAsync(TestContext.Current.CancellationToken); } // Act: FK-safe bulk delete (no seeding) - await Cleaner.DeleteAllDataAsync(); + await Cleaner.DeleteAllDataAsync(TestContext.Current.CancellationToken); // Assert (await CountItemsAsync()).ShouldBe(0); @@ -128,16 +128,16 @@ public async Task reset_all_data_clears_then_applies_seed_data() { var db = scope.ServiceProvider.GetRequiredService(); db.Items.Add(new Item { Id = Guid.NewGuid(), Name = "Noise Item" }); - await db.SaveChangesAsync(); + await db.SaveChangesAsync(TestContext.Current.CancellationToken); } // Act: delete all + run IInitialData seeders - await Cleaner.ResetAllDataAsync(); + await Cleaner.ResetAllDataAsync(TestContext.Current.CancellationToken); // Assert: exactly the seed rows remain using var checkScope = _ctx.Host.Services.CreateScope(); var checkDb = checkScope.ServiceProvider.GetRequiredService(); - var items = await checkDb.Items.OrderBy(x => x.Name).ToListAsync(); + var items = await checkDb.Items.OrderBy(x => x.Name).ToListAsync(cancellationToken: TestContext.Current.CancellationToken); items.Count.ShouldBe(SeedItemsForTests.Items.Length); items.Select(x => x.Name).ShouldBe( diff --git a/src/Persistence/EfCoreTests/dbContext_abstraction_scenarios.cs b/src/Persistence/EfCoreTests/dbContext_abstraction_scenarios.cs index 0d3fcc136..1ff4652e9 100644 --- a/src/Persistence/EfCoreTests/dbContext_abstraction_scenarios.cs +++ b/src/Persistence/EfCoreTests/dbContext_abstraction_scenarios.cs @@ -89,7 +89,7 @@ CREATE TABLE customers_abs_schema.customers ( .IncludeType(); opts.Services.AddResourceSetupOnStartup(StartupAction.ResetState); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var orderId = Guid.NewGuid(); var customerId = Guid.NewGuid(); @@ -99,10 +99,10 @@ CREATE TABLE customers_abs_schema.customers ( await using var scope = host.Services.CreateAsyncScope(); (await scope.ServiceProvider.GetRequiredService() - .Orders.AnyAsync(o => o.Id == orderId)) + .Orders.AnyAsync(o => o.Id == orderId, cancellationToken: TestContext.Current.CancellationToken)) .ShouldBeTrue("abstracted handler must commit through the IOrderRepository transaction"); (await scope.ServiceProvider.GetRequiredService() - .Customers.AnyAsync(c => c.Id == customerId)) + .Customers.AnyAsync(c => c.Id == customerId, cancellationToken: TestContext.Current.CancellationToken)) .ShouldBeTrue("direct handler must commit through the CustomersDbContext transaction"); } @@ -155,7 +155,7 @@ CREATE TABLE store_abs_schema.orders ( .IncludeType(); opts.Services.AddResourceSetupOnStartup(StartupAction.ResetState); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var itemId = Guid.NewGuid(); var orderId = Guid.NewGuid(); @@ -165,8 +165,8 @@ CREATE TABLE store_abs_schema.orders ( await using var scope = host.Services.CreateAsyncScope(); var db = scope.ServiceProvider.GetRequiredService(); - (await db.Items.AnyAsync(i => i.Id == itemId)).ShouldBeTrue(); - (await db.StoreOrders.AnyAsync(o => o.Id == orderId)).ShouldBeTrue(); + (await db.Items.AnyAsync(i => i.Id == itemId, cancellationToken: TestContext.Current.CancellationToken)).ShouldBeTrue(); + (await db.StoreOrders.AnyAsync(o => o.Id == orderId, cancellationToken: TestContext.Current.CancellationToken)).ShouldBeTrue(); } // --- Scenario 3: same handler uses both abstractions; assert SAME DbContext instance ------- @@ -212,7 +212,7 @@ CREATE TABLE store_abs_schema.orders ( .IncludeType(); opts.Services.AddResourceSetupOnStartup(StartupAction.ResetState); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var itemId = Guid.NewGuid(); var orderId = Guid.NewGuid(); @@ -230,8 +230,8 @@ CREATE TABLE store_abs_schema.orders ( // And both writes must have landed via that single context's single SaveChanges. await using var scope = host.Services.CreateAsyncScope(); var db = scope.ServiceProvider.GetRequiredService(); - (await db.Items.AnyAsync(i => i.Id == itemId)).ShouldBeTrue(); - (await db.StoreOrders.AnyAsync(o => o.Id == orderId)).ShouldBeTrue(); + (await db.Items.AnyAsync(i => i.Id == itemId, cancellationToken: TestContext.Current.CancellationToken)).ShouldBeTrue(); + (await db.StoreOrders.AnyAsync(o => o.Id == orderId, cancellationToken: TestContext.Current.CancellationToken)).ShouldBeTrue(); } // EF Core's EnsureCreatedAsync is a no-op when the database already exists — and the shared diff --git a/src/Persistence/EfCoreTests/dbContext_transactions_with_abstractions_tests.cs b/src/Persistence/EfCoreTests/dbContext_transactions_with_abstractions_tests.cs index e09645918..5ece22b69 100644 --- a/src/Persistence/EfCoreTests/dbContext_transactions_with_abstractions_tests.cs +++ b/src/Persistence/EfCoreTests/dbContext_transactions_with_abstractions_tests.cs @@ -63,7 +63,7 @@ public async Task can_apply_transactional_middleware_to_abstraction() opts.Policies.AutoApplyTransactions(); opts.Discovery.DisableConventionalDiscovery().IncludeType(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.GetRuntime(); var chain = runtime.Handlers.ChainFor(); @@ -95,7 +95,7 @@ public async Task codegen_works_with_abstraction() opts.Policies.AutoApplyTransactions(); opts.Discovery.DisableConventionalDiscovery().IncludeType(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); // If it compiles and runs without error, the cast worked Should.NotThrow(async () => await host.InvokeMessageAndWaitAsync(new DbContextAbstractionTestFixture.AbstractionCommand())); @@ -120,7 +120,7 @@ public async Task should_add_save_changes_async_call_to_postprocessors() opts.Policies.AutoApplyTransactions(); opts.Discovery.DisableConventionalDiscovery().IncludeType(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.GetRuntime(); var chain = runtime.Handlers.ChainFor(); diff --git a/src/Persistence/EfCoreTests/eager_idempotency_with_non_wolverine_mapped_db_context.cs b/src/Persistence/EfCoreTests/eager_idempotency_with_non_wolverine_mapped_db_context.cs index 3a9883537..c021efa2c 100644 --- a/src/Persistence/EfCoreTests/eager_idempotency_with_non_wolverine_mapped_db_context.cs +++ b/src/Persistence/EfCoreTests/eager_idempotency_with_non_wolverine_mapped_db_context.cs @@ -46,7 +46,7 @@ public async Task happy_path_eager_idempotency() var ok = await transaction.TryMakeEagerIdempotencyCheckAsync(envelope, new DurabilitySettings(), CancellationToken.None); ok.ShouldBeTrue(); - await dbContext.Database.CurrentTransaction!.CommitAsync(); + await dbContext.Database.CurrentTransaction!.CommitAsync(TestContext.Current.CancellationToken); var persisted = (await runtime.Storage.Admin.AllIncomingAsync()).Single(x => x.Id == envelope.Id); persisted.Data!.Length.ShouldBe(0); @@ -56,12 +56,12 @@ public async Task happy_path_eager_idempotency() persisted.KeepUntil.HasValue.ShouldBeTrue(); using var conn = new SqlConnection(Servers.SqlServerConnectionString); - await conn.OpenAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); var raw = await conn .CreateCommand($"select keep_until from dbo.{DatabaseConstants.IncomingTable} where id = @id") .With("id", persisted.Id) - .ExecuteScalarAsync(); + .ExecuteScalarAsync(TestContext.Current.CancellationToken); raw.ShouldNotBeNull(); raw.ShouldBeOfType().ShouldBeGreaterThan(DateTimeOffset.UtcNow); @@ -107,7 +107,7 @@ public async Task persist_batch_outgoing_envelopes_uses_outgoing_table() var transaction = new EfCoreEnvelopeTransaction(dbContext, context); await transaction.PersistOutgoingAsync([envelope1, envelope2]); - await dbContext.Database.CurrentTransaction!.CommitAsync(); + await dbContext.Database.CurrentTransaction!.CommitAsync(TestContext.Current.CancellationToken); var outgoing = await runtime.Storage.Admin.AllOutgoingAsync(); outgoing.ShouldContain(x => x.Id == envelope1.Id); @@ -135,7 +135,7 @@ public async Task sad_path_eager_idempotency() var durabilitySettings = new DurabilitySettings(); var ok = await transaction.TryMakeEagerIdempotencyCheckAsync(envelope, durabilitySettings, CancellationToken.None); ok.ShouldBeTrue(); - await dbContext.Database.CurrentTransaction!.CommitAsync(); + await dbContext.Database.CurrentTransaction!.CommitAsync(TestContext.Current.CancellationToken); // Kind of resetting it here envelope.WasPersistedInInbox = false; diff --git a/src/Persistence/EfCoreTests/end_to_end_efcore_persistence.cs b/src/Persistence/EfCoreTests/end_to_end_efcore_persistence.cs index 88a07fbc2..9f55837ec 100644 --- a/src/Persistence/EfCoreTests/end_to_end_efcore_persistence.cs +++ b/src/Persistence/EfCoreTests/end_to_end_efcore_persistence.cs @@ -196,7 +196,7 @@ public void outbox_for_db_context_mapped() [Fact] public async Task persisting_against_mapped_dbcontext_does_not_start_an_explicit_transaction() { - await Host.ResetResourceState(); + await Host.ResetResourceState(cancellation: TestContext.Current.CancellationToken); var envelope = new Envelope { @@ -227,7 +227,7 @@ public async Task persisting_against_mapped_dbcontext_does_not_start_an_explicit [Fact] public async Task persist_an_outgoing_envelope_raw() { - await Host.ResetResourceState(); + await Host.ResetResourceState(cancellation: TestContext.Current.CancellationToken); var envelope = new Envelope { @@ -247,7 +247,7 @@ public async Task persist_an_outgoing_envelope_raw() await messaging.Transaction!.PersistOutgoingAsync(envelope); messaging.DbContext.Items.Add(new Item { Id = Guid.NewGuid(), Name = Guid.NewGuid().ToString() }); - await messaging.SaveChangesAndFlushMessagesAsync(); + await messaging.SaveChangesAndFlushMessagesAsync(TestContext.Current.CancellationToken); } var persisted = await Host.Services.GetRequiredService() @@ -268,7 +268,7 @@ public async Task persist_an_outgoing_envelope_raw() [Fact] public async Task persist_an_outgoing_envelope_mapped() { - await Host.ResetResourceState(); + await Host.ResetResourceState(cancellation: TestContext.Current.CancellationToken); var envelope = new Envelope { @@ -290,7 +290,7 @@ public async Task persist_an_outgoing_envelope_mapped() await messaging.Transaction!.PersistOutgoingAsync(envelope); messaging.DbContext.Items.Add(new Item { Id = Guid.NewGuid(), Name = Guid.NewGuid().ToString() }); - await messaging.SaveChangesAndFlushMessagesAsync(); + await messaging.SaveChangesAndFlushMessagesAsync(TestContext.Current.CancellationToken); } var persisted = await Host.Services.GetRequiredService() @@ -327,7 +327,7 @@ public async Task use_non_generic_outbox_raw() context.Items.Add(new Item { Id = id, Name = "Bill" }); await messaging.SendAsync(new OutboxedMessage { Id = id }); - await messaging.SaveChangesAndFlushMessagesAsync(); + await messaging.SaveChangesAndFlushMessagesAsync(TestContext.Current.CancellationToken); } var message = await waiter; @@ -336,7 +336,7 @@ public async Task use_non_generic_outbox_raw() using (var nested = Host.Services.CreateScope()) { var context = nested.ServiceProvider.GetRequiredService(); - (await context.Items.FindAsync(id)).ShouldNotBeNull(); + (await context.Items.FindAsync(new object?[] { id }, TestContext.Current.CancellationToken)).ShouldNotBeNull(); } } @@ -359,7 +359,7 @@ public async Task use_non_generic_outbox_mapped() context.Items.Add(new Item { Id = id, Name = "Bill" }); await messaging.SendAsync(new OutboxedMessage { Id = id }); - await messaging.SaveChangesAndFlushMessagesAsync(); + await messaging.SaveChangesAndFlushMessagesAsync(TestContext.Current.CancellationToken); } var message = await waiter; @@ -368,7 +368,7 @@ public async Task use_non_generic_outbox_mapped() using (var nested = Host.Services.CreateScope()) { var context = nested.ServiceProvider.GetRequiredService(); - (await context.Items.FindAsync(id)).ShouldNotBeNull(); + (await context.Items.FindAsync(new object?[] { id }, TestContext.Current.CancellationToken)).ShouldNotBeNull(); } } @@ -388,7 +388,7 @@ public async Task use_generic_outbox_raw() outbox.DbContext.Items.Add(new Item { Id = id, Name = "Bill" }); await outbox.SendAsync(new OutboxedMessage { Id = id }); - await outbox.SaveChangesAndFlushMessagesAsync(); + await outbox.SaveChangesAndFlushMessagesAsync(TestContext.Current.CancellationToken); } var message = await waiter; @@ -397,7 +397,7 @@ public async Task use_generic_outbox_raw() using (var nested = Host.Services.CreateScope()) { var context = nested.ServiceProvider.GetRequiredService(); - (await context.Items.FindAsync(id)).ShouldNotBeNull(); + (await context.Items.FindAsync(new object?[] { id }, TestContext.Current.CancellationToken)).ShouldNotBeNull(); } } @@ -418,7 +418,7 @@ public async Task DbContextOutbox_generic_can_opt_into_multiple_save_changes_and outbox.DbContext.Items.Add(new Item { Id = id1, Name = "First" }); await outbox.SendAsync(new OutboxedMessage { Id = id1 }); - await outbox.SaveChangesAndFlushMessagesAsync(MultiFlushMode.AllowMultiples); + await outbox.SaveChangesAndFlushMessagesAsync(MultiFlushMode.AllowMultiples, TestContext.Current.CancellationToken); context.MultiFlushMode.ShouldBe(MultiFlushMode.OnlyOnce); var message1 = await waiter1; @@ -428,7 +428,7 @@ public async Task DbContextOutbox_generic_can_opt_into_multiple_save_changes_and outbox.DbContext.Items.Add(new Item { Id = id2, Name = "Second" }); await outbox.SendAsync(new OutboxedMessage { Id = id2 }); - await outbox.SaveChangesAndFlushMessagesAsync(MultiFlushMode.AllowMultiples); + await outbox.SaveChangesAndFlushMessagesAsync(MultiFlushMode.AllowMultiples, TestContext.Current.CancellationToken); context.MultiFlushMode.ShouldBe(MultiFlushMode.OnlyOnce); var message2 = await waiter2; @@ -438,8 +438,8 @@ public async Task DbContextOutbox_generic_can_opt_into_multiple_save_changes_and using (var nested = Host.Services.CreateScope()) { var context = nested.ServiceProvider.GetRequiredService(); - (await context.Items.FindAsync(id1)).ShouldNotBeNull(); - (await context.Items.FindAsync(id2)).ShouldNotBeNull(); + (await context.Items.FindAsync(new object?[] { id1 }, TestContext.Current.CancellationToken)).ShouldNotBeNull(); + (await context.Items.FindAsync(new object?[] { id2 }, TestContext.Current.CancellationToken)).ShouldNotBeNull(); } } @@ -462,7 +462,7 @@ public async Task DbContextOutbox_non_generic_can_opt_into_multiple_save_changes context.Items.Add(new Item { Id = id1, Name = "First" }); await outbox.SendAsync(new OutboxedMessage { Id = id1 }); - await outbox.SaveChangesAndFlushMessagesAsync(MultiFlushMode.AllowMultiples); + await outbox.SaveChangesAndFlushMessagesAsync(MultiFlushMode.AllowMultiples, TestContext.Current.CancellationToken); messageContext.MultiFlushMode.ShouldBe(MultiFlushMode.OnlyOnce); var message1 = await waiter1; @@ -472,7 +472,7 @@ public async Task DbContextOutbox_non_generic_can_opt_into_multiple_save_changes context.Items.Add(new Item { Id = id2, Name = "Second" }); await outbox.SendAsync(new OutboxedMessage { Id = id2 }); - await outbox.SaveChangesAndFlushMessagesAsync(MultiFlushMode.AllowMultiples); + await outbox.SaveChangesAndFlushMessagesAsync(MultiFlushMode.AllowMultiples, TestContext.Current.CancellationToken); messageContext.MultiFlushMode.ShouldBe(MultiFlushMode.OnlyOnce); var message2 = await waiter2; @@ -482,8 +482,8 @@ public async Task DbContextOutbox_non_generic_can_opt_into_multiple_save_changes using (var nested = Host.Services.CreateScope()) { var context = nested.ServiceProvider.GetRequiredService(); - (await context.Items.FindAsync(id1)).ShouldNotBeNull(); - (await context.Items.FindAsync(id2)).ShouldNotBeNull(); + (await context.Items.FindAsync(new object?[] { id1 }, TestContext.Current.CancellationToken)).ShouldNotBeNull(); + (await context.Items.FindAsync(new object?[] { id2 }, TestContext.Current.CancellationToken)).ShouldNotBeNull(); } } @@ -503,7 +503,7 @@ public async Task use_generic_outbox_mapped() outbox.DbContext.Items.Add(new Item { Id = id, Name = "Bill" }); await outbox.SendAsync(new OutboxedMessage { Id = id }); - await outbox.SaveChangesAndFlushMessagesAsync(); + await outbox.SaveChangesAndFlushMessagesAsync(TestContext.Current.CancellationToken); } var message = await waiter; @@ -512,14 +512,14 @@ public async Task use_generic_outbox_mapped() using (var nested = Host.Services.CreateScope()) { var context = nested.ServiceProvider.GetRequiredService(); - (await context.Items.FindAsync(id)).ShouldNotBeNull(); + (await context.Items.FindAsync(new object?[] { id }, TestContext.Current.CancellationToken)).ShouldNotBeNull(); } } [Fact] public async Task persist_an_incoming_envelope_raw() { - await Host.ResetResourceState(); + await Host.ResetResourceState(cancellation: TestContext.Current.CancellationToken); var envelope = new Envelope { @@ -544,7 +544,7 @@ public async Task persist_an_incoming_envelope_raw() messaging.Enroll(context); await messaging.As().Transaction!.PersistIncomingAsync(envelope); - await messaging.SaveChangesAndFlushMessagesAsync(); + await messaging.SaveChangesAndFlushMessagesAsync(TestContext.Current.CancellationToken); } var persisted = await Host.Services.GetRequiredService() @@ -564,7 +564,7 @@ public async Task persist_an_incoming_envelope_raw() [Fact] public async Task persist_an_incoming_envelope_mapped() { - await Host.ResetResourceState(); + await Host.ResetResourceState(cancellation: TestContext.Current.CancellationToken); var envelope = new Envelope { @@ -589,7 +589,7 @@ public async Task persist_an_incoming_envelope_mapped() messaging.Enroll(context); await messaging.As().Transaction!.PersistIncomingAsync(envelope); - await messaging.SaveChangesAndFlushMessagesAsync(); + await messaging.SaveChangesAndFlushMessagesAsync(TestContext.Current.CancellationToken); } var persisted = await Host.Services.GetRequiredService() diff --git a/src/Persistence/EfCoreTests/idempotency_with_inline_or_buffered_endpoints_end_to_end.cs b/src/Persistence/EfCoreTests/idempotency_with_inline_or_buffered_endpoints_end_to_end.cs index e2eb7a99b..9c837850b 100644 --- a/src/Persistence/EfCoreTests/idempotency_with_inline_or_buffered_endpoints_end_to_end.cs +++ b/src/Persistence/EfCoreTests/idempotency_with_inline_or_buffered_endpoints_end_to_end.cs @@ -59,7 +59,7 @@ public async Task happy_and_sad_path(IdempotencyStyle idempotency, bool isWolver opts.PersistMessagesWithSqlServer(Servers.SqlServerConnectionString, "idempotency"); opts.UseEntityFrameworkCoreTransactions(); opts.UseEntityFrameworkCoreWolverineManagedMigrations(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var messageId = Guid.NewGuid(); var tracked1 = await host.SendMessageAndWaitAsync(new MaybeIdempotent(messageId)); @@ -110,7 +110,7 @@ public async Task happy_and_sad_path_with_message_and_destination_tracking(Idemp opts.PersistMessagesWithSqlServer(Servers.SqlServerConnectionString, "idempotency"); opts.UseEntityFrameworkCoreTransactions(); opts.UseEntityFrameworkCoreWolverineManagedMigrations(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var messageId = Guid.NewGuid(); var tracked1 = await host.SendMessageAndWaitAsync(new MaybeIdempotent(messageId)); @@ -155,7 +155,7 @@ public async Task apply_idempotency_to_non_transactional_handler() // THIS RIGHT HERE opts.Policies.AutoApplyIdempotencyOnNonTransactionalHandlers(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); #endregion diff --git a/src/Persistence/EfCoreTests/persisting_envelopes_with_sqlserver.cs b/src/Persistence/EfCoreTests/persisting_envelopes_with_sqlserver.cs index a22fa1f5e..dc0577381 100644 --- a/src/Persistence/EfCoreTests/persisting_envelopes_with_sqlserver.cs +++ b/src/Persistence/EfCoreTests/persisting_envelopes_with_sqlserver.cs @@ -155,11 +155,11 @@ public async Task persist_outgoing_batch_uses_add_range() var transaction = new EfCoreEnvelopeTransaction(dbContext, context); await transaction.PersistOutgoingAsync(envelopes); - await dbContext.SaveChangesAsync(); + await dbContext.SaveChangesAsync(TestContext.Current.CancellationToken); if (dbContext.Database.CurrentTransaction != null) { - await dbContext.Database.CurrentTransaction.CommitAsync(); + await dbContext.Database.CurrentTransaction.CommitAsync(TestContext.Current.CancellationToken); } var storage = _host.Services.GetRequiredService(); diff --git a/src/Persistence/EfCoreTests/storage_dbcontext_selection_tests.cs b/src/Persistence/EfCoreTests/storage_dbcontext_selection_tests.cs index fb6e971e9..e0eb236f7 100644 --- a/src/Persistence/EfCoreTests/storage_dbcontext_selection_tests.cs +++ b/src/Persistence/EfCoreTests/storage_dbcontext_selection_tests.cs @@ -28,8 +28,8 @@ public async Task storage_attribute_disambiguates_and_only_enrolls_that_context( { await using (var conn = new NpgsqlConnection(Servers.PostgresConnectionString)) { - await conn.OpenAsync(); - await conn.DropSchemaAsync("invoice_storage_schema"); + await conn.OpenAsync(TestContext.Current.CancellationToken); + await conn.DropSchemaAsync("invoice_storage_schema", ct: TestContext.Current.CancellationToken); await conn.CreateCommand( """ CREATE SCHEMA "invoice_storage_schema"; @@ -38,7 +38,7 @@ CREATE TABLE invoice_storage_schema.invoices ( "Memo" text NOT NULL ); """) - .ExecuteNonQueryAsync(); + .ExecuteNonQueryAsync(TestContext.Current.CancellationToken); } using var host = await Host.CreateDefaultBuilder() @@ -60,7 +60,7 @@ CREATE TABLE invoice_storage_schema.invoices ( opts.Discovery.DisableConventionalDiscovery() .IncludeType(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); host.GetRuntime().Handlers.HandlerFor(); var chain = host.GetRuntime().Handlers.ChainFor(); @@ -79,7 +79,7 @@ CREATE TABLE invoice_storage_schema.invoices ( await using var scope = host.Services.CreateAsyncScope(); var db = scope.ServiceProvider.GetRequiredService(); - (await db.Invoices.AnyAsync(i => i.Id == invoiceId)).ShouldBeTrue(); + (await db.Invoices.AnyAsync(i => i.Id == invoiceId, cancellationToken: TestContext.Current.CancellationToken)).ShouldBeTrue(); } [Fact] diff --git a/src/Persistence/EfCoreTests/transaction_middleware_mode_tests.cs b/src/Persistence/EfCoreTests/transaction_middleware_mode_tests.cs index 218ab28cf..8ee9213d0 100644 --- a/src/Persistence/EfCoreTests/transaction_middleware_mode_tests.cs +++ b/src/Persistence/EfCoreTests/transaction_middleware_mode_tests.cs @@ -38,7 +38,7 @@ public async Task eager_mode_should_add_transaction_frame() opts.Discovery.DisableConventionalDiscovery() .IncludeType(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var chain = host.GetRuntime().Handlers.ChainFor()!; @@ -71,7 +71,7 @@ public async Task lightweight_mode_should_not_add_transaction_frame() opts.Discovery.DisableConventionalDiscovery() .IncludeType(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); #endregion @@ -103,7 +103,7 @@ public async Task transactional_attribute_lightweight_overrides_eager_default() opts.Discovery.DisableConventionalDiscovery() .IncludeType() .IncludeType(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); // Verify the auto-applied handler uses the Eager default var eagerChain = host.GetRuntime().Handlers.ChainFor()!; @@ -141,7 +141,7 @@ public async Task transactional_attribute_eager_overrides_lightweight_default() opts.Discovery.DisableConventionalDiscovery() .IncludeType() .IncludeType(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); // Verify the auto-applied handler uses the Lightweight default var lightChain = host.GetRuntime().Handlers.ChainFor()!; @@ -177,7 +177,7 @@ public async Task lightweight_attribute_with_storage_side_effects_should_not_add opts.Discovery.DisableConventionalDiscovery() .IncludeType(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); // Force compilation host.GetRuntime().Handlers.HandlerFor(); @@ -209,7 +209,7 @@ public async Task eager_attribute_with_storage_side_effects_should_add_transacti opts.Discovery.DisableConventionalDiscovery() .IncludeType(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); // Force compilation host.GetRuntime().Handlers.HandlerFor(); @@ -240,7 +240,7 @@ public async Task default_mode_is_eager() opts.Discovery.DisableConventionalDiscovery() .IncludeType(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var chain = host.GetRuntime().Handlers.ChainFor()!; @@ -271,7 +271,7 @@ public async Task handler_policy_eager_mode_is_honored_for_storage_action_saga_c opts.Policies.Add>(); opts.Discovery.DisableConventionalDiscovery().IncludeType(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); host.GetRuntime().Handlers.HandlerFor(); var chain = host.GetRuntime().Handlers.ChainFor()!; diff --git a/src/Persistence/EfCoreTests/transactional_dbcontext_selection_tests.cs b/src/Persistence/EfCoreTests/transactional_dbcontext_selection_tests.cs index ff998a30c..5459680a6 100644 --- a/src/Persistence/EfCoreTests/transactional_dbcontext_selection_tests.cs +++ b/src/Persistence/EfCoreTests/transactional_dbcontext_selection_tests.cs @@ -31,8 +31,8 @@ public async Task explicit_dbcontext_type_disambiguates_and_only_enrolls_that_co { await using (var conn = new NpgsqlConnection(Servers.PostgresConnectionString)) { - await conn.OpenAsync(); - await conn.DropSchemaAsync("widget_selection_schema"); + await conn.OpenAsync(TestContext.Current.CancellationToken); + await conn.DropSchemaAsync("widget_selection_schema", ct: TestContext.Current.CancellationToken); await conn.CreateCommand( """ CREATE SCHEMA "widget_selection_schema"; @@ -41,7 +41,7 @@ CREATE TABLE widget_selection_schema.widgets ( "Name" text NOT NULL ); """) - .ExecuteNonQueryAsync(); + .ExecuteNonQueryAsync(TestContext.Current.CancellationToken); } using var host = await Host.CreateDefaultBuilder() @@ -64,7 +64,7 @@ CREATE TABLE widget_selection_schema.widgets ( opts.Discovery.DisableConventionalDiscovery() .IncludeType(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); // [Transactional]-attributed chains apply their attribute lazily on first compile, so force // it the same way transaction_middleware_mode_tests.cs does before inspecting Middleware. @@ -85,7 +85,7 @@ CREATE TABLE widget_selection_schema.widgets ( await using var scope = host.Services.CreateAsyncScope(); var db = scope.ServiceProvider.GetRequiredService(); - (await db.Widgets.AnyAsync(w => w.Id == widgetId)).ShouldBeTrue(); + (await db.Widgets.AnyAsync(w => w.Id == widgetId, cancellationToken: TestContext.Current.CancellationToken)).ShouldBeTrue(); } [Fact] @@ -133,8 +133,8 @@ public async Task explicit_dbcontext_type_can_be_a_registered_abstraction() { await using (var conn = new NpgsqlConnection(Servers.PostgresConnectionString)) { - await conn.OpenAsync(); - await conn.DropSchemaAsync("gadget_selection_schema"); + await conn.OpenAsync(TestContext.Current.CancellationToken); + await conn.DropSchemaAsync("gadget_selection_schema", ct: TestContext.Current.CancellationToken); await conn.CreateCommand( """ CREATE SCHEMA "gadget_selection_schema"; @@ -143,7 +143,7 @@ CREATE TABLE gadget_selection_schema.gadgets ( "Name" text NOT NULL ); """) - .ExecuteNonQueryAsync(); + .ExecuteNonQueryAsync(TestContext.Current.CancellationToken); } using var host = await Host.CreateDefaultBuilder() @@ -166,7 +166,7 @@ CREATE TABLE gadget_selection_schema.gadgets ( opts.Discovery.DisableConventionalDiscovery() .IncludeType(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); host.GetRuntime().Handlers.HandlerFor(); var chain = host.GetRuntime().Handlers.ChainFor(); @@ -183,7 +183,7 @@ CREATE TABLE gadget_selection_schema.gadgets ( await using var scope = host.Services.CreateAsyncScope(); var db = scope.ServiceProvider.GetRequiredService(); - (await db.Gadgets.AnyAsync(g => g.Id == gadgetId)).ShouldBeTrue(); + (await db.Gadgets.AnyAsync(g => g.Id == gadgetId, cancellationToken: TestContext.Current.CancellationToken)).ShouldBeTrue(); } } diff --git a/src/Persistence/EfCoreTests/using_add_dbcontext_with_wolverine_integration.cs b/src/Persistence/EfCoreTests/using_add_dbcontext_with_wolverine_integration.cs index 62f4daab2..f0287796f 100644 --- a/src/Persistence/EfCoreTests/using_add_dbcontext_with_wolverine_integration.cs +++ b/src/Persistence/EfCoreTests/using_add_dbcontext_with_wolverine_integration.cs @@ -80,7 +80,7 @@ public async Task happy_path_eager_idempotency() var ok = await transaction.TryMakeEagerIdempotencyCheckAsync(envelope, new DurabilitySettings(), CancellationToken.None); ok.ShouldBeTrue(); - await dbContext.Database.CurrentTransaction!.CommitAsync(); + await dbContext.Database.CurrentTransaction!.CommitAsync(TestContext.Current.CancellationToken); var persisted = (await runtime.Storage.Admin.AllIncomingAsync()).Single(x => x.Id == envelope.Id); persisted.Data!.Length.ShouldBe(0); @@ -90,12 +90,12 @@ public async Task happy_path_eager_idempotency() persisted.KeepUntil.HasValue.ShouldBeTrue(); using var conn = new SqlConnection(Servers.SqlServerConnectionString); - await conn.OpenAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); var raw = await conn .CreateCommand($"select keep_until from idempotency.{DatabaseConstants.IncomingTable} where id = @id") .With("id", persisted.Id) - .ExecuteScalarAsync(); + .ExecuteScalarAsync(TestContext.Current.CancellationToken); raw.ShouldNotBeNull(); raw.ShouldBeOfType().ShouldBeGreaterThan(DateTimeOffset.UtcNow); @@ -118,7 +118,7 @@ public async Task sad_path_eager_idempotency() var durabilitySettings = new DurabilitySettings(); var ok = await transaction.TryMakeEagerIdempotencyCheckAsync(envelope, durabilitySettings, CancellationToken.None); ok.ShouldBeTrue(); - await dbContext.Database.CurrentTransaction!.CommitAsync(); + await dbContext.Database.CurrentTransaction!.CommitAsync(TestContext.Current.CancellationToken); // Kind of resetting it here envelope.WasPersistedInInbox = false; diff --git a/src/Persistence/LeaderElection/CosmosDbTests.LeaderElection/CosmosDbTests.LeaderElection.csproj b/src/Persistence/LeaderElection/CosmosDbTests.LeaderElection/CosmosDbTests.LeaderElection.csproj index d0a1ee40f..37f99114e 100644 --- a/src/Persistence/LeaderElection/CosmosDbTests.LeaderElection/CosmosDbTests.LeaderElection.csproj +++ b/src/Persistence/LeaderElection/CosmosDbTests.LeaderElection/CosmosDbTests.LeaderElection.csproj @@ -1,6 +1,8 @@ + + true Exe false diff --git a/src/Persistence/LeaderElection/MySqlTests.LeaderElection/MySqlTests.LeaderElection.csproj b/src/Persistence/LeaderElection/MySqlTests.LeaderElection/MySqlTests.LeaderElection.csproj index e61185419..f9b748f25 100644 --- a/src/Persistence/LeaderElection/MySqlTests.LeaderElection/MySqlTests.LeaderElection.csproj +++ b/src/Persistence/LeaderElection/MySqlTests.LeaderElection/MySqlTests.LeaderElection.csproj @@ -1,6 +1,8 @@ + + true Exe false diff --git a/src/Persistence/LeaderElection/OracleTests.LeaderElection/OracleTests.LeaderElection.csproj b/src/Persistence/LeaderElection/OracleTests.LeaderElection/OracleTests.LeaderElection.csproj index f7ad2dbec..814c1f440 100644 --- a/src/Persistence/LeaderElection/OracleTests.LeaderElection/OracleTests.LeaderElection.csproj +++ b/src/Persistence/LeaderElection/OracleTests.LeaderElection/OracleTests.LeaderElection.csproj @@ -1,6 +1,8 @@ + + true Exe false diff --git a/src/Persistence/LeaderElection/PostgresqlTests.LeaderElection/PostgresqlTests.LeaderElection.csproj b/src/Persistence/LeaderElection/PostgresqlTests.LeaderElection/PostgresqlTests.LeaderElection.csproj index 87721a731..2ed682dcf 100644 --- a/src/Persistence/LeaderElection/PostgresqlTests.LeaderElection/PostgresqlTests.LeaderElection.csproj +++ b/src/Persistence/LeaderElection/PostgresqlTests.LeaderElection/PostgresqlTests.LeaderElection.csproj @@ -1,6 +1,8 @@ + + true Exe false diff --git a/src/Persistence/LeaderElection/RavenDbTests.LeaderElection/RavenDbTests.LeaderElection.csproj b/src/Persistence/LeaderElection/RavenDbTests.LeaderElection/RavenDbTests.LeaderElection.csproj index 176b08420..83c9f4aaf 100644 --- a/src/Persistence/LeaderElection/RavenDbTests.LeaderElection/RavenDbTests.LeaderElection.csproj +++ b/src/Persistence/LeaderElection/RavenDbTests.LeaderElection/RavenDbTests.LeaderElection.csproj @@ -1,6 +1,8 @@ + + true Exe net9.0 enable diff --git a/src/Persistence/LeaderElection/SqlServerTests.LeaderElection/SqlServerTests.LeaderElection.csproj b/src/Persistence/LeaderElection/SqlServerTests.LeaderElection/SqlServerTests.LeaderElection.csproj index 936676958..2680be843 100644 --- a/src/Persistence/LeaderElection/SqlServerTests.LeaderElection/SqlServerTests.LeaderElection.csproj +++ b/src/Persistence/LeaderElection/SqlServerTests.LeaderElection/SqlServerTests.LeaderElection.csproj @@ -1,6 +1,8 @@ + + true Exe false true diff --git a/src/Persistence/MartenSubscriptionTests/MartenSubscriptionTests.csproj b/src/Persistence/MartenSubscriptionTests/MartenSubscriptionTests.csproj index 113babc10..482ab1a0b 100644 --- a/src/Persistence/MartenSubscriptionTests/MartenSubscriptionTests.csproj +++ b/src/Persistence/MartenSubscriptionTests/MartenSubscriptionTests.csproj @@ -1,6 +1,8 @@ + + true Exe false true diff --git a/src/Persistence/MartenSubscriptionTests/subscriptions_end_to_end.cs b/src/Persistence/MartenSubscriptionTests/subscriptions_end_to_end.cs index ae39330bc..53e8a1dbf 100644 --- a/src/Persistence/MartenSubscriptionTests/subscriptions_end_to_end.cs +++ b/src/Persistence/MartenSubscriptionTests/subscriptions_end_to_end.cs @@ -44,7 +44,7 @@ public async Task use_unfiltered_batch_subscription() }).IntegrateWithWolverine() .UseLightweightSessions() .SubscribeToEvents(new TestBatchSubscription()); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.GetRuntime(); var routing = runtime.RoutingFor(typeof(IEvent)); @@ -81,10 +81,10 @@ public async Task use_unfiltered_batch_subscription() tracked.Executed.MessagesOf().Count().ShouldBeGreaterThanOrEqualTo(4); using var query = store.QuerySession(); - (await query.LoadAsync("A"))!.Count.ShouldBe(6); - (await query.LoadAsync("B"))!.Count.ShouldBe(7); - (await query.LoadAsync("C"))!.Count.ShouldBe(5); - (await query.LoadAsync("D"))!.Count.ShouldBe(6); + (await query.LoadAsync("A", TestContext.Current.CancellationToken))!.Count.ShouldBe(6); + (await query.LoadAsync("B", TestContext.Current.CancellationToken))!.Count.ShouldBe(7); + (await query.LoadAsync("C", TestContext.Current.CancellationToken))!.Count.ShouldBe(5); + (await query.LoadAsync("D", TestContext.Current.CancellationToken))!.Count.ShouldBe(6); } [Fact] @@ -108,7 +108,7 @@ public async Task use_filtered_batch_subscription() }).IntegrateWithWolverine() .UseLightweightSessions() .SubscribeToEvents(subscription); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var store = host.Services.GetRequiredService(); @@ -142,10 +142,10 @@ public async Task use_filtered_batch_subscription() tracked.Executed.MessagesOf().Count().ShouldBeGreaterThanOrEqualTo(2); using var query = store.QuerySession(); - (await query.LoadAsync("A"))!.Count.ShouldBe(6); - (await query.LoadAsync("B"))!.Count.ShouldBe(7); - (await query.LoadAsync("C")).ShouldBeNull(); - (await query.LoadAsync("D")).ShouldBeNull(); + (await query.LoadAsync("A", TestContext.Current.CancellationToken))!.Count.ShouldBe(6); + (await query.LoadAsync("B", TestContext.Current.CancellationToken))!.Count.ShouldBe(7); + (await query.LoadAsync("C", TestContext.Current.CancellationToken)).ShouldBeNull(); + (await query.LoadAsync("D", TestContext.Current.CancellationToken)).ShouldBeNull(); } [Fact] @@ -167,7 +167,7 @@ public async Task use_inline_subscription() }).IntegrateWithWolverine() .UseLightweightSessions() .ProcessEventsWithWolverineHandlersInStrictOrder("Inline"); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var store = host.Services.GetRequiredService(); @@ -180,7 +180,7 @@ public async Task use_inline_subscription() session.Events.StartStream(Guid.NewGuid(), new AEvent(), new AEvent(), new AEvent(), new AEvent()); session.Events.StartStream(Guid.NewGuid(), new BEvent(), new CEvent(), new CEvent(), new BEvent()); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await daemon.WaitForNonStaleData(30.Seconds()); @@ -213,7 +213,7 @@ public async Task use_inline_subscription_filtered() s.IncludeType(); s.IncludeType(); }); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var store = host.Services.GetRequiredService(); @@ -226,7 +226,7 @@ public async Task use_inline_subscription_filtered() session.Events.StartStream(Guid.NewGuid(), new AEvent(), new AEvent(), new AEvent(), new AEvent()); session.Events.StartStream(Guid.NewGuid(), new BEvent(), new CEvent(), new CEvent(), new BEvent()); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await daemon.WaitForNonStaleData(30.Seconds()); @@ -250,7 +250,7 @@ public async Task use_unfiltered_publishing_subscription() }).IntegrateWithWolverine() .UseLightweightSessions() .PublishEventsToWolverine("Publish"); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var store = host.Services.GetRequiredService(); @@ -311,7 +311,7 @@ public async Task use_filtered_publishing_subscription() x.PublishEvent(); x.PublishEvent(); }); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var store = host.Services.GetRequiredService(); @@ -378,7 +378,7 @@ public async Task non_conjoined_store_preserves_legacy_default_tenant_fallthroug { x.PublishEvent(); }); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var store = host.DocumentStore(); @@ -447,7 +447,7 @@ public async Task carry_default_tenant_id_through_under_conjoined_tenancy() { x.PublishEvent(); }); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var store = host.DocumentStore(); @@ -508,7 +508,7 @@ public async Task carry_the_tenant_id_through_on_the_subscription() x.PublishEvent(); x.PublishEvent((e, bus) => bus.PublishAsync(new TransformedMessage('D'))); }); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var store = host.DocumentStore(); @@ -572,7 +572,7 @@ public async Task use_transformed_publishing_subscription() x.PublishEvent(); x.PublishEvent((e, bus) => bus.PublishAsync(new TransformedMessage('D'))); }); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var store = host.Services.GetRequiredService(); @@ -634,7 +634,7 @@ public async Task using_singleton_scoped_subscription_from_service() }).IntegrateWithWolverine() .UseLightweightSessions() .SubscribeToEventsWithServices(ServiceLifetime.Singleton); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var store = host.Services.GetRequiredService(); @@ -647,14 +647,14 @@ public async Task using_singleton_scoped_subscription_from_service() session.Events.StartStream(Guid.NewGuid(), new AEvent(), new AEvent(), new AEvent(), new AEvent()); session.Events.StartStream(Guid.NewGuid(), new BEvent(), new CEvent(), new CEvent(), new BEvent()); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await daemon.WaitForNonStaleData(20.Seconds()); // Second round session.Events.StartStream(Guid.NewGuid(), new DEvent(), new DEvent(), new DEvent(), new DEvent()); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); // await daemon.WaitForNonStaleData(20.Seconds()); ServiceUsingSubscription.Read.Count().ShouldBe(1); @@ -686,7 +686,7 @@ public async Task using_scoped_subscription_from_service() }).IntegrateWithWolverine() .UseLightweightSessions() .SubscribeToEventsWithServices(ServiceLifetime.Scoped); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var store = host.Services.GetRequiredService(); @@ -703,7 +703,7 @@ public async Task using_scoped_subscription_from_service() session.Events.StartStream(Guid.NewGuid(), new AEvent(), new AEvent(), new AEvent(), new AEvent()); session.Events.StartStream(Guid.NewGuid(), new BEvent(), new CEvent(), new CEvent(), new BEvent()); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); } await daemon.WaitForNonStaleData(60.Seconds()); diff --git a/src/Persistence/MartenTests/AggregateHandlerWorkflow/aggregate_handler_workflow.cs b/src/Persistence/MartenTests/AggregateHandlerWorkflow/aggregate_handler_workflow.cs index c2434a1b2..0eec40835 100644 --- a/src/Persistence/MartenTests/AggregateHandlerWorkflow/aggregate_handler_workflow.cs +++ b/src/Persistence/MartenTests/AggregateHandlerWorkflow/aggregate_handler_workflow.cs @@ -249,7 +249,7 @@ public async Task if_only_returning_outgoing_messages_no_events() using (var session = theStore.LightweightSession()) { session.Events.StartStream(streamId, new AEvent(), new BEvent()); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); } var tracked = await theHost.SendMessageAndWaitAsync(new Event3(streamId)); @@ -259,7 +259,7 @@ public async Task if_only_returning_outgoing_messages_no_events() using (var session = theStore.LightweightSession()) { - var events = await session.Events.FetchStreamAsync(streamId); + var events = await session.Events.FetchStreamAsync(streamId, token: TestContext.Current.CancellationToken); events.OfType>().Any().ShouldBeFalse(); } } @@ -271,7 +271,7 @@ public async Task using_updated_aggregate_as_response() using (var session = theStore.LightweightSession()) { session.Events.StartStream(streamId, new AEvent(), new BEvent()); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); } var (tracked, updated) @@ -292,7 +292,7 @@ public async Task using_the_aggregate_in_a_before_method() { session.Events.StartStream(streamId, new AEvent(), new CEvent()); session.Events.StartStream(streamId2, new CEvent(), new CEvent()); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); } await theHost.InvokeMessageAndWaitAsync(new RaiseIfValidated(streamId)); @@ -301,11 +301,11 @@ public async Task using_the_aggregate_in_a_before_method() using (var session = theStore.LightweightSession()) { // Should not apply anything new if there is a value for ACount - var existing1 = await session.LoadAsync(streamId); + var existing1 = await session.LoadAsync(streamId, TestContext.Current.CancellationToken); existing1!.BCount.ShouldBe(0); // Should apply anything new if there was no value for ACount - var existing2 = await session.LoadAsync(streamId2); + var existing2 = await session.LoadAsync(streamId2, TestContext.Current.CancellationToken); existing2!.BCount.ShouldBe(1); } } diff --git a/src/Persistence/MartenTests/AggregateHandlerWorkflow/aggregate_handler_workflow_with_ievent.cs b/src/Persistence/MartenTests/AggregateHandlerWorkflow/aggregate_handler_workflow_with_ievent.cs index a07d28272..3a375b7ae 100644 --- a/src/Persistence/MartenTests/AggregateHandlerWorkflow/aggregate_handler_workflow_with_ievent.cs +++ b/src/Persistence/MartenTests/AggregateHandlerWorkflow/aggregate_handler_workflow_with_ievent.cs @@ -52,7 +52,7 @@ public async Task use_ievent_as_Guid_id() opts.Policies.AutoApplyTransactions(); opts.Durability.Mode = DurabilityMode.Solo; opts.Services.AddResourceSetupOnStartup(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var store = host.DocumentStore(); using var session = store.LightweightSession(); @@ -60,13 +60,13 @@ public async Task use_ievent_as_Guid_id() var streamId = Guid.NewGuid(); session.Events.StartStream(streamId, new AEvent(), new BEvent()); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); var tracked = await host.InvokeMessageAndWaitAsync(new RaiseABC(streamId)); tracked.Executed.SingleEnvelope>().ShouldNotBeNull(); - var doc = await session.LoadAsync(streamId); + var doc = await session.LoadAsync(streamId, TestContext.Current.CancellationToken); doc!.DCount.ShouldBe(1); } @@ -99,7 +99,7 @@ public async Task using_string_as_stream_key() opts.Services.AddResourceSetupOnStartup(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var store = host.DocumentStore(); using var session = store.LightweightSession(); @@ -110,7 +110,7 @@ public async Task using_string_as_stream_key() tracked.Executed.SingleEnvelope>().ShouldNotBeNull(); - var doc = await session.LoadAsync(streamKey); + var doc = await session.LoadAsync(streamKey, TestContext.Current.CancellationToken); doc!.DCount.ShouldBe(1); } diff --git a/src/Persistence/MartenTests/AggregateHandlerWorkflow/mixed_aggregate_handler_with_multiple_streams.cs b/src/Persistence/MartenTests/AggregateHandlerWorkflow/mixed_aggregate_handler_with_multiple_streams.cs index 854298b68..12babbdbf 100644 --- a/src/Persistence/MartenTests/AggregateHandlerWorkflow/mixed_aggregate_handler_with_multiple_streams.cs +++ b/src/Persistence/MartenTests/AggregateHandlerWorkflow/mixed_aggregate_handler_with_multiple_streams.cs @@ -30,12 +30,12 @@ public async Task get_the_correct_aggregate_back_out() m.Projections.Snapshot(SnapshotLifecycle.Inline); m.Projections.Snapshot(SnapshotLifecycle.Inline); }).IntegrateWithWolverine(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); using var session = host.DocumentStore().LightweightSession(); var inventoryId = session.Events.StartStream(new InventoryStarted("XFX", 100, 10)).Id; var accountId = session.Events.StartStream(new XAccountOpened(2000)).Id; - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); var (tracked, account) = await host.InvokeMessageAndWaitAsync(new MakePurchase(accountId, inventoryId, 30)); account!.Balance.ShouldBe(1700); diff --git a/src/Persistence/MartenTests/AggregateHandlerWorkflow/natural_key_aggregate_handler_workflow.cs b/src/Persistence/MartenTests/AggregateHandlerWorkflow/natural_key_aggregate_handler_workflow.cs index 004825b10..f87e0d1c9 100644 --- a/src/Persistence/MartenTests/AggregateHandlerWorkflow/natural_key_aggregate_handler_workflow.cs +++ b/src/Persistence/MartenTests/AggregateHandlerWorkflow/natural_key_aggregate_handler_workflow.cs @@ -62,13 +62,13 @@ public async Task handle_command_with_natural_key_returning_single_event() await using var session = _store.LightweightSession(); session.Events.StartStream(streamId, new NkHandlerOrderCreated(orderNumber, "Alice")); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await _host.TrackActivity() .SendMessageAndWaitAsync(new AddNkOrderItem(orderNumber, "Widget", 9.99m)); await using var verify = _store.LightweightSession(); - var aggregate = await verify.LoadAsync(streamId); + var aggregate = await verify.LoadAsync(streamId, TestContext.Current.CancellationToken); aggregate.ShouldNotBeNull(); aggregate!.TotalAmount.ShouldBe(9.99m); @@ -84,14 +84,14 @@ public async Task handle_command_with_natural_key_returning_multiple_events() await using var session = _store.LightweightSession(); session.Events.StartStream(streamId, new NkHandlerOrderCreated(orderNumber, "Bob")); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await _host.TrackActivity() .SendMessageAndWaitAsync(new AddNkOrderItems(orderNumber, [("Gadget", 19.99m), ("Doohickey", 5.50m)])); await using var verify = _store.LightweightSession(); - var aggregate = await verify.LoadAsync(streamId); + var aggregate = await verify.LoadAsync(streamId, TestContext.Current.CancellationToken); aggregate.ShouldNotBeNull(); aggregate!.TotalAmount.ShouldBe(25.49m); @@ -107,13 +107,13 @@ public async Task handle_command_with_natural_key_using_event_stream() session.Events.StartStream(streamId, new NkHandlerOrderCreated(orderNumber, "Charlie"), new NkHandlerItemAdded("Widget", 10.00m)); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await _host.TrackActivity() .SendMessageAndWaitAsync(new CompleteNkOrder(orderNumber)); await using var verify = _store.LightweightSession(); - var aggregate = await verify.LoadAsync(streamId); + var aggregate = await verify.LoadAsync(streamId, TestContext.Current.CancellationToken); aggregate.ShouldNotBeNull(); aggregate!.IsComplete.ShouldBeTrue(); diff --git a/src/Persistence/MartenTests/AggregateHandlerWorkflow/override_of_event_metadata.cs b/src/Persistence/MartenTests/AggregateHandlerWorkflow/override_of_event_metadata.cs index ca34cc804..f06dcf98e 100644 --- a/src/Persistence/MartenTests/AggregateHandlerWorkflow/override_of_event_metadata.cs +++ b/src/Persistence/MartenTests/AggregateHandlerWorkflow/override_of_event_metadata.cs @@ -42,17 +42,17 @@ public async Task return_event_with_metadata_from_aggregate_handler() opts.Services.AddResourceSetupOnStartup(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var id = Guid.NewGuid(); using var session = host.DocumentStore().LightweightSession(); session.Events.StartStream(id, new AEvent()); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await host.InvokeMessageAndWaitAsync(new EmitEventsWithMetadata(id)); - var stream = await session.Events.FetchStreamAsync(id); + var stream = await session.Events.FetchStreamAsync(id, token: TestContext.Current.CancellationToken); foreach (var e in stream) { diff --git a/src/Persistence/MartenTests/AggregateHandlerWorkflow/strong_named_identifiers.cs b/src/Persistence/MartenTests/AggregateHandlerWorkflow/strong_named_identifiers.cs index c2cd4e4c9..6b7f2126e 100644 --- a/src/Persistence/MartenTests/AggregateHandlerWorkflow/strong_named_identifiers.cs +++ b/src/Persistence/MartenTests/AggregateHandlerWorkflow/strong_named_identifiers.cs @@ -45,10 +45,10 @@ public async Task use_read_aggregate_by_itself() using var session = theHost.DocumentStore().LightweightSession(); session.Events.StartStream(streamId, new AEvent(), new BEvent(), new CEvent(), new CEvent()); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); var bus = theHost.MessageBus(); - var aggregate = await bus.InvokeAsync(new FetchCounts(new LetterId(streamId))); + var aggregate = await bus.InvokeAsync(new FetchCounts(new LetterId(streamId)), TestContext.Current.CancellationToken); aggregate.ACount.ShouldBe(1); aggregate.BCount.ShouldBe(1); @@ -62,12 +62,12 @@ public async Task single_usage_of_write_aggregate() using var session = theHost.DocumentStore().LightweightSession(); session.Events.StartStream(streamId, new AEvent(), new BEvent(), new CEvent(), new CEvent()); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await theHost.InvokeAsync(new IncrementStrongA(new LetterId(streamId))); var bus = theHost.MessageBus(); - var aggregate = await bus.InvokeAsync(new FetchCounts(new LetterId(streamId))); + var aggregate = await bus.InvokeAsync(new FetchCounts(new LetterId(streamId)), TestContext.Current.CancellationToken); aggregate.ACount.ShouldBe(2); aggregate.BCount.ShouldBe(1); @@ -85,14 +85,14 @@ public async Task batch_query_usage_of_write_aggregate() session.Events.StartStream(stream2Id, new AEvent(), new BEvent(), new BEvent(), new AEvent()); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await theHost.InvokeMessageAndWaitAsync(new IncrementBOnBoth(new LetterId(stream1Id), new LetterId(stream2Id))); - var aggregate1 = await session.Events.FetchLatest(stream1Id); + var aggregate1 = await session.Events.FetchLatest(stream1Id, TestContext.Current.CancellationToken); aggregate1!.BCount.ShouldBe(2); - var aggregate2 = await session.Events.FetchLatest(stream2Id); + var aggregate2 = await session.Events.FetchLatest(stream2Id, TestContext.Current.CancellationToken); aggregate2!.BCount.ShouldBe(3); } @@ -108,16 +108,16 @@ public async Task batch_query_with_both_read_and_write_aggregate() session.Events.StartStream(stream2Id, new AEvent(), new BEvent(), new BEvent(), new AEvent(), new DEvent()); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await theHost.InvokeMessageAndWaitAsync(new AddFrom(new LetterId(stream1Id), new LetterId(stream2Id))); - var aggregate1 = await session.Events.FetchLatest(stream1Id); + var aggregate1 = await session.Events.FetchLatest(stream1Id, TestContext.Current.CancellationToken); aggregate1!.BCount.ShouldBe(3); aggregate1.ACount.ShouldBe(3); aggregate1.DCount.ShouldBe(1); - var aggregate2 = await session.Events.FetchLatest(stream2Id); + var aggregate2 = await session.Events.FetchLatest(stream2Id, TestContext.Current.CancellationToken); aggregate2!.BCount.ShouldBe(2); } diff --git a/src/Persistence/MartenTests/AggregateHandlerWorkflow/tenant_partitioned_aggregate_matrix_phase1b.cs b/src/Persistence/MartenTests/AggregateHandlerWorkflow/tenant_partitioned_aggregate_matrix_phase1b.cs index a256a606d..c1717fe2b 100644 --- a/src/Persistence/MartenTests/AggregateHandlerWorkflow/tenant_partitioned_aggregate_matrix_phase1b.cs +++ b/src/Persistence/MartenTests/AggregateHandlerWorkflow/tenant_partitioned_aggregate_matrix_phase1b.cs @@ -81,7 +81,7 @@ public async Task empty_result_makes_no_write() // Still just the seed event — no new append, aggregate unchanged. await using var session = theStore.LightweightSession("tenant1"); - (await session.Events.FetchStreamAsync(id)).Count.ShouldBe(1); + (await session.Events.FetchStreamAsync(id, token: TestContext.Current.CancellationToken)).Count.ShouldBe(1); (await LoadTally("tenant1", id))!.Total.ShouldBe(0); } diff --git a/src/Persistence/MartenTests/AggregateHandlerWorkflow/tenant_partitioned_events_aggregate_workflow.cs b/src/Persistence/MartenTests/AggregateHandlerWorkflow/tenant_partitioned_events_aggregate_workflow.cs index 4ecc95245..9e5d06329 100644 --- a/src/Persistence/MartenTests/AggregateHandlerWorkflow/tenant_partitioned_events_aggregate_workflow.cs +++ b/src/Persistence/MartenTests/AggregateHandlerWorkflow/tenant_partitioned_events_aggregate_workflow.cs @@ -142,7 +142,7 @@ public async Task no_tenant_falls_to_the_default_partition_isolated() // Landed in the default-tenant partition... await using (var session = theStore.LightweightSession()) { - (await session.LoadAsync(id))!.Total.ShouldBe(9); + (await session.LoadAsync(id, TestContext.Current.CancellationToken))!.Total.ShouldBe(9); } // ...and is invisible to the named-tenant partitions. diff --git a/src/Persistence/MartenTests/AncillaryStores/bootstrapping_ancillary_marten_stores_with_wolverine.cs b/src/Persistence/MartenTests/AncillaryStores/bootstrapping_ancillary_marten_stores_with_wolverine.cs index 71e1d5070..a31c86b65 100644 --- a/src/Persistence/MartenTests/AncillaryStores/bootstrapping_ancillary_marten_stores_with_wolverine.cs +++ b/src/Persistence/MartenTests/AncillaryStores/bootstrapping_ancillary_marten_stores_with_wolverine.cs @@ -241,7 +241,7 @@ public async Task try_to_use_the_session_transactional_middleware_end_to_end() var store = theHost.DocumentStore(); using var session = store.QuerySession(); - var player = await session.LoadAsync(message.Id); + var player = await session.LoadAsync(message.Id, TestContext.Current.CancellationToken); player.ShouldNotBeNull(); } diff --git a/src/Persistence/MartenTests/AncillaryStores/storage_attribute_routes_to_marten_store.cs b/src/Persistence/MartenTests/AncillaryStores/storage_attribute_routes_to_marten_store.cs index ee43ac1fa..dc99e8d39 100644 --- a/src/Persistence/MartenTests/AncillaryStores/storage_attribute_routes_to_marten_store.cs +++ b/src/Persistence/MartenTests/AncillaryStores/storage_attribute_routes_to_marten_store.cs @@ -55,7 +55,7 @@ public async Task storage_attribute_opens_and_commits_through_the_marten_ancilla var store = theHost.DocumentStore(); await using var session = store.QuerySession(); - (await session.LoadAsync(message.Id)).ShouldNotBeNull(); + (await session.LoadAsync(message.Id, TestContext.Current.CancellationToken)).ShouldNotBeNull(); } } diff --git a/src/Persistence/MartenTests/AncillaryStores/tenant_partitioned_ancillary_store.cs b/src/Persistence/MartenTests/AncillaryStores/tenant_partitioned_ancillary_store.cs index 233969a26..2440f66ff 100644 --- a/src/Persistence/MartenTests/AncillaryStores/tenant_partitioned_ancillary_store.cs +++ b/src/Persistence/MartenTests/AncillaryStores/tenant_partitioned_ancillary_store.cs @@ -79,17 +79,17 @@ public async ValueTask DisposeAsync() public async Task ancillary_store_append_lands_in_the_routed_tenant_partition() { var id = "thing-" + Guid.NewGuid().ToString("N"); - await theHost.MessageBus().InvokeForTenantAsync("tenant1", new RecordPartThing(id, 3)); + await theHost.MessageBus().InvokeForTenantAsync("tenant1", new RecordPartThing(id, 3), TestContext.Current.CancellationToken); await using (var s1 = theStore.LightweightSession("tenant1")) { - (await s1.Events.FetchStreamAsync(id)).Count.ShouldBe(1); + (await s1.Events.FetchStreamAsync(id, token: TestContext.Current.CancellationToken)).Count.ShouldBe(1); } // Isolated: the same stream id is absent from tenant2's partition of the ancillary store. await using (var s2 = theStore.LightweightSession("tenant2")) { - (await s2.Events.FetchStreamAsync(id)).Count.ShouldBe(0); + (await s2.Events.FetchStreamAsync(id, token: TestContext.Current.CancellationToken)).Count.ShouldBe(0); } } } diff --git a/src/Persistence/MartenTests/Bugs/Bug_1175_schema_name_with_queues.cs b/src/Persistence/MartenTests/Bugs/Bug_1175_schema_name_with_queues.cs index b9511b510..eac996093 100644 --- a/src/Persistence/MartenTests/Bugs/Bug_1175_schema_name_with_queues.cs +++ b/src/Persistence/MartenTests/Bugs/Bug_1175_schema_name_with_queues.cs @@ -44,7 +44,7 @@ public async Task send_messages_with_postgresql_queueing() opts.Durability.Mode = DurabilityMode.Solo; opts.Services.AddResourceSetupOnStartup(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); using var listener = await Host.CreateDefaultBuilder() .UseWolverine(opts => @@ -74,7 +74,7 @@ public async Task send_messages_with_postgresql_queueing() opts.Durability.Mode = DurabilityMode.Solo; opts.Services.AddResourceSetupOnStartup(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var tracked = await sender.TrackActivity().AlsoTrack(listener).SendMessageAndWaitAsync(new ColorRequest("red")); tracked.Received.SingleMessage().Color.ShouldBe("red"); diff --git a/src/Persistence/MartenTests/Bugs/Bug_191_marten_aggregate_handler_command_should_not_require_version.cs b/src/Persistence/MartenTests/Bugs/Bug_191_marten_aggregate_handler_command_should_not_require_version.cs index 9b9e0ad10..650775730 100644 --- a/src/Persistence/MartenTests/Bugs/Bug_191_marten_aggregate_handler_command_should_not_require_version.cs +++ b/src/Persistence/MartenTests/Bugs/Bug_191_marten_aggregate_handler_command_should_not_require_version.cs @@ -45,7 +45,7 @@ public async Task execute_without_code_compilation_errors() using (var session = _host.Services.GetRequiredService().LightweightSession()) { session.Events.StartStream(id, new ThingStarted(id, "stuff")); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); } await _host.InvokeMessageAndWaitAsync(new UpdateThing(id, "new stuff")); diff --git a/src/Persistence/MartenTests/Bugs/Bug_215_erroneous_failure_ack_on_invoke_async_of_t.cs b/src/Persistence/MartenTests/Bugs/Bug_215_erroneous_failure_ack_on_invoke_async_of_t.cs index 313cf4a79..fc8428e66 100644 --- a/src/Persistence/MartenTests/Bugs/Bug_215_erroneous_failure_ack_on_invoke_async_of_t.cs +++ b/src/Persistence/MartenTests/Bugs/Bug_215_erroneous_failure_ack_on_invoke_async_of_t.cs @@ -28,18 +28,18 @@ public async Task no_failure_ack_on_invoke_async() .IncludeType(typeof(LookupHandler)); opts.Durability.Mode = DurabilityMode.Solo; opts.Services.AddResourceSetupOnStartup(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var data = new Bug215Data(); using (var session = host.Services.GetRequiredService().LightweightSession()) { session.Store(data); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); } var bus = host.MessageBus(); - var response = await bus.InvokeAsync(new Lookup(data.Id)); + var response = await bus.InvokeAsync(new Lookup(data.Id), TestContext.Current.CancellationToken); response.ShouldNotBeNull(); } diff --git a/src/Persistence/MartenTests/Bugs/Bug_218_auto_transaction_when_session_is_dependency_of_a_dependency.cs b/src/Persistence/MartenTests/Bugs/Bug_218_auto_transaction_when_session_is_dependency_of_a_dependency.cs index 9cc78098c..4c0f38a72 100644 --- a/src/Persistence/MartenTests/Bugs/Bug_218_auto_transaction_when_session_is_dependency_of_a_dependency.cs +++ b/src/Persistence/MartenTests/Bugs/Bug_218_auto_transaction_when_session_is_dependency_of_a_dependency.cs @@ -27,14 +27,14 @@ public async Task should_apply_transaction() opts.Discovery.DisableConventionalDiscovery() .IncludeType(); opts.Durability.Mode = DurabilityMode.Solo; - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var id = Guid.NewGuid(); await host.InvokeMessageAndWaitAsync(new CreateBug218(id)); using var session = host.Services.GetRequiredService().LightweightSession(); - var doc = await session.LoadAsync(id); + var doc = await session.LoadAsync(id, TestContext.Current.CancellationToken); doc.ShouldNotBeNull(); } diff --git a/src/Persistence/MartenTests/Bugs/Bug_225_compound_handlers_and_marten_event_streams.cs b/src/Persistence/MartenTests/Bugs/Bug_225_compound_handlers_and_marten_event_streams.cs index b8f2e1ec1..853353428 100644 --- a/src/Persistence/MartenTests/Bugs/Bug_225_compound_handlers_and_marten_event_streams.cs +++ b/src/Persistence/MartenTests/Bugs/Bug_225_compound_handlers_and_marten_event_streams.cs @@ -29,14 +29,14 @@ public async Task should_apply_transaction() .IncludeType(); opts.Durability.Mode = DurabilityMode.Solo; }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var id = Guid.NewGuid(); await host.InvokeMessageAndWaitAsync(new StoreSomething2(id)); using var session = host.Services.GetRequiredService().LightweightSession(); - var stream = await session.Events.FetchStreamAsync(id); + var stream = await session.Events.FetchStreamAsync(id, token: TestContext.Current.CancellationToken); stream.ShouldNotBeEmpty(); } diff --git a/src/Persistence/MartenTests/Bugs/Bug_226_disambiguate_loggers.cs b/src/Persistence/MartenTests/Bugs/Bug_226_disambiguate_loggers.cs index a3f4a6cc7..cd363cfcc 100644 --- a/src/Persistence/MartenTests/Bugs/Bug_226_disambiguate_loggers.cs +++ b/src/Persistence/MartenTests/Bugs/Bug_226_disambiguate_loggers.cs @@ -35,7 +35,7 @@ public async Task should_find_handler() .IncludeType(); opts.Durability.Mode = DurabilityMode.Solo; }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var id = Guid.NewGuid(); diff --git a/src/Persistence/MartenTests/Bugs/Bug_2318_ancillary_dlq_replay.cs b/src/Persistence/MartenTests/Bugs/Bug_2318_ancillary_dlq_replay.cs index 35f4067c0..37877ca4b 100644 --- a/src/Persistence/MartenTests/Bugs/Bug_2318_ancillary_dlq_replay.cs +++ b/src/Persistence/MartenTests/Bugs/Bug_2318_ancillary_dlq_replay.cs @@ -139,7 +139,7 @@ await _host .InvokeMessageAndWaitAsync(message); // Give time for the message to be dead-lettered - await Task.Delay(5.Seconds()); + await Task.Delay(5.Seconds(), TestContext.Current.CancellationToken); var runtime = _host.GetRuntime(); var ancillaryStore = runtime.Stores.FindAncillaryStore(typeof(IAncillaryStore2318)); @@ -167,7 +167,7 @@ await ancillaryStore.DeadLetters.ReplayAsync( ancillaryStore.StartScheduledJobs(runtime); // Wait for the replayed message to be processed - await Task.Delay(10.Seconds()); + await Task.Delay(10.Seconds(), TestContext.Current.CancellationToken); // Step 4: Verify the envelope is NOT stuck as Incoming in the ancillary store var incoming = await ancillaryStore.Admin.AllIncomingAsync(); diff --git a/src/Persistence/MartenTests/Bugs/Bug_2382_ancillary_store_inbox.cs b/src/Persistence/MartenTests/Bugs/Bug_2382_ancillary_store_inbox.cs index 121ce9582..c38394985 100644 --- a/src/Persistence/MartenTests/Bugs/Bug_2382_ancillary_store_inbox.cs +++ b/src/Persistence/MartenTests/Bugs/Bug_2382_ancillary_store_inbox.cs @@ -129,7 +129,7 @@ await _host .TrackActivity() .SendMessageAndWaitAsync(message); - await Task.Delay(500); + await Task.Delay(500, TestContext.Current.CancellationToken); var runtime = _host.Services.GetRequiredService(); @@ -150,7 +150,7 @@ await _host .TrackActivity() .SendMessageAndWaitAsync(message); - await Task.Delay(500); + await Task.Delay(500, TestContext.Current.CancellationToken); var runtime = _host.Services.GetRequiredService(); @@ -177,18 +177,18 @@ await _host .TrackActivity() .SendMessageAndWaitAsync(mainMessage); - await Task.Delay(500); + await Task.Delay(500, TestContext.Current.CancellationToken); // Verify ancillary store has the document var ancillaryStore = _host.Services.GetRequiredService(); await using var ancillarySession = ancillaryStore.LightweightSession(); - var ancillaryDoc = await ancillarySession.LoadAsync(ancillaryMessage.Id); + var ancillaryDoc = await ancillarySession.LoadAsync(ancillaryMessage.Id, TestContext.Current.CancellationToken); ancillaryDoc.ShouldNotBeNull(); // Verify main store has the document var mainStore = _host.Services.GetRequiredService(); await using var mainSession = mainStore.LightweightSession(); - var mainDoc = await mainSession.LoadAsync(mainMessage.Id); + var mainDoc = await mainSession.LoadAsync(mainMessage.Id, TestContext.Current.CancellationToken); mainDoc.ShouldNotBeNull(); // Neither should have lingering incoming envelopes @@ -209,7 +209,7 @@ await _host // Verify the document was stored in the ancillary store var ancillaryStore = _host.Services.GetRequiredService(); await using var session = ancillaryStore.LightweightSession(); - var doc = await session.LoadAsync(message.Id); + var doc = await session.LoadAsync(message.Id, TestContext.Current.CancellationToken); doc.ShouldNotBeNull(); } } diff --git a/src/Persistence/MartenTests/Bugs/Bug_2387_write_aggregate_throw_exception_codegen.cs b/src/Persistence/MartenTests/Bugs/Bug_2387_write_aggregate_throw_exception_codegen.cs index ace9b1eff..c863545ee 100644 --- a/src/Persistence/MartenTests/Bugs/Bug_2387_write_aggregate_throw_exception_codegen.cs +++ b/src/Persistence/MartenTests/Bugs/Bug_2387_write_aggregate_throw_exception_codegen.cs @@ -64,7 +64,7 @@ public async Task codegen_compiles_with_write_aggregate_throw_exception_and_vali await using var session = _store.LightweightSession(); var action = session.Events.StartStream(new Bug2387Created("test")); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); // If codegen is broken, this will throw a compilation error: // CS0841: Cannot use local variable 'stream_entity' before it is declared diff --git a/src/Persistence/MartenTests/Bugs/Bug_2545_raise_side_effects_with_metadata_override.cs b/src/Persistence/MartenTests/Bugs/Bug_2545_raise_side_effects_with_metadata_override.cs index 48c22daa1..72d86625e 100644 --- a/src/Persistence/MartenTests/Bugs/Bug_2545_raise_side_effects_with_metadata_override.cs +++ b/src/Persistence/MartenTests/Bugs/Bug_2545_raise_side_effects_with_metadata_override.cs @@ -51,14 +51,14 @@ public async Task metadata_on_PublishMessage_flows_to_handler_context_and_marten opts.Discovery.DisableConventionalDiscovery() .IncludeType(typeof(Bug2545SideEffectHandler)); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var streamId = Guid.NewGuid(); Bug2545SideEffectHandler.Received.Clear(); // Clear any prior state from earlier test runs. var store = host.Services.GetRequiredService(); - await store.Advanced.Clean.CompletelyRemoveAllAsync(); + await store.Advanced.Clean.CompletelyRemoveAllAsync(TestContext.Current.CancellationToken); var tracked = await host .TrackActivity() diff --git a/src/Persistence/MartenTests/Bugs/Bug_2576_ancillary_scheduled_message_stuck_incoming.cs b/src/Persistence/MartenTests/Bugs/Bug_2576_ancillary_scheduled_message_stuck_incoming.cs index be00ffc12..acdf47fa6 100644 --- a/src/Persistence/MartenTests/Bugs/Bug_2576_ancillary_scheduled_message_stuck_incoming.cs +++ b/src/Persistence/MartenTests/Bugs/Bug_2576_ancillary_scheduled_message_stuck_incoming.cs @@ -140,7 +140,7 @@ await _host // The scheduled message has to wake up out of the scheduled-jobs poller // and run through the handler. Give it a moment. - await Task.Delay(5.Seconds()); + await Task.Delay(5.Seconds(), TestContext.Current.CancellationToken); var runtime = _host.GetRuntime(); var ancillaryStore = runtime.Stores.FindAncillaryStore(typeof(IAncillaryStore2576)); diff --git a/src/Persistence/MartenTests/Bugs/Bug_2595_explicit_delivery_options_sagaid_should_win.cs b/src/Persistence/MartenTests/Bugs/Bug_2595_explicit_delivery_options_sagaid_should_win.cs index a2cf2a984..4d0fcb6b4 100644 --- a/src/Persistence/MartenTests/Bugs/Bug_2595_explicit_delivery_options_sagaid_should_win.cs +++ b/src/Persistence/MartenTests/Bugs/Bug_2595_explicit_delivery_options_sagaid_should_win.cs @@ -83,7 +83,7 @@ public async Task explicit_delivery_options_sagaid_on_saga_start_cascade_should_ // not own its document table; load by id rather than asserting total // table count, so concurrent or prior runs don't break the assertion). var childId = Guid.Parse(doWorkEnvelope.SagaId!); - var child = await session.LoadAsync(childId); + var child = await session.LoadAsync(childId, TestContext.Current.CancellationToken); child.ShouldNotBeNull("ChildSaga.Start must have inserted the saga document"); // Final proof: the WorkDone reply auto-propagated the (correct) child diff --git a/src/Persistence/MartenTests/Bugs/Bug_262_test_does_not_complete_with_timeout_message.cs b/src/Persistence/MartenTests/Bugs/Bug_262_test_does_not_complete_with_timeout_message.cs index 5de8e14e9..fe696c9a2 100644 --- a/src/Persistence/MartenTests/Bugs/Bug_262_test_does_not_complete_with_timeout_message.cs +++ b/src/Persistence/MartenTests/Bugs/Bug_262_test_does_not_complete_with_timeout_message.cs @@ -39,7 +39,7 @@ public async Task should_work_but_doesnt() // Without UseDurableLocalQueues it's green. w.Policies.UseDurableLocalQueues(); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var id = Guid.NewGuid(); @@ -50,7 +50,7 @@ await host.TrackActivity() using var session = host.Services.GetRequiredService().LightweightSession(); - var saga = await session.LoadAsync(id); + var saga = await session.LoadAsync(id, TestContext.Current.CancellationToken); saga.ShouldNotBeNull(); saga.TimedOut.ShouldBeTrue(); } diff --git a/src/Persistence/MartenTests/Bugs/Bug_2669_ancillary_marten_store_local_message_from_main_store.cs b/src/Persistence/MartenTests/Bugs/Bug_2669_ancillary_marten_store_local_message_from_main_store.cs index 798e08306..f7982cd96 100644 --- a/src/Persistence/MartenTests/Bugs/Bug_2669_ancillary_marten_store_local_message_from_main_store.cs +++ b/src/Persistence/MartenTests/Bugs/Bug_2669_ancillary_marten_store_local_message_from_main_store.cs @@ -128,7 +128,7 @@ await _host .GetRequiredService() .LightweightSession(); - var document = await session.LoadAsync(id); + var document = await session.LoadAsync(id, TestContext.Current.CancellationToken); document.ShouldNotBeNull(); } diff --git a/src/Persistence/MartenTests/Bugs/Bug_305_invoke_async_with_return_not_publishing_with_tuple_return_value.cs b/src/Persistence/MartenTests/Bugs/Bug_305_invoke_async_with_return_not_publishing_with_tuple_return_value.cs index 718cbb9f4..88feecf31 100644 --- a/src/Persistence/MartenTests/Bugs/Bug_305_invoke_async_with_return_not_publishing_with_tuple_return_value.cs +++ b/src/Persistence/MartenTests/Bugs/Bug_305_invoke_async_with_return_not_publishing_with_tuple_return_value.cs @@ -26,7 +26,7 @@ public async Task should_publish_the_return_value() opts.Services.AddMarten(Servers.PostgresConnectionString).IntegrateWithWolverine(); // Add the auto transaction middleware attachment policy opts.Policies.AutoApplyTransactions(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var (tracked, created) = await host.InvokeMessageAndWaitAsync(new CreateItemCommand { Name = "Trevor" }); @@ -51,7 +51,7 @@ public async Task honor_the_attribute() opts.Services.AddMarten(Servers.PostgresConnectionString).IntegrateWithWolverine(); // Add the auto transaction middleware attachment policy opts.Policies.AutoApplyTransactions(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); Func execute = async c => { diff --git a/src/Persistence/MartenTests/Bugs/Bug_309_service_dependencies_should_be_deep_on_injected_arguments.cs b/src/Persistence/MartenTests/Bugs/Bug_309_service_dependencies_should_be_deep_on_injected_arguments.cs index 41e9dbf77..36b7875db 100644 --- a/src/Persistence/MartenTests/Bugs/Bug_309_service_dependencies_should_be_deep_on_injected_arguments.cs +++ b/src/Persistence/MartenTests/Bugs/Bug_309_service_dependencies_should_be_deep_on_injected_arguments.cs @@ -26,13 +26,13 @@ public async Task discover_session_is_required_by_constructor_argument_of_handle opts.Services.AddScoped(); opts.Discovery.DisableConventionalDiscovery().IncludeType(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var (_, created) = await host.InvokeMessageAndWaitAsync(new CreateItem()); using var session = host.DocumentStore().LightweightSession(); - var item = await session.LoadAsync(created!.Id); + var item = await session.LoadAsync(created!.Id, TestContext.Current.CancellationToken); item.ShouldNotBeNull(); } } diff --git a/src/Persistence/MartenTests/Bugs/Bug_310_saga_handler_that_returns_another_saga.cs b/src/Persistence/MartenTests/Bugs/Bug_310_saga_handler_that_returns_another_saga.cs index 66e89a3ed..f06268a3e 100644 --- a/src/Persistence/MartenTests/Bugs/Bug_310_saga_handler_that_returns_another_saga.cs +++ b/src/Persistence/MartenTests/Bugs/Bug_310_saga_handler_that_returns_another_saga.cs @@ -48,10 +48,10 @@ public async Task one_saga_spawns_another() using var session = _host.Services.GetRequiredService().LightweightSession(); - var saga1 = await session.LoadAsync(id); + var saga1 = await session.LoadAsync(id, TestContext.Current.CancellationToken); saga1!.One.ShouldBeTrue(); - var saga2 = await session.LoadAsync(id); + var saga2 = await session.LoadAsync(id, TestContext.Current.CancellationToken); saga2!.Two.ShouldBeTrue(); saga2.Three.ShouldBeTrue(); } diff --git a/src/Persistence/MartenTests/Bugs/Bug_581_complex_dependency_graph_transactional_middleware_application.cs b/src/Persistence/MartenTests/Bugs/Bug_581_complex_dependency_graph_transactional_middleware_application.cs index 1845f02bf..2653537cf 100644 --- a/src/Persistence/MartenTests/Bugs/Bug_581_complex_dependency_graph_transactional_middleware_application.cs +++ b/src/Persistence/MartenTests/Bugs/Bug_581_complex_dependency_graph_transactional_middleware_application.cs @@ -47,7 +47,7 @@ public async Task apply_transactional_middleware_when_session_is_used_internally opts.Policies.ForMessagesOfType() .AddMiddleware(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.GetRuntime(); var handlers = runtime.Handlers; diff --git a/src/Persistence/MartenTests/Bugs/Bug_756_composite_handler_on_saga.cs b/src/Persistence/MartenTests/Bugs/Bug_756_composite_handler_on_saga.cs index f8c72f6e7..82feefc3d 100644 --- a/src/Persistence/MartenTests/Bugs/Bug_756_composite_handler_on_saga.cs +++ b/src/Persistence/MartenTests/Bugs/Bug_756_composite_handler_on_saga.cs @@ -21,7 +21,7 @@ public async Task compile_successfully() opts.Discovery.IncludeType(); opts.Services.AddMarten(Servers.PostgresConnectionString).IntegrateWithWolverine(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); await host.InvokeMessageAndWaitAsync(new DoSomething(Guid.NewGuid())); } diff --git a/src/Persistence/MartenTests/Bugs/Bug_778_multiple_marten_ops_in_tuple.cs b/src/Persistence/MartenTests/Bugs/Bug_778_multiple_marten_ops_in_tuple.cs index 375f7660c..3c522764e 100644 --- a/src/Persistence/MartenTests/Bugs/Bug_778_multiple_marten_ops_in_tuple.cs +++ b/src/Persistence/MartenTests/Bugs/Bug_778_multiple_marten_ops_in_tuple.cs @@ -27,7 +27,7 @@ public async Task call_both_side_effects() }).IntegrateWithWolverine(); opts.Policies.AutoApplyTransactions(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var command = new SpawnTwo(Guid.NewGuid().ToString(), Guid.NewGuid().ToString()); @@ -35,8 +35,8 @@ public async Task call_both_side_effects() var store = host.Services.GetRequiredService(); using var session = store.LightweightSession(); - var person1 = await session.LoadAsync(command.Name1); - var person2 = await session.LoadAsync(command.Name2); + var person1 = await session.LoadAsync(command.Name1, TestContext.Current.CancellationToken); + var person2 = await session.LoadAsync(command.Name2, TestContext.Current.CancellationToken); person1.ShouldNotBeNull(); person2.ShouldNotBeNull(); diff --git a/src/Persistence/MartenTests/Bugs/Bug_826_issue_with_paused_listener.cs b/src/Persistence/MartenTests/Bugs/Bug_826_issue_with_paused_listener.cs index 39aa89885..d8716b1d3 100644 --- a/src/Persistence/MartenTests/Bugs/Bug_826_issue_with_paused_listener.cs +++ b/src/Persistence/MartenTests/Bugs/Bug_826_issue_with_paused_listener.cs @@ -53,7 +53,7 @@ public async Task can_resume_listening() .IntegrateWithWolverine(); }); - using var host = await builder.StartAsync(); + using var host = await builder.StartAsync(cancellationToken: TestContext.Current.CancellationToken); await host.TrackActivity() .WaitForMessageToBeReceivedAt(host) diff --git a/src/Persistence/MartenTests/Bugs/Bug_971_replay_dead_letter_queue_of_event_wrapper.cs b/src/Persistence/MartenTests/Bugs/Bug_971_replay_dead_letter_queue_of_event_wrapper.cs index 8126890d4..1d54bab32 100644 --- a/src/Persistence/MartenTests/Bugs/Bug_971_replay_dead_letter_queue_of_event_wrapper.cs +++ b/src/Persistence/MartenTests/Bugs/Bug_971_replay_dead_letter_queue_of_event_wrapper.cs @@ -39,7 +39,7 @@ public async Task can_replay_dead_letter_event() .AddAsyncDaemon(DaemonMode.Solo) .IntegrateWithWolverine() .PublishEventsToWolverine("MaybeErrors", r => r.PublishEvent()); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.GetRuntime(); await runtime.Storage.Admin.RebuildAsync(); @@ -49,7 +49,7 @@ public async Task can_replay_dead_letter_event() using (var session = host.DocumentStore().LightweightSession()) { session.Events.StartStream(new ErrorCausingEvent()); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); } await host.WaitForNonStaleProjectionDataAsync(60.Seconds()); diff --git a/src/Persistence/MartenTests/Bugs/bug_369_reply_to_local_message_tries_to_be_Outgoing.cs b/src/Persistence/MartenTests/Bugs/bug_369_reply_to_local_message_tries_to_be_Outgoing.cs index e84e79046..a9e751b6b 100644 --- a/src/Persistence/MartenTests/Bugs/bug_369_reply_to_local_message_tries_to_be_Outgoing.cs +++ b/src/Persistence/MartenTests/Bugs/bug_369_reply_to_local_message_tries_to_be_Outgoing.cs @@ -27,7 +27,7 @@ public async Task why_are_we_going_as_outgoing() opts.Services.AddResourceSetupOnStartup(); opts.Policies.UseDurableInboxOnAllListeners(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var tracked = await host.SendMessageAndWaitAsync(new Ping()); diff --git a/src/Persistence/MartenTests/Bugs/event_forwarding_bug.cs b/src/Persistence/MartenTests/Bugs/event_forwarding_bug.cs index dcdd76d5d..610a93ce5 100644 --- a/src/Persistence/MartenTests/Bugs/event_forwarding_bug.cs +++ b/src/Persistence/MartenTests/Bugs/event_forwarding_bug.cs @@ -37,7 +37,7 @@ public async Task publish_ievent_of_t() m.Projections.LiveStreamAggregation(); }).UseLightweightSessions() .IntegrateWithWolverine(x => x.UseFastEventForwarding = true); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.GetRuntime(); var routing = runtime.RoutingFor(typeof(Event)); diff --git a/src/Persistence/MartenTests/Bugs/event_forwarding_routing_bug.cs b/src/Persistence/MartenTests/Bugs/event_forwarding_routing_bug.cs index 80ebccd93..5f2a97753 100644 --- a/src/Persistence/MartenTests/Bugs/event_forwarding_routing_bug.cs +++ b/src/Persistence/MartenTests/Bugs/event_forwarding_routing_bug.cs @@ -31,7 +31,7 @@ public async Task forwarded_events_respects_routing_rules() }) .IntegrateWithWolverine(x => x.UseFastEventForwarding = true); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var session = await host.SendMessageAndWaitAsync(new Event(new SomeEvent())); session.Executed.SingleEnvelope>() @@ -59,7 +59,7 @@ public async Task subscription_events_respects_routing_rules() .IntegrateWithWolverine() .PublishEventsToWolverine("forwarded-events"); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var bus = host.MessageBus(); bus.PreviewSubscriptions(new Event(new SomeEvent())) diff --git a/src/Persistence/MartenTests/Dcb/boundary_model_workflow_tests.cs b/src/Persistence/MartenTests/Dcb/boundary_model_workflow_tests.cs index db760445a..6145ac592 100644 --- a/src/Persistence/MartenTests/Dcb/boundary_model_workflow_tests.cs +++ b/src/Persistence/MartenTests/Dcb/boundary_model_workflow_tests.cs @@ -117,7 +117,7 @@ public async Task can_fetch_for_writing_by_tags_across_multiple_tag_types() .Or(courseId) .Or(studentId); - var boundary = await session.Events.FetchForWritingByTags(query); + var boundary = await session.Events.FetchForWritingByTags(query, TestContext.Current.CancellationToken); boundary.Events.Count.ShouldBe(2); boundary.Aggregate.ShouldNotBeNull(); boundary.Aggregate.CourseId.ShouldBe(courseId); @@ -138,8 +138,7 @@ await theHost.InvokeMessageAndWaitAsync( // Verify the subscription event was appended and discoverable by tag await using var session = theStore.LightweightSession(); - var events = await session.Events.QueryByTagsAsync( - new EventTagQuery().Or(studentId)); + var events = await session.Events.QueryByTagsAsync(new EventTagQuery().Or(studentId), TestContext.Current.CancellationToken); events.ShouldContain(e => e.Data is StudentSubscribedToCourse); } @@ -156,7 +155,7 @@ public async Task boundary_model_handler_throws_when_student_not_enrolled() new CourseCreated(FacultyId.Default, courseId, "Math 101", 10)); courseCreated.WithTag(courseId); session.Events.Append(courseId.Value, courseCreated); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); // The handler should throw because student is not enrolled await Should.ThrowAsync(async () => @@ -178,7 +177,7 @@ public async Task boundary_model_handler_throws_when_course_does_not_exist() new StudentEnrolledInFaculty(FacultyId.Default, studentId, "Alice", "Smith")); enrolled.WithTag(studentId); session.Events.Append(studentId.Value, enrolled); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await Should.ThrowAsync(async () => { @@ -208,7 +207,7 @@ public async Task boundary_model_handler_throws_when_course_is_fully_booked() new StudentSubscribedToCourse(FacultyId.Default, otherStudentId, courseId)); subscribed.WithTag(otherStudentId, courseId); session.Events.Append(otherStudentId.Value, subscribed); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); // Now try to subscribe our student — should fail because course is full await Should.ThrowAsync(async () => diff --git a/src/Persistence/MartenTests/Dcb/dedup_load_boundary_frame_tests.cs b/src/Persistence/MartenTests/Dcb/dedup_load_boundary_frame_tests.cs index 6c8568698..242d88163 100644 --- a/src/Persistence/MartenTests/Dcb/dedup_load_boundary_frame_tests.cs +++ b/src/Persistence/MartenTests/Dcb/dedup_load_boundary_frame_tests.cs @@ -129,7 +129,7 @@ public async Task chain_with_two_boundary_model_parameters_compiles_and_runs() enrolled.WithTag(studentId); session.Events.Append(studentId.Value, enrolled); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); } // Pre-fix: this throws at handler-compilation with CS0128. @@ -137,8 +137,7 @@ await theHost.InvokeMessageAndWaitAsync( new TwoBoundaryModelParamsCommand(studentId, courseId)); await using var verifySession = theStore.LightweightSession(); - var events = await verifySession.Events.QueryByTagsAsync( - new EventTagQuery().Or(studentId)); + var events = await verifySession.Events.QueryByTagsAsync(new EventTagQuery().Or(studentId), TestContext.Current.CancellationToken); events.ShouldContain(e => e.Data is StudentSubscribedToCourse); } diff --git a/src/Persistence/MartenTests/Distribution/failover_preserves_per_tenant_progression_floors.cs b/src/Persistence/MartenTests/Distribution/failover_preserves_per_tenant_progression_floors.cs index 598630bb4..0a0e0392b 100644 --- a/src/Persistence/MartenTests/Distribution/failover_preserves_per_tenant_progression_floors.cs +++ b/src/Persistence/MartenTests/Distribution/failover_preserves_per_tenant_progression_floors.cs @@ -175,7 +175,7 @@ public async Task surviving_node_resumes_each_tenant_from_its_progression_floor( // Kill the node that owns tenant-b's agent (both agents, by affinity). Same stop pattern as // tenant_partitioned_distribution_multinode.agents_fail_over_to_the_surviving_node_when_a_node_leaves. owner.GetRuntime().Agents.DisableHealthChecks(); - await owner.StopAsync(); + await owner.StopAsync(TestContext.Current.CancellationToken); // If the owner was the leader (the usual case — see class comment), the survivor must first // assume leadership before it can evaluate assignments. Returns immediately when the survivor @@ -212,7 +212,7 @@ await survivor.WaitUntilAssignmentsChangeTo(w => break; } - await Task.Delay(250.Milliseconds()); + await Task.Delay(250.Milliseconds(), TestContext.Current.CancellationToken); } docB.ShouldNotBeNull(); diff --git a/src/Persistence/MartenTests/Distribution/find_agent_uri_for_registered_projection.cs b/src/Persistence/MartenTests/Distribution/find_agent_uri_for_registered_projection.cs index 069ee1821..1a79c9fe1 100644 --- a/src/Persistence/MartenTests/Distribution/find_agent_uri_for_registered_projection.cs +++ b/src/Persistence/MartenTests/Distribution/find_agent_uri_for_registered_projection.cs @@ -19,7 +19,7 @@ public async Task resolves_registered_shard_without_a_running_agent() .OfType().Single(); // "Trip:All" is the JasperFx ShardName.Identity for the registered TripProjection. - var uri = await family.FindAgentUriAsync("Trip:All", null); + var uri = await family.FindAgentUriAsync("Trip:All", null, TestContext.Current.CancellationToken); uri.ShouldNotBeNull(); uri!.AbsoluteUri.ShouldBe("event-subscriptions://marten/main/localhost.postgres/trip/all"); @@ -31,7 +31,7 @@ public async Task returns_null_for_an_unregistered_shard() var family = theOriginalHost.Services.GetServices() .OfType().Single(); - var uri = await family.FindAgentUriAsync("DoesNotExist:All", null); + var uri = await family.FindAgentUriAsync("DoesNotExist:All", null, TestContext.Current.CancellationToken); uri.ShouldBeNull(); } diff --git a/src/Persistence/MartenTests/Distribution/find_agent_uri_per_tenant_database.cs b/src/Persistence/MartenTests/Distribution/find_agent_uri_per_tenant_database.cs index e71c0c476..9f673a05f 100644 --- a/src/Persistence/MartenTests/Distribution/find_agent_uri_per_tenant_database.cs +++ b/src/Persistence/MartenTests/Distribution/find_agent_uri_per_tenant_database.cs @@ -39,13 +39,13 @@ await theOriginalHost.WaitUntilAssignmentsChangeTo(w => var family = theOriginalHost.Services.GetServices() .OfType().Single(); - (await family.FindAgentUriAsync("Trip:All", "tenant1"))!.AbsoluteUri + (await family.FindAgentUriAsync("Trip:All", "tenant1", TestContext.Current.CancellationToken))!.AbsoluteUri .ShouldBe("event-subscriptions://marten/main/localhost.tenant1/trip/all"); - (await family.FindAgentUriAsync("Day:All", "tenant2"))!.AbsoluteUri + (await family.FindAgentUriAsync("Day:All", "tenant2", TestContext.Current.CancellationToken))!.AbsoluteUri .ShouldBe("event-subscriptions://marten/main/localhost.tenant2/day/all"); // An unknown tenant still resolves to nothing - (await family.FindAgentUriAsync("Trip:All", "tenant-nope")).ShouldBeNull(); + (await family.FindAgentUriAsync("Trip:All", "tenant-nope", TestContext.Current.CancellationToken)).ShouldBeNull(); } } diff --git a/src/Persistence/MartenTests/Distribution/inline_projection_rebuild.cs b/src/Persistence/MartenTests/Distribution/inline_projection_rebuild.cs index 32bbefdb4..eb25ff1ed 100644 --- a/src/Persistence/MartenTests/Distribution/inline_projection_rebuild.cs +++ b/src/Persistence/MartenTests/Distribution/inline_projection_rebuild.cs @@ -69,12 +69,12 @@ public async Task rebuild_a_registered_inline_projection_that_has_no_live_agent( await using (var session = store.LightweightSession()) { session.Events.StartStream(streamId, new TripStarted { Day = 1 }, new TripEnded { Day = 2 }); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); } await using (var session = store.QuerySession()) { - (await session.LoadAsync(streamId)).ShouldNotBeNull("Inline projection should have created the Trip"); + (await session.LoadAsync(streamId, TestContext.Current.CancellationToken)).ShouldNotBeNull("Inline projection should have created the Trip"); } var family = _host.Services.GetServices() @@ -82,18 +82,18 @@ public async Task rebuild_a_registered_inline_projection_that_has_no_live_agent( // An Inline projection is not distributed as an agent — there is no agent URI to route a rebuild // through. This is exactly the case the transient-rebuild path exists for. - (await family.FindAgentUriAsync("Trip:All", null)).ShouldBeNull( + (await family.FindAgentUriAsync("Trip:All", null, TestContext.Current.CancellationToken)).ShouldBeNull( "An Inline projection has no distributed agent, so it resolves no agent URI."); // Wipe the read model — only a genuine rebuild re-applies the events to restore it. await using (var session = store.LightweightSession()) { session.DeleteWhere(_ => true); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); } await using (var session = store.QuerySession()) { - (await session.Query().CountAsync()).ShouldBe(0); + (await session.Query().CountAsync(token: TestContext.Current.CancellationToken)).ShouldBe(0); } // Rebuild via the transient-agent path: Wolverine finds the registered Inline projection, spins a @@ -104,7 +104,7 @@ public async Task rebuild_a_registered_inline_projection_that_has_no_live_agent( // PROOF the rebuild ran: the Trip read model is restored from the event stream. await using (var session = store.QuerySession()) { - (await session.LoadAsync(streamId)).ShouldNotBeNull( + (await session.LoadAsync(streamId, TestContext.Current.CancellationToken)).ShouldNotBeNull( "The transient rebuild should have restored the Inline projection's read model."); } } diff --git a/src/Persistence/MartenTests/Distribution/runtime_tenant_churn_under_managed_distribution.cs b/src/Persistence/MartenTests/Distribution/runtime_tenant_churn_under_managed_distribution.cs index 52310cc60..1b3f23b3a 100644 --- a/src/Persistence/MartenTests/Distribution/runtime_tenant_churn_under_managed_distribution.cs +++ b/src/Persistence/MartenTests/Distribution/runtime_tenant_churn_under_managed_distribution.cs @@ -170,7 +170,7 @@ await theHost.WaitUntilAssignmentsChangeTo(w => // Phase 2: WHILE the host is running, add tenant-b to the same shard database through the // running store — the same provisioning path the sibling tests use before startup. - await theStore.Advanced.AddTenantToShardAsync(TenantB, "shard-1", default); + await theStore.Advanced.AddTenantToShardAsync(TenantB, "shard-1", TestContext.Current.CancellationToken); // Within the assignment-evaluation window (CheckAssignmentPeriod = 1s; generous ceiling for CI) // the leader re-enumerates the usage and starts tenant-b's agent. diff --git a/src/Persistence/MartenTests/Distribution/store_scoped_find_agent_uri_3647.cs b/src/Persistence/MartenTests/Distribution/store_scoped_find_agent_uri_3647.cs index 31463faf4..ae447c196 100644 --- a/src/Persistence/MartenTests/Distribution/store_scoped_find_agent_uri_3647.cs +++ b/src/Persistence/MartenTests/Distribution/store_scoped_find_agent_uri_3647.cs @@ -96,7 +96,7 @@ public async Task both_stores_resolve_an_agent_uri_for_the_shared_projection_nam [Fact] public async Task scoping_to_the_main_store_resolves_that_store_s_agent_uri() { - var uri = await theFamily.FindAgentUriAsync(identityOf(_main), "Trip:All", null); + var uri = await theFamily.FindAgentUriAsync(identityOf(_main), "Trip:All", null, TestContext.Current.CancellationToken); uri.ShouldNotBeNull(); EventSubscriptionAgentFamily.StoreIdentityOf(uri!) @@ -108,7 +108,7 @@ public async Task scoping_to_the_ancillary_store_resolves_that_store_s_agent_uri { // The mirror image. Asserting both directions is what proves the overload narrows by store rather // than merely agreeing with the family's enumeration order. - var uri = await theFamily.FindAgentUriAsync(identityOf(_ancillary), "Trip:All", null); + var uri = await theFamily.FindAgentUriAsync(identityOf(_ancillary), "Trip:All", null, TestContext.Current.CancellationToken); uri.ShouldNotBeNull(); EventSubscriptionAgentFamily.StoreIdentityOf(uri!) @@ -119,8 +119,8 @@ public async Task scoping_to_the_ancillary_store_resolves_that_store_s_agent_uri public async Task the_two_store_scoped_lookups_return_different_uris() { // The single assertion that would have caught the bug: same shard identity, two stores, two answers. - var main = await theFamily.FindAgentUriAsync(identityOf(_main), "Trip:All", null); - var ancillary = await theFamily.FindAgentUriAsync(identityOf(_ancillary), "Trip:All", null); + var main = await theFamily.FindAgentUriAsync(identityOf(_main), "Trip:All", null, TestContext.Current.CancellationToken); + var ancillary = await theFamily.FindAgentUriAsync(identityOf(_ancillary), "Trip:All", null, TestContext.Current.CancellationToken); main.ShouldNotBeNull(); ancillary.ShouldNotBeNull(); @@ -134,11 +134,11 @@ public async Task the_two_store_scoped_lookups_return_different_uris() [Fact] public async Task the_store_blind_overload_still_resolves_but_cannot_be_steered() { - var blind = await theFamily.FindAgentUriAsync("Trip:All", null); + var blind = await theFamily.FindAgentUriAsync("Trip:All", null, TestContext.Current.CancellationToken); blind.ShouldNotBeNull(); - var main = await theFamily.FindAgentUriAsync(identityOf(_main), "Trip:All", null); - var ancillary = await theFamily.FindAgentUriAsync(identityOf(_ancillary), "Trip:All", null); + var main = await theFamily.FindAgentUriAsync(identityOf(_main), "Trip:All", null, TestContext.Current.CancellationToken); + var ancillary = await theFamily.FindAgentUriAsync(identityOf(_ancillary), "Trip:All", null, TestContext.Current.CancellationToken); new[] { main, ancillary }.ShouldContain(blind); } @@ -146,14 +146,14 @@ public async Task the_store_blind_overload_still_resolves_but_cannot_be_steered( [Fact] public async Task a_store_outside_this_family_resolves_nothing() { - (await theFamily.FindAgentUriAsync("someone-else:Marten", "Trip:All", null)).ShouldBeNull( + (await theFamily.FindAgentUriAsync("someone-else:Marten", "Trip:All", null, TestContext.Current.CancellationToken)).ShouldBeNull( "so a caller looping over families can try the next one"); } [Fact] public async Task an_unregistered_shard_in_a_known_store_resolves_nothing() { - (await theFamily.FindAgentUriAsync(identityOf(_main), "DoesNotExist:All", null)).ShouldBeNull(); + (await theFamily.FindAgentUriAsync(identityOf(_main), "DoesNotExist:All", null, TestContext.Current.CancellationToken)).ShouldBeNull(); } [Fact] @@ -161,7 +161,7 @@ public async Task the_store_identity_match_is_case_insensitive() { // System.Uri lowercases the authority while EventStoreIdentity preserves casing (GH-3168), so the // lookup has to normalize the same way the family keys its stores. - var uri = await theFamily.FindAgentUriAsync(identityOf(_main).ToUpperInvariant(), "Trip:All", null); + var uri = await theFamily.FindAgentUriAsync(identityOf(_main).ToUpperInvariant(), "Trip:All", null, TestContext.Current.CancellationToken); uri.ShouldNotBeNull(); EventSubscriptionAgentFamily.StoreIdentityOf(uri!).ShouldBe(identityOf(_main).ToLowerInvariant()); diff --git a/src/Persistence/MartenTests/Distribution/store_scoped_transient_rebuild_3618.cs b/src/Persistence/MartenTests/Distribution/store_scoped_transient_rebuild_3618.cs index 15504af9d..f8036f935 100644 --- a/src/Persistence/MartenTests/Distribution/store_scoped_transient_rebuild_3618.cs +++ b/src/Persistence/MartenTests/Distribution/store_scoped_transient_rebuild_3618.cs @@ -115,7 +115,7 @@ public void both_stores_are_managed_by_the_one_family() public async Task neither_store_has_a_live_agent_for_the_inline_projection() { // Establishes that this is the no-live-agent path, not the store-scoped live-agent path. - (await theFamily.FindAgentUriAsync("Trip:All", null)).ShouldBeNull(); + (await theFamily.FindAgentUriAsync("Trip:All", null, TestContext.Current.CancellationToken)).ShouldBeNull(); } [Fact] diff --git a/src/Persistence/MartenTests/Distribution/subscription_descriptor_agent_uris.cs b/src/Persistence/MartenTests/Distribution/subscription_descriptor_agent_uris.cs index bb3b03b56..6e7d61f29 100644 --- a/src/Persistence/MartenTests/Distribution/subscription_descriptor_agent_uris.cs +++ b/src/Persistence/MartenTests/Distribution/subscription_descriptor_agent_uris.cs @@ -31,7 +31,7 @@ public async Task agent_uris_match_event_subscription_family_uris() opts.Projections.Add(ProjectionLifecycle.Async); opts.Projections.Add(ProjectionLifecycle.Async); }); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var eventStore = host.Services.GetServices().Single(); var usage = await eventStore.TryCreateUsage(CancellationToken.None); @@ -90,7 +90,7 @@ public async Task agent_uris_are_empty_for_inline_projections() opts.Projections.Add(ProjectionLifecycle.Inline); }); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var eventStore = host.Services.GetServices().Single(); var usage = await eventStore.TryCreateUsage(CancellationToken.None); diff --git a/src/Persistence/MartenTests/Distribution/tenant_partitioned_distribution_multinode.cs b/src/Persistence/MartenTests/Distribution/tenant_partitioned_distribution_multinode.cs index 66df52f9f..3ce641bf8 100644 --- a/src/Persistence/MartenTests/Distribution/tenant_partitioned_distribution_multinode.cs +++ b/src/Persistence/MartenTests/Distribution/tenant_partitioned_distribution_multinode.cs @@ -158,7 +158,7 @@ await theOriginalHost.WaitUntilAssignmentsChangeTo(w => // The second node leaves the cluster — its subscription agents must reassign to the survivor // (all six per-tenant agents now on the original node). second.GetRuntime().Agents.DisableHealthChecks(); - await second.StopAsync(); + await second.StopAsync(TestContext.Current.CancellationToken); await theOriginalHost.WaitUntilAssignmentsChangeTo(w => { diff --git a/src/Persistence/MartenTests/MartenOutbox_end_to_end.cs b/src/Persistence/MartenTests/MartenOutbox_end_to_end.cs index ffbbd2f02..aefc660bb 100644 --- a/src/Persistence/MartenTests/MartenOutbox_end_to_end.cs +++ b/src/Persistence/MartenTests/MartenOutbox_end_to_end.cs @@ -52,7 +52,7 @@ public async Task persist_and_send_message_one_tx() await outbox.PublishAsync(new OutboxedMessage { Id = id }); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); } var message = await waiter; @@ -61,7 +61,7 @@ public async Task persist_and_send_message_one_tx() await using var query = _host.Services.GetRequiredService() .QuerySession(); ; - (await query.LoadAsync(id)).ShouldNotBeNull(); + (await query.LoadAsync(id, TestContext.Current.CancellationToken)).ShouldNotBeNull(); } } diff --git a/src/Persistence/MartenTests/MartenTests.csproj b/src/Persistence/MartenTests/MartenTests.csproj index 598f3a542..3400fdef1 100644 --- a/src/Persistence/MartenTests/MartenTests.csproj +++ b/src/Persistence/MartenTests/MartenTests.csproj @@ -1,6 +1,8 @@ + + true Exe net9.0;net10.0 false diff --git a/src/Persistence/MartenTests/MultiTenancy/agent_mechanics.cs b/src/Persistence/MartenTests/MultiTenancy/agent_mechanics.cs index c4ccfeb4f..87bd42fcc 100644 --- a/src/Persistence/MartenTests/MultiTenancy/agent_mechanics.cs +++ b/src/Persistence/MartenTests/MultiTenancy/agent_mechanics.cs @@ -20,14 +20,14 @@ public async Task all_agents_start() { await using (var conn = new NpgsqlConnection(Servers.PostgresConnectionString)) { - await conn.OpenAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); var sql = $@" DELETE FROM control.{DatabaseConstants.NodeAssignmentsTableName}; DELETE FROM control.{DatabaseConstants.NodeTableName}; "; await using var command = conn.CreateCommand(sql); - await command.ExecuteNonQueryAsync(); + await command.ExecuteNonQueryAsync(TestContext.Current.CancellationToken); await conn.CloseAsync(); } diff --git a/src/Persistence/MartenTests/MultiTenancy/basic_bootstrapping_and_database_configuration.cs b/src/Persistence/MartenTests/MultiTenancy/basic_bootstrapping_and_database_configuration.cs index b1fb4987b..3fb85cd68 100644 --- a/src/Persistence/MartenTests/MultiTenancy/basic_bootstrapping_and_database_configuration.cs +++ b/src/Persistence/MartenTests/MultiTenancy/basic_bootstrapping_and_database_configuration.cs @@ -61,9 +61,9 @@ public async Task tenant_databases_have_envelope_tables() { foreach (var database in Stores.ActiveDatabases().OfType().Where(x => x.Name != "Master")) { - await using var conn = (NpgsqlConnection)await database.DataSource.OpenConnectionAsync(); + await using var conn = (NpgsqlConnection)await database.DataSource.OpenConnectionAsync(TestContext.Current.CancellationToken); - var tables = (await conn.ExistingTablesAsync()).ToArray(); + var tables = (await conn.ExistingTablesAsync(ct: TestContext.Current.CancellationToken)).ToArray(); tables = tables.Where(x => x.Schema == "control").ToArray(); tables.ShouldContain(x => x.Name == DatabaseConstants.IncomingTable); @@ -79,9 +79,9 @@ public async Task tenant_databases_do_not_have_node_and_assignment_tables() { foreach (var database in Stores.ActiveDatabases().OfType().Where(x => x.Name != "Main")) { - await using var conn = (NpgsqlConnection)await database.DataSource.OpenConnectionAsync(); + await using var conn = (NpgsqlConnection)await database.DataSource.OpenConnectionAsync(TestContext.Current.CancellationToken); - var tables = (await conn.ExistingTablesAsync()).Where(x => x.Schema == "mt").ToArray(); + var tables = (await conn.ExistingTablesAsync(ct: TestContext.Current.CancellationToken)).Where(x => x.Schema == "mt").ToArray(); tables.ShouldNotContain(x => x.Name == DatabaseConstants.NodeTableName); tables.ShouldNotContain(x => x.Name == DatabaseConstants.NodeAssignmentsTableName); tables.ShouldNotContain(x => x.Name == DatabaseConstants.ControlQueueTableName); @@ -99,9 +99,9 @@ public async Task finds_database_for_default_is_master() [Fact] public async Task master_database_has_every_storage_table() { - await using var conn = (NpgsqlConnection)await Stores.Main.As().DataSource.OpenConnectionAsync(); + await using var conn = (NpgsqlConnection)await Stores.Main.As().DataSource.OpenConnectionAsync(TestContext.Current.CancellationToken); - var tables = (await conn.ExistingTablesAsync()).Where(x => x.Schema == "control").ToArray(); + var tables = (await conn.ExistingTablesAsync(ct: TestContext.Current.CancellationToken)).Where(x => x.Schema == "control").ToArray(); tables.ShouldContain(x => x.Name == DatabaseConstants.IncomingTable); tables.ShouldContain(x => x.Name == DatabaseConstants.OutgoingTable); tables.ShouldContain(x => x.Name == DatabaseConstants.DeadLetterTable); diff --git a/src/Persistence/MartenTests/MultiTenancy/conjoined_tenancy.cs b/src/Persistence/MartenTests/MultiTenancy/conjoined_tenancy.cs index 62b4cf17c..121a47924 100644 --- a/src/Persistence/MartenTests/MultiTenancy/conjoined_tenancy.cs +++ b/src/Persistence/MartenTests/MultiTenancy/conjoined_tenancy.cs @@ -62,21 +62,21 @@ await _host.ExecuteAndWaitAsync(c => // Check the first tenant using (var session = store.LightweightSession("one")) { - var document = await session.LoadAsync(id); + var document = await session.LoadAsync(id, TestContext.Current.CancellationToken); document!.Location.ShouldBe("Andor"); } // Check the second tenant using (var session = store.LightweightSession("two")) { - var document = await session.LoadAsync(id); + var document = await session.LoadAsync(id, TestContext.Current.CancellationToken); document!.Location.ShouldBe("Tear"); } // Check the third tenant using (var session = store.LightweightSession("three")) { - var document = await session.LoadAsync(id); + var document = await session.LoadAsync(id, TestContext.Current.CancellationToken); document!.Location.ShouldBe("Illian"); } } diff --git a/src/Persistence/MartenTests/MultiTenancy/dynamically_spin_up_new_durability_agents_for_new_tenant_databases.cs b/src/Persistence/MartenTests/MultiTenancy/dynamically_spin_up_new_durability_agents_for_new_tenant_databases.cs index e5bdaccb7..f0c8c07d8 100644 --- a/src/Persistence/MartenTests/MultiTenancy/dynamically_spin_up_new_durability_agents_for_new_tenant_databases.cs +++ b/src/Persistence/MartenTests/MultiTenancy/dynamically_spin_up_new_durability_agents_for_new_tenant_databases.cs @@ -141,7 +141,7 @@ public async Task ability_to_execute_commands_immediately_on_new_tenant_database var store = _host.Services.GetRequiredService(); using var session = store.LightweightSession("tenant1"); - var doc = await session.LoadAsync(command.Id); + var doc = await session.LoadAsync(command.Id, TestContext.Current.CancellationToken); doc.ShouldNotBeNull(); } @@ -181,7 +181,7 @@ public async Task ability_to_execute_commands_immediately_on_new_tenant_database // the configured tenant databases on startup .ApplyAllDatabaseChangesOnStartup(); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var tenancy = (MasterTableTenancy)theStore.Options.Tenancy; await tenancy.AddDatabaseRecordAsync("tenant1", tenant1ConnectionString); @@ -193,7 +193,7 @@ public async Task ability_to_execute_commands_immediately_on_new_tenant_database var store = otherHost.Services.GetRequiredService(); using var session = store.LightweightSession("tenant1"); - var doc = await session.LoadAsync(command.Id); + var doc = await session.LoadAsync(command.Id, TestContext.Current.CancellationToken); doc.ShouldNotBeNull(); } diff --git a/src/Persistence/MartenTests/MultiTenancy/dynamically_spin_up_new_tenant_databases_with_autocreate.cs b/src/Persistence/MartenTests/MultiTenancy/dynamically_spin_up_new_tenant_databases_with_autocreate.cs index 808ebb624..162275025 100644 --- a/src/Persistence/MartenTests/MultiTenancy/dynamically_spin_up_new_tenant_databases_with_autocreate.cs +++ b/src/Persistence/MartenTests/MultiTenancy/dynamically_spin_up_new_tenant_databases_with_autocreate.cs @@ -40,7 +40,7 @@ await host.WaitUntilAssignmentsChangeTo(w => // Apply Marten migrations to the tenant database var db = await tenancy.FindOrCreateDatabase("tenant1"); - await db.ApplyAllConfiguredChangesToDatabaseAsync(AutoCreate.CreateOrUpdate); + await db.ApplyAllConfiguredChangesToDatabaseAsync(AutoCreate.CreateOrUpdate, ct: TestContext.Current.CancellationToken); // Wait for the agent of the new tenant to start await host.WaitUntilAssignmentsChangeTo(w => @@ -57,10 +57,10 @@ await host.WaitUntilAssignmentsChangeTo(w => // Assert the handling of the command await using var session = store.LightweightSession("tenant1"); - var doc = await session.LoadAsync(command.Id); + var doc = await session.LoadAsync(command.Id, TestContext.Current.CancellationToken); doc.ShouldNotBeNull(); - await host.StopAsync(); + await host.StopAsync(TestContext.Current.CancellationToken); } } diff --git a/src/Persistence/MartenTests/MultiTenancy/end_to_end.cs b/src/Persistence/MartenTests/MultiTenancy/end_to_end.cs index 1902d58da..fdf247d2d 100644 --- a/src/Persistence/MartenTests/MultiTenancy/end_to_end.cs +++ b/src/Persistence/MartenTests/MultiTenancy/end_to_end.cs @@ -16,14 +16,14 @@ public end_to_end(MultiTenancyFixture fixture) : base(fixture) public async Task send_tenant_related_message() { var store = Fixture.Host!.Services.GetRequiredService(); - await store.Advanced.Clean.DeleteAllDocumentsAsync(); + await store.Advanced.Clean.DeleteAllDocumentsAsync(TestContext.Current.CancellationToken); var tracked = await Fixture.Host.SendMessageAndWaitAsync(new CreateTenantDoc("Tom", 11), new DeliveryOptions { TenantId = "tenant2" }); using var session = store.LightweightSession("tenant2"); - var loaded = await session.LoadAsync("Tom"); + var loaded = await session.LoadAsync("Tom", TestContext.Current.CancellationToken); loaded!.Number.ShouldBe(11); } } diff --git a/src/Persistence/MartenTests/MultiTenancy/multi_tenancy_queue_usage.cs b/src/Persistence/MartenTests/MultiTenancy/multi_tenancy_queue_usage.cs index c83f30df7..f70c04a56 100644 --- a/src/Persistence/MartenTests/MultiTenancy/multi_tenancy_queue_usage.cs +++ b/src/Persistence/MartenTests/MultiTenancy/multi_tenancy_queue_usage.cs @@ -184,7 +184,7 @@ public async Task spin_up_new_databases_and_see_listeners_be_created() if (has3 && has4) return; - await Task.Delay(250.Milliseconds()); + await Task.Delay(250.Milliseconds(), TestContext.Current.CancellationToken); } throw new TimeoutException("Did not detect the two new per tenant listeners were started up"); @@ -204,7 +204,7 @@ public async Task send_message_through_tenant() .Destination.ShouldBe(new Uri("postgresql://one/tenant3")); await using var session = theStore.LightweightSession("tenant3"); - var doc = await session.LoadAsync(message.Id); + var doc = await session.LoadAsync(message.Id, TestContext.Current.CancellationToken); doc.ShouldNotBeNull(); doc.Number.ShouldBe(10); } diff --git a/src/Persistence/MartenTests/MultiTenancy/using_tenant_specific_queues_and_subscriptions.cs b/src/Persistence/MartenTests/MultiTenancy/using_tenant_specific_queues_and_subscriptions.cs index c0e03a3dd..fb9553767 100644 --- a/src/Persistence/MartenTests/MultiTenancy/using_tenant_specific_queues_and_subscriptions.cs +++ b/src/Persistence/MartenTests/MultiTenancy/using_tenant_specific_queues_and_subscriptions.cs @@ -236,7 +236,7 @@ await receiver1.WaitUntilAssignmentsChangeTo(w => return; } - await Task.Delay(500.Milliseconds()); + await Task.Delay(500.Milliseconds(), TestContext.Current.CancellationToken); } throw new TimeoutException("The expected final state was never reached"); diff --git a/src/Persistence/MartenTests/Persistence/end_to_end_with_persistence.cs b/src/Persistence/MartenTests/Persistence/end_to_end_with_persistence.cs index 575bf3816..ed91a8a04 100644 --- a/src/Persistence/MartenTests/Persistence/end_to_end_with_persistence.cs +++ b/src/Persistence/MartenTests/Persistence/end_to_end_with_persistence.cs @@ -119,11 +119,11 @@ public async Task publish_locally() var documentStore = theReceiver.Get(); await using (var session = documentStore.QuerySession()) { - var item2 = await session.LoadAsync(item.Id); + var item2 = await session.LoadAsync(item.Id, TestContext.Current.CancellationToken); if (item2 == null) { - await Task.Delay(500); - item2 = await session.LoadAsync(item.Id); + await Task.Delay(500, TestContext.Current.CancellationToken); + item2 = await session.LoadAsync(item.Id, TestContext.Current.CancellationToken); } item2!.Name.ShouldBe("Shoe"); diff --git a/src/Persistence/MartenTests/Requirements/using_data_requirements.cs b/src/Persistence/MartenTests/Requirements/using_data_requirements.cs index 68a64989f..f7ed29146 100644 --- a/src/Persistence/MartenTests/Requirements/using_data_requirements.cs +++ b/src/Persistence/MartenTests/Requirements/using_data_requirements.cs @@ -57,7 +57,7 @@ public async Task single_requirement_must_exist_happy_path() using (var session = _store.LightweightSession()) { session.Store(new ThingCategory { Id = "widgets" }); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); } // Act @@ -66,7 +66,7 @@ public async Task single_requirement_must_exist_happy_path() // Assert: Thing was created using (var session = _store.LightweightSession()) { - var thing = await session.LoadAsync("widget-1"); + var thing = await session.LoadAsync("widget-1", TestContext.Current.CancellationToken); thing.ShouldNotBeNull(); thing.CategoryId.ShouldBe("widgets"); } @@ -93,7 +93,7 @@ public async Task enumerable_requirements_happy_path() using (var session = _store.LightweightSession()) { session.Store(new ThingCategory { Id = "gadgets" }); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); } // Act @@ -102,7 +102,7 @@ public async Task enumerable_requirements_happy_path() // Assert: Thing was created using (var session = _store.LightweightSession()) { - var thing = await session.LoadAsync("gadget-1"); + var thing = await session.LoadAsync("gadget-1", TestContext.Current.CancellationToken); thing.ShouldNotBeNull(); thing.CategoryId.ShouldBe("gadgets"); } @@ -126,7 +126,7 @@ public async Task enumerable_requirements_sad_path_thing_already_exists() { session.Store(new ThingCategory { Id = "dupes" }); session.Store(new Thing { Id = "existing-thing", CategoryId = "dupes" }); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); } // MustNotExist should fail because thing already exists @@ -147,7 +147,7 @@ public async Task requirement_with_entity_attribute_happy_path() using (var session = _store.LightweightSession()) { session.Store(new ThingCategory { Id = "tools" }); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); } // Act @@ -156,7 +156,7 @@ public async Task requirement_with_entity_attribute_happy_path() // Assert: Thing was created using (var session = _store.LightweightSession()) { - var thing = await session.LoadAsync("tool-1"); + var thing = await session.LoadAsync("tool-1", TestContext.Current.CancellationToken); thing.ShouldNotBeNull(); thing.CategoryId.ShouldBe("tools"); } @@ -182,14 +182,14 @@ public async Task document_exists_attribute_happy_path() using (var session = _store.LightweightSession()) { session.Store(new ThingCategory { Id = "attr-cat" }); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); } await _host.InvokeMessageAndWaitAsync(new CreateThingByAttribute("attr-thing", "attr-cat")); using (var session = _store.LightweightSession()) { - var thing = await session.LoadAsync("attr-thing"); + var thing = await session.LoadAsync("attr-thing", TestContext.Current.CancellationToken); thing.ShouldNotBeNull(); thing.CategoryId.ShouldBe("attr-cat"); } @@ -214,14 +214,14 @@ public async Task document_exists_attribute_explicit_happy_path() using (var session = _store.LightweightSession()) { session.Store(new ThingCategory { Id = "explicit-cat" }); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); } await _host.InvokeMessageAndWaitAsync(new CreateThingByAttributeExplicit("explicit-thing", "explicit-cat")); using (var session = _store.LightweightSession()) { - var thing = await session.LoadAsync("explicit-thing"); + var thing = await session.LoadAsync("explicit-thing", TestContext.Current.CancellationToken); thing.ShouldNotBeNull(); thing.CategoryId.ShouldBe("explicit-cat"); } @@ -253,7 +253,7 @@ public async Task document_does_not_exist_attribute_sad_path() using (var session = _store.LightweightSession()) { session.Store(new Thing { Id = "already-here", CategoryId = "whatever" }); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); } await Should.ThrowAsync(async () => diff --git a/src/Persistence/MartenTests/Saga/RevisionedSaga.cs b/src/Persistence/MartenTests/Saga/RevisionedSaga.cs index 87db08eac..ead0935c9 100644 --- a/src/Persistence/MartenTests/Saga/RevisionedSaga.cs +++ b/src/Persistence/MartenTests/Saga/RevisionedSaga.cs @@ -61,10 +61,10 @@ public async Task execute_using_update_revision() var execution = Task.Run(async () => { await theHost.MessageBus().InvokeAsync(slow); - }); + }, TestContext.Current.CancellationToken); await RevisionedSaga.InSlowMessage.Task; - await theHost.MessageBus().InvokeAsync(new Command1(id)); + await theHost.MessageBus().InvokeAsync(new Command1(id), TestContext.Current.CancellationToken); slow.Source.SetResult(); diff --git a/src/Persistence/MartenTests/Saga/When_handling_messages_in_saga.cs b/src/Persistence/MartenTests/Saga/When_handling_messages_in_saga.cs index ead254e59..44eeb3c0b 100644 --- a/src/Persistence/MartenTests/Saga/When_handling_messages_in_saga.cs +++ b/src/Persistence/MartenTests/Saga/When_handling_messages_in_saga.cs @@ -25,7 +25,7 @@ await Host.CreateDefaultBuilder() opts.Policies.AutoApplyTransactions(); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var subscriptionId = Guid.NewGuid(); @@ -58,7 +58,7 @@ await Host.CreateDefaultBuilder() opts.Policies.AutoApplyTransactions(); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var subscriptionId = Guid.NewGuid(); @@ -79,7 +79,7 @@ await Host.CreateDefaultBuilder() .IncludeType(); opts.Durability.Mode = DurabilityMode.Solo; }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var subscriptionId = Guid.NewGuid(); @@ -106,7 +106,7 @@ await Host.CreateDefaultBuilder() .IncludeType(); opts.Durability.Mode = DurabilityMode.Solo; }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var subscriptionId = Guid.NewGuid(); diff --git a/src/Persistence/MartenTests/Saga/multiple_sagas_for_same_message.cs b/src/Persistence/MartenTests/Saga/multiple_sagas_for_same_message.cs index ee16cc93f..db55d9470 100644 --- a/src/Persistence/MartenTests/Saga/multiple_sagas_for_same_message.cs +++ b/src/Persistence/MartenTests/Saga/multiple_sagas_for_same_message.cs @@ -51,11 +51,11 @@ public async Task two_sagas_start_from_same_message() await using var session = _host.DocumentStore().QuerySession(); - var shipping = await session.LoadAsync(id); + var shipping = await session.LoadAsync(id, TestContext.Current.CancellationToken); shipping.ShouldNotBeNull(); shipping.ProductName.ShouldBe("Widget"); - var billing = await session.LoadAsync(id); + var billing = await session.LoadAsync(id, TestContext.Current.CancellationToken); billing.ShouldNotBeNull(); billing.ProductName.ShouldBe("Widget"); } @@ -68,8 +68,8 @@ public async Task two_sagas_handle_subsequent_messages_independently() await using var session = _host.DocumentStore().QuerySession(); await _host.SendMessageAndWaitAsync(new OrderPlaced(id, "Gadget")); - (await session.LoadAsync(id)).ShouldNotBeNull(); - (await session.LoadAsync(id)).ShouldNotBeNull(); + (await session.LoadAsync(id, TestContext.Current.CancellationToken)).ShouldNotBeNull(); + (await session.LoadAsync(id, TestContext.Current.CancellationToken)).ShouldNotBeNull(); // Complete only the shipping saga @@ -78,11 +78,11 @@ public async Task two_sagas_handle_subsequent_messages_independently() // Shipping saga should be deleted (completed) - var shipping = await session.LoadAsync(id); + var shipping = await session.LoadAsync(id, TestContext.Current.CancellationToken); shipping.ShouldBeNull(); // Billing saga should still exist - var billing = await session.LoadAsync(id); + var billing = await session.LoadAsync(id, TestContext.Current.CancellationToken); billing.ShouldNotBeNull(); billing.ProductName.ShouldBe("Gadget"); @@ -90,7 +90,7 @@ public async Task two_sagas_handle_subsequent_messages_independently() await _host.SendMessageAndWaitAsync(new PaymentReceived(id)); await using var session2 = _host.DocumentStore().QuerySession(); - (await session2.LoadAsync(id)).ShouldBeNull(); + (await session2.LoadAsync(id, TestContext.Current.CancellationToken)).ShouldBeNull(); } } diff --git a/src/Persistence/MartenTests/Saga/not_found_usage.cs b/src/Persistence/MartenTests/Saga/not_found_usage.cs index ff10d8665..9eb0ee339 100644 --- a/src/Persistence/MartenTests/Saga/not_found_usage.cs +++ b/src/Persistence/MartenTests/Saga/not_found_usage.cs @@ -50,7 +50,7 @@ public async Task try_to_call_handle_on_already_expired_invitation() await using var query = _host.DocumentStore().LightweightSession(); // Should be deleted at this point - (await query.LoadAsync(id)).ShouldBeNull(); + (await query.LoadAsync(id, TestContext.Current.CancellationToken)).ShouldBeNull(); // NotFound should fire here, and no exceptions await _host.InvokeMessageAndWaitAsync(new InvitationTimeout( id)); diff --git a/src/Persistence/MartenTests/Saga/soft_deleted_saga_experiment.cs b/src/Persistence/MartenTests/Saga/soft_deleted_saga_experiment.cs index b962da663..10e833275 100644 --- a/src/Persistence/MartenTests/Saga/soft_deleted_saga_experiment.cs +++ b/src/Persistence/MartenTests/Saga/soft_deleted_saga_experiment.cs @@ -61,7 +61,7 @@ public async Task saga_is_soft_deleted_when_completed() await using var session = _host.DocumentStore().QuerySession(); // Verify saga exists - var saga = await session.LoadAsync(id); + var saga = await session.LoadAsync(id, TestContext.Current.CancellationToken); saga.ShouldNotBeNull(); saga.ProductName.ShouldBe("Widget"); @@ -70,14 +70,14 @@ public async Task saga_is_soft_deleted_when_completed() // LoadAsync does NOT filter soft-deleted documents — this is standard Marten behavior await using var session2 = _host.DocumentStore().QuerySession(); - var afterComplete = await session2.LoadAsync(id); + var afterComplete = await session2.LoadAsync(id, TestContext.Current.CancellationToken); afterComplete.ShouldNotBeNull("LoadAsync returns soft-deleted documents"); // But a LINQ query WITHOUT MaybeDeleted() filters the soft-deleted saga out var filteredQuery = await session2 .Query() .Where(x => x.Id == id) - .FirstOrDefaultAsync(); + .FirstOrDefaultAsync(token: TestContext.Current.CancellationToken); filteredQuery.ShouldBeNull("LINQ queries filter soft-deleted documents by default"); // With MaybeDeleted(), we can still find the soft-deleted saga @@ -85,7 +85,7 @@ public async Task saga_is_soft_deleted_when_completed() .Query() .Where(x => x.Id == id) .Where(x => x.MaybeDeleted()) - .FirstOrDefaultAsync(); + .FirstOrDefaultAsync(token: TestContext.Current.CancellationToken); includingDeleted.ShouldNotBeNull(); includingDeleted.ProductName.ShouldBe("Widget"); } @@ -117,7 +117,7 @@ public async Task send_message_to_completed_soft_deleted_saga_resurrects_it() // The saga is resurrected — LoadAsync finds soft-deleted docs, and the // handler updates the document, removing the soft-delete marker - var normalLoad = await session.LoadAsync(id); + var normalLoad = await session.LoadAsync(id, TestContext.Current.CancellationToken); normalLoad.ShouldNotBeNull("Saga should be resurrected after receiving a message"); normalLoad.WasHandledAfterCompletion.ShouldBeTrue(); } diff --git a/src/Persistence/MartenTests/Saga/starting_saga_by_returning_it_from_handler.cs b/src/Persistence/MartenTests/Saga/starting_saga_by_returning_it_from_handler.cs index fc299672b..d2de1debc 100644 --- a/src/Persistence/MartenTests/Saga/starting_saga_by_returning_it_from_handler.cs +++ b/src/Persistence/MartenTests/Saga/starting_saga_by_returning_it_from_handler.cs @@ -27,7 +27,7 @@ public async Task create_sagas_from_a_starting_message() .IncludeType(typeof(StartSagasThing)); opts.Policies.AutoApplyTransactions(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var sagaId = Guid.NewGuid(); await host.InvokeMessageAndWaitAsync(new StartSagas(sagaId)); @@ -35,19 +35,19 @@ public async Task create_sagas_from_a_starting_message() var store = host.Services.GetRequiredService(); using var session = store.LightweightSession(); - var one = await session.LoadAsync(sagaId); + var one = await session.LoadAsync(sagaId, TestContext.Current.CancellationToken); one.ShouldNotBeNull(); // The cascading messages should have set this one.GotOne.ShouldBeTrue(); - var two = await session.LoadAsync(sagaId); + var two = await session.LoadAsync(sagaId, TestContext.Current.CancellationToken); two.ShouldNotBeNull(); // The cascading messages should have set this two.GotOne.ShouldBeTrue(); - await host.StopAsync(); + await host.StopAsync(TestContext.Current.CancellationToken); host.Dispose(); } } diff --git a/src/Persistence/MartenTests/Saga/strong_typed_id_saga.cs b/src/Persistence/MartenTests/Saga/strong_typed_id_saga.cs index 9015db0ac..cf3ef97f7 100644 --- a/src/Persistence/MartenTests/Saga/strong_typed_id_saga.cs +++ b/src/Persistence/MartenTests/Saga/strong_typed_id_saga.cs @@ -116,7 +116,7 @@ public async Task start_saga_with_strong_typed_id() await _host.InvokeMessageAndWaitAsync(new StartOrderSaga(orderId, "Han Solo")); using var session = _host.DocumentStore().QuerySession(); - var saga = await session.LoadAsync(orderId); + var saga = await session.LoadAsync(orderId, TestContext.Current.CancellationToken); saga.ShouldNotBeNull(); saga.Id.ShouldBe(orderId); @@ -132,7 +132,7 @@ public async Task handle_message_with_strong_typed_id_on_existing_saga() await _host.InvokeMessageAndWaitAsync(new PickOrderItems(orderId)); using var session = _host.DocumentStore().QuerySession(); - var saga = await session.LoadAsync(orderId); + var saga = await session.LoadAsync(orderId, TestContext.Current.CancellationToken); saga.ShouldNotBeNull(); saga.ItemsPicked.ShouldBeTrue(); @@ -149,7 +149,7 @@ public async Task complete_saga_with_strong_typed_id() await _host.InvokeMessageAndWaitAsync(new ShipOrder(orderId)); using var session = _host.DocumentStore().QuerySession(); - var saga = await session.LoadAsync(orderId); + var saga = await session.LoadAsync(orderId, TestContext.Current.CancellationToken); // Saga should be deleted when completed saga.ShouldBeNull(); @@ -164,7 +164,7 @@ public async Task cancel_saga_with_strong_typed_id() await _host.InvokeMessageAndWaitAsync(new CancelOrderSaga(orderId)); using var session = _host.DocumentStore().QuerySession(); - var saga = await session.LoadAsync(orderId); + var saga = await session.LoadAsync(orderId, TestContext.Current.CancellationToken); // Saga should be deleted after cancel (MarkCompleted) saga.ShouldBeNull(); @@ -180,7 +180,7 @@ public async Task multiple_steps_with_strong_typed_id() await _host.InvokeMessageAndWaitAsync(new ProcessOrderPayment(orderId)); using var session = _host.DocumentStore().QuerySession(); - var saga = await session.LoadAsync(orderId); + var saga = await session.LoadAsync(orderId, TestContext.Current.CancellationToken); saga.ShouldNotBeNull(); saga.ItemsPicked.ShouldBeTrue(); diff --git a/src/Persistence/MartenTests/Sample/SampleApp.cs b/src/Persistence/MartenTests/Sample/SampleApp.cs index c800cf085..1ea52d562 100644 --- a/src/Persistence/MartenTests/Sample/SampleApp.cs +++ b/src/Persistence/MartenTests/Sample/SampleApp.cs @@ -53,7 +53,7 @@ public async Task using_ExecuteAndWaitSync() await using (var session = theHost.Get().QuerySession()) { - (await session.LoadAsync("Tom")).ShouldNotBeNull(); + (await session.LoadAsync("Tom", TestContext.Current.CancellationToken)).ShouldNotBeNull(); } theHost.Get() @@ -67,7 +67,7 @@ public async Task using_InvokeMessageAndWait() await using (var session = theHost.Get().QuerySession()) { - (await session.LoadAsync("Bill")).ShouldNotBeNull(); + (await session.LoadAsync("Bill", TestContext.Current.CancellationToken)).ShouldNotBeNull(); } theHost.Get() diff --git a/src/Persistence/MartenTests/TestHelpers/catch_up_and_then_do_nothing.cs b/src/Persistence/MartenTests/TestHelpers/catch_up_and_then_do_nothing.cs index 87b85ade6..1b0dc25f4 100644 --- a/src/Persistence/MartenTests/TestHelpers/catch_up_and_then_do_nothing.cs +++ b/src/Persistence/MartenTests/TestHelpers/catch_up_and_then_do_nothing.cs @@ -78,10 +78,10 @@ public async Task with_main_store() session.Events.StartStream("AABBCCDDEE".ToLetterEvents()); session.Events.StartStream("AABBCCDDEE".ToLetterEvents()); session.Events.StartStream("AABBCCDDEE".ToLetterEvents()); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await _host.WaitForNonStaleProjectionDataAsync(5.Seconds()); - (await session.Query().CountAsync()).ShouldBe(3); + (await session.Query().CountAsync(token: TestContext.Current.CancellationToken)).ShouldBe(3); var tracked = await _host.TrackActivity() @@ -91,7 +91,7 @@ public async Task with_main_store() // Proving that previous data was wiped out - var all = await session.Query().ToListAsync(); + var all = await session.Query().ToListAsync(token: TestContext.Current.CancellationToken); var counts = all.Single(); counts.Id.ShouldBe(id); @@ -112,10 +112,10 @@ public async Task with_ancillary_store() session.Events.StartStream("AABBCCDDEE".ToLetterEvents()); session.Events.StartStream("AABBCCDDEE".ToLetterEvents()); session.Events.StartStream("AABBCCDDEE".ToLetterEvents()); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await _host.WaitForNonStaleProjectionDataAsync(5.Seconds()); - (await session.Query().CountAsync()).ShouldBe(3); + (await session.Query().CountAsync(token: TestContext.Current.CancellationToken)).ShouldBe(3); var tracked = await _host.TrackActivity() @@ -125,7 +125,7 @@ public async Task with_ancillary_store() // Proving that previous data was wiped out - var all = await session.Query().ToListAsync(); + var all = await session.Query().ToListAsync(token: TestContext.Current.CancellationToken); var counts = all.Single(); counts.Id.ShouldBe(id); diff --git a/src/Persistence/MartenTests/TestHelpers/catch_up_then_restart.cs b/src/Persistence/MartenTests/TestHelpers/catch_up_then_restart.cs index 51c450391..6e4a499af 100644 --- a/src/Persistence/MartenTests/TestHelpers/catch_up_then_restart.cs +++ b/src/Persistence/MartenTests/TestHelpers/catch_up_then_restart.cs @@ -76,10 +76,10 @@ public async Task with_main_store() session.Events.StartStream("AABBCCDDEE".ToLetterEvents()); session.Events.StartStream("AABBCCDDEE".ToLetterEvents()); session.Events.StartStream("AABBCCDDEE".ToLetterEvents()); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await _host.WaitForNonStaleProjectionDataAsync(5.Seconds()); - (await session.Query().CountAsync()).ShouldBe(3); + (await session.Query().CountAsync(token: TestContext.Current.CancellationToken)).ShouldBe(3); var tracked = await _host.TrackActivity() @@ -93,7 +93,7 @@ public async Task with_main_store() // Proving that previous data was wiped out - var all = await session.Query().ToListAsync(); + var all = await session.Query().ToListAsync(token: TestContext.Current.CancellationToken); var counts = all.Single(); counts.Id.ShouldBe(id); @@ -114,10 +114,10 @@ public async Task with_ancillary_store() session.Events.StartStream("AABBCCDDEE".ToLetterEvents()); session.Events.StartStream("AABBCCDDEE".ToLetterEvents()); session.Events.StartStream("AABBCCDDEE".ToLetterEvents()); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await _host.WaitForNonStaleProjectionDataAsync(5.Seconds()); - (await session.Query().CountAsync()).ShouldBe(3); + (await session.Query().CountAsync(token: TestContext.Current.CancellationToken)).ShouldBe(3); var tracked = await _host.TrackActivity() @@ -127,7 +127,7 @@ public async Task with_ancillary_store() // Proving that previous data was wiped out - var all = await session.Query().ToListAsync(); + var all = await session.Query().ToListAsync(token: TestContext.Current.CancellationToken); var counts = all.Single(); counts.Id.ShouldBe(id); diff --git a/src/Persistence/MartenTests/TestHelpers/catch_up_when_using_wolverine_distribution.cs b/src/Persistence/MartenTests/TestHelpers/catch_up_when_using_wolverine_distribution.cs index 16019d5fd..2c4e00cb9 100644 --- a/src/Persistence/MartenTests/TestHelpers/catch_up_when_using_wolverine_distribution.cs +++ b/src/Persistence/MartenTests/TestHelpers/catch_up_when_using_wolverine_distribution.cs @@ -64,10 +64,10 @@ public async Task with_main_store() session.Events.StartStream("AABBCCDDEE".ToLetterEvents()); session.Events.StartStream("AABBCCDDEE".ToLetterEvents()); session.Events.StartStream("AABBCCDDEE".ToLetterEvents()); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await _host.WaitForNonStaleProjectionDataAsync(5.Seconds()); - (await session.Query().CountAsync()).ShouldBe(3); + (await session.Query().CountAsync(token: TestContext.Current.CancellationToken)).ShouldBe(3); var tracked = await _host.TrackActivity() @@ -77,7 +77,7 @@ public async Task with_main_store() // Proving that previous data was wiped out - var all = await session.Query().ToListAsync(); + var all = await session.Query().ToListAsync(token: TestContext.Current.CancellationToken); var counts = all.Single(); counts.Id.ShouldBe(id); @@ -98,10 +98,10 @@ public async Task with_ancillary_store() session.Events.StartStream("AABBCCDDEE".ToLetterEvents()); session.Events.StartStream("AABBCCDDEE".ToLetterEvents()); session.Events.StartStream("AABBCCDDEE".ToLetterEvents()); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await _host.WaitForNonStaleProjectionDataAsync(5.Seconds()); - (await session.Query().CountAsync()).ShouldBe(3); + (await session.Query().CountAsync(token: TestContext.Current.CancellationToken)).ShouldBe(3); var tracked = await _host.TrackActivity() @@ -111,7 +111,7 @@ public async Task with_ancillary_store() // Proving that previous data was wiped out - var all = await session.Query().ToListAsync(); + var all = await session.Query().ToListAsync(token: TestContext.Current.CancellationToken); var counts = all.Single(); counts.Id.ShouldBe(id); diff --git a/src/Persistence/MartenTests/TestHelpers/cold_catch_up_with_second_subscription_consumer.cs b/src/Persistence/MartenTests/TestHelpers/cold_catch_up_with_second_subscription_consumer.cs index 3cac23f70..8b9b3aa56 100644 --- a/src/Persistence/MartenTests/TestHelpers/cold_catch_up_with_second_subscription_consumer.cs +++ b/src/Persistence/MartenTests/TestHelpers/cold_catch_up_with_second_subscription_consumer.cs @@ -80,7 +80,7 @@ public async Task cold_catch_up_on_ancillary_store_with_second_consumer() .InvokeMessageAndWaitAsync(new AppendLetters2(id, ["AAAACCCCBDEEE", "ABCDECCC", "BBBA", "DDDAE"])); await using var session = _host.DocumentStore().LightweightSession(); - var counts = (await session.Query().ToListAsync()).Single(); + var counts = (await session.Query().ToListAsync(token: TestContext.Current.CancellationToken)).Single(); counts.Id.ShouldBe(id); counts.ACount.ShouldBe(7); @@ -99,7 +99,7 @@ public async Task cold_catch_up_on_main_store_with_second_consumer() .InvokeMessageAndWaitAsync(new AppendLetters(id, ["AAAACCCCBDEEE", "ABCDECCC", "BBBA", "DDDAE"])); await using var session = _host.DocumentStore().LightweightSession(); - var counts = (await session.Query().ToListAsync()).Single(); + var counts = (await session.Query().ToListAsync(token: TestContext.Current.CancellationToken)).Single(); counts.Id.ShouldBe(id); counts.ACount.ShouldBe(7); diff --git a/src/Persistence/MartenTests/TestHelpers/cold_catch_up_with_wolverine_distribution.cs b/src/Persistence/MartenTests/TestHelpers/cold_catch_up_with_wolverine_distribution.cs index b9918adbb..23cf703aa 100644 --- a/src/Persistence/MartenTests/TestHelpers/cold_catch_up_with_wolverine_distribution.cs +++ b/src/Persistence/MartenTests/TestHelpers/cold_catch_up_with_wolverine_distribution.cs @@ -67,7 +67,7 @@ public async Task cold_catch_up_with_main_store() .InvokeMessageAndWaitAsync(new AppendLetters(id, ["AAAACCCCBDEEE", "ABCDECCC", "BBBA", "DDDAE"])); await using var session = _host.DocumentStore().LightweightSession(); - var counts = (await session.Query().ToListAsync()).Single(); + var counts = (await session.Query().ToListAsync(token: TestContext.Current.CancellationToken)).Single(); counts.Id.ShouldBe(id); counts.ACount.ShouldBe(7); @@ -86,7 +86,7 @@ public async Task cold_catch_up_with_ancillary_store() .InvokeMessageAndWaitAsync(new AppendLetters2(id, ["AAAACCCCBDEEE", "ABCDECCC", "BBBA", "DDDAE"])); await using var session = _host.DocumentStore().LightweightSession(); - var counts = (await session.Query().ToListAsync()).Single(); + var counts = (await session.Query().ToListAsync(token: TestContext.Current.CancellationToken)).Single(); counts.Id.ShouldBe(id); counts.ACount.ShouldBe(7); diff --git a/src/Persistence/MartenTests/TestHelpers/reset_data_first.cs b/src/Persistence/MartenTests/TestHelpers/reset_data_first.cs index eab3415c2..7b6f02736 100644 --- a/src/Persistence/MartenTests/TestHelpers/reset_data_first.cs +++ b/src/Persistence/MartenTests/TestHelpers/reset_data_first.cs @@ -76,10 +76,10 @@ public async Task reset_all_data_upfront() session.Events.StartStream("AABBCCDDEE".ToLetterEvents()); session.Events.StartStream("AABBCCDDEE".ToLetterEvents()); session.Events.StartStream("AABBCCDDEE".ToLetterEvents()); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await _host.WaitForNonStaleProjectionDataAsync(5.Seconds()); - (await session.Query().CountAsync()).ShouldBe(3); + (await session.Query().CountAsync(token: TestContext.Current.CancellationToken)).ShouldBe(3); var tracked = await _host.TrackActivity() @@ -90,7 +90,7 @@ public async Task reset_all_data_upfront() // Proving that previous data was wiped out - var all = await session.Query().ToListAsync(); + var all = await session.Query().ToListAsync(token: TestContext.Current.CancellationToken); var counts = all.Single(); counts.Id.ShouldBe(id); @@ -111,10 +111,10 @@ public async Task reset_all_data_upfront_to_ancillary_store() session.Events.StartStream("AABBCCDDEE".ToLetterEvents()); session.Events.StartStream("AABBCCDDEE".ToLetterEvents()); session.Events.StartStream("AABBCCDDEE".ToLetterEvents()); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await _host.WaitForNonStaleProjectionDataAsync(5.Seconds()); - (await session.Query().CountAsync()).ShouldBe(3); + (await session.Query().CountAsync(token: TestContext.Current.CancellationToken)).ShouldBe(3); var tracked = await _host.TrackActivity() @@ -125,7 +125,7 @@ public async Task reset_all_data_upfront_to_ancillary_store() // Proving that previous data was wiped out - var all = await session.Query().ToListAsync(); + var all = await session.Query().ToListAsync(token: TestContext.Current.CancellationToken); var counts = all.Single(); counts.Id.ShouldBe(id); diff --git a/src/Persistence/MartenTests/TestHelpers/second_stage_waiting.cs b/src/Persistence/MartenTests/TestHelpers/second_stage_waiting.cs index 8a8e1a1ed..1fd86a88a 100644 --- a/src/Persistence/MartenTests/TestHelpers/second_stage_waiting.cs +++ b/src/Persistence/MartenTests/TestHelpers/second_stage_waiting.cs @@ -81,10 +81,10 @@ public async Task with_main_store() session.Events.StartStream("AABBCCDDEE".ToLetterEvents()); session.Events.StartStream("AABBCCDDEE".ToLetterEvents()); session.Events.StartStream("AABBCCDDEE".ToLetterEvents()); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await _host.WaitForNonStaleProjectionDataAsync(5.Seconds()); - (await session.Query().CountAsync()).ShouldBe(3); + (await session.Query().CountAsync(token: TestContext.Current.CancellationToken)).ShouldBe(3); var tracked = await _host.TrackActivity() @@ -94,7 +94,7 @@ public async Task with_main_store() // Proving that previous data was wiped out - var all = await session.Query().ToListAsync(); + var all = await session.Query().ToListAsync(token: TestContext.Current.CancellationToken); var counts = all.Single(); counts.Id.ShouldBe(id); @@ -118,10 +118,10 @@ public async Task with_ancillary_store() session.Events.StartStream("AABBCCDDEE".ToLetterEvents()); session.Events.StartStream("AABBCCDDEE".ToLetterEvents()); session.Events.StartStream("AABBCCDDEE".ToLetterEvents()); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await _host.WaitForNonStaleProjectionDataAsync(5.Seconds()); - (await session.Query().CountAsync()).ShouldBe(3); + (await session.Query().CountAsync(token: TestContext.Current.CancellationToken)).ShouldBe(3); var tracked = await _host.TrackActivity() @@ -132,7 +132,7 @@ public async Task with_ancillary_store() // Proving that previous data was wiped out - var all = await session.Query().ToListAsync(); + var all = await session.Query().ToListAsync(token: TestContext.Current.CancellationToken); var counts = all.Single(); counts.Id.ShouldBe(id); diff --git a/src/Persistence/MartenTests/TestHelpers/wait_for_non_stale_data_after.cs b/src/Persistence/MartenTests/TestHelpers/wait_for_non_stale_data_after.cs index 34fbeafda..83f31a162 100644 --- a/src/Persistence/MartenTests/TestHelpers/wait_for_non_stale_data_after.cs +++ b/src/Persistence/MartenTests/TestHelpers/wait_for_non_stale_data_after.cs @@ -76,10 +76,10 @@ public async Task with_main_store() session.Events.StartStream("AABBCCDDEE".ToLetterEvents()); session.Events.StartStream("AABBCCDDEE".ToLetterEvents()); session.Events.StartStream("AABBCCDDEE".ToLetterEvents()); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await _host.WaitForNonStaleProjectionDataAsync(5.Seconds()); - (await session.Query().CountAsync()).ShouldBe(3); + (await session.Query().CountAsync(token: TestContext.Current.CancellationToken)).ShouldBe(3); var tracked = await _host.TrackActivity() @@ -89,7 +89,7 @@ public async Task with_main_store() // Proving that previous data was wiped out - var all = await session.Query().ToListAsync(); + var all = await session.Query().ToListAsync(token: TestContext.Current.CancellationToken); var counts = all.Single(); counts.Id.ShouldBe(id); @@ -110,10 +110,10 @@ public async Task with_ancillary_store() session.Events.StartStream("AABBCCDDEE".ToLetterEvents()); session.Events.StartStream("AABBCCDDEE".ToLetterEvents()); session.Events.StartStream("AABBCCDDEE".ToLetterEvents()); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await _host.WaitForNonStaleProjectionDataAsync(5.Seconds()); - (await session.Query().CountAsync()).ShouldBe(3); + (await session.Query().CountAsync(token: TestContext.Current.CancellationToken)).ShouldBe(3); var tracked = await _host.TrackActivity() @@ -123,7 +123,7 @@ public async Task with_ancillary_store() // Proving that previous data was wiped out - var all = await session.Query().ToListAsync(); + var all = await session.Query().ToListAsync(token: TestContext.Current.CancellationToken); var counts = all.Single(); counts.Id.ShouldBe(id); diff --git a/src/Persistence/MartenTests/basic_marten_integration.cs b/src/Persistence/MartenTests/basic_marten_integration.cs index d15b02789..6b951405a 100644 --- a/src/Persistence/MartenTests/basic_marten_integration.cs +++ b/src/Persistence/MartenTests/basic_marten_integration.cs @@ -92,12 +92,12 @@ public async Task registers_document_store_in_a_usable_way() using (var session = theHost.DocumentStore().LightweightSession()) { session.Store(doc); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); } using (var query = theHost.DocumentStore().QuerySession()) { - (await query.LoadAsync(doc.Id)).ShouldNotBeNull(); + (await query.LoadAsync(doc.Id, TestContext.Current.CancellationToken)).ShouldNotBeNull(); } } diff --git a/src/Persistence/MartenTests/batch_processing.cs b/src/Persistence/MartenTests/batch_processing.cs index 5b2dc55c1..528908c3d 100644 --- a/src/Persistence/MartenTests/batch_processing.cs +++ b/src/Persistence/MartenTests/batch_processing.cs @@ -40,10 +40,10 @@ public async Task end_to_end_with_durable() .IncludeType(typeof(BatchItemHandler)); opts.Durability.Mode = DurabilityMode.Solo; - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); await theHost.CleanAllMartenDataAsync(); - await theHost.ResetResourceState(); + await theHost.ResetResourceState(cancellation: TestContext.Current.CancellationToken); var item1 = new BatchItem("one", Guid.NewGuid()); var item2 = new BatchItem("two", Guid.NewGuid()); @@ -89,7 +89,7 @@ public async Task end_to_end_with_durable() items.ShouldContain(item8); using var session = theHost.DocumentStore().LightweightSession(); - var count = await session.Query().CountAsync(); + var count = await session.Query().CountAsync(token: TestContext.Current.CancellationToken); count.ShouldBe(8); @@ -127,7 +127,7 @@ public async Task end_to_end_with_tenancy() opts.Discovery.DisableConventionalDiscovery() .IncludeType(typeof(BatchItemHandler)); opts.Durability.Mode = DurabilityMode.Solo; - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var item1 = new BatchItem("one", Guid.NewGuid()); var item2 = new BatchItem("two", Guid.NewGuid()); @@ -139,7 +139,7 @@ public async Task end_to_end_with_tenancy() var item8 = new BatchItem("eight", Guid.NewGuid()); await theHost.CleanAllMartenDataAsync(); - await theHost.ResetResourceState(); + await theHost.ResetResourceState(cancellation: TestContext.Current.CancellationToken); Func publish = async c => { @@ -176,11 +176,11 @@ public async Task end_to_end_with_tenancy() items.ShouldContain(item8); using var blue = theHost.DocumentStore().LightweightSession("blue"); - var blueItems = await blue.Query().ToListAsync(); + var blueItems = await blue.Query().ToListAsync(token: TestContext.Current.CancellationToken); blueItems.Count.ShouldBe(5); using var green = theHost.DocumentStore().LightweightSession("green"); - var greenItems = await green.Query().ToListAsync(); + var greenItems = await green.Query().ToListAsync(token: TestContext.Current.CancellationToken); greenItems.Count.ShouldBe(3); } } diff --git a/src/Persistence/MartenTests/batch_querying_support.cs b/src/Persistence/MartenTests/batch_querying_support.cs index 787207cb7..5864f699e 100644 --- a/src/Persistence/MartenTests/batch_querying_support.cs +++ b/src/Persistence/MartenTests/batch_querying_support.cs @@ -54,7 +54,7 @@ public async Task try_batch_querying_end_to_end() var doc3 = new Doc3{Id = Guid.NewGuid().ToString()}; session.Store(doc3); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await theHost.InvokeAsync(new DoStuffWithDocs(doc1.Id, doc2.Id, doc3.Id)); } @@ -72,7 +72,7 @@ public async Task try_batch_querying_with_read_aggregate() var streamId = Guid.NewGuid(); session.Events.StartStream(streamId, new AEvent(), new BEvent(), new BEvent(), new DEvent()); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await theHost.InvokeAsync(new ReadAggregateWithDocs(doc1.Id, doc2.Id, streamId)); } diff --git a/src/Persistence/MartenTests/concurrency_resilient_sharded_processing.cs b/src/Persistence/MartenTests/concurrency_resilient_sharded_processing.cs index 196569cbf..607e65d7d 100644 --- a/src/Persistence/MartenTests/concurrency_resilient_sharded_processing.cs +++ b/src/Persistence/MartenTests/concurrency_resilient_sharded_processing.cs @@ -75,7 +75,7 @@ public async Task hammer_it_with_lots_of_messages_against_buffered() queue.BufferedInMemory(); }); }); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); // This is because of https://github.com/JasperFx/wolverine/issues/1835 var agents = await new ExclusiveListenerFamily(host.GetRuntime()).AllKnownAgentsAsync(); @@ -134,7 +134,7 @@ public async Task hammer_it_with_lots_of_messages_against_buffered_with_inferred #endregion - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); // Re-purposing the test a bit. Making sure we're constructing forwarding correctly var executor = host.GetRuntime().As().BuildFor(typeof(LogA), new StubEndpoint("Wrong", new StubTransport())); @@ -179,7 +179,7 @@ public async Task hammer_it_with_lots_of_messages_against_buffered_and_sharded_m queue.UseDurableInbox(); }); }); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); // This is just pumping out a ton of messages of different types of ILetterMessage // that simulate getting a burst of messages that all append events to Marten streams @@ -226,7 +226,7 @@ public async Task hammer_it_with_lots_of_messages_against_durable() .UseDurableInbox(); }); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var tracked = await host.ExecuteAndWaitAsync(pumpOutMessages, 60000); } diff --git a/src/Persistence/MartenTests/end_to_end_publish_messages_through_marten_to_wolverine.cs b/src/Persistence/MartenTests/end_to_end_publish_messages_through_marten_to_wolverine.cs index c3e84dfa8..0c6d8e61d 100644 --- a/src/Persistence/MartenTests/end_to_end_publish_messages_through_marten_to_wolverine.cs +++ b/src/Persistence/MartenTests/end_to_end_publish_messages_through_marten_to_wolverine.cs @@ -54,7 +54,7 @@ public async Task can_publish_messages_through_outbox() .AddAsyncDaemon(DaemonMode.Solo); opts.Policies.UseDurableLocalQueues(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var streamId = Guid.NewGuid(); @@ -100,7 +100,7 @@ public async Task can_publish_messages_through_outbox_running_inline() opts.Policies.UseDurableLocalQueues(); opts.Durability.Mode = DurabilityMode.Solo; - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var streamId = Guid.NewGuid(); @@ -145,7 +145,7 @@ public async Task can_publish_messages_through_outbox_with_tenancy() .AddAsyncDaemon(DaemonMode.Solo); opts.Policies.UseDurableLocalQueues(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var streamId = Guid.NewGuid(); @@ -200,13 +200,13 @@ public async Task can_publish_messages_through_outbox_running_inline_from_within opts.Services.AddHostedService(); opts.Policies.UseDurableLocalQueues(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var count = 0; while (count < 10) { if (GotBHandler.Received.Count >= 3) break; - await Task.Delay(250.Milliseconds()); + await Task.Delay(250.Milliseconds(), TestContext.Current.CancellationToken); } GotBHandler.Received.Count.ShouldBe(3); @@ -345,7 +345,7 @@ public async Task expect_message_from_non_tenanted_session() var store = _host.DocumentStore(); await using var session = store.LightweightSession(); var customerId = session.Events.StartStream(new CustomerAdded("Acme")).Id; - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); Func action = async _ => { @@ -370,7 +370,7 @@ public async Task expect_message_from_tenanted_session() var store = _host.DocumentStore(); await using var session = store.LightweightSession(); var customerId = session.Events.StartStream(new CustomerAdded("Acme")).Id; - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); Func action = async _ => { diff --git a/src/Persistence/MartenTests/event_stream_append_persists.cs b/src/Persistence/MartenTests/event_stream_append_persists.cs index 05c2379aa..a722bb027 100644 --- a/src/Persistence/MartenTests/event_stream_append_persists.cs +++ b/src/Persistence/MartenTests/event_stream_append_persists.cs @@ -57,7 +57,7 @@ public async Task compound_handler_event_stream_append_persists_without_auto_tra await theHost.InvokeMessageAndWaitAsync(new AppendViaStreamCommand(id)); await using var session = theStore.LightweightSession(); - var events = await session.Events.FetchStreamAsync(id); + var events = await session.Events.FetchStreamAsync(id, token: TestContext.Current.CancellationToken); events.Count.ShouldBe(1); // was 0 (append dropped) before GH-3032 } } diff --git a/src/Persistence/MartenTests/event_streaming.cs b/src/Persistence/MartenTests/event_streaming.cs index 8fc5320b8..dba5d3b1a 100644 --- a/src/Persistence/MartenTests/event_streaming.cs +++ b/src/Persistence/MartenTests/event_streaming.cs @@ -160,7 +160,7 @@ public async Task execution_of_forwarded_events_can_be_awaited_from_tests() opts.SubscribeToEvent().TransformedTo(e => new SecondMessage(e.StreamId, e.Sequence)); }); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var aggregateId = Guid.NewGuid(); await host.SaveInMartenAndWaitForOutgoingMessagesAsync(session => @@ -170,7 +170,7 @@ await host.SaveInMartenAndWaitForOutgoingMessagesAsync(session => using var store = host.Services.GetRequiredService(); await using var session = store.LightweightSession(); - var events = await session.Events.FetchStreamAsync(aggregateId); + var events = await session.Events.FetchStreamAsync(aggregateId, token: TestContext.Current.CancellationToken); events.Count.ShouldBe(2); events[0].Data.ShouldBeOfType(); events[1].Data.ShouldBeOfType(); diff --git a/src/Persistence/MartenTests/global_entity_defaults.cs b/src/Persistence/MartenTests/global_entity_defaults.cs index fed951d36..4db2fae7e 100644 --- a/src/Persistence/MartenTests/global_entity_defaults.cs +++ b/src/Persistence/MartenTests/global_entity_defaults.cs @@ -63,7 +63,7 @@ public async Task attribute_override_wins_over_global() public async Task end_to_end_with_good_data() { var thing = new GlobalThing(); - await _host.DocumentStore().BulkInsertDocumentsAsync([thing]); + await _host.DocumentStore().BulkInsertDocumentsAsync([thing], cancellation: TestContext.Current.CancellationToken); var tracked = await _host.InvokeMessageAndWaitAsync(new UseGlobalThing1(thing.Id)); diff --git a/src/Persistence/MartenTests/handler_actions_with_implied_marten_operations.cs b/src/Persistence/MartenTests/handler_actions_with_implied_marten_operations.cs index 3cb7ba385..95fd28c1b 100644 --- a/src/Persistence/MartenTests/handler_actions_with_implied_marten_operations.cs +++ b/src/Persistence/MartenTests/handler_actions_with_implied_marten_operations.cs @@ -59,7 +59,7 @@ public async Task storing_document() tracked.Sent.SingleMessage().Name.ShouldBe("Aubrey"); using var session = _store.LightweightSession(); - var doc = await session.LoadAsync("Aubrey"); + var doc = await session.LoadAsync("Aubrey", TestContext.Current.CancellationToken); doc.ShouldNotBeNull(); } @@ -69,7 +69,7 @@ public async Task insert_document() await _host.InvokeMessageAndWaitAsync(new InsertMartenDocument("Declan")); using var session = _store.LightweightSession(); - var doc = await session.LoadAsync("Declan"); + var doc = await session.LoadAsync("Declan", TestContext.Current.CancellationToken); doc.ShouldNotBeNull(); await Should.ThrowAsync(() => @@ -86,7 +86,7 @@ public async Task update_document_happy_path() using var session = _store.LightweightSession(); - var doc = await session.LoadAsync("Max"); + var doc = await session.LoadAsync("Max", TestContext.Current.CancellationToken); doc!.Number.ShouldBe(10); @@ -106,7 +106,7 @@ public async Task delete_document() await _host.InvokeMessageAndWaitAsync(new DeleteMartenDocument("Max")); using var session = _store.LightweightSession(); - var doc = await session.LoadAsync("Max"); + var doc = await session.LoadAsync("Max", TestContext.Current.CancellationToken); doc.ShouldBeNull(); } @@ -117,7 +117,7 @@ public async Task delete_document_through_send() await _host.SendMessageAndWaitAsync(new DeleteMartenDocument("Max")); using var session = _store.LightweightSession(); - var doc = await session.LoadAsync("Max"); + var doc = await session.LoadAsync("Max", TestContext.Current.CancellationToken); doc.ShouldBeNull(); } @@ -129,11 +129,11 @@ public async Task delete_document_by_int_id() var id = 2345; session.Store(new IntIdDocument { Id = id }); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await _host.InvokeMessageAndWaitAsync(new DeleteMartenDocumentByIntId(id)); - var doc = await session.LoadAsync(id); + var doc = await session.LoadAsync(id, TestContext.Current.CancellationToken); doc.ShouldBeNull(); } @@ -145,11 +145,11 @@ public async Task delete_document_by_long_id() var id = 23456L; session.Store(new LongIdDocument { Id = id }); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await _host.InvokeMessageAndWaitAsync(new DeleteMartenDocumentByLongId(id)); - var doc = await session.LoadAsync(id); + var doc = await session.LoadAsync(id, TestContext.Current.CancellationToken); doc.ShouldBeNull(); } @@ -161,11 +161,11 @@ public async Task delete_document_by_guid_id() var id = Guid.NewGuid(); session.Store(new GuidIdDocument { Id = id }); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await _host.InvokeMessageAndWaitAsync(new DeleteMartenDocumentByGuidId(id)); - var doc = await session.LoadAsync(id); + var doc = await session.LoadAsync(id, TestContext.Current.CancellationToken); doc.ShouldBeNull(); } @@ -177,11 +177,11 @@ public async Task delete_document_by_string_id() var id = "Max"; session.Store(new StringIdDocument { Id = id }); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await _host.InvokeMessageAndWaitAsync(new DeleteMartenDocumentByStringId(id)); - var doc = await session.LoadAsync(id); + var doc = await session.LoadAsync(id, TestContext.Current.CancellationToken); doc.ShouldBeNull(); } @@ -199,14 +199,14 @@ public async Task delete_documents_by_object_ids() session.Store(new LongIdDocument { Id = longId }); session.Store(new GuidIdDocument { Id = guidId }); session.Store(new StringIdDocument { Id = stringId }); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await _host.InvokeMessageAndWaitAsync(new DeleteMartenDocumentsByObjectIds(intId, longId, guidId, stringId)); - var intDoc = await session.LoadAsync(intId); - var longDoc = await session.LoadAsync(longId); - var guidDoc = await session.LoadAsync(guidId); - var stringDoc = await session.LoadAsync(stringId); + var intDoc = await session.LoadAsync(intId, TestContext.Current.CancellationToken); + var longDoc = await session.LoadAsync(longId, TestContext.Current.CancellationToken); + var guidDoc = await session.LoadAsync(guidId, TestContext.Current.CancellationToken); + var stringDoc = await session.LoadAsync(stringId, TestContext.Current.CancellationToken); intDoc.ShouldBeNull(); longDoc.ShouldBeNull(); guidDoc.ShouldBeNull(); @@ -226,7 +226,7 @@ await Should.ThrowAsync(() => [Fact] public async Task delete_document_where() { - await _store.Advanced.Clean.DeleteDocumentsByTypeAsync(typeof(NamedDocument)); + await _store.Advanced.Clean.DeleteDocumentsByTypeAsync(typeof(NamedDocument), TestContext.Current.CancellationToken); await _host.InvokeMessageAndWaitAsync(new InsertMartenDocument("foo")); await _host.InvokeMessageAndWaitAsync(new InsertMartenDocument("bar")); @@ -234,7 +234,7 @@ public async Task delete_document_where() await _host.InvokeMessageAndWaitAsync(new DeleteMartenDocumentsStartingWith("ba")); await using var session = _store.LightweightSession(); - var docs = await session.Query().ToListAsync(); + var docs = await session.Query().ToListAsync(token: TestContext.Current.CancellationToken); docs.ShouldHaveSingleItem().Id.ShouldBe("foo"); } @@ -242,15 +242,15 @@ public async Task delete_document_where() [Fact] public async Task use_enumerable_of_imartenop_as_return_value() { - await _store.Advanced.Clean.DeleteDocumentsByTypeAsync(typeof(NamedDocument)); + await _store.Advanced.Clean.DeleteDocumentsByTypeAsync(typeof(NamedDocument), TestContext.Current.CancellationToken); await _host.InvokeMessageAndWaitAsync(new AppendManyNamedDocuments(["red", "blue", "green"])); using var session = _store.LightweightSession(); - (await session.LoadAsync("red"))!.Number.ShouldBe(1); - (await session.LoadAsync("blue"))!.Number.ShouldBe(2); - (await session.LoadAsync("green"))!.Number.ShouldBe(3); + (await session.LoadAsync("red", TestContext.Current.CancellationToken))!.Number.ShouldBe(1); + (await session.LoadAsync("blue", TestContext.Current.CancellationToken))!.Number.ShouldBe(2); + (await session.LoadAsync("green", TestContext.Current.CancellationToken))!.Number.ShouldBe(3); } } diff --git a/src/Persistence/MartenTests/handler_actions_with_returned_StartStream.cs b/src/Persistence/MartenTests/handler_actions_with_returned_StartStream.cs index 996a2ca26..04096e15f 100644 --- a/src/Persistence/MartenTests/handler_actions_with_returned_StartStream.cs +++ b/src/Persistence/MartenTests/handler_actions_with_returned_StartStream.cs @@ -53,7 +53,7 @@ public async Task start_stream_by_guid1() await _host.InvokeMessageAndWaitAsync(new StartStreamMessage(id)); using var session = _store.LightweightSession(); - var events = await session.Events.FetchStreamAsync(id); + var events = await session.Events.FetchStreamAsync(id, token: TestContext.Current.CancellationToken); events.Count.ShouldBe(2); events[0].Data.ShouldBeOfType(); events[1].Data.ShouldBeOfType(); @@ -105,7 +105,7 @@ public async Task start_stream_by_string() await _host.InvokeMessageAndWaitAsync(new StartStreamMessage2(id)); using var session = _store.LightweightSession(); - var events = await session.Events.FetchStreamAsync(id); + var events = await session.Events.FetchStreamAsync(id, token: TestContext.Current.CancellationToken); events.Count.ShouldBe(2); events[0].Data.ShouldBeOfType(); events[1].Data.ShouldBeOfType(); diff --git a/src/Persistence/MartenTests/idempotency_check_in_marten_envelope_transaction.cs b/src/Persistence/MartenTests/idempotency_check_in_marten_envelope_transaction.cs index a8654480e..be87ebea6 100644 --- a/src/Persistence/MartenTests/idempotency_check_in_marten_envelope_transaction.cs +++ b/src/Persistence/MartenTests/idempotency_check_in_marten_envelope_transaction.cs @@ -114,7 +114,7 @@ public async Task happy_and_sad_path(IdempotencyStyle idempotency) m.Connection(Servers.PostgresConnectionString); m.DatabaseSchemaName = "idempotent"; }).IntegrateWithWolverine(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var messageId = Guid.NewGuid(); var tracked1 = await host.SendMessageAndWaitAsync(new MaybeIdempotent(messageId)); @@ -159,7 +159,7 @@ public async Task happy_and_sad_path_with_message_and_destination_tracking(Idemp m.Connection(Servers.PostgresConnectionString); m.DatabaseSchemaName = "idempotent"; }).IntegrateWithWolverine(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var messageId = Guid.NewGuid(); var tracked1 = await host.SendMessageAndWaitAsync(new MaybeIdempotent(messageId)); diff --git a/src/Persistence/MartenTests/marten_tracking_diagnostics.cs b/src/Persistence/MartenTests/marten_tracking_diagnostics.cs index 7c16669e8..51d2ee294 100644 --- a/src/Persistence/MartenTests/marten_tracking_diagnostics.cs +++ b/src/Persistence/MartenTests/marten_tracking_diagnostics.cs @@ -44,7 +44,7 @@ public async Task save_changes_events_baked_into_codegen_when_outbox_diagnostics // with marten.savechanges.start / .finished ActivityEvents. opts.Policies.AutoApplyTransactions(); opts.Tracking.OutboxDiagnosticsEnabled = true; - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); // Force codegen by resolving the handler. host.GetRuntime().Handlers.HandlerFor(); @@ -71,7 +71,7 @@ public async Task save_changes_events_absent_from_codegen_when_outbox_diagnostic opts.Services.AddMarten(Servers.PostgresConnectionString).IntegrateWithWolverine(); opts.Policies.AutoApplyTransactions(); // OutboxDiagnosticsEnabled left at its default (false) - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); host.GetRuntime().Handlers.HandlerFor(); diff --git a/src/Persistence/MartenTests/missing_data_handling_with_entity_attributes.cs b/src/Persistence/MartenTests/missing_data_handling_with_entity_attributes.cs index 1662dccff..2fd65d78b 100644 --- a/src/Persistence/MartenTests/missing_data_handling_with_entity_attributes.cs +++ b/src/Persistence/MartenTests/missing_data_handling_with_entity_attributes.cs @@ -63,7 +63,7 @@ public async Task missing_data_goes_nowhere() public async Task end_to_end_with_good_data() { var thing = new Thing(); - await _host.DocumentStore().BulkInsertDocumentsAsync([thing]); + await _host.DocumentStore().BulkInsertDocumentsAsync([thing], cancellation: TestContext.Current.CancellationToken); var tracked = await _host.InvokeMessageAndWaitAsync(new UseThing1(thing.Id)); @@ -119,7 +119,7 @@ public async Task throw_exception_with_guid_identity_and_custom_message() public async Task end_to_end_with_guid_identity_entity() { var guidThing = new GuidThing(); - await _host.DocumentStore().BulkInsertDocumentsAsync([guidThing]); + await _host.DocumentStore().BulkInsertDocumentsAsync([guidThing], cancellation: TestContext.Current.CancellationToken); var tracked = await _host.InvokeMessageAndWaitAsync(new UseGuidThing1(guidThing.Id)); diff --git a/src/Persistence/MartenTests/non_transactional_attribute_opt_out.cs b/src/Persistence/MartenTests/non_transactional_attribute_opt_out.cs index 0af95cf54..d28530575 100644 --- a/src/Persistence/MartenTests/non_transactional_attribute_opt_out.cs +++ b/src/Persistence/MartenTests/non_transactional_attribute_opt_out.cs @@ -27,7 +27,7 @@ public async Task handler_with_non_transactional_attribute_should_not_be_transac .IntegrateWithWolverine(); opts.Policies.AutoApplyTransactions(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.GetRuntime(); @@ -50,7 +50,7 @@ public async Task handler_without_non_transactional_attribute_should_still_be_tr .IntegrateWithWolverine(); opts.Policies.AutoApplyTransactions(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.GetRuntime(); @@ -73,7 +73,7 @@ public async Task non_transactional_attribute_on_handler_class_should_opt_out() .IntegrateWithWolverine(); opts.Policies.AutoApplyTransactions(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.GetRuntime(); diff --git a/src/Persistence/MartenTests/read_aggregate_attribute_usage.cs b/src/Persistence/MartenTests/read_aggregate_attribute_usage.cs index dff45b2f0..4a06eb7ba 100644 --- a/src/Persistence/MartenTests/read_aggregate_attribute_usage.cs +++ b/src/Persistence/MartenTests/read_aggregate_attribute_usage.cs @@ -56,13 +56,13 @@ public async Task use_end_to_end_happy_past() using (var session = theStore.LightweightSession()) { session.Events.StartStream(streamId, new AEvent(), new AEvent(), new CEvent()); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); - var latest = await session.Events.FetchLatest(streamId); + var latest = await session.Events.FetchLatest(streamId, TestContext.Current.CancellationToken); latest.ShouldNotBeNull(); } - var envelope = await theHost.MessageBus().InvokeAsync(new FindAggregate(streamId)); + var envelope = await theHost.MessageBus().InvokeAsync(new FindAggregate(streamId), TestContext.Current.CancellationToken); envelope.Inner.ACount.ShouldBe(2); envelope.Inner.CCount.ShouldBe(1); } @@ -71,7 +71,7 @@ public async Task use_end_to_end_happy_past() public async Task end_to_end_sad_path() { var envelope = await theHost.MessageBus() - .InvokeAsync(new FindAggregate(Guid.NewGuid())); + .InvokeAsync(new FindAggregate(Guid.NewGuid()), TestContext.Current.CancellationToken); envelope.ShouldBeNull(); } } diff --git a/src/Persistence/MartenTests/service_location_document_session.cs b/src/Persistence/MartenTests/service_location_document_session.cs index bba13f058..5d89666ac 100644 --- a/src/Persistence/MartenTests/service_location_document_session.cs +++ b/src/Persistence/MartenTests/service_location_document_session.cs @@ -35,7 +35,7 @@ public async Task service_located_session_is_same_instance_as_the_handler_sessio // Force the capturing service to be resolved via service location so the chain creates // a child scope — the path GH-3001 primes. opts.CodeGeneration.AlwaysUseServiceLocationFor(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); SessionIdentityProbe.Reset(); diff --git a/src/Persistence/MartenTests/single_marten_op_side_effect_persists.cs b/src/Persistence/MartenTests/single_marten_op_side_effect_persists.cs index d96dfa448..125b9064b 100644 --- a/src/Persistence/MartenTests/single_marten_op_side_effect_persists.cs +++ b/src/Persistence/MartenTests/single_marten_op_side_effect_persists.cs @@ -57,7 +57,7 @@ public async Task single_start_stream_op_persists_without_auto_transactions() await theHost.InvokeMessageAndWaitAsync(new StartViaOp(id)); await using var session = theStore.LightweightSession(); - var events = await session.Events.FetchStreamAsync(id); + var events = await session.Events.FetchStreamAsync(id, token: TestContext.Current.CancellationToken); events.Count.ShouldBe(1); // was 0 (op dropped) before GH-3025 } @@ -68,7 +68,7 @@ public async Task single_store_op_persists_without_auto_transactions() await theHost.InvokeMessageAndWaitAsync(new StoreViaOp(id)); await using var session = theStore.LightweightSession(); - (await session.LoadAsync(id)).ShouldNotBeNull(); + (await session.LoadAsync(id, TestContext.Current.CancellationToken)).ShouldNotBeNull(); } } diff --git a/src/Persistence/MartenTests/strong_typed_identifiers.cs b/src/Persistence/MartenTests/strong_typed_identifiers.cs index fa36a371f..9eed2436d 100644 --- a/src/Persistence/MartenTests/strong_typed_identifiers.cs +++ b/src/Persistence/MartenTests/strong_typed_identifiers.cs @@ -40,7 +40,7 @@ public async Task use_strong_typed_identifier_with_single_entity_attribute() var knob1 = new Knob() { Name = "Single" }; using var session = _host.DocumentStore().LightweightSession(); session.Store(knob1); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await _host.InvokeAsync(new TwistKnob(knob1.Id)); } @@ -52,7 +52,7 @@ public async Task use_with_multiple_entities_so_it_has_to_use_batch_querying() var knob2 = new Knob() { Name = "Two" }; using var session = _host.DocumentStore().LightweightSession(); session.Store(knob1, knob2); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await _host.InvokeAsync(new TwistOneThenAnother(knob1.Id, knob2.Id)); } diff --git a/src/Persistence/MartenTests/transactional_frame_end_to_end.cs b/src/Persistence/MartenTests/transactional_frame_end_to_end.cs index 6f0fee385..74cd91396 100644 --- a/src/Persistence/MartenTests/transactional_frame_end_to_end.cs +++ b/src/Persistence/MartenTests/transactional_frame_end_to_end.cs @@ -36,7 +36,7 @@ public async Task the_transactional_middleware_works() await host.InvokeAsync(command); await using var query = host.DocumentStore().QuerySession(); - (await query.LoadAsync(command.Id)) + (await query.LoadAsync(command.Id, TestContext.Current.CancellationToken)) .ShouldNotBeNull(); } @@ -57,7 +57,7 @@ public async Task the_transactional_middleware_works_with_document_operations() await host.InvokeAsync(command); await using var query = host.DocumentStore().QuerySession(); - (await query.LoadAsync(command.Id)) + (await query.LoadAsync(command.Id, TestContext.Current.CancellationToken)) .ShouldNotBeNull(); } diff --git a/src/Persistence/MySql/MySqlTests/Agents/control_queue_tests.cs b/src/Persistence/MySql/MySqlTests/Agents/control_queue_tests.cs index 23a8fc10b..91784fb19 100644 --- a/src/Persistence/MySql/MySqlTests/Agents/control_queue_tests.cs +++ b/src/Persistence/MySql/MySqlTests/Agents/control_queue_tests.cs @@ -65,7 +65,7 @@ private static async Task dropControlSchema() public async Task control_queue_table_should_exist() { await using var conn = new MySqlConnection(Servers.MySqlConnectionString); - await conn.OpenAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); await using var cmd = conn.CreateCommand(); cmd.CommandText = @" @@ -75,8 +75,8 @@ FROM information_schema.tables AND table_name LIKE 'wolverine%'"; var tables = new List(); - await using var reader = await cmd.ExecuteReaderAsync(); - while (await reader.ReadAsync()) + await using var reader = await cmd.ExecuteReaderAsync(TestContext.Current.CancellationToken); + while (await reader.ReadAsync(TestContext.Current.CancellationToken)) { tables.Add(reader.GetString(0)); } diff --git a/src/Persistence/MySql/MySqlTests/MySqlTests.csproj b/src/Persistence/MySql/MySqlTests/MySqlTests.csproj index ec8719060..63275ca6f 100644 --- a/src/Persistence/MySql/MySqlTests/MySqlTests.csproj +++ b/src/Persistence/MySql/MySqlTests/MySqlTests.csproj @@ -1,6 +1,8 @@ + + true Exe false diff --git a/src/Persistence/MySql/MySqlTests/Sagas/configuring_saga_table_storage.cs b/src/Persistence/MySql/MySqlTests/Sagas/configuring_saga_table_storage.cs index 1b0821a38..aad41829a 100644 --- a/src/Persistence/MySql/MySqlTests/Sagas/configuring_saga_table_storage.cs +++ b/src/Persistence/MySql/MySqlTests/Sagas/configuring_saga_table_storage.cs @@ -27,20 +27,20 @@ public async Task add_tables_to_persistence() opts.AddSagaType("blue"); opts.PersistMessagesWithMySql(Servers.MySqlConnectionString, "color_sagas"); opts.Services.AddResourceSetupOnStartup(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); await using var conn = new MySqlConnection(Servers.MySqlConnectionString); - await conn.OpenAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); // Check that the saga tables exist var redTable = new Table(new DbObjectName("color_sagas", "red")); - (await redTable.ExistsInDatabaseAsync(conn)).ShouldBeTrue(); + (await redTable.ExistsInDatabaseAsync(conn, TestContext.Current.CancellationToken)).ShouldBeTrue(); var blueTable = new Table(new DbObjectName("color_sagas", "blue")); - (await blueTable.ExistsInDatabaseAsync(conn)).ShouldBeTrue(); + (await blueTable.ExistsInDatabaseAsync(conn, TestContext.Current.CancellationToken)).ShouldBeTrue(); await conn.CloseAsync(); - await host.StopAsync(); + await host.StopAsync(TestContext.Current.CancellationToken); } private static async Task dropSchemaAsync() diff --git a/src/Persistence/MySql/MySqlTests/Sagas/saga_storage_operations.cs b/src/Persistence/MySql/MySqlTests/Sagas/saga_storage_operations.cs index dcf1dbb01..db276c836 100644 --- a/src/Persistence/MySql/MySqlTests/Sagas/saga_storage_operations.cs +++ b/src/Persistence/MySql/MySqlTests/Sagas/saga_storage_operations.cs @@ -30,9 +30,9 @@ public saga_storage_operations() public async Task load_with_no_document_happily_returns_null() { await using var conn = new MySqlConnection(Servers.MySqlConnectionString); - await conn.OpenAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); - using var tx = await conn.BeginTransactionAsync(); + using var tx = await conn.BeginTransactionAsync(TestContext.Current.CancellationToken); var saga = await theSchema.LoadAsync(Guid.NewGuid(), tx, CancellationToken.None); saga.ShouldBeNull(); @@ -42,8 +42,8 @@ public async Task load_with_no_document_happily_returns_null() public async Task get_an_argument_out_of_range_exception_for_missing_id() { await using var conn = new MySqlConnection(Servers.MySqlConnectionString); - await conn.OpenAsync(); - await using var db = await conn.BeginTransactionAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); + await using var db = await conn.BeginTransactionAsync(TestContext.Current.CancellationToken); var saga = new MySqlLightweightSaga { @@ -61,8 +61,8 @@ await Should.ThrowAsync(async () => public async Task insert_then_load() { await using var conn = new MySqlConnection(Servers.MySqlConnectionString); - await conn.OpenAsync(); - await using var db = await conn.BeginTransactionAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); + await using var db = await conn.BeginTransactionAsync(TestContext.Current.CancellationToken); var saga = new MySqlLightweightSaga { @@ -71,9 +71,9 @@ public async Task insert_then_load() }; await theSchema.InsertAsync(saga, db, CancellationToken.None); - await db.CommitAsync(); + await db.CommitAsync(TestContext.Current.CancellationToken); - using var db2 = await conn.BeginTransactionAsync(); + using var db2 = await conn.BeginTransactionAsync(TestContext.Current.CancellationToken); var saga2 = await theSchema.LoadAsync(saga.Id, db2, CancellationToken.None); saga2.ShouldNotBeNull(); @@ -84,8 +84,8 @@ public async Task insert_then_load() public async Task insert_update_then_load() { await using var conn = new MySqlConnection(Servers.MySqlConnectionString); - await conn.OpenAsync(); - await using var db = await conn.BeginTransactionAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); + await using var db = await conn.BeginTransactionAsync(TestContext.Current.CancellationToken); var saga = new MySqlLightweightSaga { @@ -97,9 +97,9 @@ public async Task insert_update_then_load() saga.Name = "Hollywood Brown"; await theSchema.UpdateAsync(saga, db, CancellationToken.None); - await db.CommitAsync(); + await db.CommitAsync(TestContext.Current.CancellationToken); - using var db2 = await conn.BeginTransactionAsync(); + using var db2 = await conn.BeginTransactionAsync(TestContext.Current.CancellationToken); var saga2 = await theSchema.LoadAsync(saga.Id, db2, CancellationToken.None); saga2.ShouldNotBeNull(); @@ -110,8 +110,8 @@ public async Task insert_update_then_load() public async Task insert_then_delete() { await using var conn = new MySqlConnection(Servers.MySqlConnectionString); - await conn.OpenAsync(); - await using var db = await conn.BeginTransactionAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); + await using var db = await conn.BeginTransactionAsync(TestContext.Current.CancellationToken); var saga = new MySqlLightweightSaga { @@ -122,9 +122,9 @@ public async Task insert_then_delete() await theSchema.InsertAsync(saga, db, CancellationToken.None); await theSchema.DeleteAsync(saga, db, CancellationToken.None); - await db.CommitAsync(); + await db.CommitAsync(TestContext.Current.CancellationToken); - using var db2 = await conn.BeginTransactionAsync(); + using var db2 = await conn.BeginTransactionAsync(TestContext.Current.CancellationToken); var saga2 = await theSchema.LoadAsync(saga.Id, db2, CancellationToken.None); saga2.ShouldBeNull(); } @@ -135,14 +135,14 @@ public async Task concurrency_exception_when_version_does_not_match() await theSchema.EnsureStorageExistsAsync(CancellationToken.None); await using var conn = new MySqlConnection(Servers.MySqlConnectionString); - await conn.OpenAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); // Clean up the table await using var cleanCmd = conn.CreateCommand(); cleanCmd.CommandText = "DELETE FROM lightweight_sagas.mysqllightweightsaga_saga"; - await cleanCmd.ExecuteNonQueryAsync(); + await cleanCmd.ExecuteNonQueryAsync(TestContext.Current.CancellationToken); - var db = await conn.BeginTransactionAsync(); + var db = await conn.BeginTransactionAsync(TestContext.Current.CancellationToken); var saga = new MySqlLightweightSaga { @@ -151,17 +151,17 @@ public async Task concurrency_exception_when_version_does_not_match() }; await theSchema.InsertAsync(saga, db, CancellationToken.None); - await db.CommitAsync(); + await db.CommitAsync(TestContext.Current.CancellationToken); await db.DisposeAsync(); - db = await conn.BeginTransactionAsync(); + db = await conn.BeginTransactionAsync(TestContext.Current.CancellationToken); saga.Name = "Rashee Rice"; await theSchema.UpdateAsync(saga, db, CancellationToken.None); - await db.CommitAsync(); + await db.CommitAsync(TestContext.Current.CancellationToken); await db.DisposeAsync(); - db = await conn.BeginTransactionAsync(); + db = await conn.BeginTransactionAsync(TestContext.Current.CancellationToken); // I'm rewinding the version to make it throw saga.Version = 1; diff --git a/src/Persistence/MySql/MySqlTests/SchemaTests.cs b/src/Persistence/MySql/MySqlTests/SchemaTests.cs index c34f8da40..af0d98104 100644 --- a/src/Persistence/MySql/MySqlTests/SchemaTests.cs +++ b/src/Persistence/MySql/MySqlTests/SchemaTests.cs @@ -92,10 +92,10 @@ public async Task try_create_each_table_individually() var migrator = new MySqlMigrator(); // First, ensure database exists and drop all existing tables - await using var setupConn = await dataSource.OpenConnectionAsync(); + await using var setupConn = await dataSource.OpenConnectionAsync(TestContext.Current.CancellationToken); await using var setupCmd = setupConn.CreateCommand(); setupCmd.CommandText = "CREATE DATABASE IF NOT EXISTS `receiver`"; - await setupCmd.ExecuteNonQueryAsync(); + await setupCmd.ExecuteNonQueryAsync(TestContext.Current.CancellationToken); // Drop existing tables setupCmd.CommandText = @" @@ -109,7 +109,7 @@ public async Task try_create_each_table_individually() DROP TABLE IF EXISTS receiver.wolverine_outgoing_envelopes; DROP TABLE IF EXISTS receiver.wolverine_dead_letters; SET FOREIGN_KEY_CHECKS = 1;"; - await setupCmd.ExecuteNonQueryAsync(); + await setupCmd.ExecuteNonQueryAsync(TestContext.Current.CancellationToken); await setupConn.CloseAsync(); Console.WriteLine("=== Trying to create each table ===\n"); @@ -124,7 +124,7 @@ public async Task try_create_each_table_individually() try { - await using var conn = await dataSource.OpenConnectionAsync(); + await using var conn = await dataSource.OpenConnectionAsync(TestContext.Current.CancellationToken); // Execute each statement separately var statements = sql.Split(';', StringSplitOptions.RemoveEmptyEntries); @@ -135,7 +135,7 @@ public async Task try_create_each_table_individually() await using var cmd = conn.CreateCommand(); cmd.CommandText = trimmed; - await cmd.ExecuteNonQueryAsync(); + await cmd.ExecuteNonQueryAsync(TestContext.Current.CancellationToken); } await conn.CloseAsync(); @@ -148,12 +148,12 @@ public async Task try_create_each_table_individually() } // Show what tables exist now - await using var checkConn = await dataSource.OpenConnectionAsync(); + await using var checkConn = await dataSource.OpenConnectionAsync(TestContext.Current.CancellationToken); await using var checkCmd = checkConn.CreateCommand(); checkCmd.CommandText = "SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA = 'receiver'"; - await using var reader = await checkCmd.ExecuteReaderAsync(); + await using var reader = await checkCmd.ExecuteReaderAsync(TestContext.Current.CancellationToken); Console.WriteLine("\nTables that exist:"); - while (await reader.ReadAsync()) + while (await reader.ReadAsync(TestContext.Current.CancellationToken)) { Console.WriteLine($" - {reader.GetString(0)}"); } @@ -193,12 +193,12 @@ public async Task can_migrate_schema_directly() } // Verify tables exist in the receiver database - await using var conn = await dataSource.OpenConnectionAsync(); + await using var conn = await dataSource.OpenConnectionAsync(TestContext.Current.CancellationToken); await using var cmd = conn.CreateCommand(); cmd.CommandText = "SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA = 'receiver'"; - await using var reader = await cmd.ExecuteReaderAsync(); + await using var reader = await cmd.ExecuteReaderAsync(TestContext.Current.CancellationToken); Console.WriteLine("\nTables after migration in receiver database:"); - while (await reader.ReadAsync()) + while (await reader.ReadAsync(TestContext.Current.CancellationToken)) { Console.WriteLine($" - {reader.GetString(0)}"); } @@ -217,12 +217,12 @@ public async Task can_migrate_schema_directly() "wolverine_dead_letters" }; - await using var conn2 = await dataSource.OpenConnectionAsync(); + await using var conn2 = await dataSource.OpenConnectionAsync(TestContext.Current.CancellationToken); await using var cmd2 = conn2.CreateCommand(); cmd2.CommandText = "SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA = 'receiver'"; - await using var reader2 = await cmd2.ExecuteReaderAsync(); + await using var reader2 = await cmd2.ExecuteReaderAsync(TestContext.Current.CancellationToken); var actualTables = new List(); - while (await reader2.ReadAsync()) + while (await reader2.ReadAsync(TestContext.Current.CancellationToken)) { actualTables.Add(reader2.GetString(0)); } diff --git a/src/Persistence/MySql/MySqlTests/Transport/basic_functionality.cs b/src/Persistence/MySql/MySqlTests/Transport/basic_functionality.cs index ad30a7712..ffca32d29 100644 --- a/src/Persistence/MySql/MySqlTests/Transport/basic_functionality.cs +++ b/src/Persistence/MySql/MySqlTests/Transport/basic_functionality.cs @@ -74,7 +74,7 @@ public async ValueTask DisposeAsync() public async Task expected_tables_exist_for_queue() { await using var conn = new MySqlConnection(Servers.MySqlConnectionString); - await conn.OpenAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); var tables = new List(); await using var cmd = conn.CreateCommand(); @@ -83,8 +83,8 @@ SELECT table_name FROM information_schema.tables WHERE table_schema = 'wolverine_transports' AND table_name LIKE 'wolverine_queue_%'"; - await using var reader = await cmd.ExecuteReaderAsync(); - while (await reader.ReadAsync()) + await using var reader = await cmd.ExecuteReaderAsync(TestContext.Current.CancellationToken); + while (await reader.ReadAsync(TestContext.Current.CancellationToken)) { tables.Add(reader.GetString(0)); } diff --git a/src/Persistence/Oracle/OracleTests/Agents/health_check_timestamp_round_trip.cs b/src/Persistence/Oracle/OracleTests/Agents/health_check_timestamp_round_trip.cs index 481df3081..3345500ef 100644 --- a/src/Persistence/Oracle/OracleTests/Agents/health_check_timestamp_round_trip.cs +++ b/src/Persistence/Oracle/OracleTests/Agents/health_check_timestamp_round_trip.cs @@ -47,10 +47,10 @@ public async Task just_persisted_node_must_not_be_filtered_as_stale_under_non_ut // expression bakes in the wrong offset — mirrors a real Oracle DB hosted in // a non-UTC region. var nodeId = Guid.NewGuid(); - await using (var conn = await dataSource.OpenConnectionAsync()) + await using (var conn = await dataSource.OpenConnectionAsync(TestContext.Current.CancellationToken)) { await conn.CreateCommand("ALTER SESSION SET TIME_ZONE = '+05:00'") - .ExecuteNonQueryAsync(); + .ExecuteNonQueryAsync(TestContext.Current.CancellationToken); // Insert a node row using the column DEFAULT for health_check (the path // that NodeAgentController hits via PersistAsync on first heartbeat). @@ -62,7 +62,7 @@ await conn.CreateCommand("ALTER SESSION SET TIME_ZONE = '+05:00'") insertCmd.With("capabilities", string.Empty); insertCmd.With("description", "tz-repro"); insertCmd.With("version", "1.0"); - await insertCmd.ExecuteNonQueryAsync(); + await insertCmd.ExecuteNonQueryAsync(TestContext.Current.CancellationToken); } // Read back via the production API and apply the exact staleness predicate diff --git a/src/Persistence/Oracle/OracleTests/OracleTests.csproj b/src/Persistence/Oracle/OracleTests/OracleTests.csproj index f051b62a1..75b1f23f6 100644 --- a/src/Persistence/Oracle/OracleTests/OracleTests.csproj +++ b/src/Persistence/Oracle/OracleTests/OracleTests.csproj @@ -1,6 +1,8 @@ + + true Exe false diff --git a/src/Persistence/Oracle/OracleTests/Sagas/saga_storage_operations.cs b/src/Persistence/Oracle/OracleTests/Sagas/saga_storage_operations.cs index 4eed7025b..1284e3def 100644 --- a/src/Persistence/Oracle/OracleTests/Sagas/saga_storage_operations.cs +++ b/src/Persistence/Oracle/OracleTests/Sagas/saga_storage_operations.cs @@ -30,9 +30,9 @@ public saga_storage_operations() public async Task load_with_no_document_happily_returns_null() { await using var conn = new OracleConnection(Servers.OracleConnectionString); - await conn.OpenAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); - using var tx = (OracleTransaction)await conn.BeginTransactionAsync(); + using var tx = (OracleTransaction)await conn.BeginTransactionAsync(TestContext.Current.CancellationToken); var saga = await theSchema.LoadAsync(Guid.NewGuid(), tx, CancellationToken.None); saga.ShouldBeNull(); @@ -42,8 +42,8 @@ public async Task load_with_no_document_happily_returns_null() public async Task get_an_argument_out_of_range_exception_for_missing_id() { await using var conn = new OracleConnection(Servers.OracleConnectionString); - await conn.OpenAsync(); - var db = (OracleTransaction)await conn.BeginTransactionAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); + var db = (OracleTransaction)await conn.BeginTransactionAsync(TestContext.Current.CancellationToken); var saga = new OracleLightweightSaga { @@ -61,8 +61,8 @@ await Should.ThrowAsync(async () => public async Task insert_then_load() { await using var conn = new OracleConnection(Servers.OracleConnectionString); - await conn.OpenAsync(); - var db = (OracleTransaction)await conn.BeginTransactionAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); + var db = (OracleTransaction)await conn.BeginTransactionAsync(TestContext.Current.CancellationToken); var saga = new OracleLightweightSaga { @@ -71,9 +71,9 @@ public async Task insert_then_load() }; await theSchema.InsertAsync(saga, db, CancellationToken.None); - await db.CommitAsync(); + await db.CommitAsync(TestContext.Current.CancellationToken); - var db2 = (OracleTransaction)await conn.BeginTransactionAsync(); + var db2 = (OracleTransaction)await conn.BeginTransactionAsync(TestContext.Current.CancellationToken); var saga2 = await theSchema.LoadAsync(saga.Id, db2, CancellationToken.None); saga2.ShouldNotBeNull(); @@ -84,8 +84,8 @@ public async Task insert_then_load() public async Task insert_update_then_load() { await using var conn = new OracleConnection(Servers.OracleConnectionString); - await conn.OpenAsync(); - var db = (OracleTransaction)await conn.BeginTransactionAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); + var db = (OracleTransaction)await conn.BeginTransactionAsync(TestContext.Current.CancellationToken); var saga = new OracleLightweightSaga { @@ -97,9 +97,9 @@ public async Task insert_update_then_load() saga.Name = "Hollywood Brown"; await theSchema.UpdateAsync(saga, db, CancellationToken.None); - await db.CommitAsync(); + await db.CommitAsync(TestContext.Current.CancellationToken); - var db2 = (OracleTransaction)await conn.BeginTransactionAsync(); + var db2 = (OracleTransaction)await conn.BeginTransactionAsync(TestContext.Current.CancellationToken); var saga2 = await theSchema.LoadAsync(saga.Id, db2, CancellationToken.None); saga2.ShouldNotBeNull(); @@ -110,8 +110,8 @@ public async Task insert_update_then_load() public async Task insert_then_delete() { await using var conn = new OracleConnection(Servers.OracleConnectionString); - await conn.OpenAsync(); - var db = (OracleTransaction)await conn.BeginTransactionAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); + var db = (OracleTransaction)await conn.BeginTransactionAsync(TestContext.Current.CancellationToken); var saga = new OracleLightweightSaga { @@ -122,9 +122,9 @@ public async Task insert_then_delete() await theSchema.InsertAsync(saga, db, CancellationToken.None); await theSchema.DeleteAsync(saga, db, CancellationToken.None); - await db.CommitAsync(); + await db.CommitAsync(TestContext.Current.CancellationToken); - var db2 = (OracleTransaction)await conn.BeginTransactionAsync(); + var db2 = (OracleTransaction)await conn.BeginTransactionAsync(TestContext.Current.CancellationToken); var saga2 = await theSchema.LoadAsync(saga.Id, db2, CancellationToken.None); saga2.ShouldBeNull(); } @@ -135,14 +135,14 @@ public async Task concurrency_exception_when_version_does_not_match() await theSchema.EnsureStorageExistsAsync(CancellationToken.None); await using var conn = new OracleConnection(Servers.OracleConnectionString); - await conn.OpenAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); // Clean up the table await using var cleanCmd = conn.CreateCommand( $"DELETE FROM WOLVERINE.{nameof(OracleLightweightSaga).ToUpperInvariant()}_SAGA"); - await cleanCmd.ExecuteNonQueryAsync(); + await cleanCmd.ExecuteNonQueryAsync(TestContext.Current.CancellationToken); - var db = (OracleTransaction)await conn.BeginTransactionAsync(); + var db = (OracleTransaction)await conn.BeginTransactionAsync(TestContext.Current.CancellationToken); var saga = new OracleLightweightSaga { @@ -151,15 +151,15 @@ public async Task concurrency_exception_when_version_does_not_match() }; await theSchema.InsertAsync(saga, db, CancellationToken.None); - await db.CommitAsync(); + await db.CommitAsync(TestContext.Current.CancellationToken); - db = (OracleTransaction)await conn.BeginTransactionAsync(); + db = (OracleTransaction)await conn.BeginTransactionAsync(TestContext.Current.CancellationToken); saga.Name = "Rashee Rice"; await theSchema.UpdateAsync(saga, db, CancellationToken.None); - await db.CommitAsync(); + await db.CommitAsync(TestContext.Current.CancellationToken); - db = (OracleTransaction)await conn.BeginTransactionAsync(); + db = (OracleTransaction)await conn.BeginTransactionAsync(TestContext.Current.CancellationToken); // I'm rewinding the version to make it throw saga.Version = 1; diff --git a/src/Persistence/Oracle/OracleTests/mark_incoming_handled_in_transaction_binds_raw16_guid.cs b/src/Persistence/Oracle/OracleTests/mark_incoming_handled_in_transaction_binds_raw16_guid.cs index ec88cd2d9..85312974a 100644 --- a/src/Persistence/Oracle/OracleTests/mark_incoming_handled_in_transaction_binds_raw16_guid.cs +++ b/src/Persistence/Oracle/OracleTests/mark_incoming_handled_in_transaction_binds_raw16_guid.cs @@ -54,15 +54,15 @@ public async Task marks_the_envelope_handled_inside_the_callers_transaction() var keepUntil = DateTimeOffset.UtcNow.AddHours(1); - await using var conn = (OracleConnection)await theDataSource.OpenConnectionAsync(); - var tx = (DbTransaction)await conn.BeginTransactionAsync(); + await using var conn = (OracleConnection)await theDataSource.OpenConnectionAsync(TestContext.Current.CancellationToken); + var tx = (DbTransaction)await conn.BeginTransactionAsync(TestContext.Current.CancellationToken); // The exact call EfCoreEnvelopeTransaction.CommitAsync makes for a durable-inbox message, // sharing the caller's connection and transaction. await theStore.MarkIncomingEnvelopeAsHandledInTransactionAsync(conn, tx, envelope, keepUntil, CancellationToken.None); - await tx.CommitAsync(); + await tx.CommitAsync(TestContext.Current.CancellationToken); await conn.CloseAsync(); var counts = await theStore.Admin.FetchCountsAsync(); @@ -80,7 +80,7 @@ public async Task the_generic_guid_binding_that_the_old_code_used_still_fails_on var envelope = ObjectMother.Envelope(); await theStore.StoreIncomingAsync(envelope); - await using var conn = (OracleConnection)await theDataSource.OpenConnectionAsync(); + await using var conn = (OracleConnection)await theDataSource.OpenConnectionAsync(TestContext.Current.CancellationToken); // conn typed as the base DbConnection, so .With(Guid) binds through the generic Weasel.Core // extension (DbType.Guid) rather than the Oracle-aware one — the pre-fix code path. ODP.NET diff --git a/src/Persistence/PersistenceTests/Agents/Bug_3666_pause_must_not_start_the_agent_being_paused.cs b/src/Persistence/PersistenceTests/Agents/Bug_3666_pause_must_not_start_the_agent_being_paused.cs index f6f2402c6..03fc38de2 100644 --- a/src/Persistence/PersistenceTests/Agents/Bug_3666_pause_must_not_start_the_agent_being_paused.cs +++ b/src/Persistence/PersistenceTests/Agents/Bug_3666_pause_must_not_start_the_agent_being_paused.cs @@ -57,8 +57,8 @@ public async Task pausing_a_known_but_not_running_agent_never_starts_it() { using (var conn = new NpgsqlConnection(Servers.PostgresConnectionString)) { - await conn.OpenAsync(); - await conn.DropSchemaAsync("bug3666"); + await conn.OpenAsync(TestContext.Current.CancellationToken); + await conn.DropSchemaAsync("bug3666", ct: TestContext.Current.CancellationToken); await conn.CloseAsync(); } @@ -78,7 +78,7 @@ public async Task pausing_a_known_but_not_running_agent_never_starts_it() // misbehavior deterministic instead of a race against the polling loop. opts.Durability.HealthCheckPollingTime = 1.Hours(); opts.Durability.CheckAssignmentPeriod = 1.Hours(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = (WolverineRuntime)_host.Services.GetRequiredService(); @@ -98,7 +98,7 @@ public async Task pausing_a_known_but_not_running_agent_never_starts_it() } await runtime.Agents.KickstartHealthDetectionAsync(); - await Task.Delay(250); + await Task.Delay(250, TestContext.Current.CancellationToken); } // One more evaluation while every agent is observed running, so the GH-3665 @@ -122,7 +122,7 @@ public async Task pausing_a_known_but_not_running_agent_never_starts_it() // The kickstart's commands cascade through the message bus asynchronously, so give any // pre-fix churn a moment to surface before asserting silence. - await Task.Delay(2.Seconds()); + await Task.Delay(2.Seconds(), TestContext.Current.CancellationToken); recorder.StartedAgents.ShouldNotContain(uri, "pausing an agent must never start it — the kickstarted evaluation ran before the " + diff --git a/src/Persistence/PersistenceTests/Bugs/schedule_execution_outside_of_message_handler.cs b/src/Persistence/PersistenceTests/Bugs/schedule_execution_outside_of_message_handler.cs index 78ce5bb4a..f46534a41 100644 --- a/src/Persistence/PersistenceTests/Bugs/schedule_execution_outside_of_message_handler.cs +++ b/src/Persistence/PersistenceTests/Bugs/schedule_execution_outside_of_message_handler.cs @@ -18,14 +18,14 @@ public async Task try_it_out() { opts.PersistMessagesWithPostgresql(Servers.PostgresConnectionString, "wolverine"); opts.Policies.UseDurableLocalQueues(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var bus = host.MessageBus(); await bus.ScheduleAsync(new MyGuy("Hey"), 10.Minutes()); - await Task.Delay(1.Minutes()); + await Task.Delay(1.Minutes(), TestContext.Current.CancellationToken); } } diff --git a/src/Persistence/PersistenceTests/DurableFixture.cs b/src/Persistence/PersistenceTests/DurableFixture.cs index b1f481a24..b4346c2fc 100644 --- a/src/Persistence/PersistenceTests/DurableFixture.cs +++ b/src/Persistence/PersistenceTests/DurableFixture.cs @@ -130,7 +130,7 @@ public async Task can_send_items_durably_through_persisted_channels() await theSender.TrackActivity().AlsoTrack(theReceiver).SendMessageAndWaitAsync(item); - await Task.Delay(500.Milliseconds()); + await Task.Delay(500.Milliseconds(), TestContext.Current.CancellationToken); await assertReceivedItemMatchesSent(item); diff --git a/src/Persistence/PersistenceTests/ModularMonoliths/modular_monolith_usage.cs b/src/Persistence/PersistenceTests/ModularMonoliths/modular_monolith_usage.cs index 7c2cb40b3..74603c150 100644 --- a/src/Persistence/PersistenceTests/ModularMonoliths/modular_monolith_usage.cs +++ b/src/Persistence/PersistenceTests/ModularMonoliths/modular_monolith_usage.cs @@ -38,7 +38,7 @@ public async Task set_the_default_message_store_schema_name() }).IntegrateWithWolverine(); opts.Services.AddResourceSetupOnStartup(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.GetRuntime(); var stores = (await runtime.Stores.FindAllAsync()).OfType().ToArray(); @@ -72,7 +72,7 @@ public async Task set_the_default_message_store_schema_name_2() }).IntegrateWithWolverine(); opts.Services.AddResourceSetupOnStartup(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.GetRuntime(); var stores = (await runtime.Stores.FindAllAsync()).OfType().ToArray(); @@ -108,7 +108,7 @@ public async Task do_not_override_when_the_schema_name_is_explicitly_set() }).IntegrateWithWolverine(x => x.SchemaName = "different"); opts.Services.AddResourceSetupOnStartup(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.GetRuntime(); var stores = (await runtime.Stores.FindAllAsync()).OfType().ToArray(); @@ -144,7 +144,7 @@ public async Task using_the_marten_schema_name_with_no_other_settings() }).IntegrateWithWolverine(); opts.Services.AddResourceSetupOnStartup(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.GetRuntime(); diff --git a/src/Persistence/PersistenceTests/PersistenceTests.csproj b/src/Persistence/PersistenceTests/PersistenceTests.csproj index 4b43af1a0..7daff6502 100644 --- a/src/Persistence/PersistenceTests/PersistenceTests.csproj +++ b/src/Persistence/PersistenceTests/PersistenceTests.csproj @@ -1,6 +1,8 @@  + + true Exe false net9.0;net10.0 diff --git a/src/Persistence/PersistenceTests/persistence_provider_precedence_permutations.cs b/src/Persistence/PersistenceTests/persistence_provider_precedence_permutations.cs index 5b6a3528d..a7e93c694 100644 --- a/src/Persistence/PersistenceTests/persistence_provider_precedence_permutations.cs +++ b/src/Persistence/PersistenceTests/persistence_provider_precedence_permutations.cs @@ -82,7 +82,7 @@ public async Task efcore_owns_its_mapped_entity_when_marten_registers_last() m.DatabaseSchemaName = "provider_precedence"; }) .IntegrateWithWolverine(x => x.MessageStorageSchemaName = "provider_precedence"); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); await assertResolutionIsOrderIndependent(host); } @@ -101,7 +101,7 @@ public async Task efcore_owns_its_mapped_entity_when_marten_registers_first() opts.Services.AddDbContextWithWolverineIntegration(x => x.UseSqlServer(Servers.SqlServerConnectionString)); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); await assertResolutionIsOrderIndependent(host); } diff --git a/src/Persistence/Polecat/PolecatIncidentService.Tests/PolecatIncidentService.Tests.csproj b/src/Persistence/Polecat/PolecatIncidentService.Tests/PolecatIncidentService.Tests.csproj index e619bbdf3..552aa4a5e 100644 --- a/src/Persistence/Polecat/PolecatIncidentService.Tests/PolecatIncidentService.Tests.csproj +++ b/src/Persistence/Polecat/PolecatIncidentService.Tests/PolecatIncidentService.Tests.csproj @@ -1,6 +1,8 @@ + + true Exe false net10.0 diff --git a/src/Persistence/PolecatTests/AggregateHandlerWorkflow/aggregate_handler_workflow.cs b/src/Persistence/PolecatTests/AggregateHandlerWorkflow/aggregate_handler_workflow.cs index 860cbda09..6db48886c 100644 --- a/src/Persistence/PolecatTests/AggregateHandlerWorkflow/aggregate_handler_workflow.cs +++ b/src/Persistence/PolecatTests/AggregateHandlerWorkflow/aggregate_handler_workflow.cs @@ -242,7 +242,7 @@ public async Task if_only_returning_outgoing_messages_no_events() await using (var session = theStore.LightweightSession()) { session.Events.StartStream(streamId, new AEvent(), new BEvent()); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); } var tracked = await theHost.SendMessageAndWaitAsync(new PcEvent3(streamId)); @@ -252,7 +252,7 @@ public async Task if_only_returning_outgoing_messages_no_events() await using (var session = theStore.LightweightSession()) { - var events = await session.Events.FetchStreamAsync(streamId); + var events = await session.Events.FetchStreamAsync(streamId, token: TestContext.Current.CancellationToken); events.OfType>().Any().ShouldBeFalse(); } } @@ -264,7 +264,7 @@ public async Task using_updated_aggregate_as_response() await using (var session = theStore.LightweightSession()) { session.Events.StartStream(streamId, new AEvent(), new BEvent()); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); } var (tracked, updated) @@ -285,7 +285,7 @@ public async Task using_the_aggregate_in_a_before_method() { session.Events.StartStream(streamId, new AEvent(), new CEvent()); session.Events.StartStream(streamId2, new CEvent(), new CEvent()); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); } await theHost.InvokeMessageAndWaitAsync(new RaiseIfValidated(streamId)); @@ -293,10 +293,10 @@ public async Task using_the_aggregate_in_a_before_method() await using (var session = theStore.LightweightSession()) { - var existing1 = await session.LoadAsync(streamId); + var existing1 = await session.LoadAsync(streamId, TestContext.Current.CancellationToken); existing1!.BCount.ShouldBe(0); - var existing2 = await session.LoadAsync(streamId2); + var existing2 = await session.LoadAsync(streamId2, TestContext.Current.CancellationToken); existing2!.BCount.ShouldBe(1); } } diff --git a/src/Persistence/PolecatTests/AggregateHandlerWorkflow/mixed_aggregate_handler_with_multiple_streams.cs b/src/Persistence/PolecatTests/AggregateHandlerWorkflow/mixed_aggregate_handler_with_multiple_streams.cs index ee4023b67..731a92f25 100644 --- a/src/Persistence/PolecatTests/AggregateHandlerWorkflow/mixed_aggregate_handler_with_multiple_streams.cs +++ b/src/Persistence/PolecatTests/AggregateHandlerWorkflow/mixed_aggregate_handler_with_multiple_streams.cs @@ -29,14 +29,14 @@ public async Task get_the_correct_aggregate_back_out() m.Projections.Snapshot(SnapshotLifecycle.Inline); m.Projections.Snapshot(SnapshotLifecycle.Inline); }).IntegrateWithWolverine(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var store = host.Services.GetRequiredService(); - await ((DocumentStore)store).Database.ApplyAllConfiguredChangesToDatabaseAsync(); + await ((DocumentStore)store).Database.ApplyAllConfiguredChangesToDatabaseAsync(ct: TestContext.Current.CancellationToken); await using var session = store.LightweightSession(); var inventoryId = session.Events.StartStream(new InventoryStarted("XFX", 100, 10)).Id; var accountId = session.Events.StartStream(new XAccountOpened(2000)).Id; - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); var (tracked, account) = await host.InvokeMessageAndWaitAsync(new MakePurchase(accountId, inventoryId, 30)); account!.Balance.ShouldBe(1700); diff --git a/src/Persistence/PolecatTests/AggregateHandlerWorkflow/strong_named_identifiers.cs b/src/Persistence/PolecatTests/AggregateHandlerWorkflow/strong_named_identifiers.cs index 80273dc67..c8e60b6ab 100644 --- a/src/Persistence/PolecatTests/AggregateHandlerWorkflow/strong_named_identifiers.cs +++ b/src/Persistence/PolecatTests/AggregateHandlerWorkflow/strong_named_identifiers.cs @@ -46,10 +46,10 @@ public async Task use_read_aggregate_by_itself() await using var session = theStore.LightweightSession(); session.Events.StartStream(streamId, new AEvent(), new BEvent(), new CEvent(), new CEvent()); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); var bus = theHost.MessageBus(); - var aggregate = await bus.InvokeAsync(new FetchCounts(new LetterId(streamId))); + var aggregate = await bus.InvokeAsync(new FetchCounts(new LetterId(streamId)), TestContext.Current.CancellationToken); aggregate.ACount.ShouldBe(1); aggregate.BCount.ShouldBe(1); @@ -63,12 +63,12 @@ public async Task single_usage_of_write_aggregate() await using var session = theStore.LightweightSession(); session.Events.StartStream(streamId, new AEvent(), new BEvent(), new CEvent(), new CEvent()); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await theHost.InvokeAsync(new IncrementStrongA(new LetterId(streamId))); var bus = theHost.MessageBus(); - var aggregate = await bus.InvokeAsync(new FetchCounts(new LetterId(streamId))); + var aggregate = await bus.InvokeAsync(new FetchCounts(new LetterId(streamId)), TestContext.Current.CancellationToken); aggregate.ACount.ShouldBe(2); aggregate.BCount.ShouldBe(1); @@ -86,14 +86,14 @@ public async Task batch_query_usage_of_write_aggregate() session.Events.StartStream(stream2Id, new AEvent(), new BEvent(), new BEvent(), new AEvent()); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await theHost.InvokeMessageAndWaitAsync(new IncrementBOnBoth(new LetterId(stream1Id), new LetterId(stream2Id))); - var aggregate1 = await session.Events.FetchLatest(stream1Id); + var aggregate1 = await session.Events.FetchLatest(stream1Id, TestContext.Current.CancellationToken); aggregate1!.BCount.ShouldBe(2); - var aggregate2 = await session.Events.FetchLatest(stream2Id); + var aggregate2 = await session.Events.FetchLatest(stream2Id, TestContext.Current.CancellationToken); aggregate2!.BCount.ShouldBe(3); } @@ -108,16 +108,16 @@ public async Task batch_query_with_both_read_and_write_aggregate() session.Events.StartStream(stream2Id, new AEvent(), new BEvent(), new BEvent(), new AEvent(), new DEvent()); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await theHost.InvokeMessageAndWaitAsync(new AddFrom(new LetterId(stream1Id), new LetterId(stream2Id))); - var aggregate1 = await session.Events.FetchLatest(stream1Id); + var aggregate1 = await session.Events.FetchLatest(stream1Id, TestContext.Current.CancellationToken); aggregate1!.BCount.ShouldBe(3); aggregate1.ACount.ShouldBe(3); aggregate1.DCount.ShouldBe(1); - var aggregate2 = await session.Events.FetchLatest(stream2Id); + var aggregate2 = await session.Events.FetchLatest(stream2Id, TestContext.Current.CancellationToken); aggregate2!.BCount.ShouldBe(2); } } diff --git a/src/Persistence/PolecatTests/AncillaryStores/bootstrapping_ancillary_polecat_stores_with_wolverine.cs b/src/Persistence/PolecatTests/AncillaryStores/bootstrapping_ancillary_polecat_stores_with_wolverine.cs index 717f1bb55..1703678e9 100644 --- a/src/Persistence/PolecatTests/AncillaryStores/bootstrapping_ancillary_polecat_stores_with_wolverine.cs +++ b/src/Persistence/PolecatTests/AncillaryStores/bootstrapping_ancillary_polecat_stores_with_wolverine.cs @@ -126,7 +126,7 @@ public async Task try_to_use_the_session_transactional_middleware_end_to_end() // The [PolecatStore]-routed handler must have stored the Player in the ANCILLARY store. var store = theHost.Services.GetRequiredService(); await using var session = store.QuerySession(); - var player = await session.LoadAsync(message.Id); + var player = await session.LoadAsync(message.Id, TestContext.Current.CancellationToken); player.ShouldNotBeNull(); } diff --git a/src/Persistence/PolecatTests/AncillaryStores/storage_attribute_routes_to_polecat_store.cs b/src/Persistence/PolecatTests/AncillaryStores/storage_attribute_routes_to_polecat_store.cs index 799ca66d3..eef0ee08a 100644 --- a/src/Persistence/PolecatTests/AncillaryStores/storage_attribute_routes_to_polecat_store.cs +++ b/src/Persistence/PolecatTests/AncillaryStores/storage_attribute_routes_to_polecat_store.cs @@ -61,7 +61,7 @@ public async Task storage_attribute_opens_and_commits_through_the_polecat_ancill var store = theHost.Services.GetRequiredService(); await using var session = store.QuerySession(); - (await session.LoadAsync(message.Id)).ShouldNotBeNull(); + (await session.LoadAsync(message.Id, TestContext.Current.CancellationToken)).ShouldNotBeNull(); } } diff --git a/src/Persistence/PolecatTests/Bugs/Bug_191_aggregate_handler_without_version.cs b/src/Persistence/PolecatTests/Bugs/Bug_191_aggregate_handler_without_version.cs index 473537d10..ba6e3d6f5 100644 --- a/src/Persistence/PolecatTests/Bugs/Bug_191_aggregate_handler_without_version.cs +++ b/src/Persistence/PolecatTests/Bugs/Bug_191_aggregate_handler_without_version.cs @@ -44,7 +44,7 @@ public async Task execute_without_code_compilation_errors() await using (var session = _host.Services.GetRequiredService().LightweightSession()) { session.Events.StartStream(id, new PcThingStarted(id, "stuff")); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); } await _host.InvokeMessageAndWaitAsync(new UpdatePcThing(id, "new stuff")); diff --git a/src/Persistence/PolecatTests/Bugs/Bug_215_erroneous_failure_ack_on_invoke_async_of_t.cs b/src/Persistence/PolecatTests/Bugs/Bug_215_erroneous_failure_ack_on_invoke_async_of_t.cs index f166dde3e..f1920f2b6 100644 --- a/src/Persistence/PolecatTests/Bugs/Bug_215_erroneous_failure_ack_on_invoke_async_of_t.cs +++ b/src/Persistence/PolecatTests/Bugs/Bug_215_erroneous_failure_ack_on_invoke_async_of_t.cs @@ -26,21 +26,21 @@ public async Task no_failure_ack_on_invoke_async() opts.Policies.AutoApplyTransactions(); opts.Services.AddResourceSetupOnStartup(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); await ((DocumentStore)host.Services.GetRequiredService()).Database - .ApplyAllConfiguredChangesToDatabaseAsync(); + .ApplyAllConfiguredChangesToDatabaseAsync(ct: TestContext.Current.CancellationToken); var data = new PcBug215Data(); await using (var session = host.Services.GetRequiredService().LightweightSession()) { session.Store(data); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); } var bus = host.MessageBus(); - var response = await bus.InvokeAsync(new PcLookup(data.Id)); + var response = await bus.InvokeAsync(new PcLookup(data.Id), TestContext.Current.CancellationToken); response.ShouldNotBeNull(); } diff --git a/src/Persistence/PolecatTests/Bugs/Bug_225_compound_handlers_and_polecat_event_streams.cs b/src/Persistence/PolecatTests/Bugs/Bug_225_compound_handlers_and_polecat_event_streams.cs index f4a7a2c9c..5304a0fcb 100644 --- a/src/Persistence/PolecatTests/Bugs/Bug_225_compound_handlers_and_polecat_event_streams.cs +++ b/src/Persistence/PolecatTests/Bugs/Bug_225_compound_handlers_and_polecat_event_streams.cs @@ -26,17 +26,17 @@ public async Task should_apply_transaction() }).IntegrateWithWolverine(); }) .UseWolverine(opts => { opts.Policies.AutoApplyTransactions(); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); await ((DocumentStore)host.Services.GetRequiredService()).Database - .ApplyAllConfiguredChangesToDatabaseAsync(); + .ApplyAllConfiguredChangesToDatabaseAsync(ct: TestContext.Current.CancellationToken); var id = Guid.NewGuid(); await host.InvokeMessageAndWaitAsync(new PcStoreSomething2(id)); await using var session = host.Services.GetRequiredService().LightweightSession(); - var stream = await session.Events.FetchStreamAsync(id); + var stream = await session.Events.FetchStreamAsync(id, token: TestContext.Current.CancellationToken); stream.ShouldNotBeEmpty(); } diff --git a/src/Persistence/PolecatTests/Bugs/Bug_2668_outboxed_session_listener_null_message_store.cs b/src/Persistence/PolecatTests/Bugs/Bug_2668_outboxed_session_listener_null_message_store.cs index ddcee44da..3d6d76a15 100644 --- a/src/Persistence/PolecatTests/Bugs/Bug_2668_outboxed_session_listener_null_message_store.cs +++ b/src/Persistence/PolecatTests/Bugs/Bug_2668_outboxed_session_listener_null_message_store.cs @@ -104,7 +104,7 @@ await _host.TrackActivity() .SendMessageAndWaitAsync(new Bug2668Command(id, "Joe Mixon")); await using var session = _store.LightweightSession(); - var doc = await session.LoadAsync(id); + var doc = await session.LoadAsync(id, TestContext.Current.CancellationToken); doc.ShouldNotBeNull( "Handler did not persist the document — most likely because BeforeSaveChangesAsync threw NullReferenceException on the null SqlServerMessageStore (GH-2668). Confirm OutboxedSessionFactory.buildSessionOptions passes a real store to FlushOutgoingMessagesOnCommit."); doc.Name.ShouldBe("Joe Mixon"); diff --git a/src/Persistence/PolecatTests/Bugs/Bug_305_invoke_async_with_return_not_publishing_with_tuple_return_value.cs b/src/Persistence/PolecatTests/Bugs/Bug_305_invoke_async_with_return_not_publishing_with_tuple_return_value.cs index 1a8aa0ca6..3afeca92f 100644 --- a/src/Persistence/PolecatTests/Bugs/Bug_305_invoke_async_with_return_not_publishing_with_tuple_return_value.cs +++ b/src/Persistence/PolecatTests/Bugs/Bug_305_invoke_async_with_return_not_publishing_with_tuple_return_value.cs @@ -25,10 +25,10 @@ public async Task should_publish_the_return_value() }).IntegrateWithWolverine(); opts.Policies.AutoApplyTransactions(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); await ((DocumentStore)host.Services.GetRequiredService()).Database - .ApplyAllConfiguredChangesToDatabaseAsync(); + .ApplyAllConfiguredChangesToDatabaseAsync(ct: TestContext.Current.CancellationToken); var (tracked, created) = await host.InvokeMessageAndWaitAsync(new PcCreateItemCommand { Name = "Trevor" }); @@ -52,10 +52,10 @@ public async Task honor_the_attribute() }).IntegrateWithWolverine(); opts.Policies.AutoApplyTransactions(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); await ((DocumentStore)host.Services.GetRequiredService()).Database - .ApplyAllConfiguredChangesToDatabaseAsync(); + .ApplyAllConfiguredChangesToDatabaseAsync(ct: TestContext.Current.CancellationToken); Func execute = async c => { diff --git a/src/Persistence/PolecatTests/Bugs/Bug_310_saga_handler_that_returns_another_saga.cs b/src/Persistence/PolecatTests/Bugs/Bug_310_saga_handler_that_returns_another_saga.cs index 5c9db18db..efa692134 100644 --- a/src/Persistence/PolecatTests/Bugs/Bug_310_saga_handler_that_returns_another_saga.cs +++ b/src/Persistence/PolecatTests/Bugs/Bug_310_saga_handler_that_returns_another_saga.cs @@ -52,10 +52,10 @@ public async Task one_saga_spawns_another() await using var session = _host.Services.GetRequiredService().LightweightSession(); - var sagaA = await session.LoadAsync(id); + var sagaA = await session.LoadAsync(id, TestContext.Current.CancellationToken); sagaA!.One.ShouldBeTrue(); - var sagaB = await session.LoadAsync(id); + var sagaB = await session.LoadAsync(id, TestContext.Current.CancellationToken); sagaB!.Two.ShouldBeTrue(); sagaB.Three.ShouldBeTrue(); } diff --git a/src/Persistence/PolecatTests/Bugs/Bug_756_composite_handler_on_saga.cs b/src/Persistence/PolecatTests/Bugs/Bug_756_composite_handler_on_saga.cs index 001ee902c..39d5e3bb4 100644 --- a/src/Persistence/PolecatTests/Bugs/Bug_756_composite_handler_on_saga.cs +++ b/src/Persistence/PolecatTests/Bugs/Bug_756_composite_handler_on_saga.cs @@ -23,10 +23,10 @@ public async Task compile_successfully() m.ConnectionString = Servers.SqlServerConnectionString; m.DatabaseSchemaName = "bugs_756"; }).IntegrateWithWolverine(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); await ((DocumentStore)host.Services.GetRequiredService()).Database - .ApplyAllConfiguredChangesToDatabaseAsync(); + .ApplyAllConfiguredChangesToDatabaseAsync(ct: TestContext.Current.CancellationToken); await host.InvokeMessageAndWaitAsync(new PcDoSomething(Guid.NewGuid())); } diff --git a/src/Persistence/PolecatTests/Bugs/Bug_778_multiple_polecat_ops_in_tuple.cs b/src/Persistence/PolecatTests/Bugs/Bug_778_multiple_polecat_ops_in_tuple.cs index 8417f5d49..0808e74ec 100644 --- a/src/Persistence/PolecatTests/Bugs/Bug_778_multiple_polecat_ops_in_tuple.cs +++ b/src/Persistence/PolecatTests/Bugs/Bug_778_multiple_polecat_ops_in_tuple.cs @@ -26,9 +26,9 @@ public async Task call_both_side_effects() }).IntegrateWithWolverine(); opts.Policies.AutoApplyTransactions(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); - await ((DocumentStore)host.Services.GetRequiredService()).Database.ApplyAllConfiguredChangesToDatabaseAsync(); + await ((DocumentStore)host.Services.GetRequiredService()).Database.ApplyAllConfiguredChangesToDatabaseAsync(ct: TestContext.Current.CancellationToken); var command = new PcSpawnTwo(Guid.NewGuid().ToString(), Guid.NewGuid().ToString()); @@ -36,8 +36,8 @@ public async Task call_both_side_effects() var store = host.Services.GetRequiredService(); await using var session = store.LightweightSession(); - var person1 = await session.LoadAsync(command.Name1); - var person2 = await session.LoadAsync(command.Name2); + var person1 = await session.LoadAsync(command.Name1, TestContext.Current.CancellationToken); + var person2 = await session.LoadAsync(command.Name2, TestContext.Current.CancellationToken); person1.ShouldNotBeNull(); person2.ShouldNotBeNull(); diff --git a/src/Persistence/PolecatTests/Dcb/boundary_model_workflow_tests.cs b/src/Persistence/PolecatTests/Dcb/boundary_model_workflow_tests.cs index 7a7c833e1..4a35e7859 100644 --- a/src/Persistence/PolecatTests/Dcb/boundary_model_workflow_tests.cs +++ b/src/Persistence/PolecatTests/Dcb/boundary_model_workflow_tests.cs @@ -104,7 +104,7 @@ public async Task can_fetch_for_writing_by_tags_across_multiple_tag_types() .Or(courseId) .Or(studentId); - var boundary = await session.Events.FetchForWritingByTags(query); + var boundary = await session.Events.FetchForWritingByTags(query, TestContext.Current.CancellationToken); boundary.Events.Count.ShouldBe(2); boundary.Aggregate.ShouldNotBeNull(); boundary.Aggregate.CourseId.ShouldBe(courseId); @@ -125,8 +125,7 @@ await theHost.InvokeMessageAndWaitAsync( // Verify the subscription event was appended and discoverable by tag await using var session = theStore.LightweightSession(); - var events = await session.Events.QueryByTagsAsync( - new EventTagQuery().Or(studentId)); + var events = await session.Events.QueryByTagsAsync(new EventTagQuery().Or(studentId), TestContext.Current.CancellationToken); events.ShouldContain(e => e.Data is StudentSubscribedToCourse); } @@ -143,7 +142,7 @@ public async Task boundary_model_handler_throws_when_student_not_enrolled() new CourseCreated(FacultyId.Default, courseId, "Math 101", 10)); courseCreated.WithTag(courseId); session.Events.Append(courseId.Value, courseCreated); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); // The handler should throw because student is not enrolled await Should.ThrowAsync(async () => @@ -165,7 +164,7 @@ public async Task boundary_model_handler_throws_when_course_does_not_exist() new StudentEnrolledInFaculty(FacultyId.Default, studentId, "Alice", "Smith")); enrolled.WithTag(studentId); session.Events.Append(studentId.Value, enrolled); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await Should.ThrowAsync(async () => { @@ -195,7 +194,7 @@ public async Task boundary_model_handler_throws_when_course_is_fully_booked() new StudentSubscribedToCourse(FacultyId.Default, otherStudentId, courseId)); subscribed.WithTag(otherStudentId, courseId); session.Events.Append(otherStudentId.Value, subscribed); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); // Now try to subscribe our student — should fail because course is full await Should.ThrowAsync(async () => diff --git a/src/Persistence/PolecatTests/Distribution/polecat_managed_event_subscription_distribution.cs b/src/Persistence/PolecatTests/Distribution/polecat_managed_event_subscription_distribution.cs index 16d7da6e5..5b367a5ca 100644 --- a/src/Persistence/PolecatTests/Distribution/polecat_managed_event_subscription_distribution.cs +++ b/src/Persistence/PolecatTests/Distribution/polecat_managed_event_subscription_distribution.cs @@ -75,7 +75,7 @@ public async Task find_agent_uri_resolves_a_registered_shard() { var family = _host.Services.GetServices().First(); - var uri = await family.FindAgentUriAsync("Trip:All", null); + var uri = await family.FindAgentUriAsync("Trip:All", null, TestContext.Current.CancellationToken); uri.ShouldNotBeNull(); uri!.AbsolutePath.TrimEnd('/').ShouldEndWith("/trip/all"); diff --git a/src/Persistence/PolecatTests/Distribution/subscription_descriptor_agent_uris.cs b/src/Persistence/PolecatTests/Distribution/subscription_descriptor_agent_uris.cs index 18dfa9efa..307077317 100644 --- a/src/Persistence/PolecatTests/Distribution/subscription_descriptor_agent_uris.cs +++ b/src/Persistence/PolecatTests/Distribution/subscription_descriptor_agent_uris.cs @@ -52,7 +52,7 @@ public async Task agent_uris_match_event_subscription_family_uris() opts.Projections.Add(ProjectionLifecycle.Async); opts.Projections.Add(ProjectionLifecycle.Async); }); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var store = host.Services.GetRequiredService(); var eventStore = (IEventStore)store; @@ -114,7 +114,7 @@ public async Task agent_uris_are_empty_for_inline_projections() opts.Projections.Add(ProjectionLifecycle.Inline); }); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var store = host.Services.GetRequiredService(); var eventStore = (IEventStore)store; diff --git a/src/Persistence/PolecatTests/PolecatTests.csproj b/src/Persistence/PolecatTests/PolecatTests.csproj index e2fde0b59..5c3bff538 100644 --- a/src/Persistence/PolecatTests/PolecatTests.csproj +++ b/src/Persistence/PolecatTests/PolecatTests.csproj @@ -1,6 +1,8 @@ + + true Exe false true diff --git a/src/Persistence/PolecatTests/Publishing/polecat_to_wolverine_outbox_registration.cs b/src/Persistence/PolecatTests/Publishing/polecat_to_wolverine_outbox_registration.cs index d0bc7e7c2..bff484a3b 100644 --- a/src/Persistence/PolecatTests/Publishing/polecat_to_wolverine_outbox_registration.cs +++ b/src/Persistence/PolecatTests/Publishing/polecat_to_wolverine_outbox_registration.cs @@ -41,7 +41,7 @@ public async Task integrate_with_wolverine_replaces_the_default_nullo_outbox() }).IntegrateWithWolverine(); opts.Services.AddResourceSetupOnStartup(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var store = (DocumentStore)host.Services.GetRequiredService(); @@ -71,7 +71,7 @@ public async Task polecat_without_integrate_with_wolverine_keeps_polecats_defaul }) .Build(); - await host.StartAsync(); + await host.StartAsync(TestContext.Current.CancellationToken); try { @@ -80,7 +80,7 @@ public async Task polecat_without_integrate_with_wolverine_keeps_polecats_defaul } finally { - await host.StopAsync(); + await host.StopAsync(TestContext.Current.CancellationToken); } } } diff --git a/src/Persistence/PolecatTests/Requirements/using_data_requirements.cs b/src/Persistence/PolecatTests/Requirements/using_data_requirements.cs index a08607041..93f4d8037 100644 --- a/src/Persistence/PolecatTests/Requirements/using_data_requirements.cs +++ b/src/Persistence/PolecatTests/Requirements/using_data_requirements.cs @@ -54,13 +54,13 @@ public async Task single_requirement_must_exist_happy_path() await using (var session = _store.LightweightSession()) { session.Store(new PcThingCategory { Id = "widgets" }); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); } await _host.InvokeMessageAndWaitAsync(new CreatePcThing("widget-1", "widgets")); await using var verify = _store.LightweightSession(); - var thing = await verify.LoadAsync("widget-1"); + var thing = await verify.LoadAsync("widget-1", TestContext.Current.CancellationToken); thing.ShouldNotBeNull(); thing!.CategoryId.ShouldBe("widgets"); } @@ -84,13 +84,13 @@ public async Task enumerable_requirements_happy_path() await using (var session = _store.LightweightSession()) { session.Store(new PcThingCategory { Id = "gadgets" }); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); } await _host.InvokeMessageAndWaitAsync(new CreatePcThing2("gadget-1", "gadgets")); await using var verify = _store.LightweightSession(); - var thing = await verify.LoadAsync("gadget-1"); + var thing = await verify.LoadAsync("gadget-1", TestContext.Current.CancellationToken); thing.ShouldNotBeNull(); thing!.CategoryId.ShouldBe("gadgets"); } @@ -111,7 +111,7 @@ public async Task enumerable_requirements_sad_path_thing_already_exists() { session.Store(new PcThingCategory { Id = "dupes" }); session.Store(new PcThing { Id = "existing-thing", CategoryId = "dupes" }); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); } await Should.ThrowAsync(async () => @@ -130,13 +130,13 @@ public async Task document_exists_attribute_happy_path() await using (var session = _store.LightweightSession()) { session.Store(new PcThingCategory { Id = "attr-cat" }); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); } await _host.InvokeMessageAndWaitAsync(new CreatePcThingByAttribute("attr-thing", "attr-cat")); await using var verify = _store.LightweightSession(); - var thing = await verify.LoadAsync("attr-thing"); + var thing = await verify.LoadAsync("attr-thing", TestContext.Current.CancellationToken); thing.ShouldNotBeNull(); thing!.CategoryId.ShouldBe("attr-cat"); } @@ -160,13 +160,13 @@ public async Task document_exists_attribute_explicit_happy_path() await using (var session = _store.LightweightSession()) { session.Store(new PcThingCategory { Id = "explicit-cat" }); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); } await _host.InvokeMessageAndWaitAsync(new CreatePcThingByAttributeExplicit("explicit-thing", "explicit-cat")); await using var verify = _store.LightweightSession(); - var thing = await verify.LoadAsync("explicit-thing"); + var thing = await verify.LoadAsync("explicit-thing", TestContext.Current.CancellationToken); thing.ShouldNotBeNull(); thing!.CategoryId.ShouldBe("explicit-cat"); } @@ -196,7 +196,7 @@ public async Task document_does_not_exist_attribute_sad_path() await using (var session = _store.LightweightSession()) { session.Store(new PcThing { Id = "already-here", CategoryId = "whatever" }); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); } await Should.ThrowAsync(async () => @@ -216,13 +216,13 @@ public async Task stacked_attributes_happy_path() await using (var session = _store.LightweightSession()) { session.Store(new PcThingCategory { Id = "stacked-cat" }); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); } await _host.InvokeMessageAndWaitAsync(new CreatePcThingStacked("stacked-thing", "stacked-cat")); await using var verify = _store.LightweightSession(); - var thing = await verify.LoadAsync("stacked-thing"); + var thing = await verify.LoadAsync("stacked-thing", TestContext.Current.CancellationToken); thing.ShouldNotBeNull(); } @@ -242,7 +242,7 @@ public async Task stacked_attributes_sad_path_thing_already_exists() { session.Store(new PcThingCategory { Id = "stacked-dupes" }); session.Store(new PcThing { Id = "stacked-existing", CategoryId = "stacked-dupes" }); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); } await Should.ThrowAsync(async () => diff --git a/src/Persistence/PolecatTests/Sagas/RevisionedSaga.cs b/src/Persistence/PolecatTests/Sagas/RevisionedSaga.cs index 2ad60c098..acbe0ed07 100644 --- a/src/Persistence/PolecatTests/Sagas/RevisionedSaga.cs +++ b/src/Persistence/PolecatTests/Sagas/RevisionedSaga.cs @@ -48,10 +48,10 @@ public async Task execute_using_update_revision() var execution = Task.Run(async () => { await theHost.MessageBus().InvokeAsync(slow); - }); + }, TestContext.Current.CancellationToken); await PcRevisionedSaga.InSlowMessage.Task; - await theHost.MessageBus().InvokeAsync(new PcCommand1(id)); + await theHost.MessageBus().InvokeAsync(new PcCommand1(id), TestContext.Current.CancellationToken); slow.Source.SetResult(); diff --git a/src/Persistence/PolecatTests/Sagas/When_handling_messages_in_saga.cs b/src/Persistence/PolecatTests/Sagas/When_handling_messages_in_saga.cs index ccc14bd14..1842dcd3a 100644 --- a/src/Persistence/PolecatTests/Sagas/When_handling_messages_in_saga.cs +++ b/src/Persistence/PolecatTests/Sagas/When_handling_messages_in_saga.cs @@ -26,10 +26,10 @@ await Host.CreateDefaultBuilder() opts.Policies.AutoApplyTransactions(); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); await ((DocumentStore)host.Services.GetRequiredService()).Database - .ApplyAllConfiguredChangesToDatabaseAsync(); + .ApplyAllConfiguredChangesToDatabaseAsync(ct: TestContext.Current.CancellationToken); var subscriptionId = Guid.NewGuid(); @@ -59,10 +59,10 @@ await Host.CreateDefaultBuilder() opts.Policies.AutoApplyTransactions(); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); await ((DocumentStore)host.Services.GetRequiredService()).Database - .ApplyAllConfiguredChangesToDatabaseAsync(); + .ApplyAllConfiguredChangesToDatabaseAsync(ct: TestContext.Current.CancellationToken); var subscriptionId = Guid.NewGuid(); @@ -81,7 +81,7 @@ await Host.CreateDefaultBuilder() { // No Polecat integration - in-memory only }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var subscriptionId = Guid.NewGuid(); @@ -105,7 +105,7 @@ await Host.CreateDefaultBuilder() { // No Polecat integration - in-memory only }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var subscriptionId = Guid.NewGuid(); diff --git a/src/Persistence/PolecatTests/Sagas/multiple_sagas_for_same_message.cs b/src/Persistence/PolecatTests/Sagas/multiple_sagas_for_same_message.cs index bd42332a4..2b29f3047 100644 --- a/src/Persistence/PolecatTests/Sagas/multiple_sagas_for_same_message.cs +++ b/src/Persistence/PolecatTests/Sagas/multiple_sagas_for_same_message.cs @@ -52,11 +52,11 @@ public async Task two_sagas_start_from_same_message() await using var session = _host.Services.GetRequiredService().QuerySession(); - var shipping = await session.LoadAsync(id); + var shipping = await session.LoadAsync(id, TestContext.Current.CancellationToken); shipping.ShouldNotBeNull(); shipping.ProductName.ShouldBe("Widget"); - var billing = await session.LoadAsync(id); + var billing = await session.LoadAsync(id, TestContext.Current.CancellationToken); billing.ShouldNotBeNull(); billing.ProductName.ShouldBe("Widget"); } @@ -69,18 +69,18 @@ public async Task two_sagas_handle_subsequent_messages_independently() await using var session = _host.Services.GetRequiredService().QuerySession(); await _host.SendMessageAndWaitAsync(new PcOrderPlaced(id, "Gadget")); - (await session.LoadAsync(id)).ShouldNotBeNull(); - (await session.LoadAsync(id)).ShouldNotBeNull(); + (await session.LoadAsync(id, TestContext.Current.CancellationToken)).ShouldNotBeNull(); + (await session.LoadAsync(id, TestContext.Current.CancellationToken)).ShouldNotBeNull(); // Complete only the shipping saga await _host.SendMessageAndWaitAsync(new PcOrderShipped(id)); // Shipping saga should be deleted (completed) - var shipping = await session.LoadAsync(id); + var shipping = await session.LoadAsync(id, TestContext.Current.CancellationToken); shipping.ShouldBeNull(); // Billing saga should still exist - var billing = await session.LoadAsync(id); + var billing = await session.LoadAsync(id, TestContext.Current.CancellationToken); billing.ShouldNotBeNull(); billing.ProductName.ShouldBe("Gadget"); @@ -88,7 +88,7 @@ public async Task two_sagas_handle_subsequent_messages_independently() await _host.SendMessageAndWaitAsync(new PcPaymentReceived(id)); await using var session2 = _host.Services.GetRequiredService().QuerySession(); - (await session2.LoadAsync(id)).ShouldBeNull(); + (await session2.LoadAsync(id, TestContext.Current.CancellationToken)).ShouldBeNull(); } } diff --git a/src/Persistence/PolecatTests/Sagas/not_found_usage.cs b/src/Persistence/PolecatTests/Sagas/not_found_usage.cs index dc463bfff..077b2d601 100644 --- a/src/Persistence/PolecatTests/Sagas/not_found_usage.cs +++ b/src/Persistence/PolecatTests/Sagas/not_found_usage.cs @@ -51,7 +51,7 @@ public async Task try_to_call_handle_on_already_expired_invitation() await using var query = _host.Services.GetRequiredService().LightweightSession(); // Should be deleted at this point - (await query.LoadAsync(id)).ShouldBeNull(); + (await query.LoadAsync(id, TestContext.Current.CancellationToken)).ShouldBeNull(); // NotFound should fire here, and no exceptions await _host.InvokeMessageAndWaitAsync(new InvitationTimeout(id)); diff --git a/src/Persistence/PolecatTests/Sagas/starting_saga_by_returning_it_from_handler.cs b/src/Persistence/PolecatTests/Sagas/starting_saga_by_returning_it_from_handler.cs index f9bf895bf..7e5323118 100644 --- a/src/Persistence/PolecatTests/Sagas/starting_saga_by_returning_it_from_handler.cs +++ b/src/Persistence/PolecatTests/Sagas/starting_saga_by_returning_it_from_handler.cs @@ -26,29 +26,29 @@ public async Task create_sagas_from_a_starting_message() opts.Discovery.IncludeType(typeof(StartSagasThing)); opts.Policies.AutoApplyTransactions(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var store = host.Services.GetRequiredService(); - await ((DocumentStore)store).Database.ApplyAllConfiguredChangesToDatabaseAsync(); + await ((DocumentStore)store).Database.ApplyAllConfiguredChangesToDatabaseAsync(ct: TestContext.Current.CancellationToken); var sagaId = Guid.NewGuid(); await host.InvokeMessageAndWaitAsync(new StartSagas(sagaId)); await using var session = store.LightweightSession(); - var one = await session.LoadAsync(sagaId); + var one = await session.LoadAsync(sagaId, TestContext.Current.CancellationToken); one.ShouldNotBeNull(); // The cascading messages should have set this one.GotOne.ShouldBeTrue(); - var two = await session.LoadAsync(sagaId); + var two = await session.LoadAsync(sagaId, TestContext.Current.CancellationToken); two.ShouldNotBeNull(); // The cascading messages should have set this two.GotOne.ShouldBeTrue(); - await host.StopAsync(); + await host.StopAsync(TestContext.Current.CancellationToken); } } diff --git a/src/Persistence/PolecatTests/Sagas/strong_typed_id_saga.cs b/src/Persistence/PolecatTests/Sagas/strong_typed_id_saga.cs index 5ceff5824..c5fda009a 100644 --- a/src/Persistence/PolecatTests/Sagas/strong_typed_id_saga.cs +++ b/src/Persistence/PolecatTests/Sagas/strong_typed_id_saga.cs @@ -112,7 +112,7 @@ public async Task start_saga_with_strong_typed_id() await _host.InvokeMessageAndWaitAsync(new StartPcOrderSaga(orderId, "Han Solo")); await using var session = _host.Services.GetRequiredService().QuerySession(); - var saga = await session.LoadAsync(orderId.Value); + var saga = await session.LoadAsync(orderId.Value, TestContext.Current.CancellationToken); saga.ShouldNotBeNull(); saga.Id.ShouldBe(orderId); @@ -128,7 +128,7 @@ public async Task handle_message_with_strong_typed_id_on_existing_saga() await _host.InvokeMessageAndWaitAsync(new PickPcOrderItems(orderId)); await using var session = _host.Services.GetRequiredService().QuerySession(); - var saga = await session.LoadAsync(orderId.Value); + var saga = await session.LoadAsync(orderId.Value, TestContext.Current.CancellationToken); saga.ShouldNotBeNull(); saga.ItemsPicked.ShouldBeTrue(); @@ -145,7 +145,7 @@ public async Task complete_saga_with_strong_typed_id() await _host.InvokeMessageAndWaitAsync(new ShipPcOrder(orderId)); await using var session = _host.Services.GetRequiredService().QuerySession(); - var saga = await session.LoadAsync(orderId.Value); + var saga = await session.LoadAsync(orderId.Value, TestContext.Current.CancellationToken); // Saga should be deleted when completed saga.ShouldBeNull(); @@ -160,7 +160,7 @@ public async Task cancel_saga_with_strong_typed_id() await _host.InvokeMessageAndWaitAsync(new CancelPcOrderSaga(orderId)); await using var session = _host.Services.GetRequiredService().QuerySession(); - var saga = await session.LoadAsync(orderId.Value); + var saga = await session.LoadAsync(orderId.Value, TestContext.Current.CancellationToken); // Saga should be deleted after cancel (MarkCompleted) saga.ShouldBeNull(); @@ -176,7 +176,7 @@ public async Task multiple_steps_with_strong_typed_id() await _host.InvokeMessageAndWaitAsync(new ProcessPcOrderPayment(orderId)); await using var session = _host.Services.GetRequiredService().QuerySession(); - var saga = await session.LoadAsync(orderId.Value); + var saga = await session.LoadAsync(orderId.Value, TestContext.Current.CancellationToken); saga.ShouldNotBeNull(); saga.ItemsPicked.ShouldBeTrue(); diff --git a/src/Persistence/PolecatTests/Subscriptions/subscriptions_end_to_end.cs b/src/Persistence/PolecatTests/Subscriptions/subscriptions_end_to_end.cs index 7a1525a21..62c15eb8a 100644 --- a/src/Persistence/PolecatTests/Subscriptions/subscriptions_end_to_end.cs +++ b/src/Persistence/PolecatTests/Subscriptions/subscriptions_end_to_end.cs @@ -69,11 +69,11 @@ public async Task use_unfiltered_batch_subscription() .SubscribeToEvents(new PcTestBatchSubscription()); opts.Services.AddResourceSetupOnStartup(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var store = (DocumentStore)host.Services.GetRequiredService(); - await store.Advanced.CleanAllEventDataAsync(); - await store.Advanced.CleanAllDocumentsAsync(); + await store.Advanced.CleanAllEventDataAsync(TestContext.Current.CancellationToken); + await store.Advanced.CleanAllDocumentsAsync(TestContext.Current.CancellationToken); var daemon = await store.BuildProjectionDaemonAsync(); await daemon.StartAllAsync(); @@ -86,15 +86,15 @@ public async Task use_unfiltered_batch_subscription() session.Events.StartStream(Guid.NewGuid(), new PcDEvent(), new PcDEvent(), new PcAEvent(), new PcDEvent()); session.Events.StartStream(Guid.NewGuid(), new PcDEvent(), new PcBEvent(), new PcBEvent(), new PcBEvent()); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await daemon.WaitForNonStaleData(60.Seconds()); await using var query = store.QuerySession(); - (await query.LoadAsync("A"))!.Count.ShouldBe(6); - (await query.LoadAsync("B"))!.Count.ShouldBe(7); - (await query.LoadAsync("C"))!.Count.ShouldBe(5); - (await query.LoadAsync("D"))!.Count.ShouldBe(6); + (await query.LoadAsync("A", TestContext.Current.CancellationToken))!.Count.ShouldBe(6); + (await query.LoadAsync("B", TestContext.Current.CancellationToken))!.Count.ShouldBe(7); + (await query.LoadAsync("C", TestContext.Current.CancellationToken))!.Count.ShouldBe(5); + (await query.LoadAsync("D", TestContext.Current.CancellationToken))!.Count.ShouldBe(6); } [Fact] @@ -120,11 +120,11 @@ public async Task use_filtered_batch_subscription() .SubscribeToEvents(subscription); opts.Services.AddResourceSetupOnStartup(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var store = (DocumentStore)host.Services.GetRequiredService(); - await store.Advanced.CleanAllEventDataAsync(); - await store.Advanced.CleanAllDocumentsAsync(); + await store.Advanced.CleanAllEventDataAsync(TestContext.Current.CancellationToken); + await store.Advanced.CleanAllDocumentsAsync(TestContext.Current.CancellationToken); var daemon = await store.BuildProjectionDaemonAsync(); await daemon.StartAllAsync(); @@ -137,15 +137,15 @@ public async Task use_filtered_batch_subscription() session.Events.StartStream(Guid.NewGuid(), new PcDEvent(), new PcDEvent(), new PcAEvent(), new PcDEvent()); session.Events.StartStream(Guid.NewGuid(), new PcDEvent(), new PcBEvent(), new PcBEvent(), new PcBEvent()); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await daemon.WaitForNonStaleData(60.Seconds()); await using var query = store.QuerySession(); - (await query.LoadAsync("A"))!.Count.ShouldBe(6); - (await query.LoadAsync("B"))!.Count.ShouldBe(7); - (await query.LoadAsync("C")).ShouldBeNull(); - (await query.LoadAsync("D")).ShouldBeNull(); + (await query.LoadAsync("A", TestContext.Current.CancellationToken))!.Count.ShouldBe(6); + (await query.LoadAsync("B", TestContext.Current.CancellationToken))!.Count.ShouldBe(7); + (await query.LoadAsync("C", TestContext.Current.CancellationToken)).ShouldBeNull(); + (await query.LoadAsync("D", TestContext.Current.CancellationToken)).ShouldBeNull(); } [Fact] @@ -170,7 +170,7 @@ public async Task use_inline_subscription() .ProcessEventsWithWolverineHandlersInStrictOrder("Inline"); opts.Services.AddResourceSetupOnStartup(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var store = (DocumentStore)host.Services.GetRequiredService(); var daemon = host.Services.GetRequiredService().Daemon!; @@ -180,7 +180,7 @@ public async Task use_inline_subscription() session.Events.StartStream(Guid.NewGuid(), new PcAEvent(), new PcAEvent(), new PcAEvent(), new PcAEvent()); session.Events.StartStream(Guid.NewGuid(), new PcBEvent(), new PcCEvent(), new PcCEvent(), new PcBEvent()); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await daemon.WaitForNonStaleData(60.Seconds()); @@ -216,7 +216,7 @@ public async Task use_inline_subscription_filtered() }); opts.Services.AddResourceSetupOnStartup(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var store = (DocumentStore)host.Services.GetRequiredService(); var daemon = host.Services.GetRequiredService().Daemon!; @@ -226,7 +226,7 @@ public async Task use_inline_subscription_filtered() session.Events.StartStream(Guid.NewGuid(), new PcAEvent(), new PcAEvent(), new PcAEvent(), new PcAEvent()); session.Events.StartStream(Guid.NewGuid(), new PcBEvent(), new PcCEvent(), new PcCEvent(), new PcBEvent()); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await daemon.WaitForNonStaleData(60.Seconds()); @@ -252,11 +252,11 @@ public async Task use_unfiltered_publishing_subscription() .PublishEventsToWolverine("Publish"); opts.Services.AddResourceSetupOnStartup(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var store = (DocumentStore)host.Services.GetRequiredService(); - await store.Advanced.CleanAllEventDataAsync(); - await store.Advanced.CleanAllDocumentsAsync(); + await store.Advanced.CleanAllEventDataAsync(TestContext.Current.CancellationToken); + await store.Advanced.CleanAllDocumentsAsync(TestContext.Current.CancellationToken); var daemon = await store.BuildProjectionDaemonAsync(); await daemon.StartAllAsync(); @@ -308,11 +308,11 @@ public async Task use_filtered_publishing_subscription() }); opts.Services.AddResourceSetupOnStartup(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var store = (DocumentStore)host.Services.GetRequiredService(); - await store.Advanced.CleanAllEventDataAsync(); - await store.Advanced.CleanAllDocumentsAsync(); + await store.Advanced.CleanAllEventDataAsync(TestContext.Current.CancellationToken); + await store.Advanced.CleanAllDocumentsAsync(TestContext.Current.CancellationToken); var daemon = await store.BuildProjectionDaemonAsync(); await daemon.StartAllAsync(); @@ -369,7 +369,7 @@ public async Task use_transformed_publishing_subscription() }); opts.Services.AddResourceSetupOnStartup(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var store = (DocumentStore)host.Services.GetRequiredService(); @@ -428,7 +428,7 @@ public async Task using_singleton_scoped_subscription_from_service() .SubscribeToEventsWithServices(ServiceLifetime.Singleton); opts.Services.AddResourceSetupOnStartup(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var store = (DocumentStore)host.Services.GetRequiredService(); var daemon = host.Services.GetRequiredService().Daemon!; @@ -438,13 +438,13 @@ public async Task using_singleton_scoped_subscription_from_service() session.Events.StartStream(Guid.NewGuid(), new PcAEvent(), new PcAEvent(), new PcAEvent(), new PcAEvent()); session.Events.StartStream(Guid.NewGuid(), new PcBEvent(), new PcCEvent(), new PcCEvent(), new PcBEvent()); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await daemon.WaitForNonStaleData(60.Seconds()); // Second round session.Events.StartStream(Guid.NewGuid(), new PcDEvent(), new PcDEvent(), new PcDEvent(), new PcDEvent()); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); PcServiceUsingSubscription.Read.Count().ShouldBe(1); PcServiceUsingSubscription.Read[1].OfType().Count().ShouldBe(5); @@ -477,7 +477,7 @@ public async Task using_scoped_subscription_from_service() .SubscribeToEventsWithServices(ServiceLifetime.Scoped); opts.Services.AddResourceSetupOnStartup(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var store = (DocumentStore)host.Services.GetRequiredService(); var daemon = host.Services.GetRequiredService().Daemon!; @@ -491,7 +491,7 @@ public async Task using_scoped_subscription_from_service() session.Events.StartStream(Guid.NewGuid(), new PcAEvent(), new PcAEvent(), new PcAEvent(), new PcAEvent()); session.Events.StartStream(Guid.NewGuid(), new PcBEvent(), new PcCEvent(), new PcCEvent(), new PcBEvent()); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); } await daemon.WaitForNonStaleData(60.Seconds()); diff --git a/src/Persistence/PolecatTests/handler_actions_with_implied_polecat_operations.cs b/src/Persistence/PolecatTests/handler_actions_with_implied_polecat_operations.cs index 0188b7abe..3c39e0c33 100644 --- a/src/Persistence/PolecatTests/handler_actions_with_implied_polecat_operations.cs +++ b/src/Persistence/PolecatTests/handler_actions_with_implied_polecat_operations.cs @@ -53,7 +53,7 @@ public async Task storing_document() tracked.Sent.SingleMessage().Name.ShouldBe("Aubrey"); await using var session = _store.LightweightSession(); - var doc = await session.LoadAsync("Aubrey"); + var doc = await session.LoadAsync("Aubrey", TestContext.Current.CancellationToken); doc.ShouldNotBeNull(); } @@ -63,7 +63,7 @@ public async Task insert_document() await _host.InvokeMessageAndWaitAsync(new InsertPcDocument("Declan")); await using var session = _store.LightweightSession(); - var doc = await session.LoadAsync("Declan"); + var doc = await session.LoadAsync("Declan", TestContext.Current.CancellationToken); doc.ShouldNotBeNull(); } @@ -74,7 +74,7 @@ public async Task update_document_happy_path() await _host.InvokeMessageAndWaitAsync(new UpdatePcDocument("Max", 10)); await using var session = _store.LightweightSession(); - var doc = await session.LoadAsync("Max"); + var doc = await session.LoadAsync("Max", TestContext.Current.CancellationToken); doc!.Number.ShouldBe(10); } @@ -85,7 +85,7 @@ public async Task delete_document() await _host.InvokeMessageAndWaitAsync(new DeletePcDocument("Max")); await using var session = _store.LightweightSession(); - var doc = await session.LoadAsync("Max"); + var doc = await session.LoadAsync("Max", TestContext.Current.CancellationToken); doc.ShouldBeNull(); } @@ -97,11 +97,11 @@ public async Task delete_document_by_int_id() var id = 2345; session.Store(new PcIntIdDocument { Id = id }); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await _host.InvokeMessageAndWaitAsync(new DeletePcDocumentByIntId(id)); - var doc = await session.LoadAsync(id); + var doc = await session.LoadAsync(id, TestContext.Current.CancellationToken); doc.ShouldBeNull(); } @@ -113,11 +113,11 @@ public async Task delete_document_by_long_id() var id = 23456L; session.Store(new PcLongIdDocument { Id = id }); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await _host.InvokeMessageAndWaitAsync(new DeletePcDocumentByLongId(id)); - var doc = await session.LoadAsync(id); + var doc = await session.LoadAsync(id, TestContext.Current.CancellationToken); doc.ShouldBeNull(); } @@ -129,11 +129,11 @@ public async Task delete_document_by_guid_id() var id = Guid.NewGuid(); session.Store(new PcGuidIdDocument { Id = id }); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await _host.InvokeMessageAndWaitAsync(new DeletePcDocumentByGuidId(id)); - var doc = await session.LoadAsync(id); + var doc = await session.LoadAsync(id, TestContext.Current.CancellationToken); doc.ShouldBeNull(); } @@ -145,11 +145,11 @@ public async Task delete_document_by_string_id() var id = "Max"; session.Store(new PcStringIdDocument { Id = id }); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await _host.InvokeMessageAndWaitAsync(new DeletePcDocumentByStringId(id)); - var doc = await session.LoadAsync(id); + var doc = await session.LoadAsync(id, TestContext.Current.CancellationToken); doc.ShouldBeNull(); } @@ -159,7 +159,7 @@ public async Task delete_document_where() // Clean up first await using var cleanSession = _store.LightweightSession(); cleanSession.DeleteWhere(x => true); - await cleanSession.SaveChangesAsync(); + await cleanSession.SaveChangesAsync(TestContext.Current.CancellationToken); await _host.InvokeMessageAndWaitAsync(new InsertPcDocument("foo")); await _host.InvokeMessageAndWaitAsync(new InsertPcDocument("bar")); @@ -168,9 +168,9 @@ public async Task delete_document_where() await using var session = _store.LightweightSession(); // Load each document individually to verify - var foo = await session.LoadAsync("foo"); - var bar = await session.LoadAsync("bar"); - var baz = await session.LoadAsync("baz"); + var foo = await session.LoadAsync("foo", TestContext.Current.CancellationToken); + var bar = await session.LoadAsync("bar", TestContext.Current.CancellationToken); + var baz = await session.LoadAsync("baz", TestContext.Current.CancellationToken); foo.ShouldNotBeNull(); bar.ShouldBeNull(); @@ -183,15 +183,15 @@ public async Task use_enumerable_of_polecatop_as_return_value() // Clean up first await using var cleanSession = _store.LightweightSession(); cleanSession.DeleteWhere(x => true); - await cleanSession.SaveChangesAsync(); + await cleanSession.SaveChangesAsync(TestContext.Current.CancellationToken); await _host.InvokeMessageAndWaitAsync(new AppendManyPcNamedDocuments(["red", "blue", "green"])); await using var session = _store.LightweightSession(); - (await session.LoadAsync("red"))!.Number.ShouldBe(1); - (await session.LoadAsync("blue"))!.Number.ShouldBe(2); - (await session.LoadAsync("green"))!.Number.ShouldBe(3); + (await session.LoadAsync("red", TestContext.Current.CancellationToken))!.Number.ShouldBe(1); + (await session.LoadAsync("blue", TestContext.Current.CancellationToken))!.Number.ShouldBe(2); + (await session.LoadAsync("green", TestContext.Current.CancellationToken))!.Number.ShouldBe(3); } } diff --git a/src/Persistence/PolecatTests/handler_actions_with_returned_StartStream.cs b/src/Persistence/PolecatTests/handler_actions_with_returned_StartStream.cs index 2f6ff1e0c..0341a1fec 100644 --- a/src/Persistence/PolecatTests/handler_actions_with_returned_StartStream.cs +++ b/src/Persistence/PolecatTests/handler_actions_with_returned_StartStream.cs @@ -53,7 +53,7 @@ public async Task start_stream_by_guid1() await _host.InvokeMessageAndWaitAsync(new PcStartStreamMessage(id)); await using var session = _store.LightweightSession(); - var events = await session.Events.FetchStreamAsync(id); + var events = await session.Events.FetchStreamAsync(id, token: TestContext.Current.CancellationToken); events.Count.ShouldBe(2); events[0].Data.ShouldBeOfType(); events[1].Data.ShouldBeOfType(); diff --git a/src/Persistence/PolecatTests/missing_data_handling_with_entity_attributes.cs b/src/Persistence/PolecatTests/missing_data_handling_with_entity_attributes.cs index a3b068e1c..0e362c1ba 100644 --- a/src/Persistence/PolecatTests/missing_data_handling_with_entity_attributes.cs +++ b/src/Persistence/PolecatTests/missing_data_handling_with_entity_attributes.cs @@ -61,7 +61,7 @@ public async Task end_to_end_with_good_data() var thing = new PcThing(); await using var insertSession = _host.Services.GetRequiredService().LightweightSession(); insertSession.Store(thing); - await insertSession.SaveChangesAsync(); + await insertSession.SaveChangesAsync(TestContext.Current.CancellationToken); var tracked = await _host.InvokeMessageAndWaitAsync(new UsePcThing1(thing.Id)); @@ -118,7 +118,7 @@ public async Task end_to_end_with_guid_identity_entity() var guidThing = new PcGuidThing(); await using var insertSession = _host.Services.GetRequiredService().LightweightSession(); insertSession.Store(guidThing); - await insertSession.SaveChangesAsync(); + await insertSession.SaveChangesAsync(TestContext.Current.CancellationToken); var tracked = await _host.InvokeMessageAndWaitAsync(new UsePcGuidThing1(guidThing.Id)); diff --git a/src/Persistence/PolecatTests/natural_key_aggregate_handler_workflow.cs b/src/Persistence/PolecatTests/natural_key_aggregate_handler_workflow.cs index fc1dab7c1..33969f9c0 100644 --- a/src/Persistence/PolecatTests/natural_key_aggregate_handler_workflow.cs +++ b/src/Persistence/PolecatTests/natural_key_aggregate_handler_workflow.cs @@ -63,13 +63,13 @@ public async Task handle_command_with_natural_key_returning_single_event() await using var session = _store.LightweightSession(); session.Events.StartStream(streamId, new PcNkOrderCreated(orderNumber, "Alice")); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await _host.TrackActivity() .SendMessageAndWaitAsync(new AddPcNkOrderItem(orderNumber, "Widget", 9.99m)); await using var verify = _store.LightweightSession(); - var aggregate = await verify.LoadAsync(streamId); + var aggregate = await verify.LoadAsync(streamId, TestContext.Current.CancellationToken); aggregate.ShouldNotBeNull(); aggregate!.TotalAmount.ShouldBe(9.99m); @@ -85,14 +85,14 @@ public async Task handle_command_with_natural_key_returning_multiple_events() await using var session = _store.LightweightSession(); session.Events.StartStream(streamId, new PcNkOrderCreated(orderNumber, "Bob")); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await _host.TrackActivity() .SendMessageAndWaitAsync(new AddPcNkOrderItems(orderNumber, [("Gadget", 19.99m), ("Doohickey", 5.50m)])); await using var verify = _store.LightweightSession(); - var aggregate = await verify.LoadAsync(streamId); + var aggregate = await verify.LoadAsync(streamId, TestContext.Current.CancellationToken); aggregate.ShouldNotBeNull(); aggregate!.TotalAmount.ShouldBe(25.49m); @@ -108,13 +108,13 @@ public async Task handle_command_with_natural_key_using_event_stream() session.Events.StartStream(streamId, new PcNkOrderCreated(orderNumber, "Charlie"), new PcNkItemAdded("Widget", 10.00m)); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await _host.TrackActivity() .SendMessageAndWaitAsync(new CompletePcNkOrder(orderNumber)); await using var verify = _store.LightweightSession(); - var aggregate = await verify.LoadAsync(streamId); + var aggregate = await verify.LoadAsync(streamId, TestContext.Current.CancellationToken); aggregate.ShouldNotBeNull(); aggregate!.IsComplete.ShouldBeTrue(); diff --git a/src/Persistence/PolecatTests/non_transactional_attribute_opt_out.cs b/src/Persistence/PolecatTests/non_transactional_attribute_opt_out.cs index 068f0de8e..9dbb38d39 100644 --- a/src/Persistence/PolecatTests/non_transactional_attribute_opt_out.cs +++ b/src/Persistence/PolecatTests/non_transactional_attribute_opt_out.cs @@ -26,7 +26,7 @@ public async Task handler_with_non_transactional_attribute_should_not_be_transac }).IntegrateWithWolverine(); opts.Policies.AutoApplyTransactions(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.GetRuntime(); @@ -47,7 +47,7 @@ public async Task handler_without_non_transactional_attribute_should_still_be_tr }).IntegrateWithWolverine(); opts.Policies.AutoApplyTransactions(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.GetRuntime(); @@ -68,7 +68,7 @@ public async Task non_transactional_attribute_on_handler_class_should_opt_out() }).IntegrateWithWolverine(); opts.Policies.AutoApplyTransactions(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.GetRuntime(); diff --git a/src/Persistence/PolecatTests/read_aggregate_attribute_usage.cs b/src/Persistence/PolecatTests/read_aggregate_attribute_usage.cs index e39560d82..18a57c779 100644 --- a/src/Persistence/PolecatTests/read_aggregate_attribute_usage.cs +++ b/src/Persistence/PolecatTests/read_aggregate_attribute_usage.cs @@ -55,13 +55,13 @@ public async Task use_end_to_end_happy_past() await using (var session = theStore.LightweightSession()) { session.Events.StartStream(streamId, new AEvent(), new AEvent(), new CEvent()); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); - var latest = await session.Events.FetchLatest(streamId); + var latest = await session.Events.FetchLatest(streamId, TestContext.Current.CancellationToken); latest.ShouldNotBeNull(); } - var envelope = await theHost.MessageBus().InvokeAsync(new PcFindAggregate(streamId)); + var envelope = await theHost.MessageBus().InvokeAsync(new PcFindAggregate(streamId), TestContext.Current.CancellationToken); envelope.Inner.ACount.ShouldBe(2); envelope.Inner.CCount.ShouldBe(1); } @@ -70,7 +70,7 @@ public async Task use_end_to_end_happy_past() public async Task end_to_end_sad_path() { var envelope = await theHost.MessageBus() - .InvokeAsync(new PcFindAggregate(Guid.NewGuid())); + .InvokeAsync(new PcFindAggregate(Guid.NewGuid()), TestContext.Current.CancellationToken); envelope.ShouldBeNull(); } } diff --git a/src/Persistence/PolecatTests/strong_typed_identifiers.cs b/src/Persistence/PolecatTests/strong_typed_identifiers.cs index 3eee78e61..e79e24cf3 100644 --- a/src/Persistence/PolecatTests/strong_typed_identifiers.cs +++ b/src/Persistence/PolecatTests/strong_typed_identifiers.cs @@ -42,7 +42,7 @@ public async Task use_strong_typed_identifier_with_single_entity_attribute() var knob1 = new PcKnob { Name = "Single" }; await using var session = _host.Services.GetRequiredService().LightweightSession(); session.Store(knob1); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await _host.InvokeAsync(new TwistPcKnob(knob1.Id)); } @@ -54,7 +54,7 @@ public async Task use_with_multiple_entities_so_it_has_to_use_batch_querying() var knob2 = new PcKnob { Name = "Two" }; await using var session = _host.Services.GetRequiredService().LightweightSession(); session.Store(knob1, knob2); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); await _host.InvokeAsync(new TwistOneThenAnotherPcKnob(knob1.Id, knob2.Id)); } diff --git a/src/Persistence/PolecatTests/transactional_frame_end_to_end.cs b/src/Persistence/PolecatTests/transactional_frame_end_to_end.cs index 7215cdd47..3117ebf1f 100644 --- a/src/Persistence/PolecatTests/transactional_frame_end_to_end.cs +++ b/src/Persistence/PolecatTests/transactional_frame_end_to_end.cs @@ -22,16 +22,16 @@ public async Task the_transactional_middleware_works() m.ConnectionString = Servers.SqlServerConnectionString; m.DatabaseSchemaName = "transactional"; }).IntegrateWithWolverine(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var store = host.Services.GetRequiredService(); - await ((DocumentStore)store).Database.ApplyAllConfiguredChangesToDatabaseAsync(); + await ((DocumentStore)store).Database.ApplyAllConfiguredChangesToDatabaseAsync(ct: TestContext.Current.CancellationToken); var command = new PcCreateDocCommand(); await host.InvokeAsync(command); await using var query = store.QuerySession(); - (await query.LoadAsync(command.Id)) + (await query.LoadAsync(command.Id, TestContext.Current.CancellationToken)) .ShouldNotBeNull(); } @@ -46,16 +46,16 @@ public async Task the_transactional_middleware_works_with_document_operations() m.ConnectionString = Servers.SqlServerConnectionString; m.DatabaseSchemaName = "transactional"; }).IntegrateWithWolverine(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var store = host.Services.GetRequiredService(); - await ((DocumentStore)store).Database.ApplyAllConfiguredChangesToDatabaseAsync(); + await ((DocumentStore)store).Database.ApplyAllConfiguredChangesToDatabaseAsync(ct: TestContext.Current.CancellationToken); var command = new PcCreateDocCommand2(); await host.InvokeAsync(command); await using var query = store.QuerySession(); - (await query.LoadAsync(command.Id)) + (await query.LoadAsync(command.Id, TestContext.Current.CancellationToken)) .ShouldNotBeNull(); } } diff --git a/src/Persistence/PostgresqlTests/Agents/control_queue_tests.cs b/src/Persistence/PostgresqlTests/Agents/control_queue_tests.cs index b8f61982f..f58fb59f5 100644 --- a/src/Persistence/PostgresqlTests/Agents/control_queue_tests.cs +++ b/src/Persistence/PostgresqlTests/Agents/control_queue_tests.cs @@ -63,9 +63,9 @@ private static async Task dropControlSchema() public async Task control_queue_table_should_exist() { using var conn = new NpgsqlConnection(Servers.PostgresConnectionString); - await conn.OpenAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); - var tables = await conn.ExistingTablesAsync(schemas: ["pgcontrol"]); + var tables = await conn.ExistingTablesAsync(schemas: ["pgcontrol"], ct: TestContext.Current.CancellationToken); await conn.CloseAsync(); tables.ShouldContain(x => x.Name == DatabaseConstants.ControlQueueTableName); diff --git a/src/Persistence/PostgresqlTests/Bugs/Bug_1516_get_the_schema_names_right.cs b/src/Persistence/PostgresqlTests/Bugs/Bug_1516_get_the_schema_names_right.cs index dc459fb21..75fde89fc 100644 --- a/src/Persistence/PostgresqlTests/Bugs/Bug_1516_get_the_schema_names_right.cs +++ b/src/Persistence/PostgresqlTests/Bugs/Bug_1516_get_the_schema_names_right.cs @@ -24,7 +24,7 @@ public async Task get_the_bleeping_schema_names_right() o.PublishAllMessages().ToPostgresqlQueue("outbound"); o.ListenToPostgresqlQueue("outbound"); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var tracked = await host.TrackActivity().IncludeExternalTransports().Timeout(30.Seconds()) .SendMessageAndWaitAsync(new TraceMessage { Name = "Tom Landry" }); diff --git a/src/Persistence/PostgresqlTests/Bugs/Bug_1942_replay_dlq_to_buffered_or_inline.cs b/src/Persistence/PostgresqlTests/Bugs/Bug_1942_replay_dlq_to_buffered_or_inline.cs index f9cba4d61..3ea3b33f0 100644 --- a/src/Persistence/PostgresqlTests/Bugs/Bug_1942_replay_dlq_to_buffered_or_inline.cs +++ b/src/Persistence/PostgresqlTests/Bugs/Bug_1942_replay_dlq_to_buffered_or_inline.cs @@ -63,7 +63,7 @@ public async Task buffered_local_queue_replay_does_not_loop() opts.LocalQueueFor().BufferedInMemory(); opts.Services.AddResourceSetupOnStartup(StartupAction.ResetState); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); await runReplayScenarioAsync(host, "bug1942_buffered"); } @@ -89,7 +89,7 @@ public async Task inline_rabbitmq_listener_replay_does_not_loop() opts.ListenToRabbitQueue(queueName).ProcessInline(); opts.Services.AddResourceSetupOnStartup(StartupAction.ResetState); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); await runReplayScenarioAsync(host, "bug1942_inline"); } diff --git a/src/Persistence/PostgresqlTests/Bugs/Bug_2518_concurrent_migration_advisory_lock.cs b/src/Persistence/PostgresqlTests/Bugs/Bug_2518_concurrent_migration_advisory_lock.cs index 5c8bb0078..bc4a8b0b2 100644 --- a/src/Persistence/PostgresqlTests/Bugs/Bug_2518_concurrent_migration_advisory_lock.cs +++ b/src/Persistence/PostgresqlTests/Bugs/Bug_2518_concurrent_migration_advisory_lock.cs @@ -54,34 +54,34 @@ public async Task migration_lock_id_is_actually_held_during_migration() var lockId = new DatabaseSettings().MigrationLockId; await using var holder = new NpgsqlConnection(Servers.PostgresConnectionString); - await holder.OpenAsync(); + await holder.OpenAsync(TestContext.Current.CancellationToken); await using var contender = new NpgsqlConnection(Servers.PostgresConnectionString); - await contender.OpenAsync(); + await contender.OpenAsync(TestContext.Current.CancellationToken); - var holderResult = await holder.TryGetGlobalLock(lockId); + var holderResult = await holder.TryGetGlobalLock(lockId, cancellation: TestContext.Current.CancellationToken); try { holderResult.ShouldBe(AttainLockResult.Success); - var contenderResult = await contender.TryGetGlobalLock(lockId); + var contenderResult = await contender.TryGetGlobalLock(lockId, cancellation: TestContext.Current.CancellationToken); contenderResult.Succeeded.ShouldBeFalse( "A second session must not be able to acquire the same advisory lock"); } finally { - await holder.ReleaseGlobalLock(lockId); + await holder.ReleaseGlobalLock(lockId, cancellation: TestContext.Current.CancellationToken); } // After release, contender can acquire it - var afterRelease = await contender.TryGetGlobalLock(lockId); + var afterRelease = await contender.TryGetGlobalLock(lockId, cancellation: TestContext.Current.CancellationToken); try { afterRelease.ShouldBe(AttainLockResult.Success); } finally { - await contender.ReleaseGlobalLock(lockId); + await contender.ReleaseGlobalLock(lockId, cancellation: TestContext.Current.CancellationToken); } } diff --git a/src/Persistence/PostgresqlTests/Bugs/Bug_GH3166_dlq_null_received_at.cs b/src/Persistence/PostgresqlTests/Bugs/Bug_GH3166_dlq_null_received_at.cs index a121bdcbf..536458333 100644 --- a/src/Persistence/PostgresqlTests/Bugs/Bug_GH3166_dlq_null_received_at.cs +++ b/src/Persistence/PostgresqlTests/Bugs/Bug_GH3166_dlq_null_received_at.cs @@ -68,10 +68,10 @@ public async Task summarize_and_query_tolerate_a_null_received_at() await using (var conn = new NpgsqlConnection(Servers.PostgresConnectionString)) { - await conn.OpenAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); await using var cmd = conn.CreateCommand(); cmd.CommandText = "update dlq_nullrecv.wolverine_dead_letters set received_at = null"; - await cmd.ExecuteNonQueryAsync(); + await cmd.ExecuteNonQueryAsync(TestContext.Current.CancellationToken); } // Both of these threw on the DBNull received_at before the fix. diff --git a/src/Persistence/PostgresqlTests/DeadLetterTable_index_creation.cs b/src/Persistence/PostgresqlTests/DeadLetterTable_index_creation.cs index 5e6460f7c..f38e94701 100644 --- a/src/Persistence/PostgresqlTests/DeadLetterTable_index_creation.cs +++ b/src/Persistence/PostgresqlTests/DeadLetterTable_index_creation.cs @@ -33,7 +33,7 @@ public async ValueTask DisposeAsync() [Fact] public async Task creates_the_replayable_index_and_is_stable_without_expiration() { - await theConnection.ResetSchemaAsync("dlq_idx_no_exp"); + await theConnection.ResetSchemaAsync("dlq_idx_no_exp", ct: TestContext.Current.CancellationToken); var durability = new DurabilitySettings { DeadLetterQueueExpirationEnabled = false }; var table = new DeadLettersTable(durability, "dlq_idx_no_exp"); @@ -41,18 +41,18 @@ public async Task creates_the_replayable_index_and_is_stable_without_expiration( table.Indexes.ShouldContain(x => x.Name.Contains("replayable")); table.Indexes.ShouldNotContain(x => x.Name.Contains("expires")); - await table.ApplyChangesAsync(theConnection); + await table.ApplyChangesAsync(theConnection, ct: TestContext.Current.CancellationToken); // Re-reading the just-created schema must report NO difference. If the partial-index // predicate did not round-trip, this would come back as Update and thrash on every startup. - var delta = await table.FindDeltaAsync(theConnection); + var delta = await table.FindDeltaAsync(theConnection, TestContext.Current.CancellationToken); delta.Difference.ShouldBe(SchemaPatchDifference.None); } [Fact] public async Task creates_replayable_and_expires_indexes_and_is_stable_with_expiration() { - await theConnection.ResetSchemaAsync("dlq_idx_exp"); + await theConnection.ResetSchemaAsync("dlq_idx_exp", ct: TestContext.Current.CancellationToken); var durability = new DurabilitySettings { DeadLetterQueueExpirationEnabled = true }; var table = new DeadLettersTable(durability, "dlq_idx_exp"); @@ -60,9 +60,9 @@ public async Task creates_replayable_and_expires_indexes_and_is_stable_with_expi table.Indexes.ShouldContain(x => x.Name.Contains("replayable")); table.Indexes.ShouldContain(x => x.Name.Contains("expires")); - await table.ApplyChangesAsync(theConnection); + await table.ApplyChangesAsync(theConnection, ct: TestContext.Current.CancellationToken); - var delta = await table.FindDeltaAsync(theConnection); + var delta = await table.FindDeltaAsync(theConnection, TestContext.Current.CancellationToken); delta.Difference.ShouldBe(SchemaPatchDifference.None); } } diff --git a/src/Persistence/PostgresqlTests/MultiTenancy/multi_node_tenant_database_connections.cs b/src/Persistence/PostgresqlTests/MultiTenancy/multi_node_tenant_database_connections.cs index 93e1336aa..54fa90ad8 100644 --- a/src/Persistence/PostgresqlTests/MultiTenancy/multi_node_tenant_database_connections.cs +++ b/src/Persistence/PostgresqlTests/MultiTenancy/multi_node_tenant_database_connections.cs @@ -199,7 +199,7 @@ await leader.MessageBus().ScheduleAsync(new TenantScheduledMessage(messageId), 1 handled.ShouldBeTrue($"Scheduled message {messageId} for tenant 'red' was never executed"); // Give the losing node's poller every chance to run it a second time before counting. - await Task.Delay(5.Seconds()); + await Task.Delay(5.Seconds(), TestContext.Current.CancellationToken); theTracker.Received.Count(r => r.Id == messageId).ShouldBe(1); } diff --git a/src/Persistence/PostgresqlTests/MultiTenancy/static_multi_tenancy.cs b/src/Persistence/PostgresqlTests/MultiTenancy/static_multi_tenancy.cs index 851da141b..8e5f03df3 100644 --- a/src/Persistence/PostgresqlTests/MultiTenancy/static_multi_tenancy.cs +++ b/src/Persistence/PostgresqlTests/MultiTenancy/static_multi_tenancy.cs @@ -82,7 +82,7 @@ public async Task the_main_database_tables_include_node_persistence() { var store = theHost.Services.GetRequiredService() .ShouldBeOfType(); - var tables = await store.Main.As().SchemaTables(); + var tables = await store.Main.As().SchemaTables(TestContext.Current.CancellationToken); var expected = @" static_multi_tenancy2.blues @@ -120,7 +120,7 @@ public async Task the_tenant_databases_have_only_envelope_and_saga_tables() foreach (var tenantId in new string[] { "red", "blue", "green" }) { var messageStore = await store.Source.FindAsync(tenantId); - var tables = await messageStore.As().SchemaTables(); + var tables = await messageStore.As().SchemaTables(TestContext.Current.CancellationToken); tables.OrderBy(x => x.QualifiedName).Select(x => x.QualifiedName).ToArray() .ShouldBe(expected); diff --git a/src/Persistence/PostgresqlTests/PostgresqlMessageStoreTests.cs b/src/Persistence/PostgresqlTests/PostgresqlMessageStoreTests.cs index 703b1265d..7fd36c29f 100644 --- a/src/Persistence/PostgresqlTests/PostgresqlMessageStoreTests.cs +++ b/src/Persistence/PostgresqlTests/PostgresqlMessageStoreTests.cs @@ -83,11 +83,11 @@ public async Task delete_expired_handled_envelopes_in_batches() await using (var conn = new NpgsqlConnection(Servers.PostgresConnectionString)) { - await conn.OpenAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); await conn.CreateCommand( $"update receiver.{DatabaseConstants.IncomingTable} set {DatabaseConstants.KeepUntil} = :cutoff where status = 'Handled'") .With("cutoff", DateTimeOffset.UtcNow.Subtract(1.Hours())) - .ExecuteNonQueryAsync(); + .ExecuteNonQueryAsync(TestContext.Current.CancellationToken); await conn.CloseAsync(); } @@ -127,11 +127,11 @@ public async Task delete_old_log_node_records() await theHost.InvokeAsync(new DatabaseOperationBatch(messageDatabase, [log])); using var conn = new NpgsqlConnection(Servers.PostgresConnectionString); - await conn.OpenAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); await conn.CreateCommand( $"update receiver.{DatabaseConstants.NodeRecordTableName} set timestamp = :time where node_number = 2") .With("time", DateTimeOffset.UtcNow.Subtract(10.Days())) - .ExecuteNonQueryAsync(); + .ExecuteNonQueryAsync(TestContext.Current.CancellationToken); await conn.CloseAsync(); var recent2 = await thePersistence.Nodes.FetchRecentRecordsAsync(100); diff --git a/src/Persistence/PostgresqlTests/PostgresqlMessageStore_DQL_expiration.cs b/src/Persistence/PostgresqlTests/PostgresqlMessageStore_DQL_expiration.cs index 1e6d425a8..fefed5dc6 100644 --- a/src/Persistence/PostgresqlTests/PostgresqlMessageStore_DQL_expiration.cs +++ b/src/Persistence/PostgresqlTests/PostgresqlMessageStore_DQL_expiration.cs @@ -30,14 +30,14 @@ public async Task no_expiration_column_normally() opts.ListenAtPort(2345).UseDurableInbox(); opts.Durability.DeadLetterQueueExpirationEnabled = false; - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); using var conn = new NpgsqlConnection(Servers.PostgresConnectionString); - await conn.OpenAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); var runtime = host.GetRuntime(); - var dlq = await new DeadLettersTable(runtime.Options.Durability, "dlq_expiration").FetchExistingAsync(conn); + var dlq = await new DeadLettersTable(runtime.Options.Durability, "dlq_expiration").FetchExistingAsync(conn, TestContext.Current.CancellationToken); dlq!.ColumnFor(DatabaseConstants.Expires).ShouldBeNull(); } @@ -57,14 +57,14 @@ public async Task add_expiration_time_column_if_DLQ_expiration_is_enabled() opts.Durability.DeadLetterQueueExpirationEnabled = true; opts.Services.AddResourceSetupOnStartup(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); using var conn = new NpgsqlConnection(Servers.PostgresConnectionString); - await conn.OpenAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); var runtime = host.GetRuntime(); - var dlq = await new DeadLettersTable(runtime.Options.Durability, "dlq_expiration").FetchExistingAsync(conn); + var dlq = await new DeadLettersTable(runtime.Options.Durability, "dlq_expiration").FetchExistingAsync(conn, TestContext.Current.CancellationToken); var column = dlq!.ColumnFor(DatabaseConstants.Expires); column.ShouldNotBeNull(); column.AllowNulls.ShouldBeTrue(); diff --git a/src/Persistence/PostgresqlTests/PostgresqlMessageStore_with_IdAndDestination_Identity.cs b/src/Persistence/PostgresqlTests/PostgresqlMessageStore_with_IdAndDestination_Identity.cs index 95710597b..27f646dca 100644 --- a/src/Persistence/PostgresqlTests/PostgresqlMessageStore_with_IdAndDestination_Identity.cs +++ b/src/Persistence/PostgresqlTests/PostgresqlMessageStore_with_IdAndDestination_Identity.cs @@ -69,15 +69,15 @@ public async Task exists_should_account_for_destination_too() public async Task should_have_receive_at_in_primary_keys() { using var conn = new NpgsqlConnection(Servers.PostgresConnectionString); - await conn.OpenAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); var runtime = theHost.GetRuntime(); - var incoming = await new IncomingEnvelopeTable(runtime.Options.Durability, "receiver").FetchExistingAsync(conn); + var incoming = await new IncomingEnvelopeTable(runtime.Options.Durability, "receiver").FetchExistingAsync(conn, TestContext.Current.CancellationToken); incoming!.PrimaryKeyColumns.ShouldContain(DatabaseConstants.Id); incoming.PrimaryKeyColumns.ShouldContain(DatabaseConstants.ReceivedAt); - var dlq = await new DeadLettersTable(runtime.Options.Durability, "receiver").FetchExistingAsync(conn); + var dlq = await new DeadLettersTable(runtime.Options.Durability, "receiver").FetchExistingAsync(conn, TestContext.Current.CancellationToken); dlq!.PrimaryKeyColumns.ShouldContain(DatabaseConstants.Id); dlq.PrimaryKeyColumns.ShouldContain(DatabaseConstants.ReceivedAt); diff --git a/src/Persistence/PostgresqlTests/PostgresqlTests.csproj b/src/Persistence/PostgresqlTests/PostgresqlTests.csproj index 1cb70ad93..4d5293303 100644 --- a/src/Persistence/PostgresqlTests/PostgresqlTests.csproj +++ b/src/Persistence/PostgresqlTests/PostgresqlTests.csproj @@ -1,6 +1,8 @@ + + true Exe net9.0;net10.0 false diff --git a/src/Persistence/PostgresqlTests/Sagas/configuring_saga_table_storage.cs b/src/Persistence/PostgresqlTests/Sagas/configuring_saga_table_storage.cs index c0267a7fc..bcfdb2db5 100644 --- a/src/Persistence/PostgresqlTests/Sagas/configuring_saga_table_storage.cs +++ b/src/Persistence/PostgresqlTests/Sagas/configuring_saga_table_storage.cs @@ -26,12 +26,12 @@ public async Task add_tables_to_persistence() opts.AddSagaType("blue"); opts.PersistMessagesWithPostgresql(Servers.PostgresConnectionString, "color_sagas"); opts.Services.AddResourceSetupOnStartup(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); await using var conn = new NpgsqlConnection(Servers.PostgresConnectionString); - await conn.OpenAsync(); - (await new Table(new DbObjectName("color_sagas", "red")).ExistsInDatabaseAsync(conn)).ShouldBeTrue(); - (await new Table(new DbObjectName("color_sagas", "blue")).ExistsInDatabaseAsync(conn)).ShouldBeTrue(); + await conn.OpenAsync(TestContext.Current.CancellationToken); + (await new Table(new DbObjectName("color_sagas", "red")).ExistsInDatabaseAsync(conn, TestContext.Current.CancellationToken)).ShouldBeTrue(); + (await new Table(new DbObjectName("color_sagas", "blue")).ExistsInDatabaseAsync(conn, TestContext.Current.CancellationToken)).ShouldBeTrue(); } private static async Task dropSchemaAsync() diff --git a/src/Persistence/PostgresqlTests/Sagas/order_saga_example.cs b/src/Persistence/PostgresqlTests/Sagas/order_saga_example.cs index cde403c9b..003e41658 100644 --- a/src/Persistence/PostgresqlTests/Sagas/order_saga_example.cs +++ b/src/Persistence/PostgresqlTests/Sagas/order_saga_example.cs @@ -17,7 +17,7 @@ public async Task try_out_codegen() .UseWolverine(opts => { opts.PersistMessagesWithPostgresql(Servers.PostgresConnectionString, "order_saga"); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); await host.InvokeMessageAndWaitAsync(new StartOrder(Guid.NewGuid().ToString(), DateTime.UtcNow)); } diff --git a/src/Persistence/PostgresqlTests/Sagas/saga_storage_operations.cs b/src/Persistence/PostgresqlTests/Sagas/saga_storage_operations.cs index 20ff281c6..511180c00 100644 --- a/src/Persistence/PostgresqlTests/Sagas/saga_storage_operations.cs +++ b/src/Persistence/PostgresqlTests/Sagas/saga_storage_operations.cs @@ -28,9 +28,9 @@ public saga_storage_operations() public async Task load_with_no_document_happily_returns_null() { await using var conn = new NpgsqlConnection(Servers.PostgresConnectionString); - await conn.OpenAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); - using var tx = await conn.BeginTransactionAsync(); + using var tx = await conn.BeginTransactionAsync(TestContext.Current.CancellationToken); var saga = await theSchema.LoadAsync(Guid.NewGuid(), tx, CancellationToken.None); saga.ShouldBeNull(); @@ -40,8 +40,8 @@ public async Task load_with_no_document_happily_returns_null() public async Task get_an_argument_out_of_range_exception_for_missing_id() { await using var conn = new NpgsqlConnection(Servers.PostgresConnectionString); - await conn.OpenAsync(); - await using var db = await conn.BeginTransactionAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); + await using var db = await conn.BeginTransactionAsync(TestContext.Current.CancellationToken); var saga = new LightweightSaga { @@ -59,8 +59,8 @@ await Should.ThrowAsync(async () => public async Task insert_then_load() { await using var conn = new NpgsqlConnection(Servers.PostgresConnectionString); - await conn.OpenAsync(); - await using var db = await conn.BeginTransactionAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); + await using var db = await conn.BeginTransactionAsync(TestContext.Current.CancellationToken); var saga = new LightweightSaga { @@ -69,9 +69,9 @@ public async Task insert_then_load() }; await theSchema.InsertAsync(saga, db, CancellationToken.None); - await db.CommitAsync(); + await db.CommitAsync(TestContext.Current.CancellationToken); - using var db2 = await conn.BeginTransactionAsync(); + using var db2 = await conn.BeginTransactionAsync(TestContext.Current.CancellationToken); var saga2 = await theSchema.LoadAsync(saga.Id, db2, CancellationToken.None); saga2!.Name.ShouldBe("Xavier Worthy"); @@ -81,8 +81,8 @@ public async Task insert_then_load() public async Task insert_update_then_load() { await using var conn = new NpgsqlConnection(Servers.PostgresConnectionString); - await conn.OpenAsync(); - await using var db = await conn.BeginTransactionAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); + await using var db = await conn.BeginTransactionAsync(TestContext.Current.CancellationToken); var saga = new LightweightSaga { @@ -94,9 +94,9 @@ public async Task insert_update_then_load() saga.Name = "Hollywood Brown"; await theSchema.UpdateAsync(saga, db, CancellationToken.None); - await db.CommitAsync(); + await db.CommitAsync(TestContext.Current.CancellationToken); - using var db2 = await conn.BeginTransactionAsync(); + using var db2 = await conn.BeginTransactionAsync(TestContext.Current.CancellationToken); var saga2 = await theSchema.LoadAsync(saga.Id, db2, CancellationToken.None); saga2!.Name.ShouldBe("Hollywood Brown"); @@ -106,8 +106,8 @@ public async Task insert_update_then_load() public async Task insert_then_delete() { await using var conn = new NpgsqlConnection(Servers.PostgresConnectionString); - await conn.OpenAsync(); - await using var db = await conn.BeginTransactionAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); + await using var db = await conn.BeginTransactionAsync(TestContext.Current.CancellationToken); var saga = new LightweightSaga { @@ -118,9 +118,9 @@ public async Task insert_then_delete() await theSchema.InsertAsync(saga, db, CancellationToken.None); await theSchema.DeleteAsync(saga, db, CancellationToken.None); - await db.CommitAsync(); + await db.CommitAsync(TestContext.Current.CancellationToken); - using var db2 = await conn.BeginTransactionAsync(); + using var db2 = await conn.BeginTransactionAsync(TestContext.Current.CancellationToken); var saga2 = await theSchema.LoadAsync(saga.Id, db2, CancellationToken.None); saga2.ShouldBeNull(); } @@ -131,12 +131,12 @@ public async Task concurrency_exception_when_version_does_not_match() await theSchema.EnsureStorageExistsAsync(CancellationToken.None); await using var conn = new NpgsqlConnection(Servers.PostgresConnectionString); - await conn.OpenAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); await conn.CreateCommand("delete from lightweight_sagas.lightweightsaga_saga") - .ExecuteNonQueryAsync(); + .ExecuteNonQueryAsync(TestContext.Current.CancellationToken); - var db = await conn.BeginTransactionAsync(); + var db = await conn.BeginTransactionAsync(TestContext.Current.CancellationToken); var saga = new LightweightSaga { @@ -145,17 +145,17 @@ await conn.CreateCommand("delete from lightweight_sagas.lightweightsaga_saga") }; await theSchema.InsertAsync(saga, db, CancellationToken.None); - await db.CommitAsync(); + await db.CommitAsync(TestContext.Current.CancellationToken); await db.DisposeAsync(); - db = await conn.BeginTransactionAsync(); + db = await conn.BeginTransactionAsync(TestContext.Current.CancellationToken); saga.Name = "Rashee Rice"; await theSchema.UpdateAsync(saga, db, CancellationToken.None); - await db.CommitAsync(); + await db.CommitAsync(TestContext.Current.CancellationToken); await db.DisposeAsync(); - db = await conn.BeginTransactionAsync(); + db = await conn.BeginTransactionAsync(TestContext.Current.CancellationToken); // I'm rewinding the version to make it throw saga.Version = 1; diff --git a/src/Persistence/PostgresqlTests/Transport/basic_functionality.cs b/src/Persistence/PostgresqlTests/Transport/basic_functionality.cs index bedaee259..2a449f958 100644 --- a/src/Persistence/PostgresqlTests/Transport/basic_functionality.cs +++ b/src/Persistence/PostgresqlTests/Transport/basic_functionality.cs @@ -73,9 +73,9 @@ public async ValueTask DisposeAsync() public async Task expected_tables_exist_for_queue() { await using var conn = new NpgsqlConnection(Servers.PostgresConnectionString); - await conn.OpenAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); - var names = await conn.ExistingTablesAsync(schemas: ["transports"]); + var names = await conn.ExistingTablesAsync(schemas: ["transports"], ct: TestContext.Current.CancellationToken); await conn.CloseAsync(); diff --git a/src/Persistence/PostgresqlTests/Transport/external_message_tables.cs b/src/Persistence/PostgresqlTests/Transport/external_message_tables.cs index 45b775526..69599204b 100644 --- a/src/Persistence/PostgresqlTests/Transport/external_message_tables.cs +++ b/src/Persistence/PostgresqlTests/Transport/external_message_tables.cs @@ -52,7 +52,7 @@ public async Task can_create_basic_table() opts.UsePostgresqlPersistenceAndTransport(Servers.PostgresConnectionString, "external"); opts.Policies.UseDurableLocalQueues(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var storage = host.Services.GetRequiredService() .As(); @@ -64,11 +64,11 @@ public async Task can_create_basic_table() using var conn = new NpgsqlConnection(Servers.PostgresConnectionString); - await conn.OpenAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); await table.MigrateAsync(conn); - var delta = await table.FindDeltaAsync(conn); + var delta = await table.FindDeltaAsync(conn, TestContext.Current.CancellationToken); delta.Difference.ShouldBe(SchemaPatchDifference.None); @@ -87,7 +87,7 @@ public async Task can_create_basic_table_with_message_type() .UseWolverine(opts => { opts.UsePostgresqlPersistenceAndTransport(Servers.PostgresConnectionString, "external"); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var storage = host.Services.GetRequiredService() .As(); @@ -99,11 +99,11 @@ public async Task can_create_basic_table_with_message_type() using var conn = new NpgsqlConnection(Servers.PostgresConnectionString); - await conn.OpenAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); await table.MigrateAsync(conn); - var delta = await table.FindDeltaAsync(conn); + var delta = await table.FindDeltaAsync(conn, TestContext.Current.CancellationToken); delta.Difference.ShouldBe(SchemaPatchDifference.None); @@ -123,7 +123,7 @@ public async Task end_to_end_default_message_type() table.PollingInterval = 1.Seconds(); }); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var tracked = await host.TrackActivity().Timeout(1.Minutes()).WaitForMessageToBeReceivedAt(host).ExecuteAndWaitAsync( _ => host.SendMessageThroughExternalTable("external.incoming1", new Message1())); @@ -147,7 +147,7 @@ public async Task end_to_end_default_variable_message_types() table.PollingInterval = 1.Seconds(); }); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var tracked = await host.TrackActivity().Timeout(1.Minutes()).WaitForMessageToBeReceivedAt(host).ExecuteAndWaitAsync( _ => host.SendMessageThroughExternalTable("external.incoming1", new Message2())); @@ -174,7 +174,7 @@ public async Task end_to_end_default_variable_message_types_customize_table_in_e table.PollingInterval = 1.Seconds(); }); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var tracked = await host.TrackActivity().Timeout(1.Minutes()).WaitForMessageToBeReceivedAt(host).ExecuteAndWaitAsync( _ => host.SendMessageThroughExternalTable("external.incoming1", new Message2())); @@ -203,12 +203,12 @@ public async Task pull_in_message_that_goes_to_dead_letter_queue_and_replay_it() table.PollingInterval = 1.Seconds(); }); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); // Rig it up to fail var waiter = BlowsUpMessageHandler.WaiterForCall(true); - await host.SendMessageThroughExternalTable("external.incoming4", new BlowsUpMessage()); + await host.SendMessageThroughExternalTable("external.incoming4", new BlowsUpMessage(), token: TestContext.Current.CancellationToken); var storage = host.GetRuntime().Storage; Guid[] ids = new Guid[0]; while (!ids.Any()) diff --git a/src/Persistence/PostgresqlTests/Transport/resource_setup_against_a_missing_database.cs b/src/Persistence/PostgresqlTests/Transport/resource_setup_against_a_missing_database.cs index f2a8fbe5f..8113e746d 100644 --- a/src/Persistence/PostgresqlTests/Transport/resource_setup_against_a_missing_database.cs +++ b/src/Persistence/PostgresqlTests/Transport/resource_setup_against_a_missing_database.cs @@ -60,13 +60,13 @@ public async Task setup_resources_provisions_the_transport_onto_a_database_creat // does not exist yet. Before the discovery seam, FindResources() threw // BrokerInitializationException out of PostgresqlTransport's eager connectivity probe // before DatabaseCreator ever ran. - await host.SetupResources(); + await host.SetupResources(cancellation: TestContext.Current.CancellationToken); (await tableExistsAsync("fresh_queues", "wolverine_queue_incoming")).ShouldBeTrue(); (await tableExistsAsync("fresh", DatabaseConstants.IncomingTable)).ShouldBeTrue(); - await host.StartAsync(); - await host.StopAsync(); + await host.StartAsync(TestContext.Current.CancellationToken); + await host.StopAsync(TestContext.Current.CancellationToken); } private async Task tableExistsAsync(string schema, string table) diff --git a/src/Persistence/PostgresqlTests/Transport/sticky_listener_health_tests.cs b/src/Persistence/PostgresqlTests/Transport/sticky_listener_health_tests.cs index fcb3be08c..d58394541 100644 --- a/src/Persistence/PostgresqlTests/Transport/sticky_listener_health_tests.cs +++ b/src/Persistence/PostgresqlTests/Transport/sticky_listener_health_tests.cs @@ -134,7 +134,7 @@ public async Task get_queue_depth_returns_zero_for_empty_table() [Fact] public async Task get_queue_depth_reflects_inserted_rows() { - await using (var conn = await _dataSource.OpenConnectionAsync()) + await using (var conn = await _dataSource.OpenConnectionAsync(TestContext.Current.CancellationToken)) { try { @@ -144,7 +144,7 @@ public async Task get_queue_depth_reflects_inserted_rows() insert.CommandText = $"INSERT INTO {_tableName} (id, body, message_type, keep_until) " + "VALUES (gen_random_uuid(), '\\x00'::bytea, 'TestMessage', null)"; - await insert.ExecuteNonQueryAsync(); + await insert.ExecuteNonQueryAsync(TestContext.Current.CancellationToken); } } finally diff --git a/src/Persistence/PostgresqlTests/Transport/transport_perf_benchmark.cs b/src/Persistence/PostgresqlTests/Transport/transport_perf_benchmark.cs index fba65c4fc..140fdd32e 100644 --- a/src/Persistence/PostgresqlTests/Transport/transport_perf_benchmark.cs +++ b/src/Persistence/PostgresqlTests/Transport/transport_perf_benchmark.cs @@ -66,7 +66,7 @@ CREATE TABLE bench_c ( public async Task run() { await using var dataSource = NpgsqlDataSource.Create(ConnString); - await using var conn = await dataSource.OpenConnectionAsync(); + await using var conn = await dataSource.OpenConnectionAsync(TestContext.Current.CancellationToken); foreach (var v in Variants()) { @@ -82,7 +82,7 @@ public async Task run() await using var cmd = conn.CreateCommand(insertSql); cmd.Parameters.AddWithValue("id", Guid.NewGuid()); cmd.Parameters.AddWithValue("body", body); - await cmd.ExecuteNonQueryAsync(); + await cmd.ExecuteNonQueryAsync(TestContext.Current.CancellationToken); } sw.Stop(); var insertRate = InsertCount / sw.Elapsed.TotalSeconds; diff --git a/src/Persistence/PostgresqlTests/advisory_lock_session_hygiene.cs b/src/Persistence/PostgresqlTests/advisory_lock_session_hygiene.cs index 8fcb229cc..da167e676 100644 --- a/src/Persistence/PostgresqlTests/advisory_lock_session_hygiene.cs +++ b/src/Persistence/PostgresqlTests/advisory_lock_session_hygiene.cs @@ -31,7 +31,7 @@ public async Task lock_session_is_tagged_and_invisible_to_martens_gap_liveness_g (await holder.TryAttainLockAsync(lockId, CancellationToken.None)).ShouldBeTrue(); // Let the backend settle back to idle after the lock command. - await Task.Delay(250); + await Task.Delay(250, TestContext.Current.CancellationToken); var session = await findLockHolderSessionAsync(lockId); session.ShouldNotBeNull("the advisory lock must be held by a live backend"); @@ -72,7 +72,7 @@ public async Task application_name_is_truncated_to_postgres_limit_for_long_datab try { (await holder.TryAttainLockAsync(lockId, CancellationToken.None)).ShouldBeTrue(); - await Task.Delay(250); + await Task.Delay(250, TestContext.Current.CancellationToken); var session = await findLockHolderSessionAsync(lockId); session.ShouldNotBeNull(); diff --git a/src/Persistence/PostgresqlTests/bumping_stale_inbox_messages.cs b/src/Persistence/PostgresqlTests/bumping_stale_inbox_messages.cs index 8a0ff444e..20e689081 100644 --- a/src/Persistence/PostgresqlTests/bumping_stale_inbox_messages.cs +++ b/src/Persistence/PostgresqlTests/bumping_stale_inbox_messages.cs @@ -42,9 +42,9 @@ public async ValueTask DisposeAsync() public async Task got_the_right_column() { using var conn = new NpgsqlConnection(Servers.PostgresConnectionString); - await conn.OpenAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); - var table = await new Table(new DbObjectName("stale_outbox", DatabaseConstants.IncomingTable)).FetchExistingAsync(conn); + var table = await new Table(new DbObjectName("stale_outbox", DatabaseConstants.IncomingTable)).FetchExistingAsync(conn, TestContext.Current.CancellationToken); table!.HasColumn(DatabaseConstants.Timestamp).ShouldBeTrue(); @@ -76,21 +76,21 @@ public async Task using_the_operation() await messageStore.Inbox.StoreIncomingAsync(envelope5); using var conn = new NpgsqlConnection(Servers.PostgresConnectionString); - await conn.OpenAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); await conn.CreateCommand("update stale_outbox.wolverine_incoming_envelopes set \"timestamp\" = :time where id = :id") .With("time", DateTimeOffset.UtcNow.Subtract(2.Hours())) .With("id", envelope1.Id) - .ExecuteNonQueryAsync(); + .ExecuteNonQueryAsync(TestContext.Current.CancellationToken); await conn.CreateCommand("update stale_outbox.wolverine_incoming_envelopes set \"timestamp\" = :time where id = :id") .With("time", DateTimeOffset.UtcNow.Subtract(2.Hours())) .With("id", envelope3.Id) - .ExecuteNonQueryAsync(); + .ExecuteNonQueryAsync(TestContext.Current.CancellationToken); await conn.CreateCommand("update stale_outbox.wolverine_incoming_envelopes set \"timestamp\" = :time where id = :id") .With("time", DateTimeOffset.UtcNow.Subtract(2.Hours())) .With("id", envelope5.Id) - .ExecuteNonQueryAsync(); + .ExecuteNonQueryAsync(TestContext.Current.CancellationToken); var envelopesBefore = await messageStore.Admin.AllIncomingAsync(); envelopesBefore.Count(x => x.OwnerId == 0).ShouldBe(0); diff --git a/src/Persistence/PostgresqlTests/bumping_stale_outbox_messages.cs b/src/Persistence/PostgresqlTests/bumping_stale_outbox_messages.cs index a0c30031d..3ce08bf75 100644 --- a/src/Persistence/PostgresqlTests/bumping_stale_outbox_messages.cs +++ b/src/Persistence/PostgresqlTests/bumping_stale_outbox_messages.cs @@ -42,9 +42,9 @@ public async ValueTask DisposeAsync() public async Task got_the_right_column() { using var conn = new NpgsqlConnection(Servers.PostgresConnectionString); - await conn.OpenAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); - var table = await new Table(new DbObjectName("stale_outbox", DatabaseConstants.OutgoingTable)).FetchExistingAsync(conn); + var table = await new Table(new DbObjectName("stale_outbox", DatabaseConstants.OutgoingTable)).FetchExistingAsync(conn, TestContext.Current.CancellationToken); table!.HasColumn(DatabaseConstants.Timestamp).ShouldBeTrue(); @@ -76,21 +76,21 @@ public async Task using_the_operation() await messageStore.Outbox.StoreOutgoingAsync(envelope5, 3); using var conn = new NpgsqlConnection(Servers.PostgresConnectionString); - await conn.OpenAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); await conn.CreateCommand("update stale_outbox.wolverine_outgoing_envelopes set \"timestamp\" = :time where id = :id") .With("time", DateTimeOffset.UtcNow.Subtract(2.Hours())) .With("id", envelope1.Id) - .ExecuteNonQueryAsync(); + .ExecuteNonQueryAsync(TestContext.Current.CancellationToken); await conn.CreateCommand("update stale_outbox.wolverine_outgoing_envelopes set \"timestamp\" = :time where id = :id") .With("time", DateTimeOffset.UtcNow.Subtract(2.Hours())) .With("id", envelope3.Id) - .ExecuteNonQueryAsync(); + .ExecuteNonQueryAsync(TestContext.Current.CancellationToken); await conn.CreateCommand("update stale_outbox.wolverine_outgoing_envelopes set \"timestamp\" = :time where id = :id") .With("time", DateTimeOffset.UtcNow.Subtract(2.Hours())) .With("id", envelope5.Id) - .ExecuteNonQueryAsync(); + .ExecuteNonQueryAsync(TestContext.Current.CancellationToken); var envelopesBefore = await messageStore.Admin.AllOutgoingAsync(); envelopesBefore.Count(x => x.OwnerId == 0).ShouldBe(0); diff --git a/src/Persistence/PostgresqlTests/compliance_using_table_partitioning.cs b/src/Persistence/PostgresqlTests/compliance_using_table_partitioning.cs index 0a2950a14..853cf6abe 100644 --- a/src/Persistence/PostgresqlTests/compliance_using_table_partitioning.cs +++ b/src/Persistence/PostgresqlTests/compliance_using_table_partitioning.cs @@ -89,11 +89,11 @@ public async Task delete_expired_handled_envelopes_in_batches() // Force expiry by pushing keep_until into the past await using (var conn = new NpgsqlConnection(Servers.PostgresConnectionString)) { - await conn.OpenAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); await conn.CreateCommand( $"update receiver_partitioned.{DatabaseConstants.IncomingTable} set {DatabaseConstants.KeepUntil} = :cutoff where status = 'Handled'") .With("cutoff", DateTimeOffset.UtcNow.Subtract(1.Hours())) - .ExecuteNonQueryAsync(); + .ExecuteNonQueryAsync(TestContext.Current.CancellationToken); await conn.CloseAsync(); } @@ -133,11 +133,11 @@ public async Task delete_old_log_node_records() await theHost.InvokeAsync(new DatabaseOperationBatch(messageDatabase, [log])); using var conn = new NpgsqlConnection(Servers.PostgresConnectionString); - await conn.OpenAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); await conn.CreateCommand( $"update receiver_partitioned.{DatabaseConstants.NodeRecordTableName} set timestamp = :time where node_number = 2") .With("time", DateTimeOffset.UtcNow.Subtract(10.Days())) - .ExecuteNonQueryAsync(); + .ExecuteNonQueryAsync(TestContext.Current.CancellationToken); await conn.CloseAsync(); var recent2 = await thePersistence.Nodes.FetchRecentRecordsAsync(100); diff --git a/src/Persistence/PostgresqlTests/explicit_resource_setup_with_auto_create_none.cs b/src/Persistence/PostgresqlTests/explicit_resource_setup_with_auto_create_none.cs index 611644b32..69219ce93 100644 --- a/src/Persistence/PostgresqlTests/explicit_resource_setup_with_auto_create_none.cs +++ b/src/Persistence/PostgresqlTests/explicit_resource_setup_with_auto_create_none.cs @@ -58,7 +58,7 @@ public async Task setup_resources_builds_the_message_storage_even_when_auto_crea { using var host = configureHost().Build(); - await host.SetupResources(); + await host.SetupResources(cancellation: TestContext.Current.CancellationToken); (await envelopeTablesExist()).ShouldBeTrue(); } @@ -92,8 +92,8 @@ public async Task host_startup_with_auto_build_none_does_not_create_the_message_ try { - await host.StartAsync(); - await host.StopAsync(); + await host.StartAsync(TestContext.Current.CancellationToken); + await host.StopAsync(TestContext.Current.CancellationToken); } catch (Exception) { diff --git a/src/Persistence/PostgresqlTests/master_table_tenancy_di_registration.cs b/src/Persistence/PostgresqlTests/master_table_tenancy_di_registration.cs index f5ade2895..c9053e6ae 100644 --- a/src/Persistence/PostgresqlTests/master_table_tenancy_di_registration.cs +++ b/src/Persistence/PostgresqlTests/master_table_tenancy_di_registration.cs @@ -68,7 +68,7 @@ public async Task starts_cleanly_with_an_empty_master_tenant_table() .UseMasterTableTenancy(_ => { }); // intentionally no seeded tenants opts.Services.AddResourceSetupOnStartup(); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); // Reaching a started host without throwing is the assertion; the registration still lights up. host.Services.GetServices>().ShouldNotBeEmpty(); @@ -86,7 +86,7 @@ public async Task dynamic_tenant_lifecycle_round_trip() opts.PersistMessagesWithPostgresql(Servers.PostgresConnectionString, "mt_lifecycle_3023") .UseMasterTableTenancy(_ => { }); opts.Services.AddResourceSetupOnStartup(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var source = host.Services.GetServices>() .OfType().Single(); diff --git a/src/Persistence/PostgresqlTests/message_store_initialization_and_configuration.cs b/src/Persistence/PostgresqlTests/message_store_initialization_and_configuration.cs index 4152ced33..b71f880d6 100644 --- a/src/Persistence/PostgresqlTests/message_store_initialization_and_configuration.cs +++ b/src/Persistence/PostgresqlTests/message_store_initialization_and_configuration.cs @@ -61,9 +61,9 @@ public void main_store_role() public async Task builds_the_node_and_control_queue_tables() { using var conn = new NpgsqlConnection(Servers.PostgresConnectionString); - await conn.OpenAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); - var tables = await conn.ExistingTablesAsync(schemas: ["registry"]); + var tables = await conn.ExistingTablesAsync(schemas: ["registry"], ct: TestContext.Current.CancellationToken); await conn.CloseAsync(); tables.ShouldContain(x => x.Name == DatabaseConstants.NodeTableName); @@ -100,7 +100,7 @@ public async Task stores_the_current_node_on_startup() [Fact] public async Task deletes_the_node_on_shutdown() { - await _host.StopAsync(); + await _host.StopAsync(TestContext.Current.CancellationToken); _host.Dispose(); _host = null!; diff --git a/src/Persistence/PostgresqlTests/scheduled_messages_use_message_store_when_AlwaysMakeScheduledMessagesDurable_is_set.cs b/src/Persistence/PostgresqlTests/scheduled_messages_use_message_store_when_AlwaysMakeScheduledMessagesDurable_is_set.cs index 93dfcc763..e6d6c9dfb 100644 --- a/src/Persistence/PostgresqlTests/scheduled_messages_use_message_store_when_AlwaysMakeScheduledMessagesDurable_is_set.cs +++ b/src/Persistence/PostgresqlTests/scheduled_messages_use_message_store_when_AlwaysMakeScheduledMessagesDurable_is_set.cs @@ -49,7 +49,7 @@ public async Task local_queue_persists_scheduled_messages_to_message_store_when_ opts.Policies.AlwaysMakeScheduledMessagesDurable(); opts.Services.AddResourceSetupOnStartup(StartupAction.ResetState); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var bus = host.MessageBus(); var store = host.Services.GetRequiredService(); @@ -83,7 +83,7 @@ public async Task local_queue_uses_in_memory_scheduling_without_the_policy() opts.LocalQueueFor().BufferedInMemory(); opts.Services.AddResourceSetupOnStartup(StartupAction.ResetState); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var bus = host.MessageBus(); var store = host.Services.GetRequiredService(); @@ -93,7 +93,7 @@ public async Task local_queue_uses_in_memory_scheduling_without_the_policy() // Give any async outgoing flush a moment to complete; no scheduled rows should appear // because the in-memory scheduler is the destination, not the message store. - await Task.Delay(500); + await Task.Delay(500, TestContext.Current.CancellationToken); var counts = await store.Admin.FetchCountsAsync(); counts.Scheduled.ShouldBe(0); } diff --git a/src/Persistence/PostgresqlTests/using_default_message_schema_name.cs b/src/Persistence/PostgresqlTests/using_default_message_schema_name.cs index b37243f7a..ad5b34610 100644 --- a/src/Persistence/PostgresqlTests/using_default_message_schema_name.cs +++ b/src/Persistence/PostgresqlTests/using_default_message_schema_name.cs @@ -23,7 +23,7 @@ public async Task use_default_schema_name_when_specified_for_connection_string() opts.PersistMessagesWithPostgresql(Servers.PostgresConnectionString); opts.Services.AddResourceSetupOnStartup(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var store = host.Services.GetRequiredService(); store.ShouldBeOfType().Settings.SchemaName.ShouldBe("wolverine_default"); @@ -39,7 +39,7 @@ public async Task override_the_storage_schema() opts.PersistMessagesWithPostgresql(Servers.PostgresConnectionString, "non_default"); opts.Services.AddResourceSetupOnStartup(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var store = host.Services.GetRequiredService(); store.ShouldBeOfType().Settings.SchemaName.ShouldBe("non_default"); @@ -55,7 +55,7 @@ public async Task use_default_schema_name_when_specified_for_data_source() opts.PersistMessagesWithPostgresql(NpgsqlDataSource.Create(Servers.PostgresConnectionString)); opts.Services.AddResourceSetupOnStartup(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var store = host.Services.GetRequiredService(); store.ShouldBeOfType().Settings.SchemaName.ShouldBe("wolverine_default"); diff --git a/src/Persistence/RavenDbTests/RavenDbTests.csproj b/src/Persistence/RavenDbTests/RavenDbTests.csproj index f2875a469..b6d57cf4d 100644 --- a/src/Persistence/RavenDbTests/RavenDbTests.csproj +++ b/src/Persistence/RavenDbTests/RavenDbTests.csproj @@ -1,6 +1,8 @@ + + true Exe net9.0 enable diff --git a/src/Persistence/RavenDbTests/durability_recovery_orphaned_listener.cs b/src/Persistence/RavenDbTests/durability_recovery_orphaned_listener.cs index 8553b0aa0..ced5966d5 100644 --- a/src/Persistence/RavenDbTests/durability_recovery_orphaned_listener.cs +++ b/src/Persistence/RavenDbTests/durability_recovery_orphaned_listener.cs @@ -70,8 +70,8 @@ await session.StoreAsync(new IncomingMessage Status = EnvelopeStatus.Incoming, Body = Array.Empty(), MessageType = "orphaned" - }); - await session.SaveChangesAsync(); + }, TestContext.Current.CancellationToken); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); } var store = _host.Services.GetRequiredService().As(); diff --git a/src/Persistence/RavenDbTests/leadership_locking.cs b/src/Persistence/RavenDbTests/leadership_locking.cs index a5a09a458..b5acedbc6 100644 --- a/src/Persistence/RavenDbTests/leadership_locking.cs +++ b/src/Persistence/RavenDbTests/leadership_locking.cs @@ -105,8 +105,7 @@ public async Task expired_scheduled_job_lock_from_dead_predecessor_can_be_taken_ NodeId = Guid.NewGuid(), ExpirationTime = DateTimeOffset.UtcNow.AddMinutes(-10) }; - var put = await _store.Operations.SendAsync( - new PutCompareExchangeValueOperation("wolverine/scheduled", staleLock, 0)); + var put = await _store.Operations.SendAsync(new PutCompareExchangeValueOperation("wolverine/scheduled", staleLock, 0), token: TestContext.Current.CancellationToken); put.Successful.ShouldBeTrue(); // Build a brand-new message store with no in-memory lock state — mirrors a @@ -126,14 +125,12 @@ public async Task try_attain_renews_the_server_side_lease_when_already_held() var lockId = "wolverine/leader/locking"; (await store.Nodes.TryAttainLeadershipLockAsync(CancellationToken.None)).ShouldBeTrue(); - var initial = await _store.Operations.SendAsync( - new GetCompareExchangeValueOperation(lockId)); + var initial = await _store.Operations.SendAsync(new GetCompareExchangeValueOperation(lockId), token: TestContext.Current.CancellationToken); - await Task.Delay(10); + await Task.Delay(10, TestContext.Current.CancellationToken); (await store.Nodes.TryAttainLeadershipLockAsync(CancellationToken.None)).ShouldBeTrue(); - var renewed = await _store.Operations.SendAsync( - new GetCompareExchangeValueOperation(lockId)); + var renewed = await _store.Operations.SendAsync(new GetCompareExchangeValueOperation(lockId), token: TestContext.Current.CancellationToken); renewed.Index.ShouldBeGreaterThan(initial.Index); renewed.Value.ExpirationTime.ShouldBeGreaterThan(initial.Value.ExpirationTime); @@ -151,32 +148,27 @@ public async Task raw_compare_exchange_exclusivity_proof() var lock2 = new DistributedLock { NodeId = Guid.NewGuid(), ExpirationTime = DateTimeOffset.UtcNow.AddMinutes(5) }; // First acquisition - should succeed (key doesn't exist) - var firstPut = await _store.Operations.SendAsync( - new PutCompareExchangeValueOperation(key, lock1, 0)); + var firstPut = await _store.Operations.SendAsync(new PutCompareExchangeValueOperation(key, lock1, 0), token: TestContext.Current.CancellationToken); firstPut.Successful.ShouldBeTrue("First acquisition with index=0 must succeed"); // Second acquisition with index=0 on same key - must FAIL if CE is exclusive - var secondPut = await _store.Operations.SendAsync( - new PutCompareExchangeValueOperation(key, lock2, 0)); + var secondPut = await _store.Operations.SendAsync(new PutCompareExchangeValueOperation(key, lock2, 0), token: TestContext.Current.CancellationToken); secondPut.Successful.ShouldBeFalse( "Second acquisition with index=0 on same key must fail - CompareExchange is exclusive"); secondPut.Value.ShouldNotBeNull(); secondPut.Value.NodeId.ShouldBe(lock1.NodeId, "Existing value should still be lock1's node"); // Correct-index acquisition (using the index from first put) - should succeed - var correctIndexPut = await _store.Operations.SendAsync( - new PutCompareExchangeValueOperation(key, lock2, firstPut.Index)); + var correctIndexPut = await _store.Operations.SendAsync(new PutCompareExchangeValueOperation(key, lock2, firstPut.Index), token: TestContext.Current.CancellationToken); correctIndexPut.Successful.ShouldBeTrue("Acquisition with correct index must succeed"); // Wrong-index delete - should FAIL var wrongIndex = correctIndexPut.Index + 999; - var wrongDelete = await _store.Operations.SendAsync( - new DeleteCompareExchangeValueOperation(key, wrongIndex)); + var wrongDelete = await _store.Operations.SendAsync(new DeleteCompareExchangeValueOperation(key, wrongIndex), token: TestContext.Current.CancellationToken); wrongDelete.Successful.ShouldBeFalse("Delete with wrong index must fail"); // Correct-index delete - should succeed - var correctDelete = await _store.Operations.SendAsync( - new DeleteCompareExchangeValueOperation(key, correctIndexPut.Index)); + var correctDelete = await _store.Operations.SendAsync(new DeleteCompareExchangeValueOperation(key, correctIndexPut.Index), token: TestContext.Current.CancellationToken); correctDelete.Successful.ShouldBeTrue("Delete with correct index must succeed"); } @@ -196,8 +188,7 @@ public async Task stale_index_causes_lock_renewal_failure() var lockVal1 = new DistributedLock { NodeId = Guid.NewGuid(), ExpirationTime = DateTimeOffset.UtcNow.AddMinutes(5) }; // Acquire initially -> index becomes N - var create = await _store.Operations.SendAsync( - new PutCompareExchangeValueOperation(key, lockVal1, 0)); + var create = await _store.Operations.SendAsync(new PutCompareExchangeValueOperation(key, lockVal1, 0), token: TestContext.Current.CancellationToken); create.Successful.ShouldBeTrue(); var expectedIndex = create.Index; @@ -207,28 +198,24 @@ public async Task stale_index_causes_lock_renewal_failure() // - Caller 1 (correct index) succeeds - var lockVal2 = new DistributedLock { NodeId = Guid.NewGuid(), ExpirationTime = DateTimeOffset.UtcNow.AddMinutes(5) }; - var caller1 = await _store.Operations.SendAsync( - new PutCompareExchangeValueOperation(key, lockVal2, expectedIndex)); + var caller1 = await _store.Operations.SendAsync(new PutCompareExchangeValueOperation(key, lockVal2, expectedIndex), token: TestContext.Current.CancellationToken); caller1.Successful.ShouldBeTrue("Caller 1 renewal with correct index succeeds"); var afterCaller1Index = caller1.Index; // - Caller 2 (stale index N, but actual index is now N+1) fails - var lockVal3 = new DistributedLock { NodeId = Guid.NewGuid(), ExpirationTime = DateTimeOffset.UtcNow.AddMinutes(5) }; - var caller2 = await _store.Operations.SendAsync( - new PutCompareExchangeValueOperation(key, lockVal3, expectedIndex)); + var caller2 = await _store.Operations.SendAsync(new PutCompareExchangeValueOperation(key, lockVal3, expectedIndex), token: TestContext.Current.CancellationToken); caller2.Successful.ShouldBeFalse("Caller 2 with stale index MUST fail - proves race causes renewal failure"); // - What Wolverine does: stepDownAsync -> ReleaseLeadershipLockAsync // which deletes the lock value using its stale _lastLockIndex - // This delete ALSO fails because index is wrong! - var staleDelete = await _store.Operations.SendAsync( - new DeleteCompareExchangeValueOperation(key, expectedIndex)); + var staleDelete = await _store.Operations.SendAsync(new DeleteCompareExchangeValueOperation(key, expectedIndex), token: TestContext.Current.CancellationToken); staleDelete.Successful.ShouldBeFalse( "Delete with stale index fails - lock value remains, so another node can acquire it via take-over"); // - Cleanup: delete with correct index - - var cleanDelete = await _store.Operations.SendAsync( - new DeleteCompareExchangeValueOperation(key, afterCaller1Index)); + var cleanDelete = await _store.Operations.SendAsync(new DeleteCompareExchangeValueOperation(key, afterCaller1Index), token: TestContext.Current.CancellationToken); cleanDelete.Successful.ShouldBeTrue("Cleanup delete with correct index succeeds"); } @@ -251,8 +238,7 @@ public async Task concurrent_lock_renewal_race_orphans_the_lock() var initialLock = new DistributedLock { NodeId = owner, ExpirationTime = DateTimeOffset.UtcNow.AddMinutes(5) }; // === Step 1: Host1 acquires the lock (index=N) === - var create = await _store.Operations.SendAsync( - new PutCompareExchangeValueOperation(key, initialLock, 0)); + var create = await _store.Operations.SendAsync(new PutCompareExchangeValueOperation(key, initialLock, 0), token: TestContext.Current.CancellationToken); create.Successful.ShouldBeTrue(); var sharedIndex = create.Index; // This is like _lastLockIndex on Host1 Console.WriteLine($"Step 1: Acquired lock, index={sharedIndex}"); @@ -262,10 +248,8 @@ public async Task concurrent_lock_renewal_race_orphans_the_lock() // Caller B is CheckAgentHealth message processing var lockA = new DistributedLock { NodeId = owner, ExpirationTime = DateTimeOffset.UtcNow.AddMinutes(5) }; var lockB = new DistributedLock { NodeId = owner, ExpirationTime = DateTimeOffset.UtcNow.AddMinutes(5) }; - var resultA = await _store.Operations.SendAsync( - new PutCompareExchangeValueOperation(key, lockA, sharedIndex)); - var resultB = await _store.Operations.SendAsync( - new PutCompareExchangeValueOperation(key, lockB, sharedIndex)); + var resultA = await _store.Operations.SendAsync(new PutCompareExchangeValueOperation(key, lockA, sharedIndex), token: TestContext.Current.CancellationToken); + var resultB = await _store.Operations.SendAsync(new PutCompareExchangeValueOperation(key, lockB, sharedIndex), token: TestContext.Current.CancellationToken); // Exactly one succeeds (the one whose request wins the network race) // The other fails because the lock index was bumped by the first @@ -275,14 +259,12 @@ public async Task concurrent_lock_renewal_race_orphans_the_lock() // The FAILING caller simulates what happens in stepDownAsync: // it tries to delete the lock value using its stale sharedIndex // This delete FAILS because the lock value has a new index - var staleDelete = await _store.Operations.SendAsync( - new DeleteCompareExchangeValueOperation(key, sharedIndex)); + var staleDelete = await _store.Operations.SendAsync(new DeleteCompareExchangeValueOperation(key, sharedIndex), token: TestContext.Current.CancellationToken); staleDelete.Successful.ShouldBeFalse(); // === Step 3: Cleanup - delete with actual current index === var currentIndex = resultA.Successful ? resultA.Index : resultB.Index; - var cleanDelete = await _store.Operations.SendAsync( - new DeleteCompareExchangeValueOperation(key, currentIndex)); + var cleanDelete = await _store.Operations.SendAsync(new DeleteCompareExchangeValueOperation(key, currentIndex), token: TestContext.Current.CancellationToken); cleanDelete.Successful.ShouldBeTrue("Cleanup delete succeeds"); } @@ -308,7 +290,7 @@ public async Task concurrent_DoHealthChecksAsync_guard_prevents_spurious_stepdow opts.ServiceName = "race-test"; opts.UseRavenDbPersistence(); opts.UseTcpForControlEndpoint(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = balancedHost.GetRuntime(); await runtime.DoHealthChecksAsync(); diff --git a/src/Persistence/RavenDbTests/message_store_compliance.cs b/src/Persistence/RavenDbTests/message_store_compliance.cs index 0688ec968..6bf22c83a 100644 --- a/src/Persistence/RavenDbTests/message_store_compliance.cs +++ b/src/Persistence/RavenDbTests/message_store_compliance.cs @@ -104,7 +104,7 @@ public async Task marks_envelope_as_having_an_expires_on_mark_handled() await thePersistence.Inbox.MarkIncomingEnvelopeAsHandledAsync(envelope); using var session = _store.OpenAsyncSession(); - var incoming = await session.LoadAsync(envelope.Id.ToString()); + var incoming = await session.LoadAsync(envelope.Id.ToString(), TestContext.Current.CancellationToken); var metadata = session.Advanced.GetMetadataFor(incoming); metadata.TryGetValue("@expires", out var raw).ShouldBeTrue(); @@ -147,8 +147,7 @@ public async Task node_persistence_works_when_store_has_optimistic_concurrency_e }; optimisticStore.Conventions.UseOptimisticConcurrency = true; optimisticStore.Initialize(); - await optimisticStore.Maintenance.Server.SendAsync( - new CreateDatabaseOperation(new DatabaseRecord(optimisticStore.Database))); + await optimisticStore.Maintenance.Server.SendAsync(new CreateDatabaseOperation(new DatabaseRecord(optimisticStore.Database)), TestContext.Current.CancellationToken); var ravenStore = new RavenDbMessageStore(optimisticStore, new WolverineOptions()); diff --git a/src/Persistence/RavenDbTests/message_store_compliance_with_message_identity_using_id_and_destination.cs b/src/Persistence/RavenDbTests/message_store_compliance_with_message_identity_using_id_and_destination.cs index 51955199d..4644c72be 100644 --- a/src/Persistence/RavenDbTests/message_store_compliance_with_message_identity_using_id_and_destination.cs +++ b/src/Persistence/RavenDbTests/message_store_compliance_with_message_identity_using_id_and_destination.cs @@ -55,7 +55,7 @@ public async Task marks_envelope_as_having_an_expires_on_mark_handled() await thePersistence.Inbox.MarkIncomingEnvelopeAsHandledAsync(envelope); using var session = _store.OpenAsyncSession(); - var incoming = await session.LoadAsync(theHost.GetRuntime().Storage.As().IdentityFor(envelope)); + var incoming = await session.LoadAsync(theHost.GetRuntime().Storage.As().IdentityFor(envelope), TestContext.Current.CancellationToken); var metadata = session.Advanced.GetMetadataFor(incoming); metadata.TryGetValue("@expires", out var raw).ShouldBeTrue(); diff --git a/src/Persistence/RavenDbTests/transactional_middleware.cs b/src/Persistence/RavenDbTests/transactional_middleware.cs index b93450fb0..6aed8955a 100644 --- a/src/Persistence/RavenDbTests/transactional_middleware.cs +++ b/src/Persistence/RavenDbTests/transactional_middleware.cs @@ -37,12 +37,12 @@ public async Task use_end_to_end() // Include handlers from this test assembly opts.Discovery.IncludeAssembly(typeof(transactional_middleware).Assembly); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); await host.InvokeAsync(new RecordTeam("Chiefs", 1960)); using var session = store.OpenAsyncSession(); - var team = await session.LoadAsync("Chiefs"); + var team = await session.LoadAsync("Chiefs", TestContext.Current.CancellationToken); team.YearFounded.ShouldBe(1960); } } diff --git a/src/Persistence/SqlServerTests/Agents/control_queue_tests.cs b/src/Persistence/SqlServerTests/Agents/control_queue_tests.cs index bf1aa7b87..9e2a95817 100644 --- a/src/Persistence/SqlServerTests/Agents/control_queue_tests.cs +++ b/src/Persistence/SqlServerTests/Agents/control_queue_tests.cs @@ -64,9 +64,9 @@ private static async Task dropControlSchema() public async Task control_queue_table_should_exist() { using var conn = new SqlConnection(Servers.SqlServerConnectionString); - await conn.OpenAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); - var tables = await conn.ExistingTables("wolverine%"); + var tables = await conn.ExistingTables("wolverine%", ct: TestContext.Current.CancellationToken); await conn.CloseAsync(); tables.ShouldContain(x => x.Name == DatabaseConstants.ControlQueueTableName); diff --git a/src/Persistence/SqlServerTests/DeadLetterTable_index_creation.cs b/src/Persistence/SqlServerTests/DeadLetterTable_index_creation.cs index ba850f2cc..5d31d6b0a 100644 --- a/src/Persistence/SqlServerTests/DeadLetterTable_index_creation.cs +++ b/src/Persistence/SqlServerTests/DeadLetterTable_index_creation.cs @@ -33,7 +33,7 @@ public async ValueTask DisposeAsync() [Fact] public async Task creates_the_replayable_index_and_is_stable_without_expiration() { - await theConnection.ResetSchemaAsync("dlq_idx_no_exp"); + await theConnection.ResetSchemaAsync("dlq_idx_no_exp", ct: TestContext.Current.CancellationToken); var durability = new DurabilitySettings { DeadLetterQueueExpirationEnabled = false }; var table = new DeadLettersTable(durability, "dlq_idx_no_exp"); @@ -41,16 +41,16 @@ public async Task creates_the_replayable_index_and_is_stable_without_expiration( table.Indexes.ShouldContain(x => x.Name.Contains("replayable")); table.Indexes.ShouldNotContain(x => x.Name.Contains("expires")); - await table.ApplyChangesAsync(theConnection); + await table.ApplyChangesAsync(theConnection, ct: TestContext.Current.CancellationToken); - var delta = await table.FindDeltaAsync(theConnection); + var delta = await table.FindDeltaAsync(theConnection, TestContext.Current.CancellationToken); delta.Difference.ShouldBe(SchemaPatchDifference.None); } [Fact] public async Task creates_replayable_and_expires_indexes_and_is_stable_with_expiration() { - await theConnection.ResetSchemaAsync("dlq_idx_exp"); + await theConnection.ResetSchemaAsync("dlq_idx_exp", ct: TestContext.Current.CancellationToken); var durability = new DurabilitySettings { DeadLetterQueueExpirationEnabled = true }; var table = new DeadLettersTable(durability, "dlq_idx_exp"); @@ -58,9 +58,9 @@ public async Task creates_replayable_and_expires_indexes_and_is_stable_with_expi table.Indexes.ShouldContain(x => x.Name.Contains("replayable")); table.Indexes.ShouldContain(x => x.Name.Contains("expires")); - await table.ApplyChangesAsync(theConnection); + await table.ApplyChangesAsync(theConnection, ct: TestContext.Current.CancellationToken); - var delta = await table.FindDeltaAsync(theConnection); + var delta = await table.FindDeltaAsync(theConnection, TestContext.Current.CancellationToken); delta.Difference.ShouldBe(SchemaPatchDifference.None); } } diff --git a/src/Persistence/SqlServerTests/MultiTenancy/static_multi_tenancy.cs b/src/Persistence/SqlServerTests/MultiTenancy/static_multi_tenancy.cs index b13471eec..5a1ca53a4 100644 --- a/src/Persistence/SqlServerTests/MultiTenancy/static_multi_tenancy.cs +++ b/src/Persistence/SqlServerTests/MultiTenancy/static_multi_tenancy.cs @@ -81,7 +81,7 @@ public async Task the_main_database_tables_include_node_persistence() { var store = theHost.Services.GetRequiredService() .ShouldBeOfType(); - var tables = await store.Main.As().SchemaTables(); + var tables = await store.Main.As().SchemaTables(TestContext.Current.CancellationToken); var expected = @" static_multi_tenancy2.blues @@ -119,7 +119,7 @@ public async Task the_tenant_databases_have_only_envelope_and_saga_tables() foreach (var tenantId in new string[] { "red", "blue", "green" }) { var messageStore = await store.Source.FindAsync(tenantId); - var tables = await messageStore.As().SchemaTables(); + var tables = await messageStore.As().SchemaTables(TestContext.Current.CancellationToken); tables.OrderBy(x => x.QualifiedName).Select(x => x.QualifiedName).ToArray() .ShouldBe(expected); diff --git a/src/Persistence/SqlServerTests/Persistence/SqlServerMessageStoreTests.cs b/src/Persistence/SqlServerTests/Persistence/SqlServerMessageStoreTests.cs index 0eca3393c..1a3062f7e 100644 --- a/src/Persistence/SqlServerTests/Persistence/SqlServerMessageStoreTests.cs +++ b/src/Persistence/SqlServerTests/Persistence/SqlServerMessageStoreTests.cs @@ -77,11 +77,11 @@ public async Task delete_expired_handled_envelopes_in_batches() await using (var conn = new SqlConnection(Servers.SqlServerConnectionString)) { - await conn.OpenAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); await conn.CreateCommand( $"update receiver.{DatabaseConstants.IncomingTable} set {DatabaseConstants.KeepUntil} = @cutoff where status = 'Handled'") .With("cutoff", DateTimeOffset.UtcNow.Subtract(1.Hours())) - .ExecuteNonQueryAsync(); + .ExecuteNonQueryAsync(TestContext.Current.CancellationToken); await conn.CloseAsync(); } @@ -174,10 +174,7 @@ public async Task should_reasign_incoming_envelope_to_owner_id() var runtime = theHost.GetRuntime(); - await thePersistence.As().PollForScheduledMessagesAsync(runtime, - NullLogger.Instance, - durabilitySettings, - default); + await thePersistence.As().PollForScheduledMessagesAsync(runtime, NullLogger.Instance, durabilitySettings, TestContext.Current.CancellationToken); var stored = (await thePersistence.Admin.AllIncomingAsync()).Single(); @@ -213,11 +210,11 @@ public async Task delete_old_log_node_records() await theHost.InvokeAsync(new DatabaseOperationBatch(messageDatabase, [log])); using var conn = new SqlConnection(Servers.SqlServerConnectionString); - await conn.OpenAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); await conn.CreateCommand( $"update receiver.{DatabaseConstants.NodeRecordTableName} set timestamp = @time where node_number = 2") .With("time", DateTimeOffset.UtcNow.Subtract(10.Days())) - .ExecuteNonQueryAsync(); + .ExecuteNonQueryAsync(TestContext.Current.CancellationToken); await conn.CloseAsync(); var recent2 = await thePersistence.Nodes.FetchRecentRecordsAsync(100); diff --git a/src/Persistence/SqlServerTests/Persistence/SqlServerMessageStore_DQL_expiration.cs b/src/Persistence/SqlServerTests/Persistence/SqlServerMessageStore_DQL_expiration.cs index cab71c694..51c2f87d4 100644 --- a/src/Persistence/SqlServerTests/Persistence/SqlServerMessageStore_DQL_expiration.cs +++ b/src/Persistence/SqlServerTests/Persistence/SqlServerMessageStore_DQL_expiration.cs @@ -25,14 +25,14 @@ public async Task no_expiration_column_normally() opts.ListenAtPort(2345).UseDurableInbox(); opts.Durability.DeadLetterQueueExpirationEnabled = false; - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); using var conn = new SqlConnection(Servers.SqlServerConnectionString); - await conn.OpenAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); var runtime = host.GetRuntime(); - var dlq = await new DeadLettersTable(runtime.Options.Durability, "target").FetchExistingAsync(conn); + var dlq = await new DeadLettersTable(runtime.Options.Durability, "target").FetchExistingAsync(conn, TestContext.Current.CancellationToken); dlq!.ColumnFor(DatabaseConstants.Expires).ShouldBeNull(); } @@ -46,14 +46,14 @@ public async Task add_expiration_time_column_if_DLQ_expiration_is_enabled() opts.ListenAtPort(2345).UseDurableInbox(); opts.Durability.DeadLetterQueueExpirationEnabled = true; - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); using var conn = new SqlConnection(Servers.SqlServerConnectionString); - await conn.OpenAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); var runtime = host.GetRuntime(); - var dlq = await new DeadLettersTable(runtime.Options.Durability, "dlq_expiration").FetchExistingAsync(conn); + var dlq = await new DeadLettersTable(runtime.Options.Durability, "dlq_expiration").FetchExistingAsync(conn, TestContext.Current.CancellationToken); var column = dlq!.ColumnFor(DatabaseConstants.Expires); column.ShouldNotBeNull(); column.AllowNulls.ShouldBeTrue(); diff --git a/src/Persistence/SqlServerTests/Persistence/SqlServerMessageStore_with_IdAndDestination_Identity.cs b/src/Persistence/SqlServerTests/Persistence/SqlServerMessageStore_with_IdAndDestination_Identity.cs index e54165951..8f8f428d1 100644 --- a/src/Persistence/SqlServerTests/Persistence/SqlServerMessageStore_with_IdAndDestination_Identity.cs +++ b/src/Persistence/SqlServerTests/Persistence/SqlServerMessageStore_with_IdAndDestination_Identity.cs @@ -54,15 +54,15 @@ public override async Task BuildCleanHost() public async Task should_have_receive_at_in_primary_keys() { using var conn = new SqlConnection(Servers.SqlServerConnectionString); - await conn.OpenAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); var runtime = theHost.GetRuntime(); - var incoming = await new IncomingEnvelopeTable(runtime.Options.Durability, "receiver2").FetchExistingAsync(conn); + var incoming = await new IncomingEnvelopeTable(runtime.Options.Durability, "receiver2").FetchExistingAsync(conn, TestContext.Current.CancellationToken); incoming!.PrimaryKeyColumns.ShouldContain(DatabaseConstants.Id); incoming.PrimaryKeyColumns.ShouldContain(DatabaseConstants.ReceivedAt); - var dlq = await new DeadLettersTable(runtime.Options.Durability, "receiver2").FetchExistingAsync(conn); + var dlq = await new DeadLettersTable(runtime.Options.Durability, "receiver2").FetchExistingAsync(conn, TestContext.Current.CancellationToken); dlq!.PrimaryKeyColumns.ShouldContain(DatabaseConstants.Id); dlq.PrimaryKeyColumns.ShouldContain(DatabaseConstants.ReceivedAt); } @@ -170,10 +170,7 @@ public async Task should_reasign_incoming_envelope_to_owner_id() var runtime = theHost.GetRuntime(); - await thePersistence.As().PollForScheduledMessagesAsync(runtime, - NullLogger.Instance, - durabilitySettings, - default); + await thePersistence.As().PollForScheduledMessagesAsync(runtime, NullLogger.Instance, durabilitySettings, TestContext.Current.CancellationToken); var stored = (await thePersistence.Admin.AllIncomingAsync()).Single(); diff --git a/src/Persistence/SqlServerTests/Sagas/configuring_saga_table_storage.cs b/src/Persistence/SqlServerTests/Sagas/configuring_saga_table_storage.cs index 4d304e0d1..f27c302a8 100644 --- a/src/Persistence/SqlServerTests/Sagas/configuring_saga_table_storage.cs +++ b/src/Persistence/SqlServerTests/Sagas/configuring_saga_table_storage.cs @@ -29,14 +29,14 @@ public async Task add_tables_to_persistence() opts.PersistMessagesWithSqlServer(Servers.SqlServerConnectionString, "color_sagas"); opts.Services.AddResourceSetupOnStartup(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); #endregion await using var conn = new SqlConnection(Servers.SqlServerConnectionString); - await conn.OpenAsync(); - (await new Table(new DbObjectName("color_sagas", "red")).ExistsInDatabaseAsync(conn)).ShouldBeTrue(); - (await new Table(new DbObjectName("color_sagas", "blue")).ExistsInDatabaseAsync(conn)).ShouldBeTrue(); + await conn.OpenAsync(TestContext.Current.CancellationToken); + (await new Table(new DbObjectName("color_sagas", "red")).ExistsInDatabaseAsync(conn, TestContext.Current.CancellationToken)).ShouldBeTrue(); + (await new Table(new DbObjectName("color_sagas", "blue")).ExistsInDatabaseAsync(conn, TestContext.Current.CancellationToken)).ShouldBeTrue(); } private static async Task dropSchemaAsync() diff --git a/src/Persistence/SqlServerTests/Sagas/order_saga_example.cs b/src/Persistence/SqlServerTests/Sagas/order_saga_example.cs index 3b2a0e5ff..caa903569 100644 --- a/src/Persistence/SqlServerTests/Sagas/order_saga_example.cs +++ b/src/Persistence/SqlServerTests/Sagas/order_saga_example.cs @@ -17,7 +17,7 @@ public async Task try_out_codegen() .UseWolverine(opts => { opts.PersistMessagesWithSqlServer(Servers.SqlServerConnectionString, "order_saga"); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); await host.InvokeMessageAndWaitAsync(new StartOrder(Guid.NewGuid().ToString(), DateTime.UtcNow)); } diff --git a/src/Persistence/SqlServerTests/Sagas/saga_storage_operations.cs b/src/Persistence/SqlServerTests/Sagas/saga_storage_operations.cs index f4d3b1098..77275a22c 100644 --- a/src/Persistence/SqlServerTests/Sagas/saga_storage_operations.cs +++ b/src/Persistence/SqlServerTests/Sagas/saga_storage_operations.cs @@ -29,9 +29,9 @@ public saga_storage_operations() public async Task load_with_no_document_happily_returns_null() { await using var conn = new SqlConnection(Servers.SqlServerConnectionString); - await conn.OpenAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); - using var tx = await conn.BeginTransactionAsync(); + using var tx = await conn.BeginTransactionAsync(TestContext.Current.CancellationToken); var saga = await _theSchema.LoadAsync(Guid.NewGuid(), tx, CancellationToken.None); saga.ShouldBeNull(); @@ -41,8 +41,8 @@ public async Task load_with_no_document_happily_returns_null() public async Task get_an_argument_out_of_range_exception_for_missing_id() { await using var conn = new SqlConnection(Servers.SqlServerConnectionString); - await conn.OpenAsync(); - await using var db = await conn.BeginTransactionAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); + await using var db = await conn.BeginTransactionAsync(TestContext.Current.CancellationToken); var saga = new LightweightSaga { @@ -60,8 +60,8 @@ await Should.ThrowAsync(async () => public async Task insert_then_load() { await using var conn = new SqlConnection(Servers.SqlServerConnectionString); - await conn.OpenAsync(); - await using var db = await conn.BeginTransactionAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); + await using var db = await conn.BeginTransactionAsync(TestContext.Current.CancellationToken); var saga = new LightweightSaga { @@ -70,9 +70,9 @@ public async Task insert_then_load() }; await _theSchema.InsertAsync(saga, db, CancellationToken.None); - await db.CommitAsync(); + await db.CommitAsync(TestContext.Current.CancellationToken); - using var db2 = await conn.BeginTransactionAsync(); + using var db2 = await conn.BeginTransactionAsync(TestContext.Current.CancellationToken); var saga2 = await _theSchema.LoadAsync(saga.Id, db2, CancellationToken.None); saga2!.Name.ShouldBe("Xavier Worthy"); @@ -82,8 +82,8 @@ public async Task insert_then_load() public async Task insert_update_then_load() { await using var conn = new SqlConnection(Servers.SqlServerConnectionString); - await conn.OpenAsync(); - await using var db = await conn.BeginTransactionAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); + await using var db = await conn.BeginTransactionAsync(TestContext.Current.CancellationToken); var saga = new LightweightSaga { @@ -95,9 +95,9 @@ public async Task insert_update_then_load() saga.Name = "Hollywood Brown"; await _theSchema.UpdateAsync(saga, db, CancellationToken.None); - await db.CommitAsync(); + await db.CommitAsync(TestContext.Current.CancellationToken); - using var db2 = await conn.BeginTransactionAsync(); + using var db2 = await conn.BeginTransactionAsync(TestContext.Current.CancellationToken); var saga2 = await _theSchema.LoadAsync(saga.Id, db2, CancellationToken.None); saga2!.Name.ShouldBe("Hollywood Brown"); @@ -107,8 +107,8 @@ public async Task insert_update_then_load() public async Task insert_then_delete() { await using var conn = new SqlConnection(Servers.SqlServerConnectionString); - await conn.OpenAsync(); - await using var db = await conn.BeginTransactionAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); + await using var db = await conn.BeginTransactionAsync(TestContext.Current.CancellationToken); var saga = new LightweightSaga { @@ -119,9 +119,9 @@ public async Task insert_then_delete() await _theSchema.InsertAsync(saga, db, CancellationToken.None); await _theSchema.DeleteAsync(saga, db, CancellationToken.None); - await db.CommitAsync(); + await db.CommitAsync(TestContext.Current.CancellationToken); - using var db2 = await conn.BeginTransactionAsync(); + using var db2 = await conn.BeginTransactionAsync(TestContext.Current.CancellationToken); var saga2 = await _theSchema.LoadAsync(saga.Id, db2, CancellationToken.None); saga2.ShouldBeNull(); } @@ -130,12 +130,12 @@ public async Task insert_then_delete() public async Task concurrency_exception_when_version_does_not_match() { await using var conn = new SqlConnection(Servers.SqlServerConnectionString); - await conn.OpenAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); await conn.CreateCommand("delete from lightweight_sagas.lightweightsaga_saga") - .ExecuteNonQueryAsync(); + .ExecuteNonQueryAsync(TestContext.Current.CancellationToken); - await using var db = await conn.BeginTransactionAsync(); + await using var db = await conn.BeginTransactionAsync(TestContext.Current.CancellationToken); var saga = new LightweightSaga { diff --git a/src/Persistence/SqlServerTests/Sagas/string_identity_schema_configuration.cs b/src/Persistence/SqlServerTests/Sagas/string_identity_schema_configuration.cs index 6dec828e6..9431e5803 100644 --- a/src/Persistence/SqlServerTests/Sagas/string_identity_schema_configuration.cs +++ b/src/Persistence/SqlServerTests/Sagas/string_identity_schema_configuration.cs @@ -60,14 +60,14 @@ public void sql_server_saga_schema_can_opt_into_nvarchar_for_string_ids() public async Task can_create_nvarchar_table_and_delta_is_none() { await using var conn = new SqlConnection(Servers.SqlServerConnectionString); - await conn.OpenAsync(); - await conn.DropSchemaAsync("string_sagas"); + await conn.OpenAsync(TestContext.Current.CancellationToken); + await conn.DropSchemaAsync("string_sagas", ct: TestContext.Current.CancellationToken); var table = BuildSchema(useNVarCharForStringId: true).Table.ShouldBeOfType(); await table.MigrateAsync(conn); - var delta = await table.FindDeltaAsync(conn); + var delta = await table.FindDeltaAsync(conn, TestContext.Current.CancellationToken); delta.Difference.ShouldBe(SchemaPatchDifference.None); } @@ -75,14 +75,14 @@ public async Task can_create_nvarchar_table_and_delta_is_none() public async Task can_migrate_varchar_to_nvarchar_and_delta_is_none() { await using var conn = new SqlConnection(Servers.SqlServerConnectionString); - await conn.OpenAsync(); - await conn.DropSchemaAsync("string_sagas"); + await conn.OpenAsync(TestContext.Current.CancellationToken); + await conn.DropSchemaAsync("string_sagas", ct: TestContext.Current.CancellationToken); // Step 1: create with default varchar(100) var varcharTable = BuildSchema(useNVarCharForStringId: false).Table.ShouldBeOfType
(); await varcharTable.MigrateAsync(conn); - var initialDelta = await varcharTable.FindDeltaAsync(conn); + var initialDelta = await varcharTable.FindDeltaAsync(conn, TestContext.Current.CancellationToken); initialDelta.Difference.ShouldBe(SchemaPatchDifference.None); // Step 2: switch to nvarchar(100) and migrate @@ -90,7 +90,7 @@ public async Task can_migrate_varchar_to_nvarchar_and_delta_is_none() await nvarcharTable.MigrateAsync(conn); // Step 3: verify no remaining delta - var finalDelta = await nvarcharTable.FindDeltaAsync(conn); + var finalDelta = await nvarcharTable.FindDeltaAsync(conn, TestContext.Current.CancellationToken); finalDelta.Difference.ShouldBe(SchemaPatchDifference.None); } diff --git a/src/Persistence/SqlServerTests/SqlServerTests.csproj b/src/Persistence/SqlServerTests/SqlServerTests.csproj index ae874df2e..23ce702cb 100644 --- a/src/Persistence/SqlServerTests/SqlServerTests.csproj +++ b/src/Persistence/SqlServerTests/SqlServerTests.csproj @@ -1,6 +1,8 @@ + + true Exe false true diff --git a/src/Persistence/SqlServerTests/Transport/NServiceBus/nsb_dedicated_database_multitenancy.cs b/src/Persistence/SqlServerTests/Transport/NServiceBus/nsb_dedicated_database_multitenancy.cs index b5d896b6b..b7f7f7cdb 100644 --- a/src/Persistence/SqlServerTests/Transport/NServiceBus/nsb_dedicated_database_multitenancy.cs +++ b/src/Persistence/SqlServerTests/Transport/NServiceBus/nsb_dedicated_database_multitenancy.cs @@ -76,7 +76,7 @@ await _host.MessageBus().PublishAsync(new ReproPing(Guid.NewGuid()), for (var i = 0; i < 40 && dedicated == 0; i++) { dedicated = await RowCount(_dedicatedCs, _queue); - if (dedicated == 0) await Task.Delay(100); + if (dedicated == 0) await Task.Delay(100, TestContext.Current.CancellationToken); } dedicated.ShouldBe(1); diff --git a/src/Persistence/SqlServerTests/Transport/external_message_tables.cs b/src/Persistence/SqlServerTests/Transport/external_message_tables.cs index e61f164dd..589b7927f 100644 --- a/src/Persistence/SqlServerTests/Transport/external_message_tables.cs +++ b/src/Persistence/SqlServerTests/Transport/external_message_tables.cs @@ -46,7 +46,7 @@ public async Task can_create_basic_table() .UseWolverine(opts => { opts.UseSqlServerPersistenceAndTransport(Servers.SqlServerConnectionString, "outside"); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var storage = host.Services.GetRequiredService() .As(); @@ -58,11 +58,11 @@ public async Task can_create_basic_table() using var conn = new SqlConnection(Servers.SqlServerConnectionString); - await conn.OpenAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); await table.MigrateAsync(conn); - var delta = await table.FindDeltaAsync(conn); + var delta = await table.FindDeltaAsync(conn, TestContext.Current.CancellationToken); delta.Difference.ShouldBe(SchemaPatchDifference.None); @@ -81,7 +81,7 @@ public async Task can_create_basic_table_with_message_type() .UseWolverine(opts => { opts.UseSqlServerPersistenceAndTransport(Servers.SqlServerConnectionString, "outside"); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var storage = host.Services.GetRequiredService() .As(); @@ -93,11 +93,11 @@ public async Task can_create_basic_table_with_message_type() using var conn = new SqlConnection(Servers.SqlServerConnectionString); - await conn.OpenAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); await table.MigrateAsync(conn); - var delta = await table.FindDeltaAsync(conn); + var delta = await table.FindDeltaAsync(conn, TestContext.Current.CancellationToken); delta.Difference.ShouldBe(SchemaPatchDifference.None); @@ -117,7 +117,7 @@ public async Task end_to_end_default_message_type() table.PollingInterval = 1.Seconds(); }); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var tracked = await host .TrackActivity() @@ -144,7 +144,7 @@ public async Task end_to_end_default_variable_message_types() table.PollingInterval = 1.Seconds(); }); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var tracked = await host.TrackActivity().Timeout(1.Minutes()).WaitForMessageToBeReceivedAt(host).ExecuteAndWaitAsync( _ => host.SendMessageThroughExternalTable("outgoing.incoming1", new Message2())); @@ -171,7 +171,7 @@ public async Task end_to_end_default_variable_message_types_customize_table_in_e table.PollingInterval = 1.Seconds(); }); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var tracked = await host.TrackActivity().Timeout(1.Minutes()).WaitForMessageToBeReceivedAt(host).ExecuteAndWaitAsync( _ => host.SendMessageThroughExternalTable("outside.incoming1", new Message2())); diff --git a/src/Persistence/SqlServerTests/Transport/stateful_resource_smoke_tests.cs b/src/Persistence/SqlServerTests/Transport/stateful_resource_smoke_tests.cs index dc70ea683..04ba88d2a 100644 --- a/src/Persistence/SqlServerTests/Transport/stateful_resource_smoke_tests.cs +++ b/src/Persistence/SqlServerTests/Transport/stateful_resource_smoke_tests.cs @@ -92,8 +92,8 @@ public async Task check_positive() public async Task check_negative() { using var conn = new SqlConnection(Servers.SqlServerConnectionString); - await conn.OpenAsync(); - await conn.DropSchemaAsync("sqlserver"); + await conn.OpenAsync(TestContext.Current.CancellationToken); + await conn.DropSchemaAsync("sqlserver", ct: TestContext.Current.CancellationToken); await conn.CloseAsync(); var result = await ConfigureBuilder(false, 10) diff --git a/src/Persistence/SqlServerTests/Transport/transport_perf_benchmark.cs b/src/Persistence/SqlServerTests/Transport/transport_perf_benchmark.cs index f79107e90..78396f5c0 100644 --- a/src/Persistence/SqlServerTests/Transport/transport_perf_benchmark.cs +++ b/src/Persistence/SqlServerTests/Transport/transport_perf_benchmark.cs @@ -69,8 +69,8 @@ public async Task verify_optimized_schema_provisions_and_roundtrips() const string schema = "benchopt"; await using (var conn = new SqlConnection(ConnString)) { - await conn.OpenAsync(); - await conn.DropSchemaAsync(schema); + await conn.OpenAsync(TestContext.Current.CancellationToken); + await conn.DropSchemaAsync(schema, ct: TestContext.Current.CancellationToken); } var transport = new Wolverine.SqlServer.Transport.SqlServerTransport(new Wolverine.RDBMS.DatabaseSettings @@ -90,13 +90,13 @@ public async Task verify_optimized_schema_provisions_and_roundtrips() // Clustered index must be on seq, not the id PK. await using (var conn = new SqlConnection(ConnString)) { - await conn.OpenAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); var clusteredCol = (string?)await conn.CreateCommand( $@"select c.name from sys.indexes i join sys.index_columns ic on i.object_id=ic.object_id and i.index_id=ic.index_id join sys.columns c on ic.object_id=c.object_id and ic.column_id=c.column_id where i.object_id = object_id('{schema}.wolverine_queue_verify') and i.type_desc='CLUSTERED'") - .ExecuteScalarAsync(); + .ExecuteScalarAsync(TestContext.Current.CancellationToken); clusteredCol.ShouldBe("seq"); } @@ -117,7 +117,7 @@ public async Task verify_optimized_schema_provisions_and_roundtrips() public async Task run() { await using var conn = new SqlConnection(ConnString); - await conn.OpenAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); foreach (var v in Variants()) { @@ -132,7 +132,7 @@ public async Task run() { await using var cmd = conn.CreateCommand(insertSql).With("id", Guid.NewGuid()).With("body", body); cmd.CommandTimeout = 120; - await cmd.ExecuteNonQueryAsync(); + await cmd.ExecuteNonQueryAsync(TestContext.Current.CancellationToken); } sw.Stop(); var insertRate = InsertCount / sw.Elapsed.TotalSeconds; diff --git a/src/Persistence/SqlServerTests/bumping_stale_inbox_messages.cs b/src/Persistence/SqlServerTests/bumping_stale_inbox_messages.cs index 8b79e487b..07fe944dc 100644 --- a/src/Persistence/SqlServerTests/bumping_stale_inbox_messages.cs +++ b/src/Persistence/SqlServerTests/bumping_stale_inbox_messages.cs @@ -42,9 +42,9 @@ public async ValueTask DisposeAsync() public async Task got_the_right_column() { using var conn = new SqlConnection(Servers.SqlServerConnectionString); - await conn.OpenAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); - var table = await new Table(new DbObjectName("stale_outbox", DatabaseConstants.IncomingTable)).FetchExistingAsync(conn); + var table = await new Table(new DbObjectName("stale_outbox", DatabaseConstants.IncomingTable)).FetchExistingAsync(conn, TestContext.Current.CancellationToken); table!.HasColumn(DatabaseConstants.Timestamp).ShouldBeTrue(); @@ -76,21 +76,21 @@ public async Task using_the_operation() await messageStore.Inbox.StoreIncomingAsync(envelope5); using var conn = new SqlConnection(Servers.SqlServerConnectionString); - await conn.OpenAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); await conn.CreateCommand("update stale_outbox.wolverine_incoming_envelopes set timestamp = @time where id = @id") .With("time", DateTimeOffset.UtcNow.Subtract(2.Hours())) .With("id", envelope1.Id) - .ExecuteNonQueryAsync(); + .ExecuteNonQueryAsync(TestContext.Current.CancellationToken); await conn.CreateCommand("update stale_outbox.wolverine_incoming_envelopes set timestamp = @time where id = @id") .With("time", DateTimeOffset.UtcNow.Subtract(2.Hours())) .With("id", envelope3.Id) - .ExecuteNonQueryAsync(); + .ExecuteNonQueryAsync(TestContext.Current.CancellationToken); await conn.CreateCommand("update stale_outbox.wolverine_incoming_envelopes set timestamp = @time where id = @id") .With("time", DateTimeOffset.UtcNow.Subtract(2.Hours())) .With("id", envelope5.Id) - .ExecuteNonQueryAsync(); + .ExecuteNonQueryAsync(TestContext.Current.CancellationToken); var envelopesBefore = await messageStore.Admin.AllIncomingAsync(); envelopesBefore.Count(x => x.OwnerId == 0).ShouldBe(0); diff --git a/src/Persistence/SqlServerTests/bumping_stale_outbox_messages.cs b/src/Persistence/SqlServerTests/bumping_stale_outbox_messages.cs index e7bace575..0d5b2e077 100644 --- a/src/Persistence/SqlServerTests/bumping_stale_outbox_messages.cs +++ b/src/Persistence/SqlServerTests/bumping_stale_outbox_messages.cs @@ -42,9 +42,9 @@ public async ValueTask DisposeAsync() public async Task got_the_right_column() { using var conn = new SqlConnection(Servers.SqlServerConnectionString); - await conn.OpenAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); - var table = await new Table(new DbObjectName("stale_outbox", DatabaseConstants.OutgoingTable)).FetchExistingAsync(conn); + var table = await new Table(new DbObjectName("stale_outbox", DatabaseConstants.OutgoingTable)).FetchExistingAsync(conn, TestContext.Current.CancellationToken); table!.HasColumn(DatabaseConstants.Timestamp).ShouldBeTrue(); @@ -76,21 +76,21 @@ public async Task using_the_operation() await messageStore.Outbox.StoreOutgoingAsync(envelope5, 3); using var conn = new SqlConnection(Servers.SqlServerConnectionString); - await conn.OpenAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); await conn.CreateCommand("update stale_outbox.wolverine_outgoing_envelopes set \"timestamp\" = @time where id = @id") .With("time", DateTimeOffset.UtcNow.Subtract(2.Hours())) .With("id", envelope1.Id) - .ExecuteNonQueryAsync(); + .ExecuteNonQueryAsync(TestContext.Current.CancellationToken); await conn.CreateCommand("update stale_outbox.wolverine_outgoing_envelopes set \"timestamp\" = @time where id = @id") .With("time", DateTimeOffset.UtcNow.Subtract(2.Hours())) .With("id", envelope3.Id) - .ExecuteNonQueryAsync(); + .ExecuteNonQueryAsync(TestContext.Current.CancellationToken); await conn.CreateCommand("update stale_outbox.wolverine_outgoing_envelopes set \"timestamp\" = @time where id = @id") .With("time", DateTimeOffset.UtcNow.Subtract(2.Hours())) .With("id", envelope5.Id) - .ExecuteNonQueryAsync(); + .ExecuteNonQueryAsync(TestContext.Current.CancellationToken); var envelopesBefore = await messageStore.Admin.AllOutgoingAsync(); envelopesBefore.Count(x => x.OwnerId == 0).ShouldBe(0); diff --git a/src/Persistence/SqlServerTests/master_table_tenancy_dynamic_lifecycle.cs b/src/Persistence/SqlServerTests/master_table_tenancy_dynamic_lifecycle.cs index a31f5f2aa..03bdb770d 100644 --- a/src/Persistence/SqlServerTests/master_table_tenancy_dynamic_lifecycle.cs +++ b/src/Persistence/SqlServerTests/master_table_tenancy_dynamic_lifecycle.cs @@ -41,7 +41,7 @@ public async Task dynamic_tenant_lifecycle_round_trip() opts.PersistMessagesWithSqlServer(Servers.SqlServerConnectionString, "mt_lifecycle_3023") .UseMasterTableTenancy(_ => { }); opts.Services.AddResourceSetupOnStartup(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var source = host.Services.GetServices>() .OfType().Single(); diff --git a/src/Persistence/SqlServerTests/message_store_initialization_and_configuration.cs b/src/Persistence/SqlServerTests/message_store_initialization_and_configuration.cs index 522d0484e..6067dda9b 100644 --- a/src/Persistence/SqlServerTests/message_store_initialization_and_configuration.cs +++ b/src/Persistence/SqlServerTests/message_store_initialization_and_configuration.cs @@ -63,9 +63,9 @@ public void main_store_role() public async Task builds_the_node_and_control_queue_tables() { using var conn = new SqlConnection(Servers.SqlServerConnectionString); - await conn.OpenAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); - var tables = await conn.ExistingTables("wolverine%" ); + var tables = await conn.ExistingTables("wolverine%", ct: TestContext.Current.CancellationToken); await conn.CloseAsync(); tables.ShouldContain(x => x.Name == DatabaseConstants.NodeTableName); @@ -102,7 +102,7 @@ public async Task stores_the_current_node_on_startup() [Fact] public async Task deletes_the_node_on_shutdown() { - await _host.StopAsync(); + await _host.StopAsync(TestContext.Current.CancellationToken); _host.Dispose(); _host = null!; diff --git a/src/Persistence/SqlServerTests/rate_limiting_storage.cs b/src/Persistence/SqlServerTests/rate_limiting_storage.cs index 48ea09236..401867406 100644 --- a/src/Persistence/SqlServerTests/rate_limiting_storage.cs +++ b/src/Persistence/SqlServerTests/rate_limiting_storage.cs @@ -88,7 +88,7 @@ private static async Task waitForSqlServerAsync() public async Task creates_rate_limit_table_on_startup() { using var conn = new SqlConnection(Servers.SqlServerConnectionString); - await conn.OpenAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); await using var cmd = conn.CreateCommand(); cmd.CommandText = "SELECT table_schema, table_name FROM information_schema.tables WHERE table_schema = @schema AND table_name = @name"; @@ -96,9 +96,9 @@ public async Task creates_rate_limit_table_on_startup() cmd.Parameters.Add(new SqlParameter("@name", "wolverine_rate_limits")); var found = false; - await using (var reader = await cmd.ExecuteReaderAsync()) + await using (var reader = await cmd.ExecuteReaderAsync(TestContext.Current.CancellationToken)) { - if (await reader.ReadAsync()) + if (await reader.ReadAsync(TestContext.Current.CancellationToken)) { found = true; } diff --git a/src/Persistence/SqlServerTests/using_default_message_schema_name.cs b/src/Persistence/SqlServerTests/using_default_message_schema_name.cs index 9a1e05cd0..4a409ee01 100644 --- a/src/Persistence/SqlServerTests/using_default_message_schema_name.cs +++ b/src/Persistence/SqlServerTests/using_default_message_schema_name.cs @@ -22,7 +22,7 @@ public async Task use_default_schema_name_when_specified_for_connection_string() opts.PersistMessagesWithSqlServer(Servers.SqlServerConnectionString); opts.Services.AddResourceSetupOnStartup(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var store = host.Services.GetRequiredService(); store.ShouldBeOfType().Settings.SchemaName.ShouldBe("wolverine_default"); @@ -38,7 +38,7 @@ public async Task override_the_storage_schema() opts.PersistMessagesWithSqlServer(Servers.SqlServerConnectionString, "non_default"); opts.Services.AddResourceSetupOnStartup(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var store = host.Services.GetRequiredService(); store.ShouldBeOfType().Settings.SchemaName.ShouldBe("non_default"); diff --git a/src/Persistence/SqliteTests/Bug_2680_message_identity_id_and_destination_emits_invalid_ddl.cs b/src/Persistence/SqliteTests/Bug_2680_message_identity_id_and_destination_emits_invalid_ddl.cs index 368353f0e..d2315487f 100644 --- a/src/Persistence/SqliteTests/Bug_2680_message_identity_id_and_destination_emits_invalid_ddl.cs +++ b/src/Persistence/SqliteTests/Bug_2680_message_identity_id_and_destination_emits_invalid_ddl.cs @@ -75,12 +75,12 @@ public async Task host_starts_and_creates_inbox_table_with_composite_primary_key opts.PersistMessagesWithSqlite(_database.ConnectionString); opts.Services.AddResourceSetupOnStartup(); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); await using var connection = new SqliteConnection(_database.ConnectionString); - await connection.OpenAsync(); + await connection.OpenAsync(TestContext.Current.CancellationToken); - var tables = await connection.ExistingTablesAsync(schemas: ["main"]); + var tables = await connection.ExistingTablesAsync(schemas: ["main"], ct: TestContext.Current.CancellationToken); tables.ShouldContain( x => string.Equals(x.Name, DatabaseConstants.IncomingTable, StringComparison.OrdinalIgnoreCase), $"{DatabaseConstants.IncomingTable} must exist after host startup; pre-fix the migration aborts and the table is never created."); @@ -93,9 +93,9 @@ public async Task host_starts_and_creates_inbox_table_with_composite_primary_key pragma.CommandText = $"PRAGMA table_info({DatabaseConstants.IncomingTable});"; var pkColumns = new List(); - await using (var reader = await pragma.ExecuteReaderAsync()) + await using (var reader = await pragma.ExecuteReaderAsync(TestContext.Current.CancellationToken)) { - while (await reader.ReadAsync()) + while (await reader.ReadAsync(TestContext.Current.CancellationToken)) { var columnName = reader.GetString(1); var pk = reader.GetInt32(5); diff --git a/src/Persistence/SqliteTests/Bug_3071_sqlite_dlq_expiration_creates_expires_column.cs b/src/Persistence/SqliteTests/Bug_3071_sqlite_dlq_expiration_creates_expires_column.cs index 92e906465..c71978f17 100644 --- a/src/Persistence/SqliteTests/Bug_3071_sqlite_dlq_expiration_creates_expires_column.cs +++ b/src/Persistence/SqliteTests/Bug_3071_sqlite_dlq_expiration_creates_expires_column.cs @@ -73,12 +73,12 @@ public async Task dlq_table_has_expires_column_when_expiration_is_enabled() opts.Durability.DeadLetterQueueExpirationEnabled = true; opts.Services.AddResourceSetupOnStartup(); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); await using var connection = new SqliteConnection(_database.ConnectionString); - await connection.OpenAsync(); + await connection.OpenAsync(TestContext.Current.CancellationToken); - var tables = await connection.ExistingTablesAsync(schemas: ["main"]); + var tables = await connection.ExistingTablesAsync(schemas: ["main"], ct: TestContext.Current.CancellationToken); tables.ShouldContain( x => string.Equals(x.Name, DatabaseConstants.DeadLetterTable, StringComparison.OrdinalIgnoreCase), $"{DatabaseConstants.DeadLetterTable} must exist after host startup with DeadLetterQueueExpirationEnabled."); @@ -109,10 +109,10 @@ public async Task dlq_table_has_no_expires_column_when_expiration_is_disabled() opts.Durability.DeadLetterQueueExpirationEnabled = false; opts.Services.AddResourceSetupOnStartup(); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); await using var connection = new SqliteConnection(_database.ConnectionString); - await connection.OpenAsync(); + await connection.OpenAsync(TestContext.Current.CancellationToken); var columns = await GetColumnNamesAsync(connection, DatabaseConstants.DeadLetterTable); columns.ShouldNotContain(DatabaseConstants.Expires); diff --git a/src/Persistence/SqliteTests/DeadLetterTable_index_creation.cs b/src/Persistence/SqliteTests/DeadLetterTable_index_creation.cs index 865fa11f1..8ef0525f8 100644 --- a/src/Persistence/SqliteTests/DeadLetterTable_index_creation.cs +++ b/src/Persistence/SqliteTests/DeadLetterTable_index_creation.cs @@ -40,9 +40,9 @@ public async Task creates_the_replayable_index_and_is_stable_without_expiration( table.Indexes.ShouldContain(x => x.Name.Contains("replayable")); table.Indexes.ShouldNotContain(x => x.Name.Contains("expires")); - await table.ApplyChangesAsync(theConnection); + await table.ApplyChangesAsync(theConnection, ct: TestContext.Current.CancellationToken); - var delta = await table.FindDeltaAsync(theConnection); + var delta = await table.FindDeltaAsync(theConnection, TestContext.Current.CancellationToken); delta.Difference.ShouldBe(SchemaPatchDifference.None); } @@ -55,9 +55,9 @@ public async Task creates_replayable_and_expires_indexes_and_is_stable_with_expi table.Indexes.ShouldContain(x => x.Name.Contains("replayable")); table.Indexes.ShouldContain(x => x.Name.Contains("expires")); - await table.ApplyChangesAsync(theConnection); + await table.ApplyChangesAsync(theConnection, ct: TestContext.Current.CancellationToken); - var delta = await table.FindDeltaAsync(theConnection); + var delta = await table.FindDeltaAsync(theConnection, TestContext.Current.CancellationToken); delta.Difference.ShouldBe(SchemaPatchDifference.None); } } diff --git a/src/Persistence/SqliteTests/Sagas/saga_storage_operations.cs b/src/Persistence/SqliteTests/Sagas/saga_storage_operations.cs index 2ba1cf0e8..478b6f90f 100644 --- a/src/Persistence/SqliteTests/Sagas/saga_storage_operations.cs +++ b/src/Persistence/SqliteTests/Sagas/saga_storage_operations.cs @@ -55,9 +55,9 @@ public ValueTask DisposeAsync() [Fact] public async Task load_with_no_document_happily_returns_null() { - await using var conn = await _dataSource.OpenConnectionAsync(); + await using var conn = await _dataSource.OpenConnectionAsync(TestContext.Current.CancellationToken); - using var tx = await conn.BeginTransactionAsync(); + using var tx = await conn.BeginTransactionAsync(TestContext.Current.CancellationToken); var saga = await _theSchema.LoadAsync(Guid.NewGuid(), tx, CancellationToken.None); saga.ShouldBeNull(); @@ -66,8 +66,8 @@ public async Task load_with_no_document_happily_returns_null() [Fact] public async Task get_an_invalid_operation_exception_for_missing_id() { - await using var conn = await _dataSource.OpenConnectionAsync(); - await using var db = await conn.BeginTransactionAsync(); + await using var conn = await _dataSource.OpenConnectionAsync(TestContext.Current.CancellationToken); + await using var db = await conn.BeginTransactionAsync(TestContext.Current.CancellationToken); var saga = new LightweightSaga { @@ -84,8 +84,8 @@ await Should.ThrowAsync(async () => [Fact] public async Task insert_then_load() { - await using var conn = await _dataSource.OpenConnectionAsync(); - await using var db = await conn.BeginTransactionAsync(); + await using var conn = await _dataSource.OpenConnectionAsync(TestContext.Current.CancellationToken); + await using var db = await conn.BeginTransactionAsync(TestContext.Current.CancellationToken); var saga = new LightweightSaga { @@ -94,9 +94,9 @@ public async Task insert_then_load() }; await _theSchema.InsertAsync(saga, db, CancellationToken.None); - await db.CommitAsync(); + await db.CommitAsync(TestContext.Current.CancellationToken); - using var db2 = await conn.BeginTransactionAsync(); + using var db2 = await conn.BeginTransactionAsync(TestContext.Current.CancellationToken); var saga2 = await _theSchema.LoadAsync(saga.Id, db2, CancellationToken.None); saga2!.Name.ShouldBe("Xavier Worthy"); @@ -105,8 +105,8 @@ public async Task insert_then_load() [Fact] public async Task insert_update_then_load() { - await using var conn = await _dataSource.OpenConnectionAsync(); - await using var db = await conn.BeginTransactionAsync(); + await using var conn = await _dataSource.OpenConnectionAsync(TestContext.Current.CancellationToken); + await using var db = await conn.BeginTransactionAsync(TestContext.Current.CancellationToken); var saga = new LightweightSaga { @@ -118,9 +118,9 @@ public async Task insert_update_then_load() saga.Name = "Hollywood Brown"; await _theSchema.UpdateAsync(saga, db, CancellationToken.None); - await db.CommitAsync(); + await db.CommitAsync(TestContext.Current.CancellationToken); - using var db2 = await conn.BeginTransactionAsync(); + using var db2 = await conn.BeginTransactionAsync(TestContext.Current.CancellationToken); var saga2 = await _theSchema.LoadAsync(saga.Id, db2, CancellationToken.None); saga2!.Name.ShouldBe("Hollywood Brown"); @@ -129,8 +129,8 @@ public async Task insert_update_then_load() [Fact] public async Task insert_then_delete() { - await using var conn = await _dataSource.OpenConnectionAsync(); - await using var db = await conn.BeginTransactionAsync(); + await using var conn = await _dataSource.OpenConnectionAsync(TestContext.Current.CancellationToken); + await using var db = await conn.BeginTransactionAsync(TestContext.Current.CancellationToken); var saga = new LightweightSaga { @@ -141,9 +141,9 @@ public async Task insert_then_delete() await _theSchema.InsertAsync(saga, db, CancellationToken.None); await _theSchema.DeleteAsync(saga, db, CancellationToken.None); - await db.CommitAsync(); + await db.CommitAsync(TestContext.Current.CancellationToken); - using var db2 = await conn.BeginTransactionAsync(); + using var db2 = await conn.BeginTransactionAsync(TestContext.Current.CancellationToken); var saga2 = await _theSchema.LoadAsync(saga.Id, db2, CancellationToken.None); saga2.ShouldBeNull(); } @@ -151,9 +151,9 @@ public async Task insert_then_delete() [Fact] public async Task concurrency_exception_when_version_does_not_match() { - await using var conn = await _dataSource.OpenConnectionAsync(); + await using var conn = await _dataSource.OpenConnectionAsync(TestContext.Current.CancellationToken); - var db = await conn.BeginTransactionAsync(); + var db = await conn.BeginTransactionAsync(TestContext.Current.CancellationToken); var saga = new LightweightSaga { @@ -162,17 +162,17 @@ public async Task concurrency_exception_when_version_does_not_match() }; await _theSchema.InsertAsync(saga, db, CancellationToken.None); - await db.CommitAsync(); + await db.CommitAsync(TestContext.Current.CancellationToken); await db.DisposeAsync(); - db = await conn.BeginTransactionAsync(); + db = await conn.BeginTransactionAsync(TestContext.Current.CancellationToken); saga.Name = "Rashee Rice"; await _theSchema.UpdateAsync(saga, db, CancellationToken.None); - await db.CommitAsync(); + await db.CommitAsync(TestContext.Current.CancellationToken); await db.DisposeAsync(); - db = await conn.BeginTransactionAsync(); + db = await conn.BeginTransactionAsync(TestContext.Current.CancellationToken); // I'm rewinding the version to make it throw saga.Version = 1; diff --git a/src/Persistence/SqliteTests/SqliteMessageStoreTests.cs b/src/Persistence/SqliteTests/SqliteMessageStoreTests.cs index f793bcaa5..324125507 100644 --- a/src/Persistence/SqliteTests/SqliteMessageStoreTests.cs +++ b/src/Persistence/SqliteTests/SqliteMessageStoreTests.cs @@ -98,11 +98,11 @@ public async Task delete_old_log_node_records() await theHost.InvokeAsync(new DatabaseOperationBatch(messageDatabase, [log])); using var dataSource = new SqliteDataSource(_database.ConnectionString); - await using var conn = await dataSource.OpenConnectionAsync(); + await using var conn = await dataSource.OpenConnectionAsync(TestContext.Current.CancellationToken); await conn.CreateCommand( $"update {DatabaseConstants.NodeRecordTableName} set timestamp = @time where node_number = 2") .With("time", DateTimeOffset.UtcNow.Subtract(10.Days()).ToString("o")) - .ExecuteNonQueryAsync(); + .ExecuteNonQueryAsync(TestContext.Current.CancellationToken); var recent2 = await thePersistence.Nodes.FetchRecentRecordsAsync(100); diff --git a/src/Persistence/SqliteTests/SqliteTests.csproj b/src/Persistence/SqliteTests/SqliteTests.csproj index 9cb9f26e9..88e13a6f0 100644 --- a/src/Persistence/SqliteTests/SqliteTests.csproj +++ b/src/Persistence/SqliteTests/SqliteTests.csproj @@ -1,6 +1,8 @@ + + true false Exe diff --git a/src/Persistence/SqliteTests/Transport/basic_functionality.cs b/src/Persistence/SqliteTests/Transport/basic_functionality.cs index 1e75f7795..15e386b4a 100644 --- a/src/Persistence/SqliteTests/Transport/basic_functionality.cs +++ b/src/Persistence/SqliteTests/Transport/basic_functionality.cs @@ -65,9 +65,9 @@ public async ValueTask DisposeAsync() public async Task expected_tables_exist_for_queue() { using var dataSource = new SqliteDataSource(_connectionString); - await using var conn = (SqliteConnection)await dataSource.OpenConnectionAsync(); + await using var conn = (SqliteConnection)await dataSource.OpenConnectionAsync(TestContext.Current.CancellationToken); - var names = await conn.ExistingTablesAsync(); + var names = await conn.ExistingTablesAsync(ct: TestContext.Current.CancellationToken); names.Any(x => x.Name == "wolverine_queue_one").ShouldBeTrue(); names.Any(x => x.Name == "wolverine_queue_one_scheduled").ShouldBeTrue(); @@ -171,7 +171,7 @@ public async Task delete_expired_smoke_test() (await theQueue.CountAsync()).ShouldBe(3); - await theHost.StopAsync(); + await theHost.StopAsync(TestContext.Current.CancellationToken); var durableReceiver = new DurableReceiver(theQueue, theRuntime, Substitute.For()); await using var theListener = new SqliteQueueListener(theQueue, theRuntime, durableReceiver, theQueue.DataSource, null); @@ -205,7 +205,7 @@ public async Task move_from_scheduled_to_queue() (await theQueue.ScheduledCountAsync()).ShouldBe(30); (await theQueue.CountAsync()).ShouldBe(0); - await theHost.StopAsync(); + await theHost.StopAsync(TestContext.Current.CancellationToken); var durableReceiver = new DurableReceiver(theQueue, theRuntime, Substitute.For()); await using var theListener = new SqliteQueueListener(theQueue, theRuntime, durableReceiver, theQueue.DataSource, null); diff --git a/src/Persistence/SqliteTests/Transport/sqlite_advisory_lock.cs b/src/Persistence/SqliteTests/Transport/sqlite_advisory_lock.cs index d35c32c98..084a59c52 100644 --- a/src/Persistence/SqliteTests/Transport/sqlite_advisory_lock.cs +++ b/src/Persistence/SqliteTests/Transport/sqlite_advisory_lock.cs @@ -35,8 +35,8 @@ public async Task try_attain_is_idempotent() using var host = await CreateHostAsync(_db.ConnectionString); var store = (SqliteMessageStore)host.Services.GetRequiredService(); - (await store.AdvisoryLock.TryAttainLockAsync(4242, default)).ShouldBeTrue(); - (await store.AdvisoryLock.TryAttainLockAsync(4242, default)).ShouldBeTrue(); + (await store.AdvisoryLock.TryAttainLockAsync(4242, TestContext.Current.CancellationToken)).ShouldBeTrue(); + (await store.AdvisoryLock.TryAttainLockAsync(4242, TestContext.Current.CancellationToken)).ShouldBeTrue(); store.AdvisoryLock.HasLock(4242).ShouldBeTrue(); await store.AdvisoryLock.ReleaseLockAsync(4242); @@ -52,14 +52,14 @@ public async Task release_actually_deletes_the_row() using var host = await CreateHostAsync(_db.ConnectionString); var store = (SqliteMessageStore)host.Services.GetRequiredService(); - await store.AdvisoryLock.TryAttainLockAsync(7777, default); + await store.AdvisoryLock.TryAttainLockAsync(7777, TestContext.Current.CancellationToken); await store.AdvisoryLock.ReleaseLockAsync(7777); await using var conn = new SqliteConnection(_db.ConnectionString); - await conn.OpenAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); await using var cmd = conn.CreateCommand(); cmd.CommandText = "select count(*) from wolverine_locks where lock_id = 7777"; - ((long)(await cmd.ExecuteScalarAsync())!).ShouldBe(0); + ((long)(await cmd.ExecuteScalarAsync(TestContext.Current.CancellationToken))!).ShouldBe(0); } [Fact] @@ -72,21 +72,21 @@ public async Task stale_row_is_reaped_on_attempt() await using (var seed = new SqliteConnection(_db.ConnectionString)) { - await seed.OpenAsync(); + await seed.OpenAsync(TestContext.Current.CancellationToken); await using var cmd = seed.CreateCommand(); cmd.CommandText = "INSERT INTO wolverine_locks (lock_id, acquired_at) VALUES ($id, $when)"; cmd.Parameters.AddWithValue("$id", 9001); // Pre-date by 10s; TTL is 1s in this test cmd.Parameters.AddWithValue("$when", DateTime.UtcNow.AddSeconds(-10).ToString("yyyy-MM-dd HH:mm:ss")); - await cmd.ExecuteNonQueryAsync(); + await cmd.ExecuteNonQueryAsync(TestContext.Current.CancellationToken); } var dataSource = new Weasel.Sqlite.SqliteDataSource(_db.ConnectionString); await using var lockA = new SqliteAdvisoryLock(dataSource, NullLogger.Instance, "test", TimeSpan.FromSeconds(1)); - (await lockA.TryAttainLockAsync(9001, default)).ShouldBeTrue(); + (await lockA.TryAttainLockAsync(9001, TestContext.Current.CancellationToken)).ShouldBeTrue(); } [Fact] @@ -104,14 +104,14 @@ public async Task live_holder_is_not_stolen_after_ttl_thanks_to_heartbeat() await using var holderB = new SqliteAdvisoryLock(dataSource, NullLogger.Instance, "B", TimeSpan.FromSeconds(1)); - (await holderA.TryAttainLockAsync(9100, default)).ShouldBeTrue(); + (await holderA.TryAttainLockAsync(9100, TestContext.Current.CancellationToken)).ShouldBeTrue(); // Beat the heartbeat across more than 2× TTL while B repeatedly tries for (var i = 0; i < 6; i++) { - await Task.Delay(500); - (await holderA.TryAttainLockAsync(9100, default)).ShouldBeTrue(); // heartbeat tick - (await holderB.TryAttainLockAsync(9100, default)).ShouldBeFalse(); // never steals + await Task.Delay(500, TestContext.Current.CancellationToken); + (await holderA.TryAttainLockAsync(9100, TestContext.Current.CancellationToken)).ShouldBeTrue(); // heartbeat tick + (await holderB.TryAttainLockAsync(9100, TestContext.Current.CancellationToken)).ShouldBeFalse(); // never steals } } @@ -121,12 +121,12 @@ public async Task heartbeat_advances_acquired_at_on_reattempt() using var host = await CreateHostAsync(_db.ConnectionString); var store = (SqliteMessageStore)host.Services.GetRequiredService(); - (await store.AdvisoryLock.TryAttainLockAsync(9200, default)).ShouldBeTrue(); + (await store.AdvisoryLock.TryAttainLockAsync(9200, TestContext.Current.CancellationToken)).ShouldBeTrue(); var firstAcquired = await readAcquiredAtAsync(_db.ConnectionString, 9200); - await Task.Delay(TimeSpan.FromSeconds(1.2)); + await Task.Delay(TimeSpan.FromSeconds(1.2), TestContext.Current.CancellationToken); - (await store.AdvisoryLock.TryAttainLockAsync(9200, default)).ShouldBeTrue(); + (await store.AdvisoryLock.TryAttainLockAsync(9200, TestContext.Current.CancellationToken)).ShouldBeTrue(); var secondAcquired = await readAcquiredAtAsync(_db.ConnectionString, 9200); secondAcquired.ShouldBeGreaterThan(firstAcquired); diff --git a/src/Persistence/SqliteTests/Transport/sqlite_migration_lock.cs b/src/Persistence/SqliteTests/Transport/sqlite_migration_lock.cs index 0a2fa3bac..91cf5f28c 100644 --- a/src/Persistence/SqliteTests/Transport/sqlite_migration_lock.cs +++ b/src/Persistence/SqliteTests/Transport/sqlite_migration_lock.cs @@ -38,11 +38,11 @@ public async Task migrate_async_does_not_leave_a_row_in_wolverine_locks() var migrationLockId = store.Settings.MigrationLockId; await using var conn = new SqliteConnection(_db.ConnectionString); - await conn.OpenAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); await using var cmd = conn.CreateCommand(); cmd.CommandText = "select count(*) from wolverine_locks where lock_id = $id"; cmd.Parameters.AddWithValue("$id", migrationLockId); - var count = (long)(await cmd.ExecuteScalarAsync())!; + var count = (long)(await cmd.ExecuteScalarAsync(TestContext.Current.CancellationToken))!; count.ShouldBe(0); } @@ -57,7 +57,7 @@ public async Task two_hosts_can_start_concurrently_against_the_same_file() CreateHostAsync(_db.ConnectionString), CreateHostAsync(_db.ConnectionString)); - var hosts = await startup.WaitAsync(TimeSpan.FromSeconds(15)); + var hosts = await startup.WaitAsync(TimeSpan.FromSeconds(15), TestContext.Current.CancellationToken); try { hosts.ShouldNotBeNull(); @@ -65,7 +65,7 @@ public async Task two_hosts_can_start_concurrently_against_the_same_file() } finally { - foreach (var h in hosts) await h.StopAsync(); + foreach (var h in hosts) await h.StopAsync(TestContext.Current.CancellationToken); foreach (var h in hosts) h.Dispose(); } } diff --git a/src/Persistence/SqliteTests/Transport/transport_workflow.cs b/src/Persistence/SqliteTests/Transport/transport_workflow.cs index 017298c35..c99c9debf 100644 --- a/src/Persistence/SqliteTests/Transport/transport_workflow.cs +++ b/src/Persistence/SqliteTests/Transport/transport_workflow.cs @@ -25,7 +25,7 @@ public async Task delivers_message_to_sqlite_queue() var message = new FileBasedTransportMessage(Guid.NewGuid().ToString("N"), "welcome"); await sendToQueue(host, message); - var received = await audit.ReceivedMessage.Task.WaitAsync(10.Seconds()); + var received = await audit.ReceivedMessage.Task.WaitAsync(10.Seconds(), TestContext.Current.CancellationToken); received.MessageId.ShouldBe(message.MessageId); received.Payload.ShouldBe("welcome"); @@ -51,10 +51,10 @@ public async Task delivers_scheduled_message_to_sqlite_queue() var message = new FileBasedTransportMessage(Guid.NewGuid().ToString("N"), "scheduled"); await sendToQueue(host, message, 2.Seconds()); - await Task.Delay(300.Milliseconds()); + await Task.Delay(300.Milliseconds(), TestContext.Current.CancellationToken); audit.ReceivedMessage.Task.IsCompleted.ShouldBeFalse(); - var received = await audit.ReceivedMessage.Task.WaitAsync(10.Seconds()); + var received = await audit.ReceivedMessage.Task.WaitAsync(10.Seconds(), TestContext.Current.CancellationToken); received.Payload.ShouldBe("scheduled"); } finally @@ -78,7 +78,7 @@ public async Task scheduled_message_survives_host_restart() var message = new FileBasedTransportMessage(Guid.NewGuid().ToString("N"), "after-restart"); await sendToQueue(firstHost, message, 3.Seconds()); - await Task.Delay(300.Milliseconds()); + await Task.Delay(300.Milliseconds(), TestContext.Current.CancellationToken); audit.ReceivedMessage.Task.IsCompleted.ShouldBeFalse(); await stopHost(firstHost); @@ -86,7 +86,7 @@ public async Task scheduled_message_survives_host_restart() secondHost = await startHost(database.ConnectionString, audit); - var received = await audit.ReceivedMessage.Task.WaitAsync(10.Seconds()); + var received = await audit.ReceivedMessage.Task.WaitAsync(10.Seconds(), TestContext.Current.CancellationToken); received.MessageId.ShouldBe(message.MessageId); received.Payload.ShouldBe("after-restart"); } diff --git a/src/Persistence/SqliteTests/configuration_extension_methods.cs b/src/Persistence/SqliteTests/configuration_extension_methods.cs index bfa9c2781..94637ce33 100644 --- a/src/Persistence/SqliteTests/configuration_extension_methods.cs +++ b/src/Persistence/SqliteTests/configuration_extension_methods.cs @@ -188,7 +188,7 @@ public async Task reject_in_memory_connection_string_from_dynamic_tenant_source( opts.PersistMessagesWithSqlite(database.ConnectionString) .RegisterTenants(new LazyMemoryTenantSource("red")) .EnableMessageTransport(x => x.AutoProvision()); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var store = host.Services.GetRequiredService() .ShouldBeOfType(); @@ -201,7 +201,7 @@ public async Task reject_in_memory_connection_string_from_dynamic_tenant_source( ex.Message.ShouldContain("tenant connection string"); ex.Message.ShouldContain("file-based"); - await host.StopAsync(); + await host.StopAsync(TestContext.Current.CancellationToken); } private class LazyMemoryTenantSource : ITenantedSource diff --git a/src/Persistence/SqliteTests/extension_registrations.cs b/src/Persistence/SqliteTests/extension_registrations.cs index 015306b6c..5ef30b38f 100644 --- a/src/Persistence/SqliteTests/extension_registrations.cs +++ b/src/Persistence/SqliteTests/extension_registrations.cs @@ -19,7 +19,7 @@ public async Task should_register_message_store() .UseWolverine(opts => { opts.PersistMessagesWithSqlite(database.ConnectionString); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); host.Services.GetRequiredService() .ShouldBeOfType(); @@ -34,7 +34,7 @@ public async Task should_set_durability_agent() { opts.PersistMessagesWithSqlite(database.ConnectionString); opts.Durability.Mode = DurabilityMode.Solo; - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.GetRuntime(); runtime.Storage.ShouldBeOfType(); diff --git a/src/Persistence/SqliteTests/message_store_initialization_and_configuration.cs b/src/Persistence/SqliteTests/message_store_initialization_and_configuration.cs index df82345fb..ea03c99c9 100644 --- a/src/Persistence/SqliteTests/message_store_initialization_and_configuration.cs +++ b/src/Persistence/SqliteTests/message_store_initialization_and_configuration.cs @@ -60,9 +60,9 @@ public void main_store_role() public async Task builds_the_node_and_control_queue_tables() { using var dataSource = new SqliteDataSource(_connectionString); - await using var conn = (SqliteConnection)await dataSource.OpenConnectionAsync(); + await using var conn = (SqliteConnection)await dataSource.OpenConnectionAsync(TestContext.Current.CancellationToken); - var tables = await conn.ExistingTablesAsync(schemas: ["main"]); + var tables = await conn.ExistingTablesAsync(schemas: ["main"], ct: TestContext.Current.CancellationToken); tables.ShouldContain(x => x.Name == DatabaseConstants.NodeTableName); tables.ShouldContain(x => x.Name == DatabaseConstants.NodeAssignmentsTableName); @@ -97,7 +97,7 @@ public async Task stores_the_current_node_on_startup() [Fact] public async Task deletes_the_node_on_shutdown() { - await _host.StopAsync(); + await _host.StopAsync(TestContext.Current.CancellationToken); _host.Dispose(); _host = null!; diff --git a/src/Persistence/SqliteTests/message_workflow.cs b/src/Persistence/SqliteTests/message_workflow.cs index f0dfeadf4..c0aac8530 100644 --- a/src/Persistence/SqliteTests/message_workflow.cs +++ b/src/Persistence/SqliteTests/message_workflow.cs @@ -26,7 +26,7 @@ public async Task processes_message_through_durable_local_queue() var message = new RegistrationSubmitted(Guid.NewGuid().ToString("N"), "nina@example.com"); await host.SendAsync(message); - var received = await audit.ReceivedMessage.Task.WaitAsync(10.Seconds()); + var received = await audit.ReceivedMessage.Task.WaitAsync(10.Seconds(), TestContext.Current.CancellationToken); received.UserId.ShouldBe(message.UserId); received.Email.ShouldBe("nina@example.com"); @@ -53,7 +53,7 @@ public async Task scheduled_local_message_survives_host_restart() var message = new RegistrationSubmitted(Guid.NewGuid().ToString("N"), "marco@example.com"); await firstHost.SendAsync(message, new DeliveryOptions { ScheduleDelay = 3.Seconds() }); - await Task.Delay(300.Milliseconds()); + await Task.Delay(300.Milliseconds(), TestContext.Current.CancellationToken); audit.ReceivedMessage.Task.IsCompleted.ShouldBeFalse(); await stopHost(firstHost); @@ -61,7 +61,7 @@ public async Task scheduled_local_message_survives_host_restart() secondHost = await startHost(database.ConnectionString, audit); - var received = await audit.ReceivedMessage.Task.WaitAsync(10.Seconds()); + var received = await audit.ReceivedMessage.Task.WaitAsync(10.Seconds(), TestContext.Current.CancellationToken); received.UserId.ShouldBe(message.UserId); received.Email.ShouldBe("marco@example.com"); } diff --git a/src/Persistence/Wolverine.ClaimCheck.AmazonS3.Tests/Wolverine.ClaimCheck.AmazonS3.Tests.csproj b/src/Persistence/Wolverine.ClaimCheck.AmazonS3.Tests/Wolverine.ClaimCheck.AmazonS3.Tests.csproj index 47033869a..f290325b9 100644 --- a/src/Persistence/Wolverine.ClaimCheck.AmazonS3.Tests/Wolverine.ClaimCheck.AmazonS3.Tests.csproj +++ b/src/Persistence/Wolverine.ClaimCheck.AmazonS3.Tests/Wolverine.ClaimCheck.AmazonS3.Tests.csproj @@ -1,6 +1,8 @@ + + true Exe net9.0;net10.0 enable diff --git a/src/Persistence/Wolverine.ClaimCheck.AzureBlobStorage.Tests/Wolverine.ClaimCheck.AzureBlobStorage.Tests.csproj b/src/Persistence/Wolverine.ClaimCheck.AzureBlobStorage.Tests/Wolverine.ClaimCheck.AzureBlobStorage.Tests.csproj index 1ceb75a33..d1604419c 100644 --- a/src/Persistence/Wolverine.ClaimCheck.AzureBlobStorage.Tests/Wolverine.ClaimCheck.AzureBlobStorage.Tests.csproj +++ b/src/Persistence/Wolverine.ClaimCheck.AzureBlobStorage.Tests/Wolverine.ClaimCheck.AzureBlobStorage.Tests.csproj @@ -1,6 +1,8 @@ + + true Exe net9.0;net10.0 enable diff --git a/src/Persistence/Wolverine.ClaimCheck.GoogleCloudStorage.Tests/Wolverine.ClaimCheck.GoogleCloudStorage.Tests.csproj b/src/Persistence/Wolverine.ClaimCheck.GoogleCloudStorage.Tests/Wolverine.ClaimCheck.GoogleCloudStorage.Tests.csproj index 1411525f4..ca4142789 100644 --- a/src/Persistence/Wolverine.ClaimCheck.GoogleCloudStorage.Tests/Wolverine.ClaimCheck.GoogleCloudStorage.Tests.csproj +++ b/src/Persistence/Wolverine.ClaimCheck.GoogleCloudStorage.Tests/Wolverine.ClaimCheck.GoogleCloudStorage.Tests.csproj @@ -1,6 +1,8 @@ + + true Exe net9.0;net10.0 enable diff --git a/src/Persistence/Wolverine.ClaimCheck.Nats.Tests/Wolverine.ClaimCheck.Nats.Tests.csproj b/src/Persistence/Wolverine.ClaimCheck.Nats.Tests/Wolverine.ClaimCheck.Nats.Tests.csproj index fc887b45f..58067c20e 100644 --- a/src/Persistence/Wolverine.ClaimCheck.Nats.Tests/Wolverine.ClaimCheck.Nats.Tests.csproj +++ b/src/Persistence/Wolverine.ClaimCheck.Nats.Tests/Wolverine.ClaimCheck.Nats.Tests.csproj @@ -1,6 +1,8 @@ + + true Exe net9.0;net10.0 enable diff --git a/src/Persistence/Wolverine.ClaimCheck.Postgresql.Tests/PostgresqlClaimCheckStoreTests.cs b/src/Persistence/Wolverine.ClaimCheck.Postgresql.Tests/PostgresqlClaimCheckStoreTests.cs index 3e7a6cad2..b55f00db1 100644 --- a/src/Persistence/Wolverine.ClaimCheck.Postgresql.Tests/PostgresqlClaimCheckStoreTests.cs +++ b/src/Persistence/Wolverine.ClaimCheck.Postgresql.Tests/PostgresqlClaimCheckStoreTests.cs @@ -47,16 +47,16 @@ public async Task round_trip_store_load_delete() { var payload = Encoding.UTF8.GetBytes("hello, claim check world"); - var token = await _store.StoreAsync(payload, "text/plain"); + var token = await _store.StoreAsync(payload, "text/plain", TestContext.Current.CancellationToken); token.Id.ShouldNotBeNullOrWhiteSpace(); token.ContentType.ShouldBe("text/plain"); token.Length.ShouldBe(payload.Length); - var loaded = await _store.LoadAsync(token); + var loaded = await _store.LoadAsync(token, TestContext.Current.CancellationToken); loaded.ToArray().ShouldBe(payload); - await _store.DeleteAsync(token); + await _store.DeleteAsync(token, TestContext.Current.CancellationToken); // After delete, loading should fail with a not-found error. await Should.ThrowAsync(async () => await _store.LoadAsync(token)); @@ -68,7 +68,7 @@ public async Task delete_is_idempotent_for_missing_row() var token = new ClaimCheckToken("does_not_exist_" + Guid.NewGuid().ToString("N"), "text/plain", 0); // Should not throw even though the row was never created. - await _store.DeleteAsync(token); + await _store.DeleteAsync(token, TestContext.Current.CancellationToken); } [Fact] @@ -82,8 +82,8 @@ public async Task load_returns_exact_payload_bytes() payload[i] = (byte)i; } - var token = await _store.StoreAsync(payload, "application/octet-stream"); - var loaded = await _store.LoadAsync(token); + var token = await _store.StoreAsync(payload, "application/octet-stream", TestContext.Current.CancellationToken); + var loaded = await _store.LoadAsync(token, TestContext.Current.CancellationToken); loaded.Length.ShouldBe(payload.Length); loaded.ToArray().ShouldBe(payload); @@ -94,10 +94,10 @@ public async Task provisioning_is_idempotent_across_stores() { // A second store over the same schema/table must not fail re-running the // create-if-not-exists DDL, and must see the first store's row. - var token = await _store.StoreAsync(Encoding.UTF8.GetBytes("shared"), "text/plain"); + var token = await _store.StoreAsync(Encoding.UTF8.GetBytes("shared"), "text/plain", TestContext.Current.CancellationToken); var second = new PostgresqlClaimCheckStore(_dataSource, _schema); - var loaded = await second.LoadAsync(token); + var loaded = await second.LoadAsync(token, TestContext.Current.CancellationToken); loaded.ToArray().ShouldBe(Encoding.UTF8.GetBytes("shared")); } diff --git a/src/Persistence/Wolverine.ClaimCheck.Postgresql.Tests/Wolverine.ClaimCheck.Postgresql.Tests.csproj b/src/Persistence/Wolverine.ClaimCheck.Postgresql.Tests/Wolverine.ClaimCheck.Postgresql.Tests.csproj index 86e2d8abd..70d7d7b28 100644 --- a/src/Persistence/Wolverine.ClaimCheck.Postgresql.Tests/Wolverine.ClaimCheck.Postgresql.Tests.csproj +++ b/src/Persistence/Wolverine.ClaimCheck.Postgresql.Tests/Wolverine.ClaimCheck.Postgresql.Tests.csproj @@ -1,6 +1,8 @@ + + true Exe net9.0;net10.0 enable diff --git a/src/Samples/CQRSWithMarten/TeleHealth.Tests/GettingStarted.cs b/src/Samples/CQRSWithMarten/TeleHealth.Tests/GettingStarted.cs index 687236e7c..003ca0473 100644 --- a/src/Samples/CQRSWithMarten/TeleHealth.Tests/GettingStarted.cs +++ b/src/Samples/CQRSWithMarten/TeleHealth.Tests/GettingStarted.cs @@ -31,12 +31,12 @@ public async Task append_events() // The ProviderShift aggregate will be // updated at this time - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); // Load the persisted ProviderShift right out // of the database var shift = await session - .LoadAsync(shiftId); + .LoadAsync(shiftId, TestContext.Current.CancellationToken); } [Fact] @@ -59,7 +59,7 @@ public async Task start_a_new_shift() // Just a little reference data await using var session = store.LightweightSession(); session.Store(provider); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); var boardId = Guid.NewGuid(); @@ -72,11 +72,10 @@ public async Task start_a_new_shift() new ProviderReady() ).Id; - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); - var shift = await session.Events.AggregateStreamAsync(shiftId, - timestamp: DateTime.Today.AddHours(13)); + var shift = await session.Events.AggregateStreamAsync(shiftId, timestamp: DateTime.Today.AddHours(13), token: TestContext.Current.CancellationToken); shift!.Name.ShouldBe("Larry Bird"); } diff --git a/src/Samples/CQRSWithMarten/TeleHealth.Tests/TeleHealth.Tests.csproj b/src/Samples/CQRSWithMarten/TeleHealth.Tests/TeleHealth.Tests.csproj index 9185b0002..c73541eeb 100644 --- a/src/Samples/CQRSWithMarten/TeleHealth.Tests/TeleHealth.Tests.csproj +++ b/src/Samples/CQRSWithMarten/TeleHealth.Tests/TeleHealth.Tests.csproj @@ -1,6 +1,8 @@ + + true Exe net9.0;net10.0 false diff --git a/src/Samples/Diagnostics/DiagnosticsTests/DiagnosticsTests.csproj b/src/Samples/Diagnostics/DiagnosticsTests/DiagnosticsTests.csproj index 1e8f888f8..8d9b1b024 100644 --- a/src/Samples/Diagnostics/DiagnosticsTests/DiagnosticsTests.csproj +++ b/src/Samples/Diagnostics/DiagnosticsTests/DiagnosticsTests.csproj @@ -1,6 +1,8 @@ + + true Exe net9.0;net10.0 false diff --git a/src/Samples/EFCoreSample/ItemService.Tests/ItemService.Tests.csproj b/src/Samples/EFCoreSample/ItemService.Tests/ItemService.Tests.csproj index 08815483a..87ac6c9c1 100644 --- a/src/Samples/EFCoreSample/ItemService.Tests/ItemService.Tests.csproj +++ b/src/Samples/EFCoreSample/ItemService.Tests/ItemService.Tests.csproj @@ -1,5 +1,7 @@ + + true Exe net9.0;net10.0 diff --git a/src/Samples/EFCoreSample/ItemService.Tests/end_to_end.cs b/src/Samples/EFCoreSample/ItemService.Tests/end_to_end.cs index 78565edfa..4cf131ea8 100644 --- a/src/Samples/EFCoreSample/ItemService.Tests/end_to_end.cs +++ b/src/Samples/EFCoreSample/ItemService.Tests/end_to_end.cs @@ -24,7 +24,7 @@ public async Task run_through_the_handler() using var nested = host.Services.CreateScope(); var context = nested.ServiceProvider.GetRequiredService(); - var item = await context.Items.FirstOrDefaultAsync(x => x.Name == name); + var item = await context.Items.FirstOrDefaultAsync(x => x.Name == name, cancellationToken: TestContext.Current.CancellationToken); item.ShouldNotBeNull(); } @@ -48,7 +48,7 @@ await host.Scenario(x => using var nested = host.Services.CreateScope(); var context = nested.ServiceProvider.GetRequiredService(); - var item = await context.Items.FirstOrDefaultAsync(x => x.Name == name); + var item = await context.Items.FirstOrDefaultAsync(x => x.Name == name, cancellationToken: TestContext.Current.CancellationToken); item.ShouldNotBeNull(); } @@ -73,7 +73,7 @@ await host.Scenario(x => using var nested = host.Services.CreateScope(); var context = nested.ServiceProvider.GetRequiredService(); - var item = await context.Items.FirstOrDefaultAsync(x => x.Name == name); + var item = await context.Items.FirstOrDefaultAsync(x => x.Name == name, cancellationToken: TestContext.Current.CancellationToken); item.ShouldNotBeNull(); } @@ -87,7 +87,7 @@ public async Task fetch_through_entity_attribute() var id = Guid.NewGuid(); context.Add(new Item { Id = id, Name = name }); - await context.SaveChangesAsync(); + await context.SaveChangesAsync(TestContext.Current.CancellationToken); var response = await host.GetAsJson("/api/item/" + id); response!.Name.ShouldBe(name); diff --git a/src/Samples/EFCoreSample/ItemService.Tests/end_to_end_for_dbcontext_not_integrated_with_outbox.cs b/src/Samples/EFCoreSample/ItemService.Tests/end_to_end_for_dbcontext_not_integrated_with_outbox.cs index d4a92494e..f98a2c584 100644 --- a/src/Samples/EFCoreSample/ItemService.Tests/end_to_end_for_dbcontext_not_integrated_with_outbox.cs +++ b/src/Samples/EFCoreSample/ItemService.Tests/end_to_end_for_dbcontext_not_integrated_with_outbox.cs @@ -21,7 +21,7 @@ public async Task run_through_the_handler() using var nested = host.Services.CreateScope(); var context = nested.ServiceProvider.GetRequiredService(); - var item = await context.Items.FirstOrDefaultAsync(x => x.Name == name); + var item = await context.Items.FirstOrDefaultAsync(x => x.Name == name, cancellationToken: TestContext.Current.CancellationToken); item.ShouldNotBeNull(); } } \ No newline at end of file diff --git a/src/Samples/IncidentService/IncidentService.Tests/IncidentService.Tests.csproj b/src/Samples/IncidentService/IncidentService.Tests/IncidentService.Tests.csproj index 745b5db25..fe1238c6d 100644 --- a/src/Samples/IncidentService/IncidentService.Tests/IncidentService.Tests.csproj +++ b/src/Samples/IncidentService/IncidentService.Tests/IncidentService.Tests.csproj @@ -1,6 +1,8 @@ + + true Exe false net9.0 diff --git a/src/Samples/IncidentService/IncidentService.Tests/when_logging_an_incident.cs b/src/Samples/IncidentService/IncidentService.Tests/when_logging_an_incident.cs index a04fb8294..edec52cfb 100644 --- a/src/Samples/IncidentService/IncidentService.Tests/when_logging_an_incident.cs +++ b/src/Samples/IncidentService/IncidentService.Tests/when_logging_an_incident.cs @@ -57,7 +57,7 @@ public async Task happy_path_end_to_end() // This wallpapers over the exact projection lifecycle.... - var incident = await session.Events.FetchLatest(response.Value); + var incident = await session.Events.FetchLatest(response.Value, TestContext.Current.CancellationToken); incident!.Status.ShouldBe(IncidentStatus.Pending); } diff --git a/src/Samples/Middleware/AppWithMiddleware.Tests/AppWithMiddleware.Tests.csproj b/src/Samples/Middleware/AppWithMiddleware.Tests/AppWithMiddleware.Tests.csproj index 79a79a63e..23099752d 100644 --- a/src/Samples/Middleware/AppWithMiddleware.Tests/AppWithMiddleware.Tests.csproj +++ b/src/Samples/Middleware/AppWithMiddleware.Tests/AppWithMiddleware.Tests.csproj @@ -1,6 +1,8 @@ + + true Exe false diff --git a/src/Samples/Middleware/AppWithMiddleware.Tests/try_out_the_middleware.cs b/src/Samples/Middleware/AppWithMiddleware.Tests/try_out_the_middleware.cs index 3eb1ff5f2..e33214ab1 100644 --- a/src/Samples/Middleware/AppWithMiddleware.Tests/try_out_the_middleware.cs +++ b/src/Samples/Middleware/AppWithMiddleware.Tests/try_out_the_middleware.cs @@ -50,12 +50,12 @@ public async Task hit() var store = host.Services.GetRequiredService(); await using var session = store.LightweightSession(); session.Store(account); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); var bus = host.MessageBus(); - await bus.InvokeAsync(new DebitAccount(account.Id, 100)); + await bus.InvokeAsync(new DebitAccount(account.Id, 100), TestContext.Current.CancellationToken); - var account2 = await session.LoadAsync(account.Id); + var account2 = await session.LoadAsync(account.Id, TestContext.Current.CancellationToken); // Should be 1000 + 100 account2!.Balance.ShouldBe(900); @@ -74,7 +74,7 @@ public async Task validation_miss() var store = host.Services.GetRequiredService(); await using var session = store.LightweightSession(); session.Store(account); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); var bus = host.MessageBus(); diff --git a/src/Samples/MultiTenantedTodoService/MultiTenantedTodoWebService.Tests/MultiTenantedTodoWebService.Tests.csproj b/src/Samples/MultiTenantedTodoService/MultiTenantedTodoWebService.Tests/MultiTenantedTodoWebService.Tests.csproj index b3e3dfa22..360b38de4 100644 --- a/src/Samples/MultiTenantedTodoService/MultiTenantedTodoWebService.Tests/MultiTenantedTodoWebService.Tests.csproj +++ b/src/Samples/MultiTenantedTodoService/MultiTenantedTodoWebService.Tests/MultiTenantedTodoWebService.Tests.csproj @@ -1,6 +1,8 @@ + + true Exe false true diff --git a/src/Samples/ProcessManagerViaHandlers/ProcessManagerViaHandlers.Tests/OrderFulfillment/when_cancelling_a_fulfillment.cs b/src/Samples/ProcessManagerViaHandlers/ProcessManagerViaHandlers.Tests/OrderFulfillment/when_cancelling_a_fulfillment.cs index ad2860a6e..30a743a28 100644 --- a/src/Samples/ProcessManagerViaHandlers/ProcessManagerViaHandlers.Tests/OrderFulfillment/when_cancelling_a_fulfillment.cs +++ b/src/Samples/ProcessManagerViaHandlers/ProcessManagerViaHandlers.Tests/OrderFulfillment/when_cancelling_a_fulfillment.cs @@ -22,13 +22,13 @@ public async Task cancel_mid_process_marks_the_stream_cancelled() await Host.InvokeMessageAndWaitAsync(new CancelOrderFulfillment(id, "Fraud suspected")); await using var session = Store.LightweightSession(); - var events = await session.Events.FetchStreamAsync(id); + var events = await session.Events.FetchStreamAsync(id, token: TestContext.Current.CancellationToken); events.Count.ShouldBe(3); var cancelled = events[2].Data.ShouldBeOfType(); cancelled.Reason.ShouldBe("Fraud suspected"); - var state = await session.Events.FetchLatest(id); + var state = await session.Events.FetchLatest(id, TestContext.Current.CancellationToken); state.ShouldNotBeNull(); state.IsCancelled.ShouldBeTrue(); state.IsCompleted.ShouldBeFalse(); @@ -47,7 +47,7 @@ public async Task integration_events_after_cancellation_are_ignored() await Host.InvokeMessageAndWaitAsync(new PaymentConfirmed(id, 99m)); await using var session = Store.LightweightSession(); - var events = await session.Events.FetchStreamAsync(id); + var events = await session.Events.FetchStreamAsync(id, token: TestContext.Current.CancellationToken); events.Count.ShouldBe(2); events[0].Data.ShouldBeOfType(); @@ -64,7 +64,7 @@ public async Task second_cancel_is_a_no_op() await Host.InvokeMessageAndWaitAsync(new CancelOrderFulfillment(id, "Second reason")); await using var session = Store.LightweightSession(); - var events = await session.Events.FetchStreamAsync(id); + var events = await session.Events.FetchStreamAsync(id, token: TestContext.Current.CancellationToken); events.Count.ShouldBe(2); events[1].Data.ShouldBeOfType().Reason.ShouldBe("First reason"); diff --git a/src/Samples/ProcessManagerViaHandlers/ProcessManagerViaHandlers.Tests/OrderFulfillment/when_completing_a_fulfillment.cs b/src/Samples/ProcessManagerViaHandlers/ProcessManagerViaHandlers.Tests/OrderFulfillment/when_completing_a_fulfillment.cs index 6e989aef9..2bb05b5da 100644 --- a/src/Samples/ProcessManagerViaHandlers/ProcessManagerViaHandlers.Tests/OrderFulfillment/when_completing_a_fulfillment.cs +++ b/src/Samples/ProcessManagerViaHandlers/ProcessManagerViaHandlers.Tests/OrderFulfillment/when_completing_a_fulfillment.cs @@ -23,7 +23,7 @@ public async Task happy_path_ends_with_OrderFulfillmentCompleted() await Host.InvokeMessageAndWaitAsync(new ShipmentConfirmed(id, "TRACK-ABC")); await using var session = Store.LightweightSession(); - var events = await session.Events.FetchStreamAsync(id); + var events = await session.Events.FetchStreamAsync(id, token: TestContext.Current.CancellationToken); events.Count.ShouldBe(5); events[0].Data.ShouldBeOfType(); @@ -32,7 +32,7 @@ public async Task happy_path_ends_with_OrderFulfillmentCompleted() events[3].Data.ShouldBeOfType(); events[4].Data.ShouldBeOfType(); - var state = await session.Events.FetchLatest(id); + var state = await session.Events.FetchLatest(id, TestContext.Current.CancellationToken); state.ShouldNotBeNull(); state.IsCompleted.ShouldBeTrue(); state.IsCancelled.ShouldBeFalse(); @@ -53,7 +53,7 @@ public async Task messages_arriving_out_of_order_still_complete_the_process() await Host.InvokeMessageAndWaitAsync(new PaymentConfirmed(id, 50m)); await using var session = Store.LightweightSession(); - var state = await session.Events.FetchLatest(id); + var state = await session.Events.FetchLatest(id, TestContext.Current.CancellationToken); state.ShouldNotBeNull(); state.IsCompleted.ShouldBeTrue(); @@ -69,7 +69,7 @@ public async Task duplicate_integration_event_is_a_no_op() await Host.InvokeMessageAndWaitAsync(new PaymentConfirmed(id, 75m)); await using var session = Store.LightweightSession(); - var events = await session.Events.FetchStreamAsync(id); + var events = await session.Events.FetchStreamAsync(id, token: TestContext.Current.CancellationToken); events.Count.ShouldBe(2); events[0].Data.ShouldBeOfType(); @@ -90,7 +90,7 @@ public async Task integration_events_after_completion_are_ignored() await Host.InvokeMessageAndWaitAsync(new ShipmentConfirmed(id, "TRACK-2")); await using var session = Store.LightweightSession(); - var events = await session.Events.FetchStreamAsync(id); + var events = await session.Events.FetchStreamAsync(id, token: TestContext.Current.CancellationToken); events.Count.ShouldBe(5); } } diff --git a/src/Samples/ProcessManagerViaHandlers/ProcessManagerViaHandlers.Tests/OrderFulfillment/when_payment_times_out.cs b/src/Samples/ProcessManagerViaHandlers/ProcessManagerViaHandlers.Tests/OrderFulfillment/when_payment_times_out.cs index a074dee0e..83c956cef 100644 --- a/src/Samples/ProcessManagerViaHandlers/ProcessManagerViaHandlers.Tests/OrderFulfillment/when_payment_times_out.cs +++ b/src/Samples/ProcessManagerViaHandlers/ProcessManagerViaHandlers.Tests/OrderFulfillment/when_payment_times_out.cs @@ -58,14 +58,14 @@ await Host.InvokeMessageAndWaitAsync(new StartOrderFulfillment( await WaitForCondition(id, state => state.IsTerminal); await using var session = Store.LightweightSession(); - var events = await session.Events.FetchStreamAsync(id); + var events = await session.Events.FetchStreamAsync(id, token: TestContext.Current.CancellationToken); events.Count.ShouldBe(2); events[0].Data.ShouldBeOfType(); var cancelled = events[1].Data.ShouldBeOfType(); cancelled.Reason.ShouldBe("Payment timed out"); - var state = await session.Events.FetchLatest(id); + var state = await session.Events.FetchLatest(id, TestContext.Current.CancellationToken); state.ShouldNotBeNull(); state.IsCancelled.ShouldBeTrue(); } @@ -84,16 +84,16 @@ await Host.InvokeMessageAndWaitAsync(new StartOrderFulfillment( // Wait out the scheduler window. The timeout handler will run, observe // state.PaymentConfirmed == true, and yield break. - await Task.Delay(SchedulerObservationWindow); + await Task.Delay(SchedulerObservationWindow, TestContext.Current.CancellationToken); await using var session = Store.LightweightSession(); - var events = await session.Events.FetchStreamAsync(id); + var events = await session.Events.FetchStreamAsync(id, token: TestContext.Current.CancellationToken); events.Count.ShouldBe(2); events[0].Data.ShouldBeOfType(); events[1].Data.ShouldBeOfType(); - var state = await session.Events.FetchLatest(id); + var state = await session.Events.FetchLatest(id, TestContext.Current.CancellationToken); state.ShouldNotBeNull(); state.IsCancelled.ShouldBeFalse(); state.PaymentConfirmed.ShouldBeTrue(); diff --git a/src/Samples/ProcessManagerViaHandlers/ProcessManagerViaHandlers.Tests/OrderFulfillment/when_starting_a_fulfillment.cs b/src/Samples/ProcessManagerViaHandlers/ProcessManagerViaHandlers.Tests/OrderFulfillment/when_starting_a_fulfillment.cs index 1734f0468..ba7b7e597 100644 --- a/src/Samples/ProcessManagerViaHandlers/ProcessManagerViaHandlers.Tests/OrderFulfillment/when_starting_a_fulfillment.cs +++ b/src/Samples/ProcessManagerViaHandlers/ProcessManagerViaHandlers.Tests/OrderFulfillment/when_starting_a_fulfillment.cs @@ -26,7 +26,7 @@ public async Task creates_the_stream_with_the_started_event() await Host.InvokeMessageAndWaitAsync(command); await using var session = Store.LightweightSession(); - var events = await session.Events.FetchStreamAsync(command.OrderFulfillmentStateId); + var events = await session.Events.FetchStreamAsync(command.OrderFulfillmentStateId, token: TestContext.Current.CancellationToken); events.Count.ShouldBe(1); var started = events[0].Data.ShouldBeOfType(); @@ -35,7 +35,7 @@ public async Task creates_the_stream_with_the_started_event() started.TotalAmount.ShouldBe(command.TotalAmount); // Inline snapshot must have projected the event into the aggregate document. - var state = await session.Events.FetchLatest(command.OrderFulfillmentStateId); + var state = await session.Events.FetchLatest(command.OrderFulfillmentStateId, TestContext.Current.CancellationToken); state.ShouldNotBeNull(); state.Id.ShouldBe(command.OrderFulfillmentStateId); state.CustomerId.ShouldBe(command.CustomerId); @@ -63,7 +63,7 @@ public async Task starting_the_same_process_twice_throws_and_first_start_wins() // The first start's data must still be intact; the second start's transaction rolled back. await using var session = Store.LightweightSession(); - var events = await session.Events.FetchStreamAsync(id); + var events = await session.Events.FetchStreamAsync(id, token: TestContext.Current.CancellationToken); events.Count.ShouldBe(1); var started = events[0].Data.ShouldBeOfType(); diff --git a/src/Samples/ProcessManagerViaHandlers/ProcessManagerViaHandlers.Tests/ProcessManagerViaHandlers.Tests.csproj b/src/Samples/ProcessManagerViaHandlers/ProcessManagerViaHandlers.Tests/ProcessManagerViaHandlers.Tests.csproj index 206963e24..89feba05b 100644 --- a/src/Samples/ProcessManagerViaHandlers/ProcessManagerViaHandlers.Tests/ProcessManagerViaHandlers.Tests.csproj +++ b/src/Samples/ProcessManagerViaHandlers/ProcessManagerViaHandlers.Tests/ProcessManagerViaHandlers.Tests.csproj @@ -1,6 +1,8 @@ + + true Exe false net9.0 diff --git a/src/Samples/TestHarness/BankingService.Tests/BankingService.Tests.csproj b/src/Samples/TestHarness/BankingService.Tests/BankingService.Tests.csproj index f55740f95..6029ba009 100644 --- a/src/Samples/TestHarness/BankingService.Tests/BankingService.Tests.csproj +++ b/src/Samples/TestHarness/BankingService.Tests/BankingService.Tests.csproj @@ -1,6 +1,8 @@ + + true Exe false diff --git a/src/Samples/TodoWebService/TodoWebServiceTests/TodoWebServiceTests.csproj b/src/Samples/TodoWebService/TodoWebServiceTests/TodoWebServiceTests.csproj index ae91c5001..9968fb3e3 100644 --- a/src/Samples/TodoWebService/TodoWebServiceTests/TodoWebServiceTests.csproj +++ b/src/Samples/TodoWebService/TodoWebServiceTests/TodoWebServiceTests.csproj @@ -1,6 +1,8 @@ + + true Exe net9.0;net10.0 false diff --git a/src/Testing/BackPressureTests/BackPressureTests.csproj b/src/Testing/BackPressureTests/BackPressureTests.csproj index f7f5038f4..64b8e4345 100644 --- a/src/Testing/BackPressureTests/BackPressureTests.csproj +++ b/src/Testing/BackPressureTests/BackPressureTests.csproj @@ -1,6 +1,8 @@ + + true Exe enable false diff --git a/src/Testing/CoreTests/Acceptance/batch_coalesce_poison.cs b/src/Testing/CoreTests/Acceptance/batch_coalesce_poison.cs index f99e87ba6..0b8160b59 100644 --- a/src/Testing/CoreTests/Acceptance/batch_coalesce_poison.cs +++ b/src/Testing/CoreTests/Acceptance/batch_coalesce_poison.cs @@ -48,8 +48,8 @@ public async Task poisoning_a_coalesced_item_dead_letters_every_member_of_that_k await bus.PublishAsync(new CoalItem("A", 3, true)); await bus.PublishAsync(new CoalItem("B", 1, false)); - await CoalPoisonHandler.SurvivorSucceeded.Task.WaitAsync(10.Seconds()); - await _deadLetters.Signal.Task.WaitAsync(10.Seconds()); + await CoalPoisonHandler.SurvivorSucceeded.Task.WaitAsync(10.Seconds(), TestContext.Current.CancellationToken); + await _deadLetters.Signal.Task.WaitAsync(10.Seconds(), TestContext.Current.CancellationToken); // Every member that collapsed into the poisoned key "A" is dead-lettered - all three versions. var deadLettered = _deadLetters.DeadLettered.OfType().ToArray(); diff --git a/src/Testing/CoreTests/Acceptance/batch_handler_conflict_diagnostic.cs b/src/Testing/CoreTests/Acceptance/batch_handler_conflict_diagnostic.cs index 9efe553f8..f9cc56515 100644 --- a/src/Testing/CoreTests/Acceptance/batch_handler_conflict_diagnostic.cs +++ b/src/Testing/CoreTests/Acceptance/batch_handler_conflict_diagnostic.cs @@ -34,7 +34,7 @@ public async Task warns_by_default_when_a_direct_handler_shadows_a_batch_in_clas opts.Discovery.IncludeType(); opts.Discovery.IncludeType(); opts.BatchMessagesOf(); - }, logger).StartAsync(); + }, logger).StartAsync(cancellationToken: TestContext.Current.CancellationToken); logger.Entries.ShouldContain(x => x.Level == LogLevel.Warning && x.Message.Contains("Batch handler conflict")); @@ -75,7 +75,7 @@ public async Task no_conflict_when_only_a_batch_handler_exists() opts.Discovery.IncludeType(); opts.BatchMessagesOf(); opts.AssertNoBatchHandlerConflicts(); - }, logger).StartAsync(); + }, logger).StartAsync(cancellationToken: TestContext.Current.CancellationToken); logger.Entries.ShouldNotContain(x => x.Message.Contains("Batch handler conflict")); } @@ -94,7 +94,7 @@ public async Task no_conflict_under_separated_mode_even_with_both_handlers() opts.Discovery.IncludeType(); opts.BatchMessagesOf(); opts.AssertNoBatchHandlerConflicts(); - }, logger).StartAsync(); + }, logger).StartAsync(cancellationToken: TestContext.Current.CancellationToken); logger.Entries.ShouldNotContain(x => x.Message.Contains("Batch handler conflict")); } diff --git a/src/Testing/CoreTests/Acceptance/batch_isolate_members.cs b/src/Testing/CoreTests/Acceptance/batch_isolate_members.cs index 9df032336..6068eb85f 100644 --- a/src/Testing/CoreTests/Acceptance/batch_isolate_members.cs +++ b/src/Testing/CoreTests/Acceptance/batch_isolate_members.cs @@ -53,8 +53,8 @@ public async Task isolates_the_failing_member_by_probing_individually() // The whole batch throws the opaque ProbeFailure; IsolateBatchMembers re-runs each member as its // own size-1 batch. The two healthy singletons succeed; the poison singleton dead-letters. - await ProbeItemBatchHandler.BothGoodsSucceeded.Task.WaitAsync(10.Seconds()); - await _deadLetters.Signal.Task.WaitAsync(10.Seconds()); + await ProbeItemBatchHandler.BothGoodsSucceeded.Task.WaitAsync(10.Seconds(), TestContext.Current.CancellationToken); + await _deadLetters.Signal.Task.WaitAsync(10.Seconds(), TestContext.Current.CancellationToken); ProbeItemBatchHandler.SucceededIds.OrderBy(x => x).ShouldBe(new[] { "good1", "good2" }); @@ -94,7 +94,7 @@ public async Task falls_back_to_dead_lettering_the_single_message() { await _host.MessageBus().PublishAsync(new SoloProbe("only")); - await _deadLetters.Signal.Task.WaitAsync(10.Seconds()); + await _deadLetters.Signal.Task.WaitAsync(10.Seconds(), TestContext.Current.CancellationToken); _deadLetters.DeadLettered.OfType().Select(x => x.Id).ShouldBe(new[] { "only" }); } diff --git a/src/Testing/CoreTests/Acceptance/batch_item_isolation.cs b/src/Testing/CoreTests/Acceptance/batch_item_isolation.cs index e29e5539f..9cc1e5980 100644 --- a/src/Testing/CoreTests/Acceptance/batch_item_isolation.cs +++ b/src/Testing/CoreTests/Acceptance/batch_item_isolation.cs @@ -108,7 +108,7 @@ public async Task deadletter_and_replay_others_isolates_the_poison_item() await publishAsync(new IsoItem("a", false), new IsoItem("bad", true), new IsoItem("c", false)); // The reduced batch (survivors only) is re-run to success. - await IsoItemBatchHandler.SuccessSignal.Task.WaitAsync(10.Seconds()); + await IsoItemBatchHandler.SuccessSignal.Task.WaitAsync(10.Seconds(), TestContext.Current.CancellationToken); var successful = IsoItemBatchHandler.SuccessfulRuns.ShouldHaveSingleItem(); successful.Select(x => x.Id).OrderBy(x => x).ShouldBe(new[] { "a", "c" }); @@ -127,8 +127,8 @@ public async Task deadletter_and_ack_others_does_not_replay() await publishAsync(new IsoItem("a", false), new IsoItem("bad", true), new IsoItem("c", false)); // Wait for the poison item to be dead-lettered, then confirm no replay happened. - await _deadLetters.Signal.Task.WaitAsync(10.Seconds()); - await Task.Delay(500.Milliseconds()); + await _deadLetters.Signal.Task.WaitAsync(10.Seconds(), TestContext.Current.CancellationToken); + await Task.Delay(500.Milliseconds(), TestContext.Current.CancellationToken); _deadLetters.DeadLettered.OfType().Select(x => x.Id).ShouldBe(new[] { "bad" }); @@ -153,7 +153,7 @@ await publishAsync( new IsoItem("replay1", false), new IsoItem("replay2", false)); - await IsoItemBatchHandler.SuccessSignal.Task.WaitAsync(10.Seconds()); + await IsoItemBatchHandler.SuccessSignal.Task.WaitAsync(10.Seconds(), TestContext.Current.CancellationToken); // Only the two non-acked survivors are replayed; "ackme" was settled without a re-run. var successful = IsoItemBatchHandler.SuccessfulRuns.ShouldHaveSingleItem(); diff --git a/src/Testing/CoreTests/Acceptance/batch_probe_individually_after.cs b/src/Testing/CoreTests/Acceptance/batch_probe_individually_after.cs index 44af88ff0..14a44710c 100644 --- a/src/Testing/CoreTests/Acceptance/batch_probe_individually_after.cs +++ b/src/Testing/CoreTests/Acceptance/batch_probe_individually_after.cs @@ -48,8 +48,8 @@ public async Task retries_the_whole_batch_then_probes_individually() await bus.PublishAsync(new ProbeAfterItem("bad", true)); await bus.PublishAsync(new ProbeAfterItem("good2", false)); - await ProbeAfterHandler.BothGoodsSucceeded.Task.WaitAsync(15.Seconds()); - await _deadLetters.Signal.Task.WaitAsync(15.Seconds()); + await ProbeAfterHandler.BothGoodsSucceeded.Task.WaitAsync(15.Seconds(), TestContext.Current.CancellationToken); + await _deadLetters.Signal.Task.WaitAsync(15.Seconds(), TestContext.Current.CancellationToken); // The whole 3-item batch was retried exactly 3 times before the probe kicked in. ProbeAfterHandler.WholeBatchAttempts.ShouldBe(3); diff --git a/src/Testing/CoreTests/Acceptance/batching_with_separated_handlers.cs b/src/Testing/CoreTests/Acceptance/batching_with_separated_handlers.cs index eb04e76ed..b4639c245 100644 --- a/src/Testing/CoreTests/Acceptance/batching_with_separated_handlers.cs +++ b/src/Testing/CoreTests/Acceptance/batching_with_separated_handlers.cs @@ -59,7 +59,7 @@ public async Task separated_direct_and_batch_handler_both_run_on_local_publish() opts.MultipleHandlerBehavior = MultipleHandlerBehavior.Separated; opts.BatchMessagesOf(b => b.TriggerTime = 250.Milliseconds()); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); LoadPublisher.BatchCalls.Clear(); LoadTelemetry.SingleCalls.Clear(); @@ -79,7 +79,7 @@ await host.TrackActivity() [Fact] public async Task separated_multiple_batch_handlers_all_run() { - using var host = await ConfigureMultipleBatchHost(withDirectHandler: false).StartAsync(); + using var host = await ConfigureMultipleBatchHost(withDirectHandler: false).StartAsync(cancellationToken: TestContext.Current.CancellationToken); InvoicePublisher.Calls.Clear(); InvoiceArchiver.Calls.Clear(); @@ -100,7 +100,7 @@ await host.TrackActivity() [Fact] public async Task separated_direct_handler_plus_multiple_batch_handlers_all_run() { - using var host = await ConfigureMultipleBatchHost(withDirectHandler: true).StartAsync(); + using var host = await ConfigureMultipleBatchHost(withDirectHandler: true).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.GetRuntime(); // The direct Handle(InvoiceEvent) collides with the batch element queue, so the batch was diff --git a/src/Testing/CoreTests/Acceptance/compound_handlers.cs b/src/Testing/CoreTests/Acceptance/compound_handlers.cs index 340502c43..c1bf60eee 100644 --- a/src/Testing/CoreTests/Acceptance/compound_handlers.cs +++ b/src/Testing/CoreTests/Acceptance/compound_handlers.cs @@ -16,7 +16,7 @@ public async Task use_before_and_after_compound_handler() using var host = await Host.CreateDefaultBuilder() .UseWolverine(opts => opts.Services.AddSingleton(tracer)) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); await host.InvokeMessageAndWaitAsync(new AssignTask("green")); @@ -31,7 +31,7 @@ public async Task can_send_messages_from_before_methods_that_ultimately_stop_the { using var host = await Host.CreateDefaultBuilder() .UseWolverine() - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); // Should fail validation if Number > 20 var tracked = await host.InvokeMessageAndWaitAsync(new MaybeBadThing(20)); @@ -45,7 +45,7 @@ public async Task can_send_messages_from_before_methods_that_ultimately_stop_the { using var host = await Host.CreateDefaultBuilder() .UseWolverine() - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); // Should fail validation if Number > 20 var tracked = await host.InvokeMessageAndWaitAsync(new MaybeBadThing3(20)); @@ -59,7 +59,7 @@ public async Task can_send_messages_from_before_methods_that_ultimately_stop_the { using var host = await Host.CreateDefaultBuilder() .UseWolverine() - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); // Should fail validation if Number > 20 var tracked = await host.InvokeMessageAndWaitAsync(new MaybeBadThing4(20)); @@ -73,7 +73,7 @@ public async Task can_send_messages_from_before_methods_that_ultimately_stop_the { using var host = await Host.CreateDefaultBuilder() .UseWolverine() - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); // Should fail validation if Number > 20 var tracked = await host @@ -90,7 +90,7 @@ public async Task can_send_messages_from_before_methods_that_ultimately_stop_the { using var host = await Host.CreateDefaultBuilder() .UseWolverine() - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); // Should fail validation if Number > 20 var tracked = await host.InvokeMessageAndWaitAsync(new MaybeBadThing2(20)); @@ -104,7 +104,7 @@ public async Task can_send_messages_from_before_methods_that_ultimately_stop_the { using var host = await Host.CreateDefaultBuilder() .UseWolverine() - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); // Should fail validation if Number > 20 var tracked = await host diff --git a/src/Testing/CoreTests/Acceptance/configuring_local_queues.cs b/src/Testing/CoreTests/Acceptance/configuring_local_queues.cs index b52a389b0..5a9002f93 100644 --- a/src/Testing/CoreTests/Acceptance/configuring_local_queues.cs +++ b/src/Testing/CoreTests/Acceptance/configuring_local_queues.cs @@ -40,7 +40,7 @@ public async Task use_with_separated_mode() using var host = await new HostBuilder().UseWolverine(opts => { opts.MultipleHandlerBehavior = MultipleHandlerBehavior.Separated; - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.GetRuntime(); runtime.Endpoints.EndpointByName(typeof(MultipleMessage1Handler).FullNameInCode().ToLowerInvariant()) diff --git a/src/Testing/CoreTests/Acceptance/encryption_acceptance.cs b/src/Testing/CoreTests/Acceptance/encryption_acceptance.cs index f2b2658e8..dbc99709d 100644 --- a/src/Testing/CoreTests/Acceptance/encryption_acceptance.cs +++ b/src/Testing/CoreTests/Acceptance/encryption_acceptance.cs @@ -105,7 +105,7 @@ public async Task routing_assigns_encrypting_serializer_for_published_message() opts.PublishAllMessages().ToLocalQueue("encrypted-queue"); opts.LocalQueue("encrypted-queue"); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var bus = host.MessageBus(); @@ -132,7 +132,7 @@ public async Task receive_with_unknown_key_id_routes_to_error_queue_two_host() opts.PublishAllMessages().To($"tcp://localhost:{receiverPort}"); opts.ServiceName = "sender"; }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); // Receiver host: only knows "k1", will reject "ghost" with EncryptionKeyNotFoundException. using var receiver = await Host.CreateDefaultBuilder() @@ -144,7 +144,7 @@ public async Task receive_with_unknown_key_id_routes_to_error_queue_two_host() opts.ListenAtPort(receiverPort); opts.ServiceName = "receiver"; }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var session = await receiver .TrackActivity(TimeSpan.FromSeconds(10)) @@ -173,7 +173,7 @@ public async Task receive_with_wrong_key_bytes_routes_to_error_queue() opts.PublishAllMessages().To($"tcp://localhost:{receiverPort}"); opts.ServiceName = "sender"; }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); using var receiver = await Host.CreateDefaultBuilder() .UseWolverine(opts => @@ -184,7 +184,7 @@ public async Task receive_with_wrong_key_bytes_routes_to_error_queue() opts.ListenAtPort(receiverPort); opts.ServiceName = "receiver"; }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var session = await receiver .TrackActivity(TimeSpan.FromSeconds(10)) @@ -209,7 +209,7 @@ public async Task receive_unencrypted_message_for_required_type_routes_to_error_ opts.PublishAllMessages().To($"tcp://localhost:{receiverPort}"); opts.ServiceName = "sender"; }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); // Receiver marks EncryptedPayload as encryption-required. The HandlerPipeline // guard must DLQ the forged plain-JSON envelope before any serializer runs. @@ -223,7 +223,7 @@ public async Task receive_unencrypted_message_for_required_type_routes_to_error_ opts.ListenAtPort(receiverPort); opts.ServiceName = "receiver"; }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var session = await receiver .TrackActivity(TimeSpan.FromSeconds(10)) @@ -250,7 +250,7 @@ public async Task receive_unencrypted_message_on_required_listener_routes_to_err opts.PublishAllMessages().To($"tcp://localhost:{receiverPort}"); opts.ServiceName = "sender"; }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); // Marker is on the LISTENER (.RequireEncryption()), not on the message type. // The HandlerPipeline guard must DLQ the forged plain-JSON envelope via the @@ -264,7 +264,7 @@ public async Task receive_unencrypted_message_on_required_listener_routes_to_err opts.ListenAtPort(receiverPort).RequireEncryption(); opts.ServiceName = "receiver"; }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var session = await receiver .TrackActivity(TimeSpan.FromSeconds(10)) @@ -298,7 +298,7 @@ public async Task encrypted_message_for_required_type_round_trips_two_host() opts.PublishAllMessages().To($"tcp://localhost:{receiverPort}"); opts.ServiceName = "sender"; }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); using var receiver = await Host.CreateDefaultBuilder() .UseWolverine(opts => @@ -310,7 +310,7 @@ public async Task encrypted_message_for_required_type_round_trips_two_host() opts.ListenAtPort(receiverPort); opts.ServiceName = "receiver"; }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); await receiver .TrackActivity(TimeSpan.FromSeconds(10)) @@ -341,7 +341,7 @@ public async Task plain_message_for_unmarked_type_passes_when_encryption_is_conf opts.PublishAllMessages().To($"tcp://localhost:{receiverPort}"); opts.ServiceName = "sender"; }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); using var receiver = await Host.CreateDefaultBuilder() .UseWolverine(opts => @@ -353,7 +353,7 @@ public async Task plain_message_for_unmarked_type_passes_when_encryption_is_conf opts.ListenAtPort(receiverPort); opts.ServiceName = "receiver"; }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var session = await receiver .TrackActivity(TimeSpan.FromSeconds(10)) @@ -407,7 +407,7 @@ public async Task wire_does_not_contain_plaintext_when_encryption_is_required() catch (ObjectDisposedException) { } catch (IOException) { } catch (SocketException) { } - }); + }, TestContext.Current.CancellationToken); try { @@ -421,7 +421,7 @@ public async Task wire_does_not_contain_plaintext_when_encryption_is_required() opts.PublishAllMessages().To($"tcp://localhost:{snifferPort}"); opts.ServiceName = "sender"; }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); using var receiver = await Host.CreateDefaultBuilder() .UseWolverine(opts => @@ -433,7 +433,7 @@ public async Task wire_does_not_contain_plaintext_when_encryption_is_required() opts.ListenAtPort(receiverPort); opts.ServiceName = "receiver"; }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); await receiver .TrackActivity(TimeSpan.FromSeconds(10)) @@ -459,7 +459,7 @@ await receiver { await snifferCts.CancelAsync(); try { sniffer.Stop(); } catch { } - try { await proxyTask.WaitAsync(TimeSpan.FromSeconds(2)); } catch { } + try { await proxyTask.WaitAsync(TimeSpan.FromSeconds(2), TestContext.Current.CancellationToken); } catch { } } } @@ -561,7 +561,7 @@ public async Task receive_unencrypted_message_for_required_supertype_routes_to_e opts.PublishAllMessages().To($"tcp://localhost:{receiverPort}"); opts.ServiceName = "sender"; }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); // Receiver marks the SUPERTYPE (interface) as encryption-required. The // wire MessageType resolves to the concrete SensitiveSubtype, which is @@ -577,7 +577,7 @@ public async Task receive_unencrypted_message_for_required_supertype_routes_to_e opts.ListenAtPort(receiverPort); opts.ServiceName = "receiver"; }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var session = await receiver .TrackActivity(TimeSpan.FromSeconds(10)) diff --git a/src/Testing/CoreTests/Acceptance/execution_finished_logs_duration_3063.cs b/src/Testing/CoreTests/Acceptance/execution_finished_logs_duration_3063.cs index 5f26c4d6d..9a523d4fa 100644 --- a/src/Testing/CoreTests/Acceptance/execution_finished_logs_duration_3063.cs +++ b/src/Testing/CoreTests/Acceptance/execution_finished_logs_duration_3063.cs @@ -24,7 +24,7 @@ public async Task finished_processing_log_includes_a_nonzero_duration() { opts.Services.AddSingleton(new SingleLoggerFactory(logger)); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); // Route through the worker (Executor.ExecuteAsync), not the inline invoke path await host.SendMessageAndWaitAsync(new DurationTestMessage("hello")); diff --git a/src/Testing/CoreTests/Acceptance/indefinite_scheduled_retries.cs b/src/Testing/CoreTests/Acceptance/indefinite_scheduled_retries.cs index a3b8727d1..a8d9aaf55 100644 --- a/src/Testing/CoreTests/Acceptance/indefinite_scheduled_retries.cs +++ b/src/Testing/CoreTests/Acceptance/indefinite_scheduled_retries.cs @@ -15,7 +15,7 @@ public async Task should_indefinitively_retry_command() using var cts = new CancellationTokenSource(5.Seconds()); using var host = await Host.CreateDefaultBuilder() .UseWolverine(opts => opts.Policies.OnException().ScheduleRetryIndefinitely(100.Milliseconds())) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var messageBus = host.MessageBus(); await messageBus.SendAsync(new IndefiniteRetriesCommand(cts, SucceedAfterAttempts: 5)); @@ -34,7 +34,7 @@ public async Task should_indefinitively_requeue_command() using var cts = new CancellationTokenSource(5.Seconds()); using var host = await Host.CreateDefaultBuilder() .UseWolverine(opts => opts.Policies.OnException().RequeueIndefinitely()) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var messageBus = host.MessageBus(); await messageBus.SendAsync(new IndefiniteRetriesCommand(cts, SucceedAfterAttempts: 5)); @@ -53,7 +53,7 @@ public async Task should_indefinitively_retry_command_when_given_multiple_delays using var cts = new CancellationTokenSource(5.Seconds()); using var host = await Host.CreateDefaultBuilder() .UseWolverine(opts => opts.Policies.OnException().ScheduleRetryIndefinitely(50.Milliseconds(), 100.Milliseconds())) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var messageBus = host.MessageBus(); await messageBus.SendAsync(new IndefiniteRetriesCommand(cts, SucceedAfterAttempts: 5)); @@ -72,7 +72,7 @@ public async Task should_stop_retrying_after_cancellation() using var cts = new CancellationTokenSource(5.Seconds()); using var host = await Host.CreateDefaultBuilder() .UseWolverine(opts => opts.Policies.OnException().ScheduleRetryIndefinitely(100.Milliseconds())) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var messageBus = host.MessageBus(); await messageBus.SendAsync(new IndefiniteRetriesCommand(cts, CancelAndFailAfterAttempts: 3)); diff --git a/src/Testing/CoreTests/Acceptance/invoke_tracing_mode.cs b/src/Testing/CoreTests/Acceptance/invoke_tracing_mode.cs index ad192d4d7..9f5e9dc3e 100644 --- a/src/Testing/CoreTests/Acceptance/invoke_tracing_mode.cs +++ b/src/Testing/CoreTests/Acceptance/invoke_tracing_mode.cs @@ -30,7 +30,7 @@ public async Task invoke_with_lightweight_tracing_does_not_emit_execution_log_me }) .Build(); - await host.StartAsync(); + await host.StartAsync(TestContext.Current.CancellationToken); try { @@ -44,7 +44,7 @@ public async Task invoke_with_lightweight_tracing_does_not_emit_execution_log_me } finally { - await host.StopAsync(); + await host.StopAsync(TestContext.Current.CancellationToken); host.Dispose(); } } @@ -62,7 +62,7 @@ public async Task invoke_with_full_tracing_emits_execution_log_messages() }) .Build(); - await host.StartAsync(); + await host.StartAsync(TestContext.Current.CancellationToken); try { @@ -76,7 +76,7 @@ public async Task invoke_with_full_tracing_emits_execution_log_messages() } finally { - await host.StopAsync(); + await host.StopAsync(TestContext.Current.CancellationToken); host.Dispose(); } } @@ -94,7 +94,7 @@ public async Task invoke_with_full_tracing_emits_failure_log_on_exception() }) .Build(); - await host.StartAsync(); + await host.StartAsync(TestContext.Current.CancellationToken); try { @@ -107,7 +107,7 @@ await Should.ThrowAsync(async () => } finally { - await host.StopAsync(); + await host.StopAsync(TestContext.Current.CancellationToken); host.Dispose(); } } @@ -125,7 +125,7 @@ public async Task invoke_with_full_tracing_emits_finished_log_on_exception() }) .Build(); - await host.StartAsync(); + await host.StartAsync(TestContext.Current.CancellationToken); try { @@ -138,7 +138,7 @@ await Should.ThrowAsync(async () => } finally { - await host.StopAsync(); + await host.StopAsync(TestContext.Current.CancellationToken); host.Dispose(); } } diff --git a/src/Testing/CoreTests/Acceptance/local_invoke_does_not_publish_the_return_value.cs b/src/Testing/CoreTests/Acceptance/local_invoke_does_not_publish_the_return_value.cs index 06e9547ca..818420cd6 100644 --- a/src/Testing/CoreTests/Acceptance/local_invoke_does_not_publish_the_return_value.cs +++ b/src/Testing/CoreTests/Acceptance/local_invoke_does_not_publish_the_return_value.cs @@ -11,7 +11,7 @@ public class local_invoke_does_not_publish_the_return_value public async Task should_not_publish_the_return_value_when_invoking_locally() { using var host = await Host.CreateDefaultBuilder() - .UseWolverine().StartAsync(); + .UseWolverine().StartAsync(cancellationToken: TestContext.Current.CancellationToken); var name = "Chris Jones"; var (tracked, response) = await host.InvokeMessageAndWaitAsync(new InvokeCommand(name)); diff --git a/src/Testing/CoreTests/Acceptance/missing_handlers.cs b/src/Testing/CoreTests/Acceptance/missing_handlers.cs index cb7af5501..fc1897f1b 100644 --- a/src/Testing/CoreTests/Acceptance/missing_handlers.cs +++ b/src/Testing/CoreTests/Acceptance/missing_handlers.cs @@ -31,7 +31,7 @@ public async Task calls_all_the_missing_handlers() break; } - await Task.Delay(250); + await Task.Delay(250, TestContext.Current.CancellationToken); } RecordingMissingHandler.Recorded.Single().Message.ShouldBeSameAs(message); diff --git a/src/Testing/CoreTests/Acceptance/on_exception_convention.cs b/src/Testing/CoreTests/Acceptance/on_exception_convention.cs index c3c9fdfd8..53bbed680 100644 --- a/src/Testing/CoreTests/Acceptance/on_exception_convention.cs +++ b/src/Testing/CoreTests/Acceptance/on_exception_convention.cs @@ -95,14 +95,14 @@ public async Task middleware_on_exception() opts.Services.AddSingleton(recorder); opts.Discovery.IncludeType(typeof(NoOwnExceptionHandler)); opts.Policies.AddMiddleware(typeof(GlobalOnExceptionMiddleware)); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); await host.TrackActivity().DoNotAssertOnExceptionsDetected() .PublishMessageAndWaitAsync(new MessageForMiddlewareTest("middleware test")); foreach (var action in recorder.Actions) _output.WriteLine($"\"{action}\""); - await host.StopAsync(); + await host.StopAsync(TestContext.Current.CancellationToken); recorder.Actions.ShouldContain("MiddlewareOnException:middleware test"); } @@ -117,14 +117,14 @@ public async Task non_static_middleware_on_exception_with_constructor_injection( opts.Services.AddSingleton(recorder); opts.Discovery.IncludeType(typeof(MessageForInstanceMiddlewareHandler)); opts.Policies.AddMiddleware(typeof(InstanceOnExceptionMiddleware)); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); await host.TrackActivity().DoNotAssertOnExceptionsDetected() .PublishMessageAndWaitAsync(new MessageForInstanceMiddleware("ctor inject test")); foreach (var action in recorder.Actions) _output.WriteLine($"\"{action}\""); - await host.StopAsync(); + await host.StopAsync(TestContext.Current.CancellationToken); recorder.Actions.ShouldContain("InstanceMiddlewareOnException:ctor inject test"); } @@ -139,14 +139,14 @@ public async Task middleware_with_ilogger_injection() opts.Services.AddSingleton(recorder); opts.Discovery.IncludeType(typeof(MessageForLoggerMiddlewareHandler)); opts.Policies.AddMiddleware(typeof(LoggerOnExceptionMiddleware)); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); await host.TrackActivity().DoNotAssertOnExceptionsDetected() .PublishMessageAndWaitAsync(new MessageForLoggerMiddleware("logger test")); foreach (var action in recorder.Actions) _output.WriteLine($"\"{action}\""); - await host.StopAsync(); + await host.StopAsync(TestContext.Current.CancellationToken); recorder.Actions.ShouldContain("LoggerOnException:logger test"); } @@ -164,14 +164,14 @@ public async Task static_middleware_on_exception_with_additional_injected_parame opts.Services.AddSingleton(probe); opts.Discovery.IncludeType(typeof(MessageForStaticMiddlewareDependencyHandler)); opts.Policies.AddMiddleware(typeof(StaticMiddlewareWithDependencyOnException)); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); await host.TrackActivity().DoNotAssertOnExceptionsDetected() .PublishMessageAndWaitAsync(new MessageForStaticMiddlewareDependency("static dependency test")); foreach (var action in recorder.Actions) _output.WriteLine($"\"{action}\""); - await host.StopAsync(); + await host.StopAsync(TestContext.Current.CancellationToken); recorder.Actions.ShouldContain("StaticDependencyOnException:static dependency test"); probe.WasCalled.ShouldBeTrue(); @@ -187,14 +187,14 @@ public async Task non_static_middleware_with_before_and_on_exception() opts.Services.AddSingleton(recorder); opts.Discovery.IncludeType(typeof(MessageForBeforeAndOnExceptionHandler)); opts.Policies.AddMiddleware(typeof(BeforeAndOnExceptionMiddleware)); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); await host.TrackActivity().DoNotAssertOnExceptionsDetected() .PublishMessageAndWaitAsync(new MessageForBeforeAndOnException("before+onexception test")); foreach (var action in recorder.Actions) _output.WriteLine($"\"{action}\""); - await host.StopAsync(); + await host.StopAsync(TestContext.Current.CancellationToken); recorder.Actions.ShouldContain("BeforeMiddleware:before+onexception test"); recorder.Actions.ShouldContain("BeforeAndOnExceptionMiddleware:before+onexception test"); @@ -210,14 +210,14 @@ public async Task non_static_middleware_shares_instance_state_between_before_and opts.Services.AddSingleton(recorder); opts.Discovery.IncludeType(typeof(MessageForSharedInstanceStateHandler)); opts.Policies.AddMiddleware(typeof(SharedInstanceStateMiddleware)); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); await host.TrackActivity().DoNotAssertOnExceptionsDetected() .PublishMessageAndWaitAsync(new MessageForSharedInstanceState("shared state")); foreach (var action in recorder.Actions) _output.WriteLine($"\"{action}\""); - await host.StopAsync(); + await host.StopAsync(TestContext.Current.CancellationToken); // The SAME middleware instance must be used for Before and OnException, so the state set in // Before is visible in OnException. A fresh catch-block instance would record "". @@ -235,13 +235,13 @@ public async Task static_on_exception_return_value_is_cascaded() opts.Discovery.IncludeType(typeof(MessageForReturningOnExceptionHandler)); opts.Discovery.IncludeType(typeof(CascadedFromOnExceptionHandler)); opts.Policies.AddMiddleware(typeof(ReturningOnExceptionMiddleware)); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var session = await host.TrackActivity().DoNotAssertOnExceptionsDetected() .PublishMessageAndWaitAsync(new MessageForReturningOnException("ret")); foreach (var action in recorder.Actions) _output.WriteLine($"\"{action}\""); - await host.StopAsync(); + await host.StopAsync(TestContext.Current.CancellationToken); recorder.Actions.ShouldContain("ReturningOnException:ret"); // The message RETURNED from OnException must be cascaded/published. @@ -261,13 +261,13 @@ public async Task instance_on_exception_return_value_is_cascaded() opts.Discovery.IncludeType(typeof(MessageForInstanceReturningOnExceptionHandler)); opts.Discovery.IncludeType(typeof(CascadedFromOnExceptionHandler)); opts.Policies.AddMiddleware(typeof(InstanceReturningOnExceptionMiddleware)); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var session = await host.TrackActivity().DoNotAssertOnExceptionsDetected() .PublishMessageAndWaitAsync(new MessageForInstanceReturningOnException("ret")); foreach (var action in recorder.Actions) _output.WriteLine($"\"{action}\""); - await host.StopAsync(); + await host.StopAsync(TestContext.Current.CancellationToken); recorder.Actions.ShouldContain("InstanceReturningOnException:ret"); session.Sent.SingleEnvelope().Message diff --git a/src/Testing/CoreTests/Acceptance/remote_invocation.cs b/src/Testing/CoreTests/Acceptance/remote_invocation.cs index 314013778..82c3f9dc7 100644 --- a/src/Testing/CoreTests/Acceptance/remote_invocation.cs +++ b/src/Testing/CoreTests/Acceptance/remote_invocation.cs @@ -419,7 +419,7 @@ public async Task always_publish_response_should_also_publish_on_remote_request_ // The response should ALSO have been published as a cascading message // and handled by AlwaysPublishResponseReceivedHandler on the receiver - var handled = await AlwaysPublishResponseReceivedHandler.Received.Task.WaitAsync(10.Seconds()); + var handled = await AlwaysPublishResponseReceivedHandler.Received.Task.WaitAsync(10.Seconds(), TestContext.Current.CancellationToken); handled.ShouldBeTrue(); } } diff --git a/src/Testing/CoreTests/Acceptance/requirement_result_validation_handlers.cs b/src/Testing/CoreTests/Acceptance/requirement_result_validation_handlers.cs index 9d7fad081..3f5314488 100644 --- a/src/Testing/CoreTests/Acceptance/requirement_result_validation_handlers.cs +++ b/src/Testing/CoreTests/Acceptance/requirement_result_validation_handlers.cs @@ -12,7 +12,7 @@ public async Task happy_path_with_requirement_result_validate() { using var host = await Host.CreateDefaultBuilder() .UseWolverine() - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); RequirementResultHandler.Handled = false; @@ -26,7 +26,7 @@ public async Task sad_path_with_requirement_result_validate() { using var host = await Host.CreateDefaultBuilder() .UseWolverine() - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); RequirementResultHandler.Handled = false; @@ -40,7 +40,7 @@ public async Task happy_path_with_async_requirement_result_validate() { using var host = await Host.CreateDefaultBuilder() .UseWolverine() - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); AsyncRequirementResultHandler.Handled = false; @@ -54,7 +54,7 @@ public async Task sad_path_with_async_requirement_result_validate() { using var host = await Host.CreateDefaultBuilder() .UseWolverine() - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); AsyncRequirementResultHandler.Handled = false; @@ -68,7 +68,7 @@ public async Task sad_path_with_empty_messages_requirement_result_validate() { using var host = await Host.CreateDefaultBuilder() .UseWolverine() - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); EmptyMessagesRequirementResultHandler.Handled = false; diff --git a/src/Testing/CoreTests/Acceptance/result_types_end_to_end.cs b/src/Testing/CoreTests/Acceptance/result_types_end_to_end.cs index 00512dca8..6049de881 100644 --- a/src/Testing/CoreTests/Acceptance/result_types_end_to_end.cs +++ b/src/Testing/CoreTests/Acceptance/result_types_end_to_end.cs @@ -30,10 +30,10 @@ private static IHostBuilder hostWithFluentResultsRegistered() => [Fact] public async Task invokeasync_T_against_result_returning_handler_unwraps_success() { - using var host = await hostWithFluentResultsRegistered().StartAsync(); + using var host = await hostWithFluentResultsRegistered().StartAsync(cancellationToken: TestContext.Current.CancellationToken); var bus = host.Services.GetRequiredService(); - var placed = await bus.InvokeAsync(new CreateOrder("o-1", 5)); + var placed = await bus.InvokeAsync(new CreateOrder("o-1", 5), TestContext.Current.CancellationToken); placed.ShouldNotBeNull(); placed.OrderId.ShouldBe("o-1"); @@ -47,7 +47,7 @@ public async Task invokeasync_T_against_result_returning_handler_unwraps_success [Fact(Skip = "GH-2221 follow-up: failure-branch InvokeAsync requires seam 2 to ship the raw wrapper on the reply path so component R can throw ResultFailureException. Same bucket as B-3 — Phase 3 polish + Phase 4 HTTP.")] public async Task invokeasync_T_against_result_failure_throws_resultfailureexception() { - using var host = await hostWithFluentResultsRegistered().StartAsync(); + using var host = await hostWithFluentResultsRegistered().StartAsync(cancellationToken: TestContext.Current.CancellationToken); var bus = host.Services.GetRequiredService(); var ex = await Should.ThrowAsync(async () => @@ -64,14 +64,14 @@ public async Task invokeasync_T_against_result_failure_throws_resultfailureexcep [Fact(Skip = "GH-2221 follow-up: InvokeAsync> wrapper-passthrough requires seam 2 to keep the raw wrapper on the reply path while seam 3 unwraps for fire-and-forget. Tracked as Phase 3 polish, alongside Phase 4 HTTP.")] public async Task invokeasync_of_raw_result_T_returns_the_wrapper_on_both_branches() { - using var host = await hostWithFluentResultsRegistered().StartAsync(); + using var host = await hostWithFluentResultsRegistered().StartAsync(cancellationToken: TestContext.Current.CancellationToken); var bus = host.Services.GetRequiredService(); - var success = await bus.InvokeAsync>(new CreateOrder("o-3", 5)); + var success = await bus.InvokeAsync>(new CreateOrder("o-3", 5), TestContext.Current.CancellationToken); success.IsSuccess.ShouldBeTrue(); success.Value.OrderId.ShouldBe("o-3"); - var failure = await bus.InvokeAsync>(new CreateOrder("o-4", 0)); + var failure = await bus.InvokeAsync>(new CreateOrder("o-4", 0), TestContext.Current.CancellationToken); failure.IsFailed.ShouldBeTrue(); failure.Errors.Select(e => e.Message).ShouldContain("Quantity must be positive"); } @@ -84,7 +84,7 @@ public async Task invokeasync_of_raw_result_T_returns_the_wrapper_on_both_branch [Fact] public async Task invokeasync_void_against_result_success_cascades_inner_T() { - using var host = await hostWithFluentResultsRegistered().StartAsync(); + using var host = await hostWithFluentResultsRegistered().StartAsync(cancellationToken: TestContext.Current.CancellationToken); var book = host.Services.GetRequiredService(); var tracked = await host @@ -108,7 +108,7 @@ public async Task invokeasync_void_against_result_success_cascades_inner_T() [Fact] public async Task invokeasync_void_against_result_failure_does_not_cascade_anything() { - using var host = await hostWithFluentResultsRegistered().StartAsync(); + using var host = await hostWithFluentResultsRegistered().StartAsync(cancellationToken: TestContext.Current.CancellationToken); var book = host.Services.GetRequiredService(); var tracked = await host @@ -130,10 +130,10 @@ public async Task invokeasync_void_against_result_failure_does_not_cascade_anyth [Fact] public async Task async_handler_returning_task_of_result_unwraps_normally() { - using var host = await hostWithFluentResultsRegistered().StartAsync(); + using var host = await hostWithFluentResultsRegistered().StartAsync(cancellationToken: TestContext.Current.CancellationToken); var bus = host.Services.GetRequiredService(); - var placed = await bus.InvokeAsync(new CreateOrderAsync("o-7", 5)); + var placed = await bus.InvokeAsync(new CreateOrderAsync("o-7", 5), TestContext.Current.CancellationToken); placed.OrderId.ShouldBe("o-7"); } @@ -141,13 +141,13 @@ public async Task async_handler_returning_task_of_result_unwraps_normally() [Fact] public async Task plain_non_result_handlers_are_unaffected_when_result_types_registered() { - using var host = await hostWithFluentResultsRegistered().StartAsync(); + using var host = await hostWithFluentResultsRegistered().StartAsync(cancellationToken: TestContext.Current.CancellationToken); var bus = host.Services.GetRequiredService(); // PlainCommand returns PlainResponse directly — no Result wrapper. The seam-3 policy // should leave its return-action source on the default CascadingMessageActionSource, and // the InvokeAsync caller path should bypass the Result-aware branch. - var response = await bus.InvokeAsync(new PlainCommand("hello")); + var response = await bus.InvokeAsync(new PlainCommand("hello"), TestContext.Current.CancellationToken); response.Echo.ShouldBe("hello"); } } diff --git a/src/Testing/CoreTests/Acceptance/saga_store_diagnostics_tests.cs b/src/Testing/CoreTests/Acceptance/saga_store_diagnostics_tests.cs index 59d466c5c..4a6e1c7a4 100644 --- a/src/Testing/CoreTests/Acceptance/saga_store_diagnostics_tests.cs +++ b/src/Testing/CoreTests/Acceptance/saga_store_diagnostics_tests.cs @@ -41,7 +41,7 @@ public async Task aggregator_concatenates_all_registered_storages() opts.Services.AddSingleton(martenStub); opts.Services.AddSingleton(efStub); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var diagnostics = host.GetRuntime().SagaStorage; var registered = await diagnostics.GetRegisteredSagasAsync(CancellationToken.None); @@ -91,7 +91,7 @@ public async Task aggregator_routes_read_to_correct_storage() opts.Services.AddSingleton(martenStub); opts.Services.AddSingleton(efStub); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var diagnostics = host.GetRuntime().SagaStorage; @@ -124,7 +124,7 @@ public async Task aggregator_returns_null_for_unknown_saga_type() using var host = await Host.CreateDefaultBuilder() .UseWolverine(opts => opts.Services.AddSingleton(stub)) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var diagnostics = host.GetRuntime().SagaStorage; @@ -149,7 +149,7 @@ public async Task aggregator_returns_empty_list_for_unknown_saga_type() using var host = await Host.CreateDefaultBuilder() .UseWolverine(opts => opts.Services.AddSingleton(stub)) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var list = await host.GetRuntime().SagaStorage.ListSagaInstancesAsync( "Some.Unknown.Saga, Wherever", 10, CancellationToken.None); @@ -184,7 +184,7 @@ public async Task aggregator_routes_by_short_name_or_full_name() using var host = await Host.CreateDefaultBuilder() .UseWolverine(opts => opts.Services.AddSingleton(stub)) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var diagnostics = host.GetRuntime().SagaStorage; @@ -206,7 +206,7 @@ public async Task no_storages_registered_returns_empty_catalog() // from having to null-check IWolverineRuntime.SagaStorage. using var host = await Host.CreateDefaultBuilder() .UseWolverine(_ => { }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var diagnostics = host.GetRuntime().SagaStorage; diagnostics.ShouldNotBeNull(); @@ -243,7 +243,7 @@ public async Task saga_types_collection_is_empty_when_no_sagas() // than blowing up. opts.Discovery.DisableConventionalDiscovery(); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var capabilities = await Wolverine.Configuration.Capabilities.ServiceCapabilities.ReadFrom( host.GetRuntime(), null, CancellationToken.None); diff --git a/src/Testing/CoreTests/Acceptance/service_tags_3240.cs b/src/Testing/CoreTests/Acceptance/service_tags_3240.cs index 4a2cc6b13..1327ff8d1 100644 --- a/src/Testing/CoreTests/Acceptance/service_tags_3240.cs +++ b/src/Testing/CoreTests/Acceptance/service_tags_3240.cs @@ -19,7 +19,7 @@ public async Task user_tags_flow_to_service_capabilities() { opts.Tags.Add("team:payments"); opts.Tags.Add("tier:critical"); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var capabilities = await ServiceCapabilities.ReadFrom(host.GetRuntime(), null, CancellationToken.None); @@ -29,7 +29,7 @@ public async Task user_tags_flow_to_service_capabilities() [Fact] public async Task tags_default_to_empty() { - using var host = await Host.CreateDefaultBuilder().UseWolverine().StartAsync(); + using var host = await Host.CreateDefaultBuilder().UseWolverine().StartAsync(cancellationToken: TestContext.Current.CancellationToken); var capabilities = await ServiceCapabilities.ReadFrom(host.GetRuntime(), null, CancellationToken.None); diff --git a/src/Testing/CoreTests/Acceptance/simple_validation_handlers.cs b/src/Testing/CoreTests/Acceptance/simple_validation_handlers.cs index 25d16d90b..e2f2c7e9d 100644 --- a/src/Testing/CoreTests/Acceptance/simple_validation_handlers.cs +++ b/src/Testing/CoreTests/Acceptance/simple_validation_handlers.cs @@ -12,7 +12,7 @@ public async Task happy_path_with_ienumerable_string_validate() { using var host = await Host.CreateDefaultBuilder() .UseWolverine() - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); SimpleValidationEnumerableHandler.Handled = false; @@ -26,7 +26,7 @@ public async Task sad_path_with_ienumerable_string_validate() { using var host = await Host.CreateDefaultBuilder() .UseWolverine() - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); SimpleValidationEnumerableHandler.Handled = false; @@ -40,7 +40,7 @@ public async Task happy_path_with_string_array_validate() { using var host = await Host.CreateDefaultBuilder() .UseWolverine() - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); SimpleValidationStringArrayHandler.Handled = false; @@ -54,7 +54,7 @@ public async Task sad_path_with_string_array_validate() { using var host = await Host.CreateDefaultBuilder() .UseWolverine() - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); SimpleValidationStringArrayHandler.Handled = false; @@ -68,7 +68,7 @@ public async Task happy_path_with_async_string_array_validate() { using var host = await Host.CreateDefaultBuilder() .UseWolverine() - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); SimpleValidationAsyncHandler.Handled = false; @@ -82,7 +82,7 @@ public async Task sad_path_with_async_string_array_validate() { using var host = await Host.CreateDefaultBuilder() .UseWolverine() - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); SimpleValidationAsyncHandler.Handled = false; @@ -96,7 +96,7 @@ public async Task happy_path_with_valuetask_string_array_validate() { using var host = await Host.CreateDefaultBuilder() .UseWolverine() - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); SimpleValidationValueTaskHandler.Handled = false; @@ -110,7 +110,7 @@ public async Task sad_path_with_validationoutcome_validate() { using var host = await Host.CreateDefaultBuilder() .UseWolverine() - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); SimpleValidationValidationOutcomeHandler.Handled = false; @@ -124,7 +124,7 @@ public async Task happy_path_with_validationoutcome_validate() { using var host = await Host.CreateDefaultBuilder() .UseWolverine() - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); SimpleValidationValidationOutcomeHandler.Handled = false; @@ -138,7 +138,7 @@ public async Task sad_path_with_validationoutcome_async_validate() { using var host = await Host.CreateDefaultBuilder() .UseWolverine() - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); SimpleValidationValidationOutcomeAsyncHandler.Handled = false; @@ -152,7 +152,7 @@ public async Task happy_path_with_validationoutcome_async_validate() { using var host = await Host.CreateDefaultBuilder() .UseWolverine() - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); SimpleValidationValidationOutcomeAsyncHandler.Handled = false; @@ -166,7 +166,7 @@ public async Task sad_path_with_valuetask_string_array_validate() { using var host = await Host.CreateDefaultBuilder() .UseWolverine() - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); SimpleValidationValueTaskHandler.Handled = false; diff --git a/src/Testing/CoreTests/Acceptance/sticky_message_handlers.cs b/src/Testing/CoreTests/Acceptance/sticky_message_handlers.cs index 0bdd6858d..ed496aa03 100644 --- a/src/Testing/CoreTests/Acceptance/sticky_message_handlers.cs +++ b/src/Testing/CoreTests/Acceptance/sticky_message_handlers.cs @@ -77,7 +77,7 @@ public async Task handler_policies_apply_to_sticky_message_handlers() opts.Policies.Add(policy); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); // Original chain for StickyMessage // The sticky handler for "blue" @@ -109,7 +109,7 @@ public async Task message_should_be_handled_separately_on_different_local_queues opts.LocalQueue("blue").AddStickyHandler(typeof(BlueSticky2Handler)); opts.LocalQueue("green").AddStickyHandler(typeof(GreenSticky2Handler)); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var stickyMessage = new StickyMessage2(); var session = await host.SendMessageAndWaitAsync(stickyMessage, timeoutInMilliseconds:60000); diff --git a/src/Testing/CoreTests/Acceptance/streaming_handler_support.cs b/src/Testing/CoreTests/Acceptance/streaming_handler_support.cs index 27586b30b..42a3b03ed 100644 --- a/src/Testing/CoreTests/Acceptance/streaming_handler_support.cs +++ b/src/Testing/CoreTests/Acceptance/streaming_handler_support.cs @@ -97,12 +97,12 @@ public async Task stream_items_from_local_handler() { using var host = await Host.CreateDefaultBuilder() .UseWolverine() - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var bus = host.MessageBus(); var items = new List(); - await foreach (var item in bus.StreamAsync(new StreamRequest(3))) + await foreach (var item in bus.StreamAsync(new StreamRequest(3), TestContext.Current.CancellationToken)) { items.Add(item); } @@ -116,12 +116,12 @@ public async Task stream_returns_empty_when_handler_yields_nothing() { using var host = await Host.CreateDefaultBuilder() .UseWolverine() - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var bus = host.MessageBus(); var items = new List(); - await foreach (var item in bus.StreamAsync(new StreamRequest(0))) + await foreach (var item in bus.StreamAsync(new StreamRequest(0), TestContext.Current.CancellationToken)) { items.Add(item); } @@ -134,7 +134,7 @@ public async Task cancellation_stops_iteration() { using var host = await Host.CreateDefaultBuilder() .UseWolverine() - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var bus = host.MessageBus(); @@ -168,7 +168,7 @@ public async Task typed_async_enumerable_cascades_items_via_regular_invoke() { opts.Services.AddSingleton(tracker); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); await host.InvokeMessageAndWaitAsync(new CascadeRequest(3)); @@ -185,7 +185,7 @@ public async Task handler_exception_after_partial_yield_surfaces_to_caller_with_ // composing streaming handlers - partial results are not silently swallowed. using var host = await Host.CreateDefaultBuilder() .UseWolverine() - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var bus = host.MessageBus(); @@ -216,7 +216,7 @@ public async Task mid_stream_throw_marks_activity_status_error() using var host = await Host.CreateDefaultBuilder() .UseWolverine() - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var bus = host.MessageBus(); @@ -238,13 +238,13 @@ public async Task stream_with_delivery_options() { using var host = await Host.CreateDefaultBuilder() .UseWolverine() - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var bus = host.MessageBus(); var options = new DeliveryOptions(); var items = new List(); - await foreach (var item in bus.StreamAsync(new StreamRequest(2), options)) + await foreach (var item in bus.StreamAsync(new StreamRequest(2), options, TestContext.Current.CancellationToken)) { items.Add(item); } diff --git a/src/Testing/CoreTests/Acceptance/streaming_request_support.cs b/src/Testing/CoreTests/Acceptance/streaming_request_support.cs index 9304d34a8..36026581d 100644 --- a/src/Testing/CoreTests/Acceptance/streaming_request_support.cs +++ b/src/Testing/CoreTests/Acceptance/streaming_request_support.cs @@ -136,12 +136,12 @@ public async Task stream_request_returns_aggregated_response() { using var host = await Host.CreateDefaultBuilder() .UseWolverine() - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var bus = host.MessageBus(); var numbers = toStream(Enumerable.Range(1, 4).Select(i => new NumberToSum(i))); - var sum = await bus.StreamAsync(numbers); + var sum = await bus.StreamAsync(numbers, TestContext.Current.CancellationToken); sum.Total.ShouldBe(10); sum.Count.ShouldBe(4); @@ -152,11 +152,11 @@ public async Task empty_stream_still_returns_response() { using var host = await Host.CreateDefaultBuilder() .UseWolverine() - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var bus = host.MessageBus(); - var sum = await bus.StreamAsync(toStream(Array.Empty())); + var sum = await bus.StreamAsync(toStream(Array.Empty()), TestContext.Current.CancellationToken); sum.Total.ShouldBe(0); sum.Count.ShouldBe(0); @@ -167,12 +167,12 @@ public async Task handler_without_cancellation_token_parameter_works() { using var host = await Host.CreateDefaultBuilder() .UseWolverine() - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var bus = host.MessageBus(); var numbers = toStream([new PlainNumber(5), new PlainNumber(7)]); - var sum = await bus.StreamAsync(numbers); + var sum = await bus.StreamAsync(numbers, TestContext.Current.CancellationToken); sum.Total.ShouldBe(12); sum.Count.ShouldBe(2); @@ -183,7 +183,7 @@ public async Task no_stream_handler_throws_clear_not_supported() { using var host = await Host.CreateDefaultBuilder() .UseWolverine() - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var bus = host.MessageBus(); @@ -201,7 +201,7 @@ public async Task handler_exception_mid_drain_surfaces_to_caller() { using var host = await Host.CreateDefaultBuilder() .UseWolverine() - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var bus = host.MessageBus(); @@ -219,7 +219,7 @@ public async Task cancellation_propagates_into_the_handler() { using var host = await Host.CreateDefaultBuilder() .UseWolverine() - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var bus = host.MessageBus(); @@ -259,7 +259,7 @@ public async Task cascading_messages_from_stream_handler_are_published() { opts.Services.AddSingleton(tracker); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); NumberSum? sum = null; await host.ExecuteAndWaitAsync(async context => @@ -281,13 +281,13 @@ public async Task stream_request_with_delivery_options() { using var host = await Host.CreateDefaultBuilder() .UseWolverine() - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var bus = host.MessageBus(); var options = new DeliveryOptions(); var numbers = toStream([new NumberToSum(1), new NumberToSum(2)]); - var sum = await bus.StreamAsync(numbers, options); + var sum = await bus.StreamAsync(numbers, options, TestContext.Current.CancellationToken); sum.Total.ShouldBe(3); } @@ -299,12 +299,12 @@ public async Task ordinary_single_message_invoke_is_unaffected_by_stream_chains( // interfere with normal single-message request/reply on unrelated types. using var host = await Host.CreateDefaultBuilder() .UseWolverine() - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var bus = host.MessageBus(); var items = new List(); - await foreach (var item in bus.StreamAsync(new StreamRequest(2))) + await foreach (var item in bus.StreamAsync(new StreamRequest(2), TestContext.Current.CancellationToken)) { items.Add(item); } diff --git a/src/Testing/CoreTests/Acceptance/system_message_type_filtering.cs b/src/Testing/CoreTests/Acceptance/system_message_type_filtering.cs index 2ebc34511..892be729e 100644 --- a/src/Testing/CoreTests/Acceptance/system_message_type_filtering.cs +++ b/src/Testing/CoreTests/Acceptance/system_message_type_filtering.cs @@ -58,7 +58,7 @@ public async Task service_capabilities_excludes_system_message_types() opts.Discovery.DisableConventionalDiscovery(); opts.Discovery.IncludeType(); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var capabilities = await ServiceCapabilities.ReadFrom(host.GetRuntime(), null, CancellationToken.None); @@ -80,7 +80,7 @@ public async Task observer_does_not_receive_message_routed_for_system_types() opts.Discovery.DisableConventionalDiscovery(); opts.Discovery.IncludeType(); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.GetRuntime(); diff --git a/src/Testing/CoreTests/Acceptance/using_async_extensions.cs b/src/Testing/CoreTests/Acceptance/using_async_extensions.cs index 70ab800da..dd2486afd 100644 --- a/src/Testing/CoreTests/Acceptance/using_async_extensions.cs +++ b/src/Testing/CoreTests/Acceptance/using_async_extensions.cs @@ -25,7 +25,7 @@ public async Task apply_async_extension_with_feature_flag_positive() opts.Services.AddAsyncWolverineExtension(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = (WolverineRuntime)host.Services.GetRequiredService(); var queue = runtime.Options.Transports.TryGetEndpoint(new Uri("local://module1-high-priority")); @@ -49,7 +49,7 @@ public async Task apply_async_extension_with_feature_flag_negative() // Adding the async extension to the underlying IoC container opts.Services.AddAsyncWolverineExtension(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); #endregion diff --git a/src/Testing/CoreTests/Acceptance/using_custom_side_effect.cs b/src/Testing/CoreTests/Acceptance/using_custom_side_effect.cs index fbba1a39c..3c1da9e53 100644 --- a/src/Testing/CoreTests/Acceptance/using_custom_side_effect.cs +++ b/src/Testing/CoreTests/Acceptance/using_custom_side_effect.cs @@ -11,7 +11,7 @@ public class using_custom_side_effect public async Task use_custom_side_effect() { var host = await Host.CreateDefaultBuilder() - .UseWolverine().StartAsync(); + .UseWolverine().StartAsync(cancellationToken: TestContext.Current.CancellationToken); await host.InvokeMessageAndWaitAsync(new RecordText(Guid.NewGuid(), "some text")); } diff --git a/src/Testing/CoreTests/Acceptance/using_side_effect_as_return_values.cs b/src/Testing/CoreTests/Acceptance/using_side_effect_as_return_values.cs index 400caf207..0b7e3ee73 100644 --- a/src/Testing/CoreTests/Acceptance/using_side_effect_as_return_values.cs +++ b/src/Testing/CoreTests/Acceptance/using_side_effect_as_return_values.cs @@ -17,7 +17,7 @@ public async Task using_side_effect_as_return_value() .UseWolverine(opts => { opts.Services.AddSingleton(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var graph = host.Services.GetRequiredService(); var chain = graph.ChainFor(); diff --git a/src/Testing/CoreTests/Acceptance/wolverine_as_command_bus.cs b/src/Testing/CoreTests/Acceptance/wolverine_as_command_bus.cs index b22c23505..6dc00a1d3 100644 --- a/src/Testing/CoreTests/Acceptance/wolverine_as_command_bus.cs +++ b/src/Testing/CoreTests/Acceptance/wolverine_as_command_bus.cs @@ -54,7 +54,7 @@ public async Task will_process_inline() var message = new Message5(); - await Publisher.InvokeAsync(message); + await Publisher.InvokeAsync(message, TestContext.Current.CancellationToken); theTracker.LastMessage.ShouldBeSameAs(message); } @@ -65,7 +65,7 @@ public async Task use_retry_in_invoke() await configure(); var message = new InvokedMessage { FailThisManyTimes = 2 }; - await Publisher.InvokeAsync(message); + await Publisher.InvokeAsync(message, TestContext.Current.CancellationToken); } [Fact] @@ -75,7 +75,7 @@ public async Task will_send_cascading_messages() var message = new Message5(); - await Publisher.InvokeAsync(message); + await Publisher.InvokeAsync(message, TestContext.Current.CancellationToken); var m1 = await theTracker.Message1; m1.Id.ShouldBe(message.Id); @@ -97,7 +97,7 @@ internal async ValueTask using_global_request_and_reply(IMessageContext messagin [Fact] public async Task invoke_expecting_a_response() { - var answer = await Bus.InvokeAsync(new Question { One = 3, Two = 4 }); + var answer = await Bus.InvokeAsync(new Question { One = 3, Two = 4 }, TestContext.Current.CancellationToken); answer.Sum.ShouldBe(7); answer.Product.ShouldBe(12); @@ -106,7 +106,7 @@ public async Task invoke_expecting_a_response() [Fact] public async Task invoke_expecting_a_response_with_struct() { - var answer = await Bus.InvokeAsync(new QuestionStruct { One = 3, Two = 4 }); + var answer = await Bus.InvokeAsync(new QuestionStruct { One = 3, Two = 4 }, TestContext.Current.CancellationToken); answer.Sum.ShouldBe(7); answer.Product.ShouldBe(12); @@ -124,14 +124,14 @@ await Should.ThrowAsync(async () => [Fact] public async Task invoke_with_no_known_response_do_not_blow_up() { - (await Bus.InvokeAsync(new QuestionWithNoAnswer())) + (await Bus.InvokeAsync(new QuestionWithNoAnswer(), TestContext.Current.CancellationToken)) .ShouldBeNull(); } [Fact] public async Task should_return_result_for_command_with_castable_result() { - var answer = await Bus.InvokeAsync(new Question { One = 3, Two = 4 }); + var answer = await Bus.InvokeAsync(new Question { One = 3, Two = 4 }, TestContext.Current.CancellationToken); answer.Sum.ShouldBe(7); answer.Product.ShouldBe(12); diff --git a/src/Testing/CoreTests/Bugs/Bug_1182_infinite_loop_codegen.cs b/src/Testing/CoreTests/Bugs/Bug_1182_infinite_loop_codegen.cs index efc496b6a..4d53e723e 100644 --- a/src/Testing/CoreTests/Bugs/Bug_1182_infinite_loop_codegen.cs +++ b/src/Testing/CoreTests/Bugs/Bug_1182_infinite_loop_codegen.cs @@ -20,7 +20,7 @@ public async Task do_not_go_into_infinite_loop() .UseWolverine(opts => { opts.Discovery.DisableConventionalDiscovery().IncludeType(typeof(InfiniteCommandHandlingThing)); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var collections = host.Services.GetServices().ToArray(); diff --git a/src/Testing/CoreTests/Bugs/Bug_143_disambiguate_logger_variables.cs b/src/Testing/CoreTests/Bugs/Bug_143_disambiguate_logger_variables.cs index 7c06b204a..96db6135d 100644 --- a/src/Testing/CoreTests/Bugs/Bug_143_disambiguate_logger_variables.cs +++ b/src/Testing/CoreTests/Bugs/Bug_143_disambiguate_logger_variables.cs @@ -13,7 +13,7 @@ public async Task can_disentangle_the_variables() using var host = await Host .CreateDefaultBuilder() .UseWolverine() - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); await host.InvokeMessageAndWaitAsync(new LoggedMessage("Nick Boltan")); } diff --git a/src/Testing/CoreTests/Bugs/Bug_147_disambiguate_variables_from_multiple_handlers.cs b/src/Testing/CoreTests/Bugs/Bug_147_disambiguate_variables_from_multiple_handlers.cs index c4b3af5a6..a82405c39 100644 --- a/src/Testing/CoreTests/Bugs/Bug_147_disambiguate_variables_from_multiple_handlers.cs +++ b/src/Testing/CoreTests/Bugs/Bug_147_disambiguate_variables_from_multiple_handlers.cs @@ -12,7 +12,7 @@ public class Bug_147_disambiguate_variables_from_multiple_handlers public async Task can_return_same_type_from_multiple_handlers() { using var host = await Host.CreateDefaultBuilder() - .UseWolverine().StartAsync(); + .UseWolverine().StartAsync(cancellationToken: TestContext.Current.CancellationToken); var tracked = await host.InvokeMessageAndWaitAsync(new StartingMessage("Creed Humphrey")); diff --git a/src/Testing/CoreTests/Bugs/Bug_2004_separated_handler_stuff.cs b/src/Testing/CoreTests/Bugs/Bug_2004_separated_handler_stuff.cs index 23fa665c0..bfec9bbe5 100644 --- a/src/Testing/CoreTests/Bugs/Bug_2004_separated_handler_stuff.cs +++ b/src/Testing/CoreTests/Bugs/Bug_2004_separated_handler_stuff.cs @@ -17,7 +17,7 @@ public async Task multiple_handler_file_overwrite() opts.CodeGeneration.TypeLoadMode = TypeLoadMode.Auto; opts.MultipleHandlerBehavior = MultipleHandlerBehavior.Separated; }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); await host.SendMessageAndWaitAsync(new SayStuff0()); } diff --git a/src/Testing/CoreTests/Bugs/Bug_2023_invoke_with_discard_error_handling.cs b/src/Testing/CoreTests/Bugs/Bug_2023_invoke_with_discard_error_handling.cs index 7bb48502e..1b2cbfb13 100644 --- a/src/Testing/CoreTests/Bugs/Bug_2023_invoke_with_discard_error_handling.cs +++ b/src/Testing/CoreTests/Bugs/Bug_2023_invoke_with_discard_error_handling.cs @@ -21,7 +21,7 @@ public async Task should_throw_the_exception_from_invoke() // Do some application-specific error handling here... return new ValueTask(); }); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var bus = host.MessageBus(); diff --git a/src/Testing/CoreTests/Bugs/Bug_229_using_generic_types_with_local_queue_names.cs b/src/Testing/CoreTests/Bugs/Bug_229_using_generic_types_with_local_queue_names.cs index 384c6b28a..dde49c9b9 100644 --- a/src/Testing/CoreTests/Bugs/Bug_229_using_generic_types_with_local_queue_names.cs +++ b/src/Testing/CoreTests/Bugs/Bug_229_using_generic_types_with_local_queue_names.cs @@ -10,7 +10,7 @@ public async Task can_start_up_the_app_without_invalid_queueNames_for_message_ty { using var host = await Host.CreateDefaultBuilder() .UseWolverine() - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); } } diff --git a/src/Testing/CoreTests/Bugs/Bug_2326_disambiguate_outgoing_messages_from_multiple_middleware.cs b/src/Testing/CoreTests/Bugs/Bug_2326_disambiguate_outgoing_messages_from_multiple_middleware.cs index 836387bf2..189c32aab 100644 --- a/src/Testing/CoreTests/Bugs/Bug_2326_disambiguate_outgoing_messages_from_multiple_middleware.cs +++ b/src/Testing/CoreTests/Bugs/Bug_2326_disambiguate_outgoing_messages_from_multiple_middleware.cs @@ -16,7 +16,7 @@ public async Task can_compile_handler_with_multiple_middleware_returning_outgoin { opts.Discovery.DisableConventionalDiscovery() .IncludeType(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); // If code gen produces duplicate variable names, compilation will fail here var chain = host.GetRuntime().Handlers.ChainFor(); diff --git a/src/Testing/CoreTests/Bugs/Bug_2471_codegen_without_connectivity.cs b/src/Testing/CoreTests/Bugs/Bug_2471_codegen_without_connectivity.cs index 11e82b836..467eac74f 100644 --- a/src/Testing/CoreTests/Bugs/Bug_2471_codegen_without_connectivity.cs +++ b/src/Testing/CoreTests/Bugs/Bug_2471_codegen_without_connectivity.cs @@ -63,7 +63,7 @@ public async Task host_startup_applies_lightweight_mode_automatically_during_cod opts.Discovery.DisableConventionalDiscovery() .IncludeType(typeof(SimpleCodegenHandler2471)); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.GetRuntime(); diff --git a/src/Testing/CoreTests/Bugs/Bug_263_return_string_from_load_async.cs b/src/Testing/CoreTests/Bugs/Bug_263_return_string_from_load_async.cs index 6ce266f79..4e5b56ac7 100644 --- a/src/Testing/CoreTests/Bugs/Bug_263_return_string_from_load_async.cs +++ b/src/Testing/CoreTests/Bugs/Bug_263_return_string_from_load_async.cs @@ -10,7 +10,7 @@ public class Bug_263_return_string_from_load_async public async Task can_return_a_string_from_a_load_precursor_and_pass_to_main_handle() { using var host = await Host.CreateDefaultBuilder() - .UseWolverine().StartAsync(); + .UseWolverine().StartAsync(cancellationToken: TestContext.Current.CancellationToken); await host.InvokeMessageAndWaitAsync(new StringUsingCommand("one")); diff --git a/src/Testing/CoreTests/Bugs/Bug_263_returning_string_from_middleware_method.cs b/src/Testing/CoreTests/Bugs/Bug_263_returning_string_from_middleware_method.cs index f65c8d5ea..55d84df7c 100644 --- a/src/Testing/CoreTests/Bugs/Bug_263_returning_string_from_middleware_method.cs +++ b/src/Testing/CoreTests/Bugs/Bug_263_returning_string_from_middleware_method.cs @@ -9,7 +9,7 @@ public class Bug_263_returning_string_from_middleware_method public async Task can_return_and_use_string_from_tuple() { using var host = await Host.CreateDefaultBuilder() - .UseWolverine().StartAsync(); + .UseWolverine().StartAsync(cancellationToken: TestContext.Current.CancellationToken); await host.InvokeAsync(new Bug263("Tom")); diff --git a/src/Testing/CoreTests/Bugs/Bug_267_throw_descriptive_message_on_multiple_variables.cs b/src/Testing/CoreTests/Bugs/Bug_267_throw_descriptive_message_on_multiple_variables.cs index e3a03259a..7937ddc4f 100644 --- a/src/Testing/CoreTests/Bugs/Bug_267_throw_descriptive_message_on_multiple_variables.cs +++ b/src/Testing/CoreTests/Bugs/Bug_267_throw_descriptive_message_on_multiple_variables.cs @@ -16,7 +16,7 @@ public async Task descriptive_message_somehow() .UseWolverine(opts => { opts.DisableConventionalDiscovery().IncludeType(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); await Should.ThrowAsync(async () => { diff --git a/src/Testing/CoreTests/Bugs/Bug_2896_mixed_lifetime_enumerable_dependency.cs b/src/Testing/CoreTests/Bugs/Bug_2896_mixed_lifetime_enumerable_dependency.cs index 508aac617..c55d8dfaf 100644 --- a/src/Testing/CoreTests/Bugs/Bug_2896_mixed_lifetime_enumerable_dependency.cs +++ b/src/Testing/CoreTests/Bugs/Bug_2896_mixed_lifetime_enumerable_dependency.cs @@ -28,9 +28,9 @@ public async Task mixed_lifetime_enumerable_dependency_resolves_every_element() opts.Discovery.DisableConventionalDiscovery() .IncludeType(typeof(Bug2896Handler)); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); - await host.MessageBus().InvokeAsync(new Bug2896Message()); + await host.MessageBus().InvokeAsync(new Bug2896Message(), TestContext.Current.CancellationToken); var received = Bug2896Handler.Received.ShouldNotBeNull(); received.Length.ShouldBe(2); diff --git a/src/Testing/CoreTests/Bugs/Bug_312_multiple_handlers_for_same_message_with_same_name_bug_different_namespaces.cs b/src/Testing/CoreTests/Bugs/Bug_312_multiple_handlers_for_same_message_with_same_name_bug_different_namespaces.cs index a031b190a..d0ab7dd84 100644 --- a/src/Testing/CoreTests/Bugs/Bug_312_multiple_handlers_for_same_message_with_same_name_bug_different_namespaces.cs +++ b/src/Testing/CoreTests/Bugs/Bug_312_multiple_handlers_for_same_message_with_same_name_bug_different_namespaces.cs @@ -25,7 +25,7 @@ public async Task disambiguate_the_handler_variable_names() // not the lambda form, so allow the type explicitly. opts.CodeGeneration.AlwaysUseServiceLocationFor(); opts.Services.AddScoped(x => new IdentityService()); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); await host.InvokeMessageAndWaitAsync(new SayStuff("Hi")); } diff --git a/src/Testing/CoreTests/Bugs/Bug_3263_wire_tap_on_scheduled_send.cs b/src/Testing/CoreTests/Bugs/Bug_3263_wire_tap_on_scheduled_send.cs index 85a538f32..ca7b3619f 100644 --- a/src/Testing/CoreTests/Bugs/Bug_3263_wire_tap_on_scheduled_send.cs +++ b/src/Testing/CoreTests/Bugs/Bug_3263_wire_tap_on_scheduled_send.cs @@ -105,7 +105,7 @@ public async Task wire_tap_fires_for_scheduled_send_after_durable_recovery() await context.ForwardScheduledEnvelopeAsync(recovered); // The send-side wire tap is fired fire-and-forget from WolverineRuntime.Sent. - await Task.Delay(250); + await Task.Delay(250, TestContext.Current.CancellationToken); _wireTap.Successes.ShouldContain( e => e.MessageType == typeof(ScheduledAuditMessage).ToMessageTypeName(), @@ -143,7 +143,7 @@ public async Task wire_tap_fires_for_recovered_outgoing_message() await command.ExecuteAsync(runtime, CancellationToken.None); // The send-side wire tap is fired fire-and-forget from WolverineRuntime.Sent. - await Task.Delay(250); + await Task.Delay(250, TestContext.Current.CancellationToken); _wireTap.Successes.ShouldContain( e => e.MessageType == typeof(ScheduledAuditMessage).ToMessageTypeName(), diff --git a/src/Testing/CoreTests/Bugs/Bug_3343_separated_handlers_no_loop.cs b/src/Testing/CoreTests/Bugs/Bug_3343_separated_handlers_no_loop.cs index 70cf53a39..927401529 100644 --- a/src/Testing/CoreTests/Bugs/Bug_3343_separated_handlers_no_loop.cs +++ b/src/Testing/CoreTests/Bugs/Bug_3343_separated_handlers_no_loop.cs @@ -45,7 +45,7 @@ public async Task both_separated_handlers_run_exactly_once_no_loop() opts.Policies.OnException() .RetryWithCooldown(50.Milliseconds(), 100.Milliseconds(), 250.Milliseconds()); opts.MultipleHandlerBehavior = MultipleHandlerBehavior.Separated; - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var tracked = await host .TrackActivity() diff --git a/src/Testing/CoreTests/Bugs/Bug_3399_batched_message_separated_handler_codegen.cs b/src/Testing/CoreTests/Bugs/Bug_3399_batched_message_separated_handler_codegen.cs index f4bd0ad74..da823be4f 100644 --- a/src/Testing/CoreTests/Bugs/Bug_3399_batched_message_separated_handler_codegen.cs +++ b/src/Testing/CoreTests/Bugs/Bug_3399_batched_message_separated_handler_codegen.cs @@ -34,7 +34,7 @@ public async Task can_start_up_with_separated_batched_handler() opts.MultipleHandlerBehavior = MultipleHandlerBehavior.Separated; opts.BatchMessagesOf(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.GetRuntime(); @@ -73,7 +73,7 @@ public async Task batched_handler_actually_executes() opts.MultipleHandlerBehavior = MultipleHandlerBehavior.Separated; opts.BatchMessagesOf(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); await host.TrackActivity() .Timeout(30.Seconds()) diff --git a/src/Testing/CoreTests/Bugs/Bug_42_concurrent_creation_of_command_handlers.cs b/src/Testing/CoreTests/Bugs/Bug_42_concurrent_creation_of_command_handlers.cs index 6fbe89b85..95b0d9de1 100644 --- a/src/Testing/CoreTests/Bugs/Bug_42_concurrent_creation_of_command_handlers.cs +++ b/src/Testing/CoreTests/Bugs/Bug_42_concurrent_creation_of_command_handlers.cs @@ -18,7 +18,7 @@ public async Task try_to_break() { opts.Policies.AddMiddleware(); opts.Policies.AddMiddleware(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var bus = host.MessageBus(); diff --git a/src/Testing/CoreTests/Bugs/Bug_559_erroneous_failure_ack.cs b/src/Testing/CoreTests/Bugs/Bug_559_erroneous_failure_ack.cs index 9350f0265..8b688c64f 100644 --- a/src/Testing/CoreTests/Bugs/Bug_559_erroneous_failure_ack.cs +++ b/src/Testing/CoreTests/Bugs/Bug_559_erroneous_failure_ack.cs @@ -12,7 +12,7 @@ public Bug_559_erroneous_failure_ack(DefaultApp @default) : base(@default) public async Task no_failure_ack() { var id = Guid.NewGuid(); - var expected = await Publisher.InvokeAsync(new Bug559Request(id)); + var expected = await Publisher.InvokeAsync(new Bug559Request(id), TestContext.Current.CancellationToken); expected.ShouldBe(id); } diff --git a/src/Testing/CoreTests/Compilation/disposing_disposable_or_async_disposable.cs b/src/Testing/CoreTests/Compilation/disposing_disposable_or_async_disposable.cs index a9cb5e5d1..44f16d510 100644 --- a/src/Testing/CoreTests/Compilation/disposing_disposable_or_async_disposable.cs +++ b/src/Testing/CoreTests/Compilation/disposing_disposable_or_async_disposable.cs @@ -16,7 +16,7 @@ public async Task run_end_to_end() opts.Services.AddScoped(); opts.Services.AddScoped(); opts.Services.AddScoped(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); await host.InvokeAsync(new DisposingMessage()); diff --git a/src/Testing/CoreTests/Compilation/enumerable_dependencies.cs b/src/Testing/CoreTests/Compilation/enumerable_dependencies.cs index 468f955e3..0bb6771d9 100644 --- a/src/Testing/CoreTests/Compilation/enumerable_dependencies.cs +++ b/src/Testing/CoreTests/Compilation/enumerable_dependencies.cs @@ -36,7 +36,7 @@ public async Task can_use_mixed_scoping_of_array_elements() opts.CodeGeneration.TypeLoadMode = TypeLoadMode.Auto; - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); await host.InvokeMessageAndWaitAsync(new WidgetUsingMessage()); await host.InvokeMessageAndWaitAsync(new WidgetUsingMessage2()); diff --git a/src/Testing/CoreTests/Compilation/handler_that_uses_ilogger.cs b/src/Testing/CoreTests/Compilation/handler_that_uses_ilogger.cs index 1d362efc5..bbf3482e5 100644 --- a/src/Testing/CoreTests/Compilation/handler_that_uses_ilogger.cs +++ b/src/Testing/CoreTests/Compilation/handler_that_uses_ilogger.cs @@ -20,7 +20,7 @@ public async Task can_compile_with_ilogger_dependency_Bug_666() using var host = WolverineHost.Basic(); var bus = host.MessageBus(); - await bus.InvokeAsync(new ItemCreated()); + await bus.InvokeAsync(new ItemCreated(), TestContext.Current.CancellationToken); var graph = host.Services.GetRequiredService(); var chain = graph.ChainFor(); diff --git a/src/Testing/CoreTests/Compilation/handler_with_optional_side_effect.cs b/src/Testing/CoreTests/Compilation/handler_with_optional_side_effect.cs index ce35da510..feab3d1d3 100644 --- a/src/Testing/CoreTests/Compilation/handler_with_optional_side_effect.cs +++ b/src/Testing/CoreTests/Compilation/handler_with_optional_side_effect.cs @@ -19,7 +19,7 @@ public async Task can_compile_correctly_for_handler_with_optional_side_effect_re using var host = WolverineHost.Basic(); var bus = host.MessageBus(); - await bus.InvokeAsync(new SomeCommand()); + await bus.InvokeAsync(new SomeCommand(), TestContext.Current.CancellationToken); var graph = host.Services.GetRequiredService(); var chain = graph.ChainFor(); @@ -33,7 +33,7 @@ public async Task can_compile_correctly_for_handler_with_optional_side_effect_re using var host = WolverineHost.Basic(); var bus = host.MessageBus(); - await bus.InvokeAsync(new SomeOtherCommand()); + await bus.InvokeAsync(new SomeOtherCommand(), TestContext.Current.CancellationToken); var graph = host.Services.GetRequiredService(); var chain = graph.ChainFor(); diff --git a/src/Testing/CoreTests/Configuration/bootstrapping_specs.cs b/src/Testing/CoreTests/Configuration/bootstrapping_specs.cs index 87b1f6c8c..8438036ee 100644 --- a/src/Testing/CoreTests/Configuration/bootstrapping_specs.cs +++ b/src/Testing/CoreTests/Configuration/bootstrapping_specs.cs @@ -76,7 +76,7 @@ public async Task bootstrap_with_extension_finding_disabled() opts.UseRuntimeCompilation(); }, ExtensionDiscovery.ManualOnly) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); #endregion diff --git a/src/Testing/CoreTests/Configuration/configuring_deliver_within_rules.cs b/src/Testing/CoreTests/Configuration/configuring_deliver_within_rules.cs index c0fe2f4dd..e0cda599b 100644 --- a/src/Testing/CoreTests/Configuration/configuring_deliver_within_rules.cs +++ b/src/Testing/CoreTests/Configuration/configuring_deliver_within_rules.cs @@ -21,7 +21,7 @@ public async Task configure_remote_subscriber() opts.PublishAllMessages().ToPort(port) .DeliverWithin(3.Seconds()); opts.ListenAtPort(port); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var message = new Message1(); @@ -42,7 +42,7 @@ public async Task configure_local_queue() opts.PublishAllMessages().ToLocalQueue("volatile") .DeliverWithin(3.Seconds()); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var message = new Message1(); diff --git a/src/Testing/CoreTests/Configuration/configuring_idempotency_style.cs b/src/Testing/CoreTests/Configuration/configuring_idempotency_style.cs index 01a41291d..4c16fa97f 100644 --- a/src/Testing/CoreTests/Configuration/configuring_idempotency_style.cs +++ b/src/Testing/CoreTests/Configuration/configuring_idempotency_style.cs @@ -14,7 +14,7 @@ public async Task transactional_middleware_overrides_if_it_has_explicit_value() { using var host = await Host.CreateDefaultBuilder() .UseWolverine() - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); // Forces the codegen rules to be applied that will execute // the transactional attribute among other things @@ -43,7 +43,7 @@ public async Task use_transactional_policies_to_eager() { opts.Policies.AutoApplyTransactions(IdempotencyStyle.Eager); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); #endregion @@ -79,7 +79,7 @@ public async Task use_transactional_policies_to_optimistic() { opts.Policies.AutoApplyTransactions(IdempotencyStyle.Optimistic); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); // Forces the codegen rules to be applied that will execute // the transactional attribute among other things diff --git a/src/Testing/CoreTests/Configuration/configuring_middleware.cs b/src/Testing/CoreTests/Configuration/configuring_middleware.cs index ea9afa274..63116e4ed 100644 --- a/src/Testing/CoreTests/Configuration/configuring_middleware.cs +++ b/src/Testing/CoreTests/Configuration/configuring_middleware.cs @@ -70,7 +70,7 @@ public async Task find_message_type_of_middleware() { opts.Policies.ForMessagesOfType().AddMiddleware(typeof(MiddlewareWithMessage)); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var chain = host.GetRuntime().Handlers.HandlerFor()!.As().Chain; chain!.Middleware[1].ShouldBeOfType().Variable.VariableType diff --git a/src/Testing/CoreTests/Configuration/disabling_all_external_transports.cs b/src/Testing/CoreTests/Configuration/disabling_all_external_transports.cs index 208e8c008..7288eaf04 100644 --- a/src/Testing/CoreTests/Configuration/disabling_all_external_transports.cs +++ b/src/Testing/CoreTests/Configuration/disabling_all_external_transports.cs @@ -21,7 +21,7 @@ public async Task disable_all_external_transports_from_extension_method() // messages to run completely locally .ConfigureServices(services => services.DisableAllExternalWolverineTransports()) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); #endregion diff --git a/src/Testing/CoreTests/Configuration/endpoint_health_connection_state_default_3231.cs b/src/Testing/CoreTests/Configuration/endpoint_health_connection_state_default_3231.cs index 86171d6fe..0dbbe9f19 100644 --- a/src/Testing/CoreTests/Configuration/endpoint_health_connection_state_default_3231.cs +++ b/src/Testing/CoreTests/Configuration/endpoint_health_connection_state_default_3231.cs @@ -20,7 +20,7 @@ public async Task non_connection_aware_endpoints_report_unknown() { opts.ListenAtPort(PortFinder.GetAvailablePort()); opts.PublishAllMessages().ToPort(PortFinder.GetAvailablePort()); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var snapshots = host.GetRuntime().Endpoints.CollectEndpointHealth(); snapshots.ShouldNotBeEmpty(); diff --git a/src/Testing/CoreTests/Configuration/environment_sensitive_configuration.cs b/src/Testing/CoreTests/Configuration/environment_sensitive_configuration.cs index 01fa3479e..229035094 100644 --- a/src/Testing/CoreTests/Configuration/environment_sensitive_configuration.cs +++ b/src/Testing/CoreTests/Configuration/environment_sensitive_configuration.cs @@ -33,7 +33,7 @@ public async Task optimized_mode_takes_local_development_env_name() }); }) .UseEnvironment("LocalDevEnvironment") - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var options = host.Services.GetRequiredService(); @@ -62,7 +62,7 @@ public async Task optimized_mode_defaults_to_develop_as_local_development_env_na }); }) .UseEnvironment("Development") - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var options = host.Services.GetRequiredService(); @@ -97,7 +97,7 @@ public async Task optimized_mode_uses_prod_config_for_non_local_env() }) .UseEnvironment("LocalDevEnvironment") - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var options = host.Services.GetRequiredService(); @@ -135,7 +135,7 @@ public async Task optimized_mode_uses_given_prod_config_for_non_local_env() }) .UseEnvironment("LocalDevEnvironment") - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var options = host.Services.GetRequiredService(); diff --git a/src/Testing/CoreTests/Configuration/generated_code_output_path_configuration.cs b/src/Testing/CoreTests/Configuration/generated_code_output_path_configuration.cs index c350f64a4..0ff56dbee 100644 --- a/src/Testing/CoreTests/Configuration/generated_code_output_path_configuration.cs +++ b/src/Testing/CoreTests/Configuration/generated_code_output_path_configuration.cs @@ -51,7 +51,7 @@ public async Task critter_stack_defaults_generated_code_output_path_flows_to_wol }); }) .UseWolverine() - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var wolverineOptions = host.Services.GetRequiredService(); wolverineOptions.CodeGeneration.GeneratedCodeOutputPath @@ -73,7 +73,7 @@ public async Task explicit_wolverine_path_takes_precedence_over_critter_stack_de { opts.CodeGeneration.GeneratedCodeOutputPath = "/explicit/wolverine/path"; }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var wolverineOptions = host.Services.GetRequiredService(); wolverineOptions.CodeGeneration.GeneratedCodeOutputPath diff --git a/src/Testing/CoreTests/Configuration/handler_chain_customization_ordering.cs b/src/Testing/CoreTests/Configuration/handler_chain_customization_ordering.cs index e51683341..783edee5e 100644 --- a/src/Testing/CoreTests/Configuration/handler_chain_customization_ordering.cs +++ b/src/Testing/CoreTests/Configuration/handler_chain_customization_ordering.cs @@ -51,7 +51,7 @@ public async Task policies_are_applied_before_explicit_chain_configuration() // (1) handler policy opts.Policies.Add(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var handlers = host.GetRuntime().Handlers; @@ -88,7 +88,7 @@ public async Task ordering_is_preserved_for_saga_chains() }); opts.Policies.Add(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var handlers = host.GetRuntime().Handlers; handlers.HandlerFor().ShouldNotBeNull(); @@ -124,7 +124,7 @@ public async Task ordering_is_preserved_for_sticky_endpoint_chains() .IncludeType(typeof(PurpleStickyHandler)); opts.Policies.Add(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var handlers = host.GetRuntime().Handlers; diff --git a/src/Testing/CoreTests/Configuration/missing_handler_behavior.cs b/src/Testing/CoreTests/Configuration/missing_handler_behavior.cs index 4f915eff0..1115f3d9c 100644 --- a/src/Testing/CoreTests/Configuration/missing_handler_behavior.cs +++ b/src/Testing/CoreTests/Configuration/missing_handler_behavior.cs @@ -14,7 +14,7 @@ public async Task no_registered_missing_handlers_for_default_behavior() { using var host = await Host.CreateDefaultBuilder() .UseWolverine() - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); host.Services.GetServices().ShouldBeEmpty(); } @@ -27,7 +27,7 @@ public async Task no_registered_missing_handlers_move_to_dead_letter_queue() { opts.UnknownMessageBehavior = UnknownMessageBehavior.DeadLetterQueue; }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); host.Services.GetServices().ShouldContain(x => x is MoveUnknownMessageToDeadLetterQueue); } @@ -41,7 +41,7 @@ public async Task reentrant_config_for_overloads() opts.UnknownMessageBehavior = UnknownMessageBehavior.DeadLetterQueue; opts.UnknownMessageBehavior = UnknownMessageBehavior.LogOnly; }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); host.Services.GetServices().ShouldBeEmpty(); } @@ -56,7 +56,7 @@ public async Task reentrant_config_for_overloads_2() opts.UnknownMessageBehavior = UnknownMessageBehavior.LogOnly; opts.UnknownMessageBehavior = UnknownMessageBehavior.DeadLetterQueue; }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); host.Services.GetServices().ShouldContain(x => x is MoveUnknownMessageToDeadLetterQueue); } diff --git a/src/Testing/CoreTests/Configuration/receive_loop_health_default_3236.cs b/src/Testing/CoreTests/Configuration/receive_loop_health_default_3236.cs index e9e148924..df1d95b69 100644 --- a/src/Testing/CoreTests/Configuration/receive_loop_health_default_3236.cs +++ b/src/Testing/CoreTests/Configuration/receive_loop_health_default_3236.cs @@ -19,7 +19,7 @@ public async Task non_loop_listeners_report_unknown() .UseWolverine(opts => { opts.ListenAtPort(PortFinder.GetAvailablePort()); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var snapshots = host.GetRuntime().Endpoints.CollectEndpointHealth(); snapshots.ShouldNotBeEmpty(); diff --git a/src/Testing/CoreTests/Configuration/remembered_application_assembly_reuse_warning.cs b/src/Testing/CoreTests/Configuration/remembered_application_assembly_reuse_warning.cs index ead091570..725f542ee 100644 --- a/src/Testing/CoreTests/Configuration/remembered_application_assembly_reuse_warning.cs +++ b/src/Testing/CoreTests/Configuration/remembered_application_assembly_reuse_warning.cs @@ -31,7 +31,7 @@ public async Task a_normal_single_assembly_host_does_not_warn() // Sanity + false-positive guard: a normal host registered from this test assembly resolves the same // application assembly it adopts, so it must NOT warn. Also pins that the constructor captured the // caller's assembly (this test assembly), not "Wolverine". - using var host = await Host.CreateDefaultBuilder().UseWolverine().StartAsync(); + using var host = await Host.CreateDefaultBuilder().UseWolverine().StartAsync(cancellationToken: TestContext.Current.CancellationToken); var options = host.Services.GetRequiredService(); options.RegistrationCallingAssembly!.GetName().Name.ShouldBe(ThisTestAssembly.GetName().Name); diff --git a/src/Testing/CoreTests/Configuration/runtime_compilation_extension.cs b/src/Testing/CoreTests/Configuration/runtime_compilation_extension.cs index bb706a2c5..6ba63bd87 100644 --- a/src/Testing/CoreTests/Configuration/runtime_compilation_extension.cs +++ b/src/Testing/CoreTests/Configuration/runtime_compilation_extension.cs @@ -17,7 +17,7 @@ public async Task use_runtime_compilation_registers_assembly_generator() .UseWolverine(opts => { opts.UseRuntimeCompilation(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var generator = host.Services.GetService(); generator.ShouldNotBeNull(); @@ -33,7 +33,7 @@ public async Task use_runtime_compilation_is_idempotent() opts.UseRuntimeCompilation(); opts.UseRuntimeCompilation(); opts.UseRuntimeCompilation(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); // Should resolve a single registered instance and not throw at startup var generator = host.Services.GetService(); diff --git a/src/Testing/CoreTests/Configuration/using_solo_mode_as_override.cs b/src/Testing/CoreTests/Configuration/using_solo_mode_as_override.cs index 4e618b174..f2dcd5596 100644 --- a/src/Testing/CoreTests/Configuration/using_solo_mode_as_override.cs +++ b/src/Testing/CoreTests/Configuration/using_solo_mode_as_override.cs @@ -12,7 +12,7 @@ public async Task use_the_solo_mode_override() using var host = await Host.CreateDefaultBuilder() .UseWolverine() .ConfigureServices(services => services.UseWolverineSoloMode()) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var options = host.Services.GetRequiredService(); diff --git a/src/Testing/CoreTests/Configuration/wire_tap_configuration.cs b/src/Testing/CoreTests/Configuration/wire_tap_configuration.cs index 1b0efa8f8..f0a2ddd0b 100644 --- a/src/Testing/CoreTests/Configuration/wire_tap_configuration.cs +++ b/src/Testing/CoreTests/Configuration/wire_tap_configuration.cs @@ -37,7 +37,7 @@ public async Task wire_tap_records_success_on_message_handled() await _host.SendMessageAndWaitAsync(new WireTapMessage("hello")); // Give async fire-and-forget wire tap a moment - await Task.Delay(500); + await Task.Delay(500, TestContext.Current.CancellationToken); _wireTap.Successes.ShouldContain(e => e.Message is WireTapMessage); } @@ -55,10 +55,10 @@ public async Task wire_tap_not_called_without_configuration() opts.Services.AddSingleton(tap); // Notably: no UseWireTap() call - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); await host.SendMessageAndWaitAsync(new WireTapMessage("no-tap")); - await Task.Delay(500); + await Task.Delay(500, TestContext.Current.CancellationToken); tap.Successes.ShouldBeEmpty(); } @@ -115,7 +115,7 @@ public async Task default_wire_tap_is_used_without_key() { await _host.SendMessageAndWaitAsync(new WireTapMessage("default")); - await Task.Delay(500); + await Task.Delay(500, TestContext.Current.CancellationToken); _defaultTap.Successes.ShouldContain(e => e.Message is WireTapMessage); } @@ -125,7 +125,7 @@ public async Task keyed_wire_tap_is_used_with_service_key() { await _host.SendMessageAndWaitAsync(new KeyedWireTapMessage("special")); - await Task.Delay(500); + await Task.Delay(500, TestContext.Current.CancellationToken); _specialTap.Successes.ShouldContain(e => e.Message is KeyedWireTapMessage); _defaultTap.Successes.ShouldNotContain(e => e.Message is KeyedWireTapMessage); diff --git a/src/Testing/CoreTests/CoreTests.csproj b/src/Testing/CoreTests/CoreTests.csproj index d8e4dfb1f..e9c4a2f3d 100644 --- a/src/Testing/CoreTests/CoreTests.csproj +++ b/src/Testing/CoreTests/CoreTests.csproj @@ -1,6 +1,8 @@ + + true Exe false diff --git a/src/Testing/CoreTests/Diagnostics/WolverineDiagnosticsCommandTests.cs b/src/Testing/CoreTests/Diagnostics/WolverineDiagnosticsCommandTests.cs index 903e61843..3ca487882 100644 --- a/src/Testing/CoreTests/Diagnostics/WolverineDiagnosticsCommandTests.cs +++ b/src/Testing/CoreTests/Diagnostics/WolverineDiagnosticsCommandTests.cs @@ -133,7 +133,7 @@ public async Task codegen_preview_generates_code_for_handler() .DisableConventionalDiscovery() .IncludeType(typeof(DiagnosticsTestHandler)); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var services = host.Services; var serviceVariableSource = services.GetService(); @@ -212,7 +212,7 @@ public async Task describe_routing_handled_message_is_known_to_handler_graph() .DisableConventionalDiscovery() .IncludeType(typeof(DiagnosticsTestHandler)); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.Services.GetRequiredService(); var options = runtime.Options; @@ -243,7 +243,7 @@ public async Task describe_routing_for_unhandled_message_returns_no_routes() { opts.Discovery.DisableConventionalDiscovery(); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.Services.GetRequiredService(); WolverineSystemPart.WithinDescription = true; diff --git a/src/Testing/CoreTests/ErrorHandling/Faults/FaultPublishingPolicyResolveTests.cs b/src/Testing/CoreTests/ErrorHandling/Faults/FaultPublishingPolicyResolveTests.cs index 3631ccbe4..432839ac9 100644 --- a/src/Testing/CoreTests/ErrorHandling/Faults/FaultPublishingPolicyResolveTests.cs +++ b/src/Testing/CoreTests/ErrorHandling/Faults/FaultPublishingPolicyResolveTests.cs @@ -117,7 +117,7 @@ public async Task wolverine_runtime_freezes_fault_publishing_policy_at_startup() { using var host = await Microsoft.Extensions.Hosting.Host.CreateDefaultBuilder() .UseWolverine(opts => opts.PublishFaultEvents()) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.Services.GetRequiredService(); Should.Throw(() => diff --git a/src/Testing/CoreTests/ErrorHandling/Faults/Integration/FaultBypassTracingTests.cs b/src/Testing/CoreTests/ErrorHandling/Faults/Integration/FaultBypassTracingTests.cs index e69b761f3..64be93e73 100644 --- a/src/Testing/CoreTests/ErrorHandling/Faults/Integration/FaultBypassTracingTests.cs +++ b/src/Testing/CoreTests/ErrorHandling/Faults/Integration/FaultBypassTracingTests.cs @@ -93,7 +93,7 @@ public async Task send_side_dlq_emits_bypass_event_when_fault_publishing_is_glob { using var host = await Host.CreateDefaultBuilder() .UseWolverine(opts => opts.PublishFaultEvents()) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = (WolverineRuntime)host.Services.GetRequiredService(); var envelope = new Envelope @@ -118,7 +118,7 @@ public async Task send_side_dlq_emits_bypass_event_when_fault_publishing_is_glob t.Key == WolverineTracing.MessageType && (string?)t.Value == typeof(OrderPlaced).ToMessageTypeName()); } - finally { activity.Dispose(); listener.Dispose(); await host.StopAsync(); } + finally { activity.Dispose(); listener.Dispose(); await host.StopAsync(TestContext.Current.CancellationToken); } } [Fact] @@ -126,7 +126,7 @@ public async Task send_side_dlq_skips_bypass_event_when_fault_publishing_is_disa { using var host = await Host.CreateDefaultBuilder() .UseWolverine(_ => { /* no PublishFaultEvents */ }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = (WolverineRuntime)host.Services.GetRequiredService(); var envelope = new Envelope @@ -149,6 +149,6 @@ public async Task send_side_dlq_skips_bypass_event_when_fault_publishing_is_disa .Where(e => e.Name == WolverineTracing.FaultBypassedSendSide) .ShouldBeEmpty(); } - finally { activity.Dispose(); listener.Dispose(); await host.StopAsync(); } + finally { activity.Dispose(); listener.Dispose(); await host.StopAsync(TestContext.Current.CancellationToken); } } } diff --git a/src/Testing/CoreTests/ErrorHandling/Faults/Integration/FaultCryptoExceptionGuardTests.cs b/src/Testing/CoreTests/ErrorHandling/Faults/Integration/FaultCryptoExceptionGuardTests.cs index 781ab4037..7390cb5f8 100644 --- a/src/Testing/CoreTests/ErrorHandling/Faults/Integration/FaultCryptoExceptionGuardTests.cs +++ b/src/Testing/CoreTests/ErrorHandling/Faults/Integration/FaultCryptoExceptionGuardTests.cs @@ -78,7 +78,7 @@ public async Task try_deserialize_returns_move_to_error_queue_for_message_decryp // (see no_op_when_envelope_message_is_null in FaultPublisherTests). envelope.Message.ShouldBeNull(); } - finally { await host.StopAsync(); } + finally { await host.StopAsync(TestContext.Current.CancellationToken); } } [Fact] @@ -108,7 +108,7 @@ public async Task try_deserialize_returns_move_to_error_queue_for_unknown_encryp moveToErrorQueue.Exception.ShouldBeOfType(); envelope.Message.ShouldBeNull(); } - finally { await host.StopAsync(); } + finally { await host.StopAsync(TestContext.Current.CancellationToken); } } [Fact] @@ -140,6 +140,6 @@ public async Task try_deserialize_returns_move_to_error_queue_for_encryption_pol moveToErrorQueue.Exception.ShouldBeOfType(); envelope.Message.ShouldBeNull(); } - finally { await host.StopAsync(); } + finally { await host.StopAsync(TestContext.Current.CancellationToken); } } } diff --git a/src/Testing/CoreTests/ErrorHandling/Faults/Integration/FaultEncryptionRoundTripTests.cs b/src/Testing/CoreTests/ErrorHandling/Faults/Integration/FaultEncryptionRoundTripTests.cs index cf60a5e4d..0cf45eb65 100644 --- a/src/Testing/CoreTests/ErrorHandling/Faults/Integration/FaultEncryptionRoundTripTests.cs +++ b/src/Testing/CoreTests/ErrorHandling/Faults/Integration/FaultEncryptionRoundTripTests.cs @@ -54,7 +54,7 @@ public async Task auto_published_fault_for_encrypted_type_routes_through_encrypt opts.PublishFaultEvents(); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var session = await host.TrackActivity() .DoNotAssertOnExceptionsDetected() diff --git a/src/Testing/CoreTests/ErrorHandling/Faults/Integration/FaultRedactionIntegrationTests.cs b/src/Testing/CoreTests/ErrorHandling/Faults/Integration/FaultRedactionIntegrationTests.cs index c21983612..7ba4daa44 100644 --- a/src/Testing/CoreTests/ErrorHandling/Faults/Integration/FaultRedactionIntegrationTests.cs +++ b/src/Testing/CoreTests/ErrorHandling/Faults/Integration/FaultRedactionIntegrationTests.cs @@ -73,7 +73,7 @@ await host.TrackActivity() fault.Exception.Message.ShouldBe(string.Empty); fault.Exception.StackTrace.ShouldNotBeNull(); } - finally { await host.StopAsync(); } + finally { await host.StopAsync(TestContext.Current.CancellationToken); } } [Fact] @@ -101,6 +101,6 @@ await host.TrackActivity() var otherFault = collector.Other.ShouldHaveSingleItem(); otherFault.Exception.Message.ShouldBe("other-message-canary"); } - finally { await host.StopAsync(); } + finally { await host.StopAsync(TestContext.Current.CancellationToken); } } } diff --git a/src/Testing/CoreTests/ErrorHandling/Faults/Integration/PublishFaultEventsIntegrationTests.cs b/src/Testing/CoreTests/ErrorHandling/Faults/Integration/PublishFaultEventsIntegrationTests.cs index cfdbeed30..7ac98bccb 100644 --- a/src/Testing/CoreTests/ErrorHandling/Faults/Integration/PublishFaultEventsIntegrationTests.cs +++ b/src/Testing/CoreTests/ErrorHandling/Faults/Integration/PublishFaultEventsIntegrationTests.cs @@ -76,7 +76,7 @@ public async Task globally_enabled_publishes_fault_to_subscriber() collector.Order[0].Exception.Type.ShouldBe(typeof(InvalidOperationException).FullName); collector.Order[0].Exception.Message.ShouldBe("synthetic order failure"); } - finally { await host.StopAsync(); } + finally { await host.StopAsync(TestContext.Current.CancellationToken); } } [Fact] @@ -98,7 +98,7 @@ public async Task per_type_opt_in_publishes_fault_only_for_chosen_type() .ShouldBeEmpty(); collector.Other.ShouldBeEmpty(); } - finally { await host.StopAsync(); } + finally { await host.StopAsync(TestContext.Current.CancellationToken); } } [Fact] @@ -120,7 +120,7 @@ public async Task per_type_opt_out_overrides_global_on() .ShouldBeEmpty(); collector.Order.ShouldBeEmpty(); } - finally { await host.StopAsync(); } + finally { await host.StopAsync(TestContext.Current.CancellationToken); } } [Fact] @@ -134,7 +134,7 @@ public async Task discard_without_opt_in_does_not_publish() opts.OnException().Discard(); opts.PublishFaultEvents(); // DLQ-only — discards excluded }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); try { var session = await host.TrackActivity() @@ -144,7 +144,7 @@ public async Task discard_without_opt_in_does_not_publish() session.AutoFaultsPublished.MessagesOf>().ShouldBeEmpty(); collector.Order.ShouldBeEmpty(); } - finally { await host.StopAsync(); } + finally { await host.StopAsync(TestContext.Current.CancellationToken); } } [Fact] @@ -158,7 +158,7 @@ public async Task discard_with_include_discarded_publishes() opts.OnException().Discard(); opts.PublishFaultEvents(includeDiscarded: true); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); try { var session = await host.TrackActivity() @@ -175,7 +175,7 @@ public async Task discard_with_include_discarded_publishes() collector.Order[0].Exception.Message .ShouldBe("synthetic order failure"); } - finally { await host.StopAsync(); } + finally { await host.StopAsync(TestContext.Current.CancellationToken); } } [Fact] @@ -194,7 +194,7 @@ public async Task fault_carries_auto_header_when_observed_by_subscriber() envelope.Headers[FaultHeaders.AutoPublished].ShouldBe("true"); } - finally { await host.StopAsync(); } + finally { await host.StopAsync(TestContext.Current.CancellationToken); } } [Fact] @@ -209,7 +209,7 @@ await Should.ThrowAsync( collector.Order.ShouldBeEmpty(); } - finally { await host.StopAsync(); } + finally { await host.StopAsync(TestContext.Current.CancellationToken); } } [Fact] @@ -240,7 +240,7 @@ public async Task manually_published_fault_does_not_carry_auto_header() .MessagesOf>() .ShouldBeEmpty(); } - finally { await host.StopAsync(); } + finally { await host.StopAsync(TestContext.Current.CancellationToken); } } [Fact] @@ -277,7 +277,7 @@ await host.TrackActivity() faultSpan!.TraceId.ShouldBe(executeSpan!.TraceId); faultSpan.ParentSpanId.ShouldBe(executeSpan.SpanId); } - finally { await host.StopAsync(); } + finally { await host.StopAsync(TestContext.Current.CancellationToken); } } [Fact] @@ -301,6 +301,6 @@ public async Task fault_envelope_carries_original_correlation_headers() faultEnvelope.Headers[FaultHeaders.OriginalType] .ShouldBe(typeof(OrderPlaced).ToMessageTypeName()); } - finally { await host.StopAsync(); } + finally { await host.StopAsync(TestContext.Current.CancellationToken); } } } diff --git a/src/Testing/CoreTests/OutgoingMessagesTests.cs b/src/Testing/CoreTests/OutgoingMessagesTests.cs index 581d798fd..30df89e03 100644 --- a/src/Testing/CoreTests/OutgoingMessagesTests.cs +++ b/src/Testing/CoreTests/OutgoingMessagesTests.cs @@ -49,7 +49,7 @@ public void schedule_by_time() public async Task end_to_end() { using var host = await Host.CreateDefaultBuilder() - .UseWolverine().StartAsync(); + .UseWolverine().StartAsync(cancellationToken: TestContext.Current.CancellationToken); var guid = Guid.NewGuid(); var tracked = await host.InvokeMessageAndWaitAsync(new SpawningMessage(guid)); diff --git a/src/Testing/CoreTests/Persistence/ClaimCheck/FileSystemClaimCheckStoreTests.cs b/src/Testing/CoreTests/Persistence/ClaimCheck/FileSystemClaimCheckStoreTests.cs index dd5796790..9d11285fc 100644 --- a/src/Testing/CoreTests/Persistence/ClaimCheck/FileSystemClaimCheckStoreTests.cs +++ b/src/Testing/CoreTests/Persistence/ClaimCheck/FileSystemClaimCheckStoreTests.cs @@ -34,16 +34,16 @@ public void Dispose() public async Task store_load_delete_round_trip() { var bytes = new byte[] { 1, 2, 3, 4, 5 }; - var token = await _store.StoreAsync(bytes, "application/octet-stream"); + var token = await _store.StoreAsync(bytes, "application/octet-stream", TestContext.Current.CancellationToken); token.ShouldNotBeNull(); token.Length.ShouldBe(bytes.Length); token.ContentType.ShouldBe("application/octet-stream"); - var loaded = await _store.LoadAsync(token); + var loaded = await _store.LoadAsync(token, TestContext.Current.CancellationToken); loaded.ToArray().ShouldBe(bytes); - await _store.DeleteAsync(token); + await _store.DeleteAsync(token, TestContext.Current.CancellationToken); await Should.ThrowAsync(() => _store.LoadAsync(token)); } @@ -52,7 +52,7 @@ public async Task store_load_delete_round_trip() public async Task token_serialize_round_trip() { var bytes = new byte[] { 9, 8, 7 }; - var token = await _store.StoreAsync(bytes, "image/png"); + var token = await _store.StoreAsync(bytes, "image/png", TestContext.Current.CancellationToken); var encoded = token.Serialize(); var decoded = ClaimCheckToken.Parse(encoded); @@ -67,7 +67,7 @@ public async Task store_creates_directory_lazily() var localStore = new FileSystemClaimCheckStore(dir); Directory.Exists(dir).ShouldBeTrue(); - var token = await localStore.StoreAsync(new byte[] { 1 }, "application/octet-stream"); - (await localStore.LoadAsync(token)).ToArray().ShouldBe(new byte[] { 1 }); + var token = await localStore.StoreAsync(new byte[] { 1 }, "application/octet-stream", TestContext.Current.CancellationToken); + (await localStore.LoadAsync(token, TestContext.Current.CancellationToken)).ToArray().ShouldBe(new byte[] { 1 }); } } diff --git a/src/Testing/CoreTests/Persistence/Durability/DynamicListenersDefaultsTests.cs b/src/Testing/CoreTests/Persistence/Durability/DynamicListenersDefaultsTests.cs index 8d7161e82..5140418ea 100644 --- a/src/Testing/CoreTests/Persistence/Durability/DynamicListenersDefaultsTests.cs +++ b/src/Testing/CoreTests/Persistence/Durability/DynamicListenersDefaultsTests.cs @@ -36,19 +36,19 @@ public async Task null_listener_store_register_is_a_no_op() // flag is off. Locks down the no-op contract: no exception, no state. var store = NullListenerStore.Instance; - await store.RegisterListenerAsync(new Uri("mqtt://topic/devices/abc")); + await store.RegisterListenerAsync(new Uri("mqtt://topic/devices/abc"), TestContext.Current.CancellationToken); } [Fact] public async Task null_listener_store_returns_empty_listing() { - var listeners = await NullListenerStore.Instance.AllListenersAsync(); + var listeners = await NullListenerStore.Instance.AllListenersAsync(TestContext.Current.CancellationToken); listeners.ShouldBeEmpty(); } [Fact] public async Task null_listener_store_remove_is_a_no_op() { - await NullListenerStore.Instance.RemoveListenerAsync(new Uri("mqtt://topic/whatever")); + await NullListenerStore.Instance.RemoveListenerAsync(new Uri("mqtt://topic/whatever"), TestContext.Current.CancellationToken); } } diff --git a/src/Testing/CoreTests/Persistence/Sagas/saga_cascading_messages_with_separated_mode.cs b/src/Testing/CoreTests/Persistence/Sagas/saga_cascading_messages_with_separated_mode.cs index 85a0ae906..bb232c1a2 100644 --- a/src/Testing/CoreTests/Persistence/Sagas/saga_cascading_messages_with_separated_mode.cs +++ b/src/Testing/CoreTests/Persistence/Sagas/saga_cascading_messages_with_separated_mode.cs @@ -21,7 +21,7 @@ public async Task cascading_message_should_have_saga_id_attached() opts.CodeGeneration.TypeLoadMode = TypeLoadMode.Auto; opts.MultipleHandlerBehavior = MultipleHandlerBehavior.Separated; - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var id = Guid.NewGuid(); ExternalHandler.CascadedMessageCount = 0; @@ -63,7 +63,7 @@ public async Task cascading_message_from_start_method_should_have_saga_id() opts.CodeGeneration.TypeLoadMode = TypeLoadMode.Auto; opts.MultipleHandlerBehavior = MultipleHandlerBehavior.Separated; - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var id = Guid.NewGuid(); CascadingFromStartSaga.CascadeHandledCount = 0; diff --git a/src/Testing/CoreTests/Persistence/Sagas/using_a_saga_with_separated_behavior_mode.cs b/src/Testing/CoreTests/Persistence/Sagas/using_a_saga_with_separated_behavior_mode.cs index f869fb213..4173821d1 100644 --- a/src/Testing/CoreTests/Persistence/Sagas/using_a_saga_with_separated_behavior_mode.cs +++ b/src/Testing/CoreTests/Persistence/Sagas/using_a_saga_with_separated_behavior_mode.cs @@ -22,7 +22,7 @@ public async Task able_to_use_separated_behaviors_with_sagas() opts.CodeGeneration.TypeLoadMode = TypeLoadMode.Auto; opts.MultipleHandlerBehavior = MultipleHandlerBehavior.Separated; - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var id = Guid.NewGuid(); diff --git a/src/Testing/CoreTests/Persistence/clear_all_wolverine_storage_on_storeless_hosts.cs b/src/Testing/CoreTests/Persistence/clear_all_wolverine_storage_on_storeless_hosts.cs index 1e1e6e1bf..6d5e11cf0 100644 --- a/src/Testing/CoreTests/Persistence/clear_all_wolverine_storage_on_storeless_hosts.cs +++ b/src/Testing/CoreTests/Persistence/clear_all_wolverine_storage_on_storeless_hosts.cs @@ -20,7 +20,7 @@ public async Task safe_no_op_against_a_host_with_no_message_store() { using var host = await Host.CreateDefaultBuilder() .UseWolverine(opts => { opts.Durability.Mode = DurabilityMode.Solo; }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); await Should.NotThrowAsync(() => host.ClearAllWolverineStorageAsync()); } @@ -34,7 +34,7 @@ public async Task touches_nothing_on_a_host_with_only_local_queues() opts.Durability.Mode = DurabilityMode.Solo; opts.PublishAllMessages().ToLocalQueue("clear-all-storage"); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.GetRuntime(); diff --git a/src/Testing/CoreTests/Runtime/Agents/DynamicListeners/WolverineRuntimeListenerExtensionsTests.cs b/src/Testing/CoreTests/Runtime/Agents/DynamicListeners/WolverineRuntimeListenerExtensionsTests.cs index ed406ca1e..1cf835471 100644 --- a/src/Testing/CoreTests/Runtime/Agents/DynamicListeners/WolverineRuntimeListenerExtensionsTests.cs +++ b/src/Testing/CoreTests/Runtime/Agents/DynamicListeners/WolverineRuntimeListenerExtensionsTests.cs @@ -29,7 +29,7 @@ public WolverineRuntimeListenerExtensionsTests() public async Task register_listener_async_delegates_to_store() { var uri = new Uri("mqtt://broker/topic"); - await _runtime.RegisterListenerAsync(uri); + await _runtime.RegisterListenerAsync(uri, cancellationToken: TestContext.Current.CancellationToken); await _store.Received(1).RegisterListenerAsync(uri, Arg.Any()); } @@ -38,7 +38,7 @@ public async Task register_listener_async_delegates_to_store() public async Task remove_listener_async_delegates_to_store() { var uri = new Uri("mqtt://broker/topic"); - await _runtime.RemoveListenerAsync(uri); + await _runtime.RemoveListenerAsync(uri, cancellationToken: TestContext.Current.CancellationToken); await _store.Received(1).RemoveListenerAsync(uri, Arg.Any()); } @@ -54,7 +54,7 @@ public async Task all_registered_listeners_async_delegates_to_store() _store.AllListenersAsync(Arg.Any()) .Returns(Task.FromResult>(listed)); - var result = await _runtime.AllRegisteredListenersAsync(); + var result = await _runtime.AllRegisteredListenersAsync(cancellationToken: TestContext.Current.CancellationToken); result.ShouldBe(listed); } diff --git a/src/Testing/CoreTests/Runtime/Agents/event_subscription_agent_health_check_uses_tenant_scoped_high_water.cs b/src/Testing/CoreTests/Runtime/Agents/event_subscription_agent_health_check_uses_tenant_scoped_high_water.cs index 911cf142d..2c02df7d2 100644 --- a/src/Testing/CoreTests/Runtime/Agents/event_subscription_agent_health_check_uses_tenant_scoped_high_water.cs +++ b/src/Testing/CoreTests/Runtime/Agents/event_subscription_agent_health_check_uses_tenant_scoped_high_water.cs @@ -57,7 +57,7 @@ public async Task a_tenant_with_no_events_is_healthy_even_when_the_database_mark new ShardName("invoicejournalentries", "all", 4, "98123456"), new Uri("event-subscriptions://marten/main/db/invoicejournalentries/all/v4/98123456")); - var result = await agent.CheckHealthAsync(new HealthCheckContext()); + var result = await agent.CheckHealthAsync(new HealthCheckContext(), TestContext.Current.CancellationToken); // Before the fix: "Projection ... is 8900 events behind (critical threshold: 5000)" result.Status.ShouldBe(HealthStatus.Healthy); @@ -76,7 +76,7 @@ public async Task a_tenant_genuinely_behind_its_own_mark_is_still_reported() new ShardName("invoicejournalentries", "all", 4, "98123456"), new Uri("event-subscriptions://marten/main/db/invoicejournalentries/all/v4/98123456")); - var result = await agent.CheckHealthAsync(new HealthCheckContext()); + var result = await agent.CheckHealthAsync(new HealthCheckContext(), TestContext.Current.CancellationToken); result.Status.ShouldBe(HealthStatus.Unhealthy); result.Description!.ShouldContain("5900 events behind"); @@ -103,7 +103,7 @@ public async Task a_caught_up_tenant_does_not_trip_the_stall_detector_on_repeate // with no stall churn. (The genuinely-stalled path is exercised in the next test.) for (var i = 0; i < 5; i++) { - var result = await agent.CheckHealthAsync(new HealthCheckContext()); + var result = await agent.CheckHealthAsync(new HealthCheckContext(), TestContext.Current.CancellationToken); result.Status.ShouldBe(HealthStatus.Healthy); } } @@ -125,7 +125,7 @@ public async Task a_genuinely_stalled_tenant_degrades_then_restarts_against_its_ new Uri("event-subscriptions://marten/main/db/invoicejournalentries/all/v4/98123456")); // First check seeds stall tracking (_lastAdvancedAt = now) and is healthy. - (await agent.CheckHealthAsync(new HealthCheckContext())).Status.ShouldBe(HealthStatus.Healthy); + (await agent.CheckHealthAsync(new HealthCheckContext(), TestContext.Current.CancellationToken)).Status.ShouldBe(HealthStatus.Healthy); // The tenant's sequence never advances. Push _lastAdvancedAt past the 60s StallTimeout so the // following checks exercise the stall branch without a real-time wait. @@ -134,7 +134,7 @@ public async Task a_genuinely_stalled_tenant_degrades_then_restarts_against_its_ // The stall report cites the TENANT mark (200), not the database mark (8900). Pre-fix this idle // tenant read as 8780 events behind the database mark and was flagged Unhealthy before the stall // detector was ever consulted, so it could not have reached this Degraded stall message. - var degraded = await agent.CheckHealthAsync(new HealthCheckContext()); + var degraded = await agent.CheckHealthAsync(new HealthCheckContext(), TestContext.Current.CancellationToken); degraded.Status.ShouldBe(HealthStatus.Degraded); degraded.Description!.ShouldContain("high water mark: 200"); @@ -142,7 +142,7 @@ public async Task a_genuinely_stalled_tenant_degrades_then_restarts_against_its_ var result = degraded; for (var i = 0; i < 5 && result.Status != HealthStatus.Unhealthy; i++) { - result = await agent.CheckHealthAsync(new HealthCheckContext()); + result = await agent.CheckHealthAsync(new HealthCheckContext(), TestContext.Current.CancellationToken); } result.Status.ShouldBe(HealthStatus.Unhealthy); @@ -169,7 +169,7 @@ public async Task a_store_global_agent_still_measures_against_the_database_wide_ new ShardName("invoicejournalentries"), new Uri("event-subscriptions://marten/main/db/invoicejournalentries/all/v4")); - var result = await agent.CheckHealthAsync(new HealthCheckContext()); + var result = await agent.CheckHealthAsync(new HealthCheckContext(), TestContext.Current.CancellationToken); result.Status.ShouldBe(HealthStatus.Unhealthy); result.Description!.ShouldContain("8800 events behind"); diff --git a/src/Testing/CoreTests/Runtime/Agents/heartbeat_decoupled_from_command_execution.cs b/src/Testing/CoreTests/Runtime/Agents/heartbeat_decoupled_from_command_execution.cs index b9f9eab33..e1de63344 100644 --- a/src/Testing/CoreTests/Runtime/Agents/heartbeat_decoupled_from_command_execution.cs +++ b/src/Testing/CoreTests/Runtime/Agents/heartbeat_decoupled_from_command_execution.cs @@ -92,7 +92,7 @@ public async Task heartbeat_is_written_even_while_a_health_check_evaluation_is_w .Returns(new NodeAgentState([SelfRow(DateTimeOffset.UtcNow)], new AgentRestrictions())); var wedged = _controller.DoHealthChecksAsync(); - await entered.Task.WaitAsync(5.Seconds()); + await entered.Task.WaitAsync(5.Seconds(), TestContext.Current.CancellationToken); // The wedged evaluation is already past its own MarkHealthCheckAsync and is now stuck holding the // guard. Clear those calls, then prove the independent heartbeat path keeps writing regardless. @@ -106,7 +106,7 @@ await _persistence.Received(3).MarkHealthCheckAsync( Arg.Any(), Arg.Any()); release.SetResult(); - await wedged.WaitAsync(5.Seconds()); + await wedged.WaitAsync(5.Seconds(), TestContext.Current.CancellationToken); } [Fact] diff --git a/src/Testing/CoreTests/Runtime/Agents/leader_election_self_visibility_tests.cs b/src/Testing/CoreTests/Runtime/Agents/leader_election_self_visibility_tests.cs index 4714a9db1..c01229c41 100644 --- a/src/Testing/CoreTests/Runtime/Agents/leader_election_self_visibility_tests.cs +++ b/src/Testing/CoreTests/Runtime/Agents/leader_election_self_visibility_tests.cs @@ -195,7 +195,7 @@ public async Task reentrancy_guard_prevents_concurrent_DoHealthChecksAsync() new AgentRestrictions())); var winner = _controller.DoHealthChecksAsync(); - await entered.Task.WaitAsync(5.Seconds()); + await entered.Task.WaitAsync(5.Seconds(), TestContext.Current.CancellationToken); // While the winner is parked inside the guarded section, every other // call must bounce off the guard with AgentCommands.Empty instead of @@ -212,7 +212,7 @@ await _persistence.Received(1) .TryAttainLeadershipLockAsync(Arg.Any()); release.SetResult(); - await winner.WaitAsync(5.Seconds()); + await winner.WaitAsync(5.Seconds(), TestContext.Current.CancellationToken); _controller.IsLeader.ShouldBeTrue(); // The guard must be released once the winner completes — a diff --git a/src/Testing/CoreTests/Runtime/Agents/parallel_drain_on_stop.cs b/src/Testing/CoreTests/Runtime/Agents/parallel_drain_on_stop.cs index e26f52362..2024a2f66 100644 --- a/src/Testing/CoreTests/Runtime/Agents/parallel_drain_on_stop.cs +++ b/src/Testing/CoreTests/Runtime/Agents/parallel_drain_on_stop.cs @@ -78,7 +78,7 @@ public async Task drains_running_agents_with_bounded_parallelism() var stopping = controller.StopAsync(Substitute.For()); // Exactly `dop` drains run concurrently; the rest queue behind them (Parallel.ForEachAsync bound). - await reachedCap.Task.WaitAsync(5.Seconds()); + await reachedCap.Task.WaitAsync(5.Seconds(), TestContext.Current.CancellationToken); lock (gate) { concurrent.ShouldBe(dop); @@ -86,7 +86,7 @@ public async Task drains_running_agents_with_bounded_parallelism() } release.SetResult(); - await stopping.WaitAsync(5.Seconds()); + await stopping.WaitAsync(5.Seconds(), TestContext.Current.CancellationToken); // Every agent was stopped and removed, and parallelism never exceeded the cap. maxConcurrent.ShouldBe(dop); @@ -112,7 +112,7 @@ public async Task a_wedged_agent_does_not_abort_the_drain_of_its_peers() var badUri = new Uri("fake://bad"); controller.Agents[badUri] = new GatedAgent(badUri, () => throw new InvalidOperationException("wedged")); - await controller.StopAsync(Substitute.For()).WaitAsync(5.Seconds()); + await controller.StopAsync(Substitute.For()).WaitAsync(5.Seconds(), TestContext.Current.CancellationToken); // Every healthy agent still drained and was removed even though a peer threw. The throwing agent is // logged and left in the map (only a clean stop removes the entry), so the failure is contained. diff --git a/src/Testing/CoreTests/Runtime/Agents/pending_assignment_ledger.cs b/src/Testing/CoreTests/Runtime/Agents/pending_assignment_ledger.cs index 88ed1871a..e67f44f21 100644 --- a/src/Testing/CoreTests/Runtime/Agents/pending_assignment_ledger.cs +++ b/src/Testing/CoreTests/Runtime/Agents/pending_assignment_ledger.cs @@ -83,7 +83,7 @@ public async Task re_emits_after_the_ttl_expires_without_confirmation() assignedAgentCount(await evaluateAsync()).ShouldBe(FakeAgentFamily.Names.Length); - await Task.Delay(100.Milliseconds()); // comfortably past the 20ms TTL + await Task.Delay(100.Milliseconds(), TestContext.Current.CancellationToken); // comfortably past the 20ms TTL // A start that never took must eventually be re-driven. assignedAgentCount(await evaluateAsync()).ShouldBe(FakeAgentFamily.Names.Length); diff --git a/src/Testing/CoreTests/Runtime/Agents/scale_safe_batch_starts.cs b/src/Testing/CoreTests/Runtime/Agents/scale_safe_batch_starts.cs index fd9b6525d..360a2243a 100644 --- a/src/Testing/CoreTests/Runtime/Agents/scale_safe_batch_starts.cs +++ b/src/Testing/CoreTests/Runtime/Agents/scale_safe_batch_starts.cs @@ -100,7 +100,7 @@ public async Task starts_a_batch_with_bounded_parallelism() var exec = new StartAgents(uris).ExecuteAsync(_runtime, CancellationToken.None); // Exactly `dop` starts run concurrently; the rest queue behind them (Parallel.ForEachAsync bound). - await reachedCap.Task.WaitAsync(5.Seconds()); + await reachedCap.Task.WaitAsync(5.Seconds(), TestContext.Current.CancellationToken); lock (gate) { concurrent.ShouldBe(dop); @@ -108,7 +108,7 @@ public async Task starts_a_batch_with_bounded_parallelism() } release.SetResult(); - var result = await exec.WaitAsync(5.Seconds()); + var result = await exec.WaitAsync(5.Seconds(), TestContext.Current.CancellationToken); // Every agent eventually started, and parallelism never exceeded the cap. result.OfType().Single().AgentUris.Length.ShouldBe(total); diff --git a/src/Testing/CoreTests/Runtime/Agents/solo_mode_health_check_tracing.cs b/src/Testing/CoreTests/Runtime/Agents/solo_mode_health_check_tracing.cs index 78b37f2a0..16fff7d06 100644 --- a/src/Testing/CoreTests/Runtime/Agents/solo_mode_health_check_tracing.cs +++ b/src/Testing/CoreTests/Runtime/Agents/solo_mode_health_check_tracing.cs @@ -87,7 +87,7 @@ public async Task each_recurring_tick_is_its_own_bounded_root_trace() await _controller.StartSoloModeAsync(); // Let the recurring loop fire several times (25ms period). - await Task.Delay(400.Milliseconds()); + await Task.Delay(400.Milliseconds(), TestContext.Current.CancellationToken); // Stop the loop before asserting. await _cancellation.CancelAsync(); @@ -122,7 +122,7 @@ public async Task sampling_period_throttles_solo_mode_recurring_checks() _options.Durability.NodeAssignmentHealthCheckTraceSamplingPeriod = 1.Hours(); await _controller.StartSoloModeAsync(); - await Task.Delay(400.Milliseconds()); + await Task.Delay(400.Milliseconds(), TestContext.Current.CancellationToken); await _cancellation.CancelAsync(); // Only the startup tick should trace within a 1-hour sampling window. diff --git a/src/Testing/CoreTests/Runtime/Handlers/HandlerGraphTests.cs b/src/Testing/CoreTests/Runtime/Handlers/HandlerGraphTests.cs index 1ee6fa312..c0c25632f 100644 --- a/src/Testing/CoreTests/Runtime/Handlers/HandlerGraphTests.cs +++ b/src/Testing/CoreTests/Runtime/Handlers/HandlerGraphTests.cs @@ -22,7 +22,7 @@ public async Task can_find_the_message_type_by_the_message_type_name_of_one_of_i .UseWolverine(opts => { opts.Policies.RegisterInteropMessageAssembly(typeof(IMessageAbstraction).Assembly); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var graph = host.Services.GetRequiredService(); @@ -46,7 +46,7 @@ public async Task register_message_type() .UseWolverine(opts => { opts.RegisterMessageType(typeof(DummyMessage), "custom-alias"); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var graph = host.Services.GetRequiredService(); @@ -64,7 +64,7 @@ public async Task register_message_type_with_multiple_aliases() { opts.RegisterMessageType(typeof(DummyMessage), "custom-alias-1"); opts.RegisterMessageType(typeof(DummyMessage), "custom-alias-2"); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var graph = host.Services.GetRequiredService(); @@ -99,7 +99,7 @@ public async Task Concurrent_Registration_No_Race_Condition() using var host = await Host.CreateDefaultBuilder() .UseWolverine() - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var graph = host.Services.GetRequiredService(); var runtime = host.Services.GetRequiredService(); diff --git a/src/Testing/CoreTests/Runtime/Handlers/concurrent_saga_chain_compilation.cs b/src/Testing/CoreTests/Runtime/Handlers/concurrent_saga_chain_compilation.cs index e94f43ac7..7bcbfc493 100644 --- a/src/Testing/CoreTests/Runtime/Handlers/concurrent_saga_chain_compilation.cs +++ b/src/Testing/CoreTests/Runtime/Handlers/concurrent_saga_chain_compilation.cs @@ -24,7 +24,7 @@ public async Task concurrent_first_time_resolution_of_a_saga_handler_does_not_th opts.Discovery.DisableConventionalDiscovery().IncludeType(); opts.MultipleHandlerBehavior = MultipleHandlerBehavior.Separated; opts.CodeGeneration.TypeLoadMode = TypeLoadMode.Dynamic; - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var graph = host.Services.GetRequiredService(); diff --git a/src/Testing/CoreTests/Runtime/Heartbeat/HeartbeatBackgroundServiceTests.cs b/src/Testing/CoreTests/Runtime/Heartbeat/HeartbeatBackgroundServiceTests.cs index 1eac2daaa..14f0b3b32 100644 --- a/src/Testing/CoreTests/Runtime/Heartbeat/HeartbeatBackgroundServiceTests.cs +++ b/src/Testing/CoreTests/Runtime/Heartbeat/HeartbeatBackgroundServiceTests.cs @@ -48,7 +48,7 @@ public async Task publishes_repeatedly_at_the_configured_interval() var execution = service.StartAsync(cts.Token); // Run the service for 250ms with a 50ms interval — expect at least 2 publishes - await Task.Delay(250); + await Task.Delay(250, TestContext.Current.CancellationToken); await cts.CancelAsync(); await service.StopAsync(CancellationToken.None); @@ -72,7 +72,7 @@ public async Task heartbeat_carries_service_name_and_node_number() await service.StartAsync(cts.Token); // Wait long enough for at least one publish - await Task.Delay(120); + await Task.Delay(120, TestContext.Current.CancellationToken); await cts.CancelAsync(); await service.StopAsync(CancellationToken.None); @@ -102,7 +102,7 @@ public async Task does_not_publish_when_disabled() using var cts = new CancellationTokenSource(); await service.StartAsync(cts.Token); - await Task.Delay(120); + await Task.Delay(120, TestContext.Current.CancellationToken); await cts.CancelAsync(); await service.StopAsync(CancellationToken.None); diff --git a/src/Testing/CoreTests/Runtime/Heartbeat/solo_storeless_node_identity.cs b/src/Testing/CoreTests/Runtime/Heartbeat/solo_storeless_node_identity.cs index 591486474..9e6f7ea09 100644 --- a/src/Testing/CoreTests/Runtime/Heartbeat/solo_storeless_node_identity.cs +++ b/src/Testing/CoreTests/Runtime/Heartbeat/solo_storeless_node_identity.cs @@ -33,7 +33,7 @@ public async Task storeless_solo_gets_node_1_and_fires_lifecycle_bookends() var observer = Substitute.For(); runtime.Observer = observer; - await host.StartAsync(); + await host.StartAsync(TestContext.Current.CancellationToken); // Stable identity, set before the messaging transports start. runtime.Options.Durability.AssignedNodeNumber.ShouldBe(1); @@ -42,7 +42,7 @@ public async Task storeless_solo_gets_node_1_and_fires_lifecycle_bookends() await observer.Received(1).NodeStarted(); await observer.DidNotReceive().NodeStopped(); - await host.StopAsync(); + await host.StopAsync(TestContext.Current.CancellationToken); await observer.Received(1).NodeStopped(); } @@ -78,8 +78,8 @@ public async Task does_not_fire_for_a_storeless_non_solo_host() var observer = Substitute.For(); runtime.Observer = observer; - await host.StartAsync(); - await host.StopAsync(); + await host.StartAsync(TestContext.Current.CancellationToken); + await host.StopAsync(TestContext.Current.CancellationToken); await observer.DidNotReceive().NodeStarted(); await observer.DidNotReceive().NodeStopped(); diff --git a/src/Testing/CoreTests/Runtime/Interop/when_reading_and_writing_CloudEvents_data.cs b/src/Testing/CoreTests/Runtime/Interop/when_reading_and_writing_CloudEvents_data.cs index 75cc65b66..60fd38fe2 100644 --- a/src/Testing/CoreTests/Runtime/Interop/when_reading_and_writing_CloudEvents_data.cs +++ b/src/Testing/CoreTests/Runtime/Interop/when_reading_and_writing_CloudEvents_data.cs @@ -98,7 +98,7 @@ public async Task try_deserialize_envelope_unwraps_metadata_when_message_type_is .UseWolverine(opts => { opts.RegisterMessageType(typeof(ApproveOrder), "com.dapr.event.sent"); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.Services.GetRequiredService(); var serializer = new CloudEventsMapper(runtime.Options.HandlerGraph, diff --git a/src/Testing/CoreTests/Runtime/Partitioning/ShardedExecutionBlockSmokeTests.cs b/src/Testing/CoreTests/Runtime/Partitioning/ShardedExecutionBlockSmokeTests.cs index 3c451c28b..8679b0a1e 100644 --- a/src/Testing/CoreTests/Runtime/Partitioning/ShardedExecutionBlockSmokeTests.cs +++ b/src/Testing/CoreTests/Runtime/Partitioning/ShardedExecutionBlockSmokeTests.cs @@ -31,7 +31,7 @@ public async Task do_not_blow_up() envelope.Message = new Coffee2(Guid.NewGuid().ToString()); await block.PostAsync(envelope); } - }); + }, TestContext.Current.CancellationToken); } await Task.WhenAll(tasks); diff --git a/src/Testing/CoreTests/Runtime/Partitioning/global_partitioning_with_separated_handlers.cs b/src/Testing/CoreTests/Runtime/Partitioning/global_partitioning_with_separated_handlers.cs index 1c96c576e..0b85d11f2 100644 --- a/src/Testing/CoreTests/Runtime/Partitioning/global_partitioning_with_separated_handlers.cs +++ b/src/Testing/CoreTests/Runtime/Partitioning/global_partitioning_with_separated_handlers.cs @@ -51,7 +51,7 @@ public async Task multiple_global_partitions_with_separated_handlers_for_same_me opts.MessagePartitioning .ByMessage(m => m.GroupId) .ByMessage(m => m.GroupId); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var tracked = await host.SendMessageAndWaitAsync( new PartitionedCommand("group-1", "test-payload"), diff --git a/src/Testing/CoreTests/Runtime/Partitioning/sticky_handlers_with_global_partitioning.cs b/src/Testing/CoreTests/Runtime/Partitioning/sticky_handlers_with_global_partitioning.cs index 85012091e..ac0e22101 100644 --- a/src/Testing/CoreTests/Runtime/Partitioning/sticky_handlers_with_global_partitioning.cs +++ b/src/Testing/CoreTests/Runtime/Partitioning/sticky_handlers_with_global_partitioning.cs @@ -48,7 +48,7 @@ public async Task sticky_handler_should_execute_exactly_once_per_handler_with_gl // This is the key: propagate group ID to partition key (as in the bug report) opts.Policies.PropagateGroupIdToPartitionKey(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var message = new StickyPartitionedMessage("group-1", "test-payload"); var session = await host.SendMessageAndWaitAsync(message, timeoutInMilliseconds: 15000); @@ -90,7 +90,7 @@ public async Task sticky_handler_should_execute_exactly_once_with_multiple_messa .ByMessage(m => m.Id); opts.Policies.PropagateGroupIdToPartitionKey(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); // Send 3 messages with the same group ID for (int i = 0; i < 3; i++) diff --git a/src/Testing/CoreTests/Runtime/Routing/description_mode_routes_are_not_cached.cs b/src/Testing/CoreTests/Runtime/Routing/description_mode_routes_are_not_cached.cs index 97d5e816b..26bd3b0a1 100644 --- a/src/Testing/CoreTests/Runtime/Routing/description_mode_routes_are_not_cached.cs +++ b/src/Testing/CoreTests/Runtime/Routing/description_mode_routes_are_not_cached.cs @@ -22,7 +22,7 @@ public async Task within_description_routing_is_not_cached_but_normal_routing_is .UseWolverine(opts => { opts.Discovery.DisableConventionalDiscovery().IncludeType(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.GetRuntime(); diff --git a/src/Testing/CoreTests/Runtime/Routing/explain_routing.cs b/src/Testing/CoreTests/Runtime/Routing/explain_routing.cs index ed13a7791..7d3719818 100644 --- a/src/Testing/CoreTests/Runtime/Routing/explain_routing.cs +++ b/src/Testing/CoreTests/Runtime/Routing/explain_routing.cs @@ -27,7 +27,7 @@ public async Task explains_local_routing() { using var host = await Host.CreateDefaultBuilder() .UseWolverine(opts => opts.Discovery.IncludeType(typeof(ExplainLocalHandler))) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var explanation = host.GetRuntime().ExplainRoutingFor(typeof(ExplainLocalMessage)); @@ -50,7 +50,7 @@ public async Task explicit_routing_terminates_and_later_sources_are_skipped() // Explicit publishing rule — ExplicitRouting is terminating opts.PublishMessage().ToPort(port); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var explanation = host.GetRuntime().ExplainRoutingFor(typeof(ExplainPublishedMessage)); @@ -68,7 +68,7 @@ public async Task explains_a_message_routed_nowhere() { using var host = await Host.CreateDefaultBuilder() .UseWolverine(opts => opts.Discovery.IncludeType(typeof(ExplainLocalHandler))) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var explanation = host.GetRuntime().ExplainRoutingFor(typeof(ExplainUnroutedMessage)); @@ -81,7 +81,7 @@ public async Task reports_local_routing_convention_disabled_flag() { using var enabled = await Host.CreateDefaultBuilder() .UseWolverine(opts => opts.Discovery.IncludeType(typeof(ExplainLocalHandler))) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); enabled.GetRuntime().ExplainRoutingFor(typeof(ExplainLocalMessage)) .LocalRoutingConventionDisabled.ShouldBeFalse(); @@ -91,7 +91,7 @@ public async Task reports_local_routing_convention_disabled_flag() opts.Discovery.IncludeType(typeof(ExplainLocalHandler)); opts.Policies.DisableConventionalLocalRouting(); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var explanation = disabled.GetRuntime().ExplainRoutingFor(typeof(ExplainLocalMessage)); explanation.LocalRoutingConventionDisabled.ShouldBeTrue(); @@ -101,7 +101,7 @@ public async Task reports_local_routing_convention_disabled_flag() [Fact] public async Task flags_system_message_types() { - using var host = await Host.CreateDefaultBuilder().UseWolverine().StartAsync(); + using var host = await Host.CreateDefaultBuilder().UseWolverine().StartAsync(cancellationToken: TestContext.Current.CancellationToken); var explanation = host.GetRuntime().ExplainRoutingFor(typeof(ExplainAgentCommand)); explanation.IsSystemMessageType.ShouldBeTrue(); @@ -112,7 +112,7 @@ public async Task text_output_carries_stable_labels_for_humans_and_agents() { using var host = await Host.CreateDefaultBuilder() .UseWolverine(opts => opts.Discovery.IncludeType(typeof(ExplainLocalHandler))) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var text = host.GetRuntime().ExplainRoutingFor(typeof(ExplainLocalMessage)).ToText(); diff --git a/src/Testing/CoreTests/Runtime/Routing/observer_message_routed_skipped_during_description.cs b/src/Testing/CoreTests/Runtime/Routing/observer_message_routed_skipped_during_description.cs index 65be093a5..bf5a7a5c3 100644 --- a/src/Testing/CoreTests/Runtime/Routing/observer_message_routed_skipped_during_description.cs +++ b/src/Testing/CoreTests/Runtime/Routing/observer_message_routed_skipped_during_description.cs @@ -30,7 +30,7 @@ public async Task does_not_fire_during_description_but_fires_normally_outside() .UseWolverine(opts => { opts.Discovery.DisableConventionalDiscovery().IncludeType(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.GetRuntime(); var fakeObserver = Substitute.For(); diff --git a/src/Testing/CoreTests/Runtime/Routing/routing_rules.cs b/src/Testing/CoreTests/Runtime/Routing/routing_rules.cs index b3ef99e9c..818a10f7a 100644 --- a/src/Testing/CoreTests/Runtime/Routing/routing_rules.cs +++ b/src/Testing/CoreTests/Runtime/Routing/routing_rules.cs @@ -23,7 +23,7 @@ public class routing_rules public async Task local_routing_is_applied_automatically() { using var host = await Host.CreateDefaultBuilder() - .UseWolverine().StartAsync(); + .UseWolverine().StartAsync(cancellationToken: TestContext.Current.CancellationToken); var bus = host.MessageBus(); bus.PreviewSubscriptions(new BlueMessage()) @@ -34,7 +34,7 @@ public async Task local_routing_is_applied_automatically() public async Task create_descriptor() { using var host = await Host.CreateDefaultBuilder() - .UseWolverine().StartAsync(); + .UseWolverine().StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.GetRuntime(); @@ -52,7 +52,7 @@ public async Task can_disable_local_routing_convention() .UseWolverine(opts => { opts.Policies.DisableConventionalLocalRouting(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var bus = host.MessageBus(); bus.PreviewSubscriptions(new BlueMessage()) @@ -63,7 +63,7 @@ public async Task can_disable_local_routing_convention() public async Task respect_local_queue() { using var host = await Host.CreateDefaultBuilder() - .UseWolverine().StartAsync(); + .UseWolverine().StartAsync(cancellationToken: TestContext.Current.CancellationToken); var bus = host.MessageBus(); bus.PreviewSubscriptions(new GreenMessage()) @@ -80,7 +80,7 @@ public async Task explicit_routing_to_local_wins() .UseWolverine(opts => { opts.PublishMessage().ToLocalQueue("purple"); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var bus = host.MessageBus(); bus.PreviewSubscriptions(new BlueMessage()) @@ -94,7 +94,7 @@ public async Task capture_message_types_from_explicit_rules() .UseWolverine(opts => { opts.PublishMessage().ToLocalQueue("purple"); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); host.GetRuntime().Options.HandlerGraph.AllMessageTypes().ShouldContain(typeof(BlueMessage)); } @@ -123,7 +123,7 @@ public async Task explicit_routing_to_elsewhere_wins() .UseWolverine(opts => { opts.PublishMessage().ToPort(port); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var bus = host.MessageBus(); bus.PreviewSubscriptions(new BlueMessage()) @@ -146,7 +146,7 @@ public async Task local_takes_precedence_on_other_routers() .UseWolverine(opts => { opts.RouteWith(convention); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var bus = host.MessageBus(); bus.PreviewSubscriptions(new BlueMessage()) @@ -169,7 +169,7 @@ public async Task fall_through_to_other_rules_if_no_local() .UseWolverine(opts => { opts.RouteWith(convention); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var bus = host.MessageBus(); bus.PreviewSubscriptions(new RedMessage()) @@ -180,7 +180,7 @@ public async Task fall_through_to_other_rules_if_no_local() public async Task use_local_invoker_if_local_exists() { using var host = await Host.CreateDefaultBuilder() - .UseWolverine().StartAsync(); + .UseWolverine().StartAsync(cancellationToken: TestContext.Current.CancellationToken); var collection = host.Services.GetRequiredService(); var local = collection.FindInvoker(typeof(BlueMessage)).ShouldBeOfType(); @@ -197,7 +197,7 @@ public async Task favor_local_invoker_if_local_exists() .UseWolverine(opts => { opts.PublishMessage().ToPort(port); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var collection = host.Services.GetRequiredService(); var local = collection.FindInvoker(typeof(BlueMessage)).ShouldBeOfType(); @@ -214,7 +214,7 @@ public async Task use_messageroute_if_cannot_handle_and_subscriber_exists() .UseWolverine(opts => { opts.PublishMessage().ToPort(port); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var collection = host.Services.GetRequiredService(); var remote = collection.FindInvoker(typeof(RedMessage)).ShouldBeOfType(); @@ -230,7 +230,7 @@ public async Task use_no_handler_if_no_handler_and_no_subscriber() .UseWolverine(opts => { - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var collection = host.Services.GetRequiredService(); collection.FindInvoker(typeof(RedMessage)) @@ -248,7 +248,7 @@ public async Task route_with_fluent_interface() //opts.Discovery.IncludeAssembly(typeof(Module2Message1).Assembly); opts.Publish().MessagesFromAssembly(typeof(Module2Message1).Assembly).ToPort(port); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var bus = host.MessageBus(); var envelopes = bus.PreviewSubscriptions(new Module2Message1()); @@ -265,7 +265,7 @@ public async Task group_id_application() { opts.PublishMessage().ToPort(port); opts.MessagePartitioning.ByMessage(x => x.GroupId); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var bus = host.MessageBus(); diff --git a/src/Testing/CoreTests/Runtime/Routing/separated_batch_routing.cs b/src/Testing/CoreTests/Runtime/Routing/separated_batch_routing.cs index eefbd0e95..a75abd2da 100644 --- a/src/Testing/CoreTests/Runtime/Routing/separated_batch_routing.cs +++ b/src/Testing/CoreTests/Runtime/Routing/separated_batch_routing.cs @@ -34,7 +34,7 @@ public async Task batch_lives_on_its_own_queue_and_message_fans_out_to_both() opts.MultipleHandlerBehavior = MultipleHandlerBehavior.Separated; opts.BatchMessagesOf(); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.GetRuntime(); @@ -74,7 +74,7 @@ public async Task separated_external_arrival_resolves_to_fanout_for_conflicting_ // reach both the direct handler and the batch. opts.ListenForMessagesFrom("stub://external"); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.GetRuntime(); var external = runtime.Options.Transports.AllEndpoints() @@ -100,7 +100,7 @@ public async Task produced_array_fans_out_to_each_sticky_handler_queue() opts.MultipleHandlerBehavior = MultipleHandlerBehavior.Separated; opts.BatchMessagesOf(); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.GetRuntime(); diff --git a/src/Testing/CoreTests/Runtime/Serialization/Encryption/CachingKeyProviderTests.cs b/src/Testing/CoreTests/Runtime/Serialization/Encryption/CachingKeyProviderTests.cs index 7154cc712..38f926928 100644 --- a/src/Testing/CoreTests/Runtime/Serialization/Encryption/CachingKeyProviderTests.cs +++ b/src/Testing/CoreTests/Runtime/Serialization/Encryption/CachingKeyProviderTests.cs @@ -36,9 +36,9 @@ public async Task first_call_hits_inner_then_cache_serves_subsequent_calls() var inner = new CountingProvider(new() { ["k1"] = Key32(0x01) }, "k1"); var caching = new CachingKeyProvider(inner, TimeSpan.FromMinutes(1)); - await caching.GetKeyAsync("k1", default); - await caching.GetKeyAsync("k1", default); - await caching.GetKeyAsync("k1", default); + await caching.GetKeyAsync("k1", TestContext.Current.CancellationToken); + await caching.GetKeyAsync("k1", TestContext.Current.CancellationToken); + await caching.GetKeyAsync("k1", TestContext.Current.CancellationToken); inner.CallCount.ShouldBe(1); } @@ -49,9 +49,9 @@ public async Task ttl_expiry_re_fetches() var inner = new CountingProvider(new() { ["k1"] = Key32(0x01) }, "k1"); var caching = new CachingKeyProvider(inner, TimeSpan.FromMilliseconds(50)); - await caching.GetKeyAsync("k1", default); - await Task.Delay(80); - await caching.GetKeyAsync("k1", default); + await caching.GetKeyAsync("k1", TestContext.Current.CancellationToken); + await Task.Delay(80, TestContext.Current.CancellationToken); + await caching.GetKeyAsync("k1", TestContext.Current.CancellationToken); inner.CallCount.ShouldBe(2); } @@ -65,9 +65,9 @@ public async Task concurrent_requests_for_same_key_deduplicate() var caching = new CachingKeyProvider(inner, TimeSpan.FromMinutes(1)); - var task1 = caching.GetKeyAsync("k1", default).AsTask(); - var task2 = caching.GetKeyAsync("k1", default).AsTask(); - var task3 = caching.GetKeyAsync("k1", default).AsTask(); + var task1 = caching.GetKeyAsync("k1", TestContext.Current.CancellationToken).AsTask(); + var task2 = caching.GetKeyAsync("k1", TestContext.Current.CancellationToken).AsTask(); + var task3 = caching.GetKeyAsync("k1", TestContext.Current.CancellationToken).AsTask(); // GetOrAdd is synchronous, so dedup has already happened — no need to // sleep before releasing. Only ONE call has even reached Hook(). @@ -85,8 +85,8 @@ public async Task different_keys_do_not_block_each_other() "k1"); var caching = new CachingKeyProvider(inner, TimeSpan.FromMinutes(1)); - await caching.GetKeyAsync("k1", default); - await caching.GetKeyAsync("k2", default); + await caching.GetKeyAsync("k1", TestContext.Current.CancellationToken); + await caching.GetKeyAsync("k2", TestContext.Current.CancellationToken); inner.CallCount.ShouldBe(2); } @@ -118,7 +118,7 @@ await Should.ThrowAsync(async () => // The faulted entry should have been evicted; second call must hit the inner // provider again and succeed. - var key = await caching.GetKeyAsync("k1", default); + var key = await caching.GetKeyAsync("k1", TestContext.Current.CancellationToken); key.ShouldBe(Key32(0x01)); attempt.ShouldBe(2); } @@ -190,21 +190,21 @@ public async Task cache_evicts_least_recently_used_when_max_entries_exceeded() var inner = new MultiKeyCountingProvider("a"); var sut = new CachingKeyProvider(inner, TimeSpan.FromMinutes(5), maxEntries: 3); - await sut.GetKeyAsync("a", default); - await sut.GetKeyAsync("b", default); - await sut.GetKeyAsync("c", default); - await sut.GetKeyAsync("a", default); // touch 'a' so 'b' becomes oldest - await sut.GetKeyAsync("d", default); // forces eviction of 'b' + await sut.GetKeyAsync("a", TestContext.Current.CancellationToken); + await sut.GetKeyAsync("b", TestContext.Current.CancellationToken); + await sut.GetKeyAsync("c", TestContext.Current.CancellationToken); + await sut.GetKeyAsync("a", TestContext.Current.CancellationToken); // touch 'a' so 'b' becomes oldest + await sut.GetKeyAsync("d", TestContext.Current.CancellationToken); // forces eviction of 'b' inner.CallsFor("a").ShouldBe(1); inner.CallsFor("b").ShouldBe(1); inner.CallsFor("c").ShouldBe(1); inner.CallsFor("d").ShouldBe(1); - await sut.GetKeyAsync("b", default); // evicted, must re-fetch + await sut.GetKeyAsync("b", TestContext.Current.CancellationToken); // evicted, must re-fetch inner.CallsFor("b").ShouldBe(2); - await sut.GetKeyAsync("a", default); // still cached + await sut.GetKeyAsync("a", TestContext.Current.CancellationToken); // still cached inner.CallsFor("a").ShouldBe(1); } @@ -233,14 +233,14 @@ public async Task max_entries_one_evicts_immediately_on_second_distinct_key() var inner = new MultiKeyCountingProvider("a"); var sut = new CachingKeyProvider(inner, TimeSpan.FromMinutes(5), maxEntries: 1); - await sut.GetKeyAsync("a", default); - await sut.GetKeyAsync("a", default); // still cached + await sut.GetKeyAsync("a", TestContext.Current.CancellationToken); + await sut.GetKeyAsync("a", TestContext.Current.CancellationToken); // still cached inner.CallsFor("a").ShouldBe(1); - await sut.GetKeyAsync("b", default); // evicts 'a' + await sut.GetKeyAsync("b", TestContext.Current.CancellationToken); // evicts 'a' inner.CallsFor("b").ShouldBe(1); - await sut.GetKeyAsync("a", default); // 'a' was evicted, must re-fetch + await sut.GetKeyAsync("a", TestContext.Current.CancellationToken); // 'a' was evicted, must re-fetch inner.CallsFor("a").ShouldBe(2); } @@ -253,9 +253,9 @@ public async Task entry_just_before_ttl_is_still_cached() var inner = new CountingProvider(new() { ["k1"] = Key32(0x01) }, "k1"); var caching = new CachingKeyProvider(inner, TimeSpan.FromSeconds(5)); - await caching.GetKeyAsync("k1", default); - await Task.Delay(50); // well within TTL - await caching.GetKeyAsync("k1", default); + await caching.GetKeyAsync("k1", TestContext.Current.CancellationToken); + await Task.Delay(50, TestContext.Current.CancellationToken); // well within TTL + await caching.GetKeyAsync("k1", TestContext.Current.CancellationToken); inner.CallCount.ShouldBe(1); } diff --git a/src/Testing/CoreTests/Runtime/Serialization/Encryption/InMemoryKeyProviderTests.cs b/src/Testing/CoreTests/Runtime/Serialization/Encryption/InMemoryKeyProviderTests.cs index 49a31d9d9..385796455 100644 --- a/src/Testing/CoreTests/Runtime/Serialization/Encryption/InMemoryKeyProviderTests.cs +++ b/src/Testing/CoreTests/Runtime/Serialization/Encryption/InMemoryKeyProviderTests.cs @@ -59,7 +59,7 @@ public async Task constructor_takes_defensive_copy_of_caller_arrays() Array.Clear(keyBytes); - var stored = await provider.GetKeyAsync("k1", default); + var stored = await provider.GetKeyAsync("k1", TestContext.Current.CancellationToken); stored.ShouldAllBe(b => b == 0x42); } } diff --git a/src/Testing/CoreTests/Runtime/Serialization/Encryption/MessageTypePoliciesEncryptFaultPairingTests.cs b/src/Testing/CoreTests/Runtime/Serialization/Encryption/MessageTypePoliciesEncryptFaultPairingTests.cs index f4d95e48e..74d27d51a 100644 --- a/src/Testing/CoreTests/Runtime/Serialization/Encryption/MessageTypePoliciesEncryptFaultPairingTests.cs +++ b/src/Testing/CoreTests/Runtime/Serialization/Encryption/MessageTypePoliciesEncryptFaultPairingTests.cs @@ -66,7 +66,7 @@ public async Task Manually_published_FaultT_routes_through_encrypting_serializer opts.PublishAllMessages().ToLocalQueue("target"); opts.LocalQueue("target"); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var bus = host.MessageBus(); diff --git a/src/Testing/CoreTests/Runtime/Serialization/Encryption/WolverineOptionsEncryptionTests.cs b/src/Testing/CoreTests/Runtime/Serialization/Encryption/WolverineOptionsEncryptionTests.cs index a2796949a..f167811be 100644 --- a/src/Testing/CoreTests/Runtime/Serialization/Encryption/WolverineOptionsEncryptionTests.cs +++ b/src/Testing/CoreTests/Runtime/Serialization/Encryption/WolverineOptionsEncryptionTests.cs @@ -26,7 +26,7 @@ public async Task use_encryption_swaps_default_serializer() { using var host = await Host.CreateDefaultBuilder() .UseWolverine(opts => opts.UseEncryption(NewProvider())) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var options = host.Services.GetRequiredService().Options; options.DefaultSerializer.ShouldBeOfType(); @@ -38,7 +38,7 @@ public async Task use_encryption_keeps_inner_json_serializer_resolvable() { using var host = await Host.CreateDefaultBuilder() .UseWolverine(opts => opts.UseEncryption(NewProvider())) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var options = host.Services.GetRequiredService().Options; var json = options.TryFindSerializer(EnvelopeConstants.JsonContentType); @@ -67,7 +67,7 @@ public async Task per_type_encrypt_routes_only_matching_type_to_encrypting_seria opts.PublishAllMessages().ToLocalQueue("target"); opts.LocalQueue("target"); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var bus = host.MessageBus(); @@ -97,7 +97,7 @@ public async Task endpoint_encrypted_routes_outgoing_through_encrypting_content_ opts.PublishAllMessages().ToLocalQueue("encrypted-q").Encrypted(); opts.LocalQueue("encrypted-q"); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var bus = host.MessageBus(); @@ -153,7 +153,7 @@ public async Task RequiresEncryption_uses_listener_endpoint_uri_not_envelope_des opts.LocalQueue("encryption-required-queue").RequireEncryption(); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.Services.GetRequiredService(); var endpoint = (LocalQueue?)runtime.Endpoints.EndpointByName("encryption-required-queue") @@ -197,7 +197,7 @@ public async Task fault_envelope_to_listener_with_RequireEncryption_is_DLQd_when })); opts.LocalQueue("fault-encryption-required").RequireEncryption(); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.Services.GetRequiredService(); var endpoint = (LocalQueue?)runtime.Endpoints.EndpointByName("fault-encryption-required") @@ -235,7 +235,7 @@ public async Task RequireEncryption_on_listener_registers_listener_uri() opts.LocalQueue("test-encrypted").RequireEncryption(); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.Services.GetRequiredService(); var queueUri = runtime.Endpoints.EndpointByName("test-encrypted")?.Uri @@ -325,7 +325,7 @@ public async Task no_endpoint_pipeline_still_enforces_per_type_encryption_marker })); opts.Policies.ForMessagesOfType().Encrypt(); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = (WolverineRuntime)host.Services.GetRequiredService(); var pipelineNoEndpoint = new HandlerPipeline(runtime, runtime); @@ -363,7 +363,7 @@ public async Task unmarked_type_is_serialized_by_inner_not_encrypting_serializer opts.PublishAllMessages().ToLocalQueue("target"); opts.LocalQueue("target"); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var bus = host.MessageBus(); diff --git a/src/Testing/CoreTests/Runtime/Stubs/using_stubs_end_to_end.cs b/src/Testing/CoreTests/Runtime/Stubs/using_stubs_end_to_end.cs index b4d04cadd..ab5f425ae 100644 --- a/src/Testing/CoreTests/Runtime/Stubs/using_stubs_end_to_end.cs +++ b/src/Testing/CoreTests/Runtime/Stubs/using_stubs_end_to_end.cs @@ -46,7 +46,7 @@ public async ValueTask DisposeAsync() public async Task baseline_state() { var bus = theSender.MessageBus(); - var response = await bus.InvokeAsync(new StubMessage1("green")); + var response = await bus.InvokeAsync(new StubMessage1("green"), TestContext.Current.CancellationToken); response.Id.ShouldBe("green"); } @@ -60,10 +60,10 @@ public async Task stub_single_message() }); var bus = theSender.MessageBus(); - var response = await bus.InvokeAsync(new StubMessage1("green")); + var response = await bus.InvokeAsync(new StubMessage1("green"), TestContext.Current.CancellationToken); response.Id.ShouldBe("green-1"); - var response2 = await bus.InvokeAsync(new StubMessage2("green")); + var response2 = await bus.InvokeAsync(new StubMessage2("green"), TestContext.Current.CancellationToken); response2.Id.ShouldBe("green"); } @@ -75,7 +75,7 @@ public async Task clear_all_reverts_back_to_normal() theSender.ClearAllWolverineStubs(); var bus = theSender.MessageBus(); - var response = await bus.InvokeAsync(new StubMessage1("green")); + var response = await bus.InvokeAsync(new StubMessage1("green"), TestContext.Current.CancellationToken); response.Id.ShouldBe("green"); } @@ -87,7 +87,7 @@ public async Task clear_specific_reverts_back_to_normal() theSender.WolverineStubs(x => x.Clear()); var bus = theSender.MessageBus(); - var response = await bus.InvokeAsync(new StubMessage1("green")); + var response = await bus.InvokeAsync(new StubMessage1("green"), TestContext.Current.CancellationToken); response.Id.ShouldBe("green"); } @@ -97,12 +97,12 @@ public async Task apply_second_stub_on_same_message_type() theSender.StubWolverineMessageHandling(m => new StubResponse1(m.Id + "-1")); var bus = theSender.MessageBus(); - var response = await bus.InvokeAsync(new StubMessage1("green")); + var response = await bus.InvokeAsync(new StubMessage1("green"), TestContext.Current.CancellationToken); response.Id.ShouldBe("green-1"); theSender.StubWolverineMessageHandling(m => new StubResponse1(m.Id + "-2")); - var response2 = await bus.InvokeAsync(new StubMessage1("green")); + var response2 = await bus.InvokeAsync(new StubMessage1("green"), TestContext.Current.CancellationToken); response2.Id.ShouldBe("green-2"); } } diff --git a/src/Testing/CoreTests/Runtime/WorkerQueues/buffered_receiver_null_listener_guard_3013.cs b/src/Testing/CoreTests/Runtime/WorkerQueues/buffered_receiver_null_listener_guard_3013.cs index 7d842e249..ff14bf497 100644 --- a/src/Testing/CoreTests/Runtime/WorkerQueues/buffered_receiver_null_listener_guard_3013.cs +++ b/src/Testing/CoreTests/Runtime/WorkerQueues/buffered_receiver_null_listener_guard_3013.cs @@ -28,7 +28,7 @@ public async Task listenerless_envelope_does_not_NRE_in_defer_or_complete_blocks using var host = await Host.CreateDefaultBuilder() .ConfigureLogging(logging => logging.AddProvider(captor)) .UseWolverine(opts => { opts.LocalQueue("buffered-3013"); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.Services.GetRequiredService(); var endpoint = (LocalQueue?)runtime.Endpoints.EndpointByName("buffered-3013") diff --git a/src/Testing/CoreTests/Runtime/WorkerQueues/inline_receiver_drain_and_latch.cs b/src/Testing/CoreTests/Runtime/WorkerQueues/inline_receiver_drain_and_latch.cs index 7df3d4eeb..8b29901b5 100644 --- a/src/Testing/CoreTests/Runtime/WorkerQueues/inline_receiver_drain_and_latch.cs +++ b/src/Testing/CoreTests/Runtime/WorkerQueues/inline_receiver_drain_and_latch.cs @@ -63,17 +63,17 @@ public async Task drain_waits_for_in_flight_message_to_complete_when_latched() var envelope = ObjectMother.Envelope(); // Start receiving on a background task — it will block in InvokeAsync - var receiveTask = Task.Run(() => theReceiver.ReceivedAsync(theListener, envelope).AsTask()); + var receiveTask = Task.Run(() => theReceiver.ReceivedAsync(theListener, envelope).AsTask(), TestContext.Current.CancellationToken); // Give the receive task time to enter the pipeline - await Task.Delay(50); + await Task.Delay(50, TestContext.Current.CancellationToken); Assert.Equal(1, theReceiver.QueueCount); // Simulate shutdown: Latch() is called first, then DrainAsync() theReceiver.Latch(); var drainTask = theReceiver.DrainAsync().AsTask(); - await Task.Delay(50); + await Task.Delay(50, TestContext.Current.CancellationToken); Assert.False(drainTask.IsCompleted, "DrainAsync should not complete while a message is in-flight"); @@ -82,7 +82,7 @@ public async Task drain_waits_for_in_flight_message_to_complete_when_latched() await receiveTask; // Drain should now complete - await drainTask.WaitAsync(TimeSpan.FromSeconds(5)); + await drainTask.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); Assert.Equal(0, theReceiver.QueueCount); } @@ -99,10 +99,10 @@ public async Task drain_returns_immediately_without_prior_latch_to_avoid_deadloc var envelope = ObjectMother.Envelope(); // Start receiving on a background task — it will block in InvokeAsync - var receiveTask = Task.Run(() => theReceiver.ReceivedAsync(theListener, envelope).AsTask()); + var receiveTask = Task.Run(() => theReceiver.ReceivedAsync(theListener, envelope).AsTask(), TestContext.Current.CancellationToken); // Give the receive task time to enter the pipeline - await Task.Delay(50); + await Task.Delay(50, TestContext.Current.CancellationToken); Assert.Equal(1, theReceiver.QueueCount); @@ -200,8 +200,8 @@ public async Task drain_times_out_when_message_blocks_forever() var envelope = ObjectMother.Envelope(); // Start a receive that will block - _ = Task.Run(() => theReceiver.ReceivedAsync(theListener, envelope).AsTask()); - await Task.Delay(50); + _ = Task.Run(() => theReceiver.ReceivedAsync(theListener, envelope).AsTask(), TestContext.Current.CancellationToken); + await Task.Delay(50, TestContext.Current.CancellationToken); // Simulate shutdown: Latch() first, then DrainAsync should time out theReceiver.Latch(); @@ -238,17 +238,17 @@ public async Task drain_does_not_signal_until_all_batch_messages_are_handled() var envelope3 = ObjectMother.Envelope(); // Start batch receive on a background task — it will block on the first message - var receiveTask = Task.Run(() => theReceiver.ReceivedAsync(theListener, new[] { envelope1, envelope2, envelope3 }).AsTask()); + var receiveTask = Task.Run(() => theReceiver.ReceivedAsync(theListener, new[] { envelope1, envelope2, envelope3 }).AsTask(), TestContext.Current.CancellationToken); // Give the receive task time to enter the pipeline for envelope1 - await Task.Delay(50); + await Task.Delay(50, TestContext.Current.CancellationToken); Assert.Equal(3, theReceiver.QueueCount); // Simulate shutdown: Latch() first, then DrainAsync while the first message is still in-flight. theReceiver.Latch(); var drainTask = theReceiver.DrainAsync().AsTask(); - await Task.Delay(50); + await Task.Delay(50, TestContext.Current.CancellationToken); Assert.False(drainTask.IsCompleted, "DrainAsync must not complete while batch messages are still in-flight"); @@ -256,10 +256,10 @@ public async Task drain_does_not_signal_until_all_batch_messages_are_handled() firstMessageBlocking.SetResult(); // Wait for the full batch receive to complete - await receiveTask.WaitAsync(TimeSpan.FromSeconds(5)); + await receiveTask.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); // Drain should now complete since all messages are processed/deferred - await drainTask.WaitAsync(TimeSpan.FromSeconds(5)); + await drainTask.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); Assert.Equal(0, theReceiver.QueueCount); @@ -297,25 +297,25 @@ public async Task batch_messages_are_processed_not_deferred_while_draining() var envelope3 = ObjectMother.Envelope(); // Start batch receive — it will block on the first message - var receiveTask = Task.Run(() => theReceiver.ReceivedAsync(theListener, new[] { envelope1, envelope2, envelope3 }).AsTask()); + var receiveTask = Task.Run(() => theReceiver.ReceivedAsync(theListener, new[] { envelope1, envelope2, envelope3 }).AsTask(), TestContext.Current.CancellationToken); // Give the receive task time to enter the pipeline for envelope1 - await Task.Delay(50); + await Task.Delay(50, TestContext.Current.CancellationToken); Assert.Equal(3, theReceiver.QueueCount); // Simulate shutdown: Latch() first, then DrainAsync while the first message is still in-flight theReceiver.Latch(); var drainTask = theReceiver.DrainAsync().AsTask(); - await Task.Delay(50); + await Task.Delay(50, TestContext.Current.CancellationToken); Assert.False(drainTask.IsCompleted, "DrainAsync must not complete while batch messages are still in-flight"); // Release the first message — with ProcessInlineWhileDraining, remaining messages should be processed, not deferred firstMessageBlocking.SetResult(); - await receiveTask.WaitAsync(TimeSpan.FromSeconds(5)); - await drainTask.WaitAsync(TimeSpan.FromSeconds(5)); + await receiveTask.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + await drainTask.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); Assert.Equal(0, theReceiver.QueueCount); @@ -388,8 +388,8 @@ public async Task messages_are_processed_during_non_wait_drain() var envelope2 = ObjectMother.Envelope(); // Start batch receive — it will block on the first message - var receiveTask = Task.Run(() => theReceiver.ReceivedAsync(theListener, new[] { envelope1, envelope2 }).AsTask()); - await Task.Delay(50); + var receiveTask = Task.Run(() => theReceiver.ReceivedAsync(theListener, new[] { envelope1, envelope2 }).AsTask(), TestContext.Current.CancellationToken); + await Task.Delay(50, TestContext.Current.CancellationToken); // DrainAsync without prior Latch() — returns immediately (non-wait path) var drainTask = theReceiver.DrainAsync(); @@ -397,7 +397,7 @@ public async Task messages_are_processed_during_non_wait_drain() // Release the first message — envelope2 should still be processed firstMessageBlocking.SetResult(); - await receiveTask.WaitAsync(TimeSpan.FromSeconds(5)); + await receiveTask.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); // Both messages should have been processed, not deferred await theListener.DidNotReceive().DeferAsync(envelope2); diff --git a/src/Testing/CoreTests/Runtime/envelope_pool_tests.cs b/src/Testing/CoreTests/Runtime/envelope_pool_tests.cs index dde8260d6..cbb1e1b66 100644 --- a/src/Testing/CoreTests/Runtime/envelope_pool_tests.cs +++ b/src/Testing/CoreTests/Runtime/envelope_pool_tests.cs @@ -158,7 +158,7 @@ public async Task Tracked_session_envelope_record_survives_after_handler_returns opts.Discovery.DisableConventionalDiscovery() .IncludeType(); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); EnvelopeCapturingHandler.LastSeen = null; EnvelopeCapturingHandler.CapturedId = default; diff --git a/src/Testing/CoreTests/Runtime/handler_type_activity_tagging.cs b/src/Testing/CoreTests/Runtime/handler_type_activity_tagging.cs index 1739f5bd0..cd8eaa544 100644 --- a/src/Testing/CoreTests/Runtime/handler_type_activity_tagging.cs +++ b/src/Testing/CoreTests/Runtime/handler_type_activity_tagging.cs @@ -41,7 +41,7 @@ public async Task should_tag_handler_type_on_activity_for_message_handler() await _host.InvokeMessageAndWaitAsync(new TracingTestMessage("hello")); // Give a moment for activities to be captured - await Task.Delay(100.Milliseconds()); + await Task.Delay(100.Milliseconds(), TestContext.Current.CancellationToken); var handlerActivities = _capturedActivities .Where(a => a.GetTagItem(WolverineTracing.HandlerType) != null) @@ -60,7 +60,7 @@ public async Task should_tag_message_handler_on_activity_for_message_handler() { await _host.InvokeMessageAndWaitAsync(new TracingTestMessage("hello")); - await Task.Delay(100.Milliseconds()); + await Task.Delay(100.Milliseconds(), TestContext.Current.CancellationToken); var handlerActivities = _capturedActivities .Where(a => a.GetTagItem(WolverineTracing.MessageHandler) != null) @@ -79,7 +79,7 @@ public async Task handler_type_and_message_handler_tags_should_have_same_value() { await _host.InvokeMessageAndWaitAsync(new TracingTestMessage("hello")); - await Task.Delay(100.Milliseconds()); + await Task.Delay(100.Milliseconds(), TestContext.Current.CancellationToken); var activity = _capturedActivities .FirstOrDefault(a => a.GetTagItem(WolverineTracing.HandlerType) != null); diff --git a/src/Testing/CoreTests/Runtime/histogram_bucket_boundaries_3224.cs b/src/Testing/CoreTests/Runtime/histogram_bucket_boundaries_3224.cs index 74a11051a..eb214ce1a 100644 --- a/src/Testing/CoreTests/Runtime/histogram_bucket_boundaries_3224.cs +++ b/src/Testing/CoreTests/Runtime/histogram_bucket_boundaries_3224.cs @@ -42,7 +42,7 @@ public async Task histograms_use_the_configured_bucket_boundaries() opts.ServiceName = serviceName; opts.Metrics.HistogramBucketBoundaries = boundaries; opts.Discovery.DisableConventionalDiscovery().IncludeType(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); // Drive a message so both histograms (execution-time + effective-time) record. await host.TrackActivity().SendMessageAndWaitAsync(new MetricSuccess()); diff --git a/src/Testing/CoreTests/Runtime/resource_migration_failure_mode_on_startup.cs b/src/Testing/CoreTests/Runtime/resource_migration_failure_mode_on_startup.cs index 8eeb1e84d..85711c093 100644 --- a/src/Testing/CoreTests/Runtime/resource_migration_failure_mode_on_startup.cs +++ b/src/Testing/CoreTests/Runtime/resource_migration_failure_mode_on_startup.cs @@ -35,7 +35,7 @@ public async Task continue_on_failures_lets_the_application_start() opts.ResourceMigrationFailureMode = ResourceMigrationFailureMode.ContinueOnFailures; opts.Transports.Add(new ThrowingTransport()); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); // If we got here, startup continued despite the transport's InitializeAsync throwing host.Services.GetService(typeof(IWolverineRuntime)).ShouldNotBeNull(); diff --git a/src/Testing/CoreTests/Runtime/service_location_message_context.cs b/src/Testing/CoreTests/Runtime/service_location_message_context.cs index 96fbc8202..cdb88a559 100644 --- a/src/Testing/CoreTests/Runtime/service_location_message_context.cs +++ b/src/Testing/CoreTests/Runtime/service_location_message_context.cs @@ -36,7 +36,7 @@ public async Task service_located_bus_publishes_through_active_context_when_chai // the ServiceLocationAwareExecutor wraps it. Mirrors the pattern in the // existing service_location_assertions tests. opts.CodeGeneration.AlwaysUseServiceLocationFor(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var session = await host.TrackActivity().IncludeExternalTransports().ExecuteAndWaitAsync(c => c.PublishAsync(new ServiceLocatedBusCommand("hello"))); @@ -59,7 +59,7 @@ public async Task clean_chain_still_runs_and_does_not_force_service_location() .UseWolverine(opts => { opts.ServiceLocationPolicy = ServiceLocationPolicy.NotAllowed; - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); CleanCommandProbe.Reset(); @@ -74,7 +74,7 @@ public async Task message_bus_resolves_outside_handler_invocation() // Outside any handler invocation the scope holder is empty, so IMessageBus falls back to a // fresh MessageContext — resolution must still succeed for hosted services / admin tools. using var host = await Host.CreateDefaultBuilder() - .UseWolverine().StartAsync(); + .UseWolverine().StartAsync(cancellationToken: TestContext.Current.CancellationToken); var bus = host.MessageBus(); bus.ShouldNotBeNull(); @@ -92,7 +92,7 @@ public async Task service_located_message_context_is_same_instance_as_handler_ar // Force the capturing service to be resolved via service location so the // chain is flagged UsesServiceLocation = true. opts.CodeGeneration.AlwaysUseServiceLocationFor(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); ContextIdentityProbe.Reset(); diff --git a/src/Testing/CoreTests/Runtime/tracking_diagnostics_opt_in.cs b/src/Testing/CoreTests/Runtime/tracking_diagnostics_opt_in.cs index 6dd5735ae..0fb02db7d 100644 --- a/src/Testing/CoreTests/Runtime/tracking_diagnostics_opt_in.cs +++ b/src/Testing/CoreTests/Runtime/tracking_diagnostics_opt_in.cs @@ -71,7 +71,7 @@ private void writeGeneratedSource(IHost host, string label) [Fact] public async Task all_tracking_flags_default_to_false() { - using var host = await Host.CreateDefaultBuilder().UseWolverine().StartAsync(); + using var host = await Host.CreateDefaultBuilder().UseWolverine().StartAsync(cancellationToken: TestContext.Current.CancellationToken); var options = host.GetRuntime().Options; @@ -105,7 +105,7 @@ public async Task record_cause_and_effect_call_baked_into_codegen_when_enabled() finally { listener.Dispose(); - await host.StopAsync(); + await host.StopAsync(TestContext.Current.CancellationToken); host.Dispose(); } } @@ -133,7 +133,7 @@ public async Task record_cause_and_effect_call_absent_from_codegen_when_disabled finally { listener.Dispose(); - await host.StopAsync(); + await host.StopAsync(TestContext.Current.CancellationToken); host.Dispose(); } } @@ -151,7 +151,7 @@ public async Task handler_started_and_finished_events_emit_when_enabled() try { await host.InvokeMessageAndWaitAsync(new TrackingDiagnosticsMessage("hello")); - await Task.Delay(100.Milliseconds()); + await Task.Delay(100.Milliseconds(), TestContext.Current.CancellationToken); writeGeneratedSource(host, "HandlerExecutionDiagnosticsEnabled = true"); @@ -167,7 +167,7 @@ public async Task handler_started_and_finished_events_emit_when_enabled() finally { listener.Dispose(); - await host.StopAsync(); + await host.StopAsync(TestContext.Current.CancellationToken); host.Dispose(); } } @@ -180,7 +180,7 @@ public async Task handler_started_and_finished_events_do_not_emit_when_disabled( try { await host.InvokeMessageAndWaitAsync(new TrackingDiagnosticsMessage("hello")); - await Task.Delay(100.Milliseconds()); + await Task.Delay(100.Milliseconds(), TestContext.Current.CancellationToken); writeGeneratedSource(host, "HandlerExecutionDiagnosticsEnabled = false (default)"); @@ -196,7 +196,7 @@ public async Task handler_started_and_finished_events_do_not_emit_when_disabled( finally { listener.Dispose(); - await host.StopAsync(); + await host.StopAsync(TestContext.Current.CancellationToken); host.Dispose(); } } @@ -231,7 +231,7 @@ public async Task handler_started_and_finished_event_calls_baked_into_codegen_wh finally { listener.Dispose(); - await host.StopAsync(); + await host.StopAsync(TestContext.Current.CancellationToken); host.Dispose(); } } @@ -260,7 +260,7 @@ public async Task handler_started_and_finished_event_calls_absent_from_codegen_w finally { listener.Dispose(); - await host.StopAsync(); + await host.StopAsync(TestContext.Current.CancellationToken); host.Dispose(); } } @@ -274,7 +274,7 @@ public async Task transport_lag_tag_emits_when_handler_diagnostics_enabled() try { await host.InvokeMessageAndWaitAsync(new TrackingDiagnosticsMessage("hello")); - await Task.Delay(100.Milliseconds()); + await Task.Delay(100.Milliseconds(), TestContext.Current.CancellationToken); var handlerActivity = captured.FirstOrDefault(a => a.GetTagItem(WolverineTracing.MessageHandler) is string h @@ -286,7 +286,7 @@ public async Task transport_lag_tag_emits_when_handler_diagnostics_enabled() finally { listener.Dispose(); - await host.StopAsync(); + await host.StopAsync(TestContext.Current.CancellationToken); host.Dispose(); } } @@ -299,7 +299,7 @@ public async Task transport_lag_tag_absent_when_handler_diagnostics_disabled() try { await host.InvokeMessageAndWaitAsync(new TrackingDiagnosticsMessage("hello")); - await Task.Delay(100.Milliseconds()); + await Task.Delay(100.Milliseconds(), TestContext.Current.CancellationToken); var handlerActivity = captured.FirstOrDefault(a => a.GetTagItem(WolverineTracing.MessageHandler) is string h @@ -312,7 +312,7 @@ public async Task transport_lag_tag_absent_when_handler_diagnostics_disabled() finally { listener.Dispose(); - await host.StopAsync(); + await host.StopAsync(TestContext.Current.CancellationToken); host.Dispose(); } } @@ -336,14 +336,14 @@ public async Task deserialize_span_does_not_start_when_disabled() try { await host.InvokeMessageAndWaitAsync(new TrackingDiagnosticsMessage("hello")); - await Task.Delay(100.Milliseconds()); + await Task.Delay(100.Milliseconds(), TestContext.Current.CancellationToken); captured.Any(a => a.OperationName == WolverineTracing.Deserialize).ShouldBeFalse(); } finally { listener.Dispose(); - await host.StopAsync(); + await host.StopAsync(TestContext.Current.CancellationToken); host.Dispose(); } } @@ -398,7 +398,7 @@ public async Task deserialize_span_records_exception_detail_on_failure_when_enab finally { listener.Dispose(); - await host.StopAsync(); + await host.StopAsync(TestContext.Current.CancellationToken); host.Dispose(); } } diff --git a/src/Testing/CoreTests/Runtime/using_wolverine_activators.cs b/src/Testing/CoreTests/Runtime/using_wolverine_activators.cs index 31d718605..4e28fad8d 100644 --- a/src/Testing/CoreTests/Runtime/using_wolverine_activators.cs +++ b/src/Testing/CoreTests/Runtime/using_wolverine_activators.cs @@ -22,7 +22,7 @@ public async Task an_activator_is_called() opts.Services.AddSingleton(activator1); opts.Services.AddSingleton(activator2); opts.Services.AddSingleton(activator3); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.GetRuntime(); diff --git a/src/Testing/CoreTests/Serialization/WolverineRuntimeLimitsWireupTests.cs b/src/Testing/CoreTests/Serialization/WolverineRuntimeLimitsWireupTests.cs index 30837c8c8..43c96aaa6 100644 --- a/src/Testing/CoreTests/Serialization/WolverineRuntimeLimitsWireupTests.cs +++ b/src/Testing/CoreTests/Serialization/WolverineRuntimeLimitsWireupTests.cs @@ -27,7 +27,7 @@ public async Task host_startup_publishes_configured_limits_to_envelope_serialize opts.MaxIncomingEnvelopeDataSize = 9 * 1024 * 1024; opts.MaxIncomingEnvelopeHeaderCount = 256; }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); EnvelopeSerializer.Limits.MaxBatchSize.ShouldBe(4242); EnvelopeSerializer.Limits.MaxDataSize.ShouldBe(9 * 1024 * 1024); @@ -39,7 +39,7 @@ public async Task host_startup_with_default_options_leaves_default_limits() { using var host = await Host.CreateDefaultBuilder() .UseWolverine(_ => { }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); EnvelopeSerializer.Limits.ShouldBe(EnvelopeReaderLimits.Default); WireProtocol.MaxFrameSize.ShouldBe(WireProtocol.DefaultMaxFrameSize); @@ -53,7 +53,7 @@ public async Task host_startup_publishes_configured_tcp_frame_size_to_wire_proto { opts.MaxIncomingTcpFrameSize = 7 * 1024 * 1024; }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); WireProtocol.MaxFrameSize.ShouldBe(7 * 1024 * 1024); } diff --git a/src/Testing/CoreTests/Serialization/serialization_configuration.cs b/src/Testing/CoreTests/Serialization/serialization_configuration.cs index f97de4ab2..7921ddcf9 100644 --- a/src/Testing/CoreTests/Serialization/serialization_configuration.cs +++ b/src/Testing/CoreTests/Serialization/serialization_configuration.cs @@ -18,7 +18,7 @@ public async Task by_default_every_endpoint_has_json_serializer_with_default_set { opts.PublishAllMessages().To("stub://one"); opts.PublishAllMessages().To("stub://two"); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var root = host.Services.GetRequiredService(); @@ -39,7 +39,7 @@ public async Task can_override_the_json_serialization_on_subscriber() opts.PublishAllMessages().To("stub://two") .CustomNewtonsoftJsonSerialization(customSettings); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var root = host.Services.GetRequiredService(); root.Endpoints.EndpointFor("stub://one".ToUri())! @@ -62,7 +62,7 @@ public async Task can_find_other_serializer_from_parent() opts.ListenForMessagesFrom("stub://two") .CustomNewtonsoftJsonSerialization(customSettings); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var root = host.Services.GetRequiredService(); root.Endpoints.EndpointFor("stub://one".ToUri())! @@ -87,7 +87,7 @@ public async Task can_override_the_default_serializer_on_sender() opts.ListenForMessagesFrom("stub://two") .CustomNewtonsoftJsonSerialization(customSettings); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var root = host.Services.GetRequiredService(); root.Endpoints.EndpointFor("stub://one".ToUri())! @@ -105,7 +105,7 @@ public async Task can_override_the_json_serialization_on_listener() opts.ListenForMessagesFrom("stub://two") .CustomNewtonsoftJsonSerialization(customSettings); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var root = host.Services.GetRequiredService(); root.Endpoints.EndpointFor("stub://one".ToUri())! @@ -127,7 +127,7 @@ public async Task can_override_the_default_serialization_on_listener() opts.ListenForMessagesFrom("stub://two") .DefaultSerializer(fooSerializer); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var root = host.Services.GetRequiredService(); root.Endpoints.EndpointFor("stub://one".ToUri())! @@ -148,7 +148,7 @@ public async Task can_override_the_default_app_wide() opts.PublishAllMessages().To("stub://one"); opts.ListenForMessagesFrom("stub://two"); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var root = host.Services.GetRequiredService(); root.Endpoints.EndpointFor("stub://one".ToUri())! @@ -174,7 +174,7 @@ public async Task custom_serializer_on_sender_is_used_to_produce_outgoing_envelo // Sibling sender with no override — must stay on the global STJ default. opts.PublishMessage().To("stub://plain"); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.Services.GetRequiredService(); var router = runtime.RoutingFor(typeof(CustomSerializedMessage)); diff --git a/src/Testing/CoreTests/Shims/mediatr_usage.cs b/src/Testing/CoreTests/Shims/mediatr_usage.cs index c95d4df31..8079be7aa 100644 --- a/src/Testing/CoreTests/Shims/mediatr_usage.cs +++ b/src/Testing/CoreTests/Shims/mediatr_usage.cs @@ -13,8 +13,7 @@ public mediatr_usage(DefaultApp @default) : base(@default) [Fact] public async Task response_is_returned_from_invoke_async() { - var response = await Host.MessageBus().InvokeAsync( - new RequestWithResponse("response-test")); + var response = await Host.MessageBus().InvokeAsync(new RequestWithResponse("response-test"), TestContext.Current.CancellationToken); response.ShouldNotBeNull(); response.Data.ShouldBe("passed: response-test"); @@ -23,8 +22,7 @@ public async Task response_is_returned_from_invoke_async() [Fact] public async Task response_type_is_correct() { - var response = await Host.MessageBus().InvokeAsync( - new RequestWithResponse("type-test")); + var response = await Host.MessageBus().InvokeAsync(new RequestWithResponse("type-test"), TestContext.Current.CancellationToken); response.ShouldBeOfType(); } @@ -32,8 +30,7 @@ public async Task response_type_is_correct() [Fact] public async Task invoke_mediatr_handler_with_response() { - var response = await Host.MessageBus().InvokeAsync( - new RequestWithResponse("test")); + var response = await Host.MessageBus().InvokeAsync(new RequestWithResponse("test"), TestContext.Current.CancellationToken); response.ShouldNotBeNull(); response.Data.ShouldBe("passed: test"); diff --git a/src/Testing/CoreTests/TestMessageContextTests.cs b/src/Testing/CoreTests/TestMessageContextTests.cs index c03a37b5d..6d8098d50 100644 --- a/src/Testing/CoreTests/TestMessageContextTests.cs +++ b/src/Testing/CoreTests/TestMessageContextTests.cs @@ -22,7 +22,7 @@ public void basic_members() public async Task invoke_a_message_inline() { var message = new Message2(); - await theContext.InvokeAsync(message); + await theContext.InvokeAsync(message, TestContext.Current.CancellationToken); theSpy.Invoked.ShouldHaveMessageOfType() .ShouldBeSameAs(message); @@ -177,7 +177,7 @@ public async Task respond_to_sender() public async Task invoke_remotely() { var message1 = new Message1(); - await theContext.InvokeAsync(message1); + await theContext.InvokeAsync(message1, TestContext.Current.CancellationToken); theSpy.Invoked.ShouldHaveMessageOfType(); } @@ -188,7 +188,7 @@ public async Task send_and_await_to_destination() var uri = "something://one".ToUri(); var message1 = new Message1(); - await theContext.EndpointFor(uri).InvokeAsync(message1); + await theContext.EndpointFor(uri).InvokeAsync(message1, TestContext.Current.CancellationToken); var env = theSpy.Sent.ShouldHaveEnvelopeForMessageType(); env.Destination.ShouldBe(uri); @@ -199,7 +199,7 @@ public async Task send_and_await_to_specific_endpoint() { var message1 = new Message1(); - await theContext.EndpointFor("endpoint1").InvokeAsync(message1); + await theContext.EndpointFor("endpoint1").InvokeAsync(message1, TestContext.Current.CancellationToken); var env = theSpy.Sent.ShouldHaveEnvelopeForMessageType(); env.EndpointName.ShouldBe("endpoint1"); @@ -211,7 +211,7 @@ public async Task invoke_with_expected_response_no_filter_hit() var response = new NumberResponse(11); theSpy.WhenInvokedMessageOf().RespondWith(response); - (await theContext.InvokeAsync(new NumberRequest(3, 4))) + (await theContext.InvokeAsync(new NumberRequest(3, 4), TestContext.Current.CancellationToken)) .ShouldBeSameAs(response); } @@ -234,10 +234,10 @@ public async Task invoke_with_expected_response_and_filter_hit() theSpy.WhenInvokedMessageOf(x => x.X == 3).RespondWith(response1); theSpy.WhenInvokedMessageOf(x => x.X == 5).RespondWith(response2); - (await theContext.InvokeAsync(new NumberRequest(3, 4))) + (await theContext.InvokeAsync(new NumberRequest(3, 4), TestContext.Current.CancellationToken)) .ShouldBeSameAs(response1); - (await theContext.InvokeAsync(new NumberRequest(5, 4))) + (await theContext.InvokeAsync(new NumberRequest(5, 4), TestContext.Current.CancellationToken)) .ShouldBeSameAs(response2); } @@ -263,7 +263,7 @@ public async Task stream_request_records_invocation_and_returns_configured_respo theSpy.WhenInvokedMessageOf>().RespondWith(response); var stream = numberRequests(); - (await theContext.StreamAsync(stream)) + (await theContext.StreamAsync(stream, TestContext.Current.CancellationToken)) .ShouldBeSameAs(response); theSpy.Invoked.Single().ShouldBeSameAs(stream); @@ -297,9 +297,9 @@ public async Task invoke_with_expected_response_no_filter_hit_to_endpoint_by_uri var destination2 = new Uri("stub://two"); theSpy.WhenInvokedMessageOf(destination:destination2).RespondWith(response2); - (await theContext.EndpointFor(destination1).InvokeAsync(new NumberRequest(4, 5))).ShouldBeSameAs(response1); + (await theContext.EndpointFor(destination1).InvokeAsync(new NumberRequest(4, 5), TestContext.Current.CancellationToken)).ShouldBeSameAs(response1); - (await theContext.EndpointFor(destination2).InvokeAsync(new NumberRequest(4, 5))).ShouldBeSameAs(response2); + (await theContext.EndpointFor(destination2).InvokeAsync(new NumberRequest(4, 5), TestContext.Current.CancellationToken)).ShouldBeSameAs(response2); } [Fact] @@ -325,7 +325,7 @@ public async Task invoke_with_expected_response_and_filter_hit_to_endpoint_by_ur var destination1 = new Uri("stub://one"); theSpy.WhenInvokedMessageOf(x => x.X == 4,destination:destination1).RespondWith(response1); - (await theContext.EndpointFor(destination1).InvokeAsync(new NumberRequest(4, 5))).ShouldBeSameAs(response1); + (await theContext.EndpointFor(destination1).InvokeAsync(new NumberRequest(4, 5), TestContext.Current.CancellationToken)).ShouldBeSameAs(response1); } [Fact] @@ -354,9 +354,9 @@ public async Task invoke_with_expected_response_no_filter_hit_to_endpoint_by_nam theSpy.WhenInvokedMessageOf(endpointName:"two").RespondWith(response2); - (await theContext.EndpointFor("one").InvokeAsync(new NumberRequest(4, 5))).ShouldBeSameAs(response1); + (await theContext.EndpointFor("one").InvokeAsync(new NumberRequest(4, 5), TestContext.Current.CancellationToken)).ShouldBeSameAs(response1); - (await theContext.EndpointFor("two").InvokeAsync(new NumberRequest(4, 5))).ShouldBeSameAs(response2); + (await theContext.EndpointFor("two").InvokeAsync(new NumberRequest(4, 5), TestContext.Current.CancellationToken)).ShouldBeSameAs(response2); } [Fact] @@ -380,7 +380,7 @@ public async Task invoke_with_expected_response_and_filter_hit_to_endpoint_by_na var response1 = new NumberResponse(11); theSpy.WhenInvokedMessageOf(x => x.X == 4,endpointName:"one").RespondWith(response1); - (await theContext.EndpointFor("one").InvokeAsync(new NumberRequest(4, 5))).ShouldBeSameAs(response1); + (await theContext.EndpointFor("one").InvokeAsync(new NumberRequest(4, 5), TestContext.Current.CancellationToken)).ShouldBeSameAs(response1); } [Fact] @@ -404,7 +404,7 @@ public async Task invoke_acknowledgement_with_delivery_options_to_endpoint_by_ur var uri = "something://one".ToUri(); var message1 = new Message1(); - await theContext.EndpointFor(uri).InvokeAsync(message1, new DeliveryOptions().WithHeader("ack-test", "value")); + await theContext.EndpointFor(uri).InvokeAsync(message1, new DeliveryOptions().WithHeader("ack-test", "value"), TestContext.Current.CancellationToken); var envelope = theSpy.Sent.ShouldHaveEnvelopeForMessageType(); envelope.Destination.ShouldBe(uri); @@ -416,7 +416,7 @@ public async Task invoke_acknowledgement_with_delivery_options_to_endpoint_by_na { var message1 = new Message1(); - await theContext.EndpointFor("endpoint1").InvokeAsync(message1, new DeliveryOptions().WithHeader("ack-name-test", "value")); + await theContext.EndpointFor("endpoint1").InvokeAsync(message1, new DeliveryOptions().WithHeader("ack-name-test", "value"), TestContext.Current.CancellationToken); var envelope = theSpy.Sent.ShouldHaveEnvelopeForMessageType(); envelope.EndpointName.ShouldBe("endpoint1"); @@ -429,9 +429,7 @@ public async Task invoke_with_expected_response_and_delivery_options_no_filter_h var response = new NumberResponse(11); theSpy.WhenInvokedMessageOf().RespondWith(response); - var result = await theContext.InvokeAsync( - new NumberRequest(3, 4), - new DeliveryOptions().WithHeader("custom", "value")); + var result = await theContext.InvokeAsync(new NumberRequest(3, 4), new DeliveryOptions().WithHeader("custom", "value"), TestContext.Current.CancellationToken); result.ShouldBeSameAs(response); @@ -447,15 +445,11 @@ public async Task invoke_with_expected_response_and_delivery_options_and_filter_ theSpy.WhenInvokedMessageOf(x => x.X == 3).RespondWith(response1); theSpy.WhenInvokedMessageOf(x => x.X == 5).RespondWith(response2); - var result1 = await theContext.InvokeAsync( - new NumberRequest(3, 4), - new DeliveryOptions().WithHeader("test", "one")); + var result1 = await theContext.InvokeAsync(new NumberRequest(3, 4), new DeliveryOptions().WithHeader("test", "one"), TestContext.Current.CancellationToken); result1.ShouldBeSameAs(response1); - var result2 = await theContext.InvokeAsync( - new NumberRequest(5, 4), - new DeliveryOptions().WithHeader("test", "two")); + var result2 = await theContext.InvokeAsync(new NumberRequest(5, 4), new DeliveryOptions().WithHeader("test", "two"), TestContext.Current.CancellationToken); result2.ShouldBeSameAs(response2); } @@ -484,9 +478,7 @@ public async Task invoke_with_expected_response_and_delivery_options_to_endpoint theSpy.WhenInvokedMessageOf(destination: destination).RespondWith(response); var result = await theContext.EndpointFor(destination) - .InvokeAsync( - new NumberRequest(4, 5), - new DeliveryOptions().WithHeader("uri-test", "value")); + .InvokeAsync(new NumberRequest(4, 5), new DeliveryOptions().WithHeader("uri-test", "value"), TestContext.Current.CancellationToken); result.ShouldBeSameAs(response); @@ -503,9 +495,7 @@ public async Task invoke_with_expected_response_and_delivery_options_and_filter_ theSpy.WhenInvokedMessageOf(x => x.X == 4, destination: destination).RespondWith(response); var result = await theContext.EndpointFor(destination) - .InvokeAsync( - new NumberRequest(4, 5), - new DeliveryOptions().WithHeader("filter-uri-test", "value")); + .InvokeAsync(new NumberRequest(4, 5), new DeliveryOptions().WithHeader("filter-uri-test", "value"), TestContext.Current.CancellationToken); result.ShouldBeSameAs(response); } @@ -517,9 +507,7 @@ public async Task invoke_with_expected_response_and_delivery_options_to_endpoint theSpy.WhenInvokedMessageOf(endpointName: "one").RespondWith(response); var result = await theContext.EndpointFor("one") - .InvokeAsync( - new NumberRequest(4, 5), - new DeliveryOptions().WithHeader("name-test", "value")); + .InvokeAsync(new NumberRequest(4, 5), new DeliveryOptions().WithHeader("name-test", "value"), TestContext.Current.CancellationToken); result.ShouldBeSameAs(response); @@ -535,9 +523,7 @@ public async Task invoke_with_expected_response_and_delivery_options_and_filter_ theSpy.WhenInvokedMessageOf(x => x.X == 4, endpointName: "one").RespondWith(response); var result = await theContext.EndpointFor("one") - .InvokeAsync( - new NumberRequest(4, 5), - new DeliveryOptions().WithHeader("filter-name-test", "value")); + .InvokeAsync(new NumberRequest(4, 5), new DeliveryOptions().WithHeader("filter-name-test", "value"), TestContext.Current.CancellationToken); result.ShouldBeSameAs(response); } @@ -548,7 +534,7 @@ public async Task stream_records_message_and_yields_empty_sequence() var request = new NumberRequest(3, 4); var items = new List(); - await foreach (var item in theContext.StreamAsync(request)) + await foreach (var item in theContext.StreamAsync(request, TestContext.Current.CancellationToken)) { items.Add(item); } @@ -563,9 +549,7 @@ public async Task stream_with_delivery_options_records_envelope_with_header_appl var request = new NumberRequest(3, 4); var items = new List(); - await foreach (var item in theContext.StreamAsync( - request, - new DeliveryOptions().WithHeader("stream-test", "value"))) + await foreach (var item in theContext.StreamAsync(request, new DeliveryOptions().WithHeader("stream-test", "value"), TestContext.Current.CancellationToken)) { items.Add(item); } diff --git a/src/Testing/CoreTests/Tracking/when_session_is_tracked_for_published_message_without_handler.cs b/src/Testing/CoreTests/Tracking/when_session_is_tracked_for_published_message_without_handler.cs index 7c42a31ea..fafe1e28f 100644 --- a/src/Testing/CoreTests/Tracking/when_session_is_tracked_for_published_message_without_handler.cs +++ b/src/Testing/CoreTests/Tracking/when_session_is_tracked_for_published_message_without_handler.cs @@ -79,7 +79,7 @@ public async Task should_be_included_in_sent_record_collection() public async Task should_apply_equally_when_tracked_across_multiple_hosts() { using var secondHost = await Host.CreateDefaultBuilder() - .UseWolverine().StartAsync(); + .UseWolverine().StartAsync(cancellationToken: TestContext.Current.CancellationToken); var randomEventEmitter = _host.Services.GetRequiredService(); diff --git a/src/Testing/CoreTests/Transports/Sending/BatchedSenderTests.cs b/src/Testing/CoreTests/Transports/Sending/BatchedSenderTests.cs index 38c43e4da..5f6653807 100644 --- a/src/Testing/CoreTests/Transports/Sending/BatchedSenderTests.cs +++ b/src/Testing/CoreTests/Transports/Sending/BatchedSenderTests.cs @@ -106,7 +106,7 @@ public async Task flushes_partial_batch_after_configured_timeout() var sw = Stopwatch.StartNew(); await sender.SendAsync(Envelope.ForPing(TransportConstants.LocalUri)); - await flushed.Task.WaitAsync(2.Seconds()); + await flushed.Task.WaitAsync(2.Seconds(), TestContext.Current.CancellationToken); sw.Stop(); sw.Elapsed.ShouldBeGreaterThanOrEqualTo(40.Milliseconds()); diff --git a/src/Testing/CoreTests/Transports/Sending/SendingAgentDisposalTests.cs b/src/Testing/CoreTests/Transports/Sending/SendingAgentDisposalTests.cs index e56040515..9ae6a117b 100644 --- a/src/Testing/CoreTests/Transports/Sending/SendingAgentDisposalTests.cs +++ b/src/Testing/CoreTests/Transports/Sending/SendingAgentDisposalTests.cs @@ -27,9 +27,9 @@ public async Task circuit_watcher_dispose_stops_the_ping_loop() // that cancellation, so settle first before taking the baseline -- otherwise a tick that // was already running when Dispose() was called could tick over during the assertion // window below and cause a spurious failure. - await Task.Delay(200.Milliseconds()); + await Task.Delay(200.Milliseconds(), TestContext.Current.CancellationToken); var countAtDispose = circuit.CallCount; - await Task.Delay(200.Milliseconds()); + await Task.Delay(200.Milliseconds(), TestContext.Current.CancellationToken); // Before the fix, Dispose() only released the Task wrapper -- pingUntilConnectedAsync kept // running against the caller's (still live) token, so this count kept climbing forever. @@ -62,9 +62,9 @@ public async Task disposing_a_sending_agent_stops_its_circuit_watcher() // See circuit_watcher_dispose_stops_the_ping_loop above: settle before taking the baseline // so an already-in-flight ping can't tick over during the assertion window below. - await Task.Delay(200.Milliseconds()); + await Task.Delay(200.Milliseconds(), TestContext.Current.CancellationToken); var pingCountAtDispose = sender.PingCount; - await Task.Delay(200.Milliseconds()); + await Task.Delay(200.Milliseconds(), TestContext.Current.CancellationToken); // Before the fix, SendingAgent.DisposeAsync() never touched the CircuitWatcher, so a sender // pointed at a permanently unreachable destination (e.g. Kafka against a dead broker) kept diff --git a/src/Testing/CoreTests/Transports/SharedMemory/shared_memory_envelope_pooling_3015.cs b/src/Testing/CoreTests/Transports/SharedMemory/shared_memory_envelope_pooling_3015.cs index f31aecf10..8f8a96ef4 100644 --- a/src/Testing/CoreTests/Transports/SharedMemory/shared_memory_envelope_pooling_3015.cs +++ b/src/Testing/CoreTests/Transports/SharedMemory/shared_memory_envelope_pooling_3015.cs @@ -28,7 +28,7 @@ public async Task shared_memory_handoff_copies_pooled_envelope_before_sender_rec opts.Discovery.DisableConventionalDiscovery(); opts.PublishAllMessages().ToSharedMemoryTopic(topicName); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.Services.GetRequiredService() .ShouldBeOfType(); @@ -145,7 +145,7 @@ await waitFor(receivers[1].Entered, "the second Shared Memory receiver to retain await diagnosticAgent.DisposeAsync(); foreach (var subscription in subscriptions) await subscription.StopAsync(); - await host.StopAsync(); + await host.StopAsync(TestContext.Current.CancellationToken); await SharedMemoryQueueManager.ClearAllAsync(); } } diff --git a/src/Testing/CoreTests/Transports/background_receive_loop_3236.cs b/src/Testing/CoreTests/Transports/background_receive_loop_3236.cs index 029d6b646..17f051a24 100644 --- a/src/Testing/CoreTests/Transports/background_receive_loop_3236.cs +++ b/src/Testing/CoreTests/Transports/background_receive_loop_3236.cs @@ -86,13 +86,13 @@ public async Task a_hung_iteration_freezes_the_heartbeat() }); theLoop.Start(); - await entered.Task.WaitAsync(5.Seconds()); // heartbeat was bumped before the iteration call + await entered.Task.WaitAsync(5.Seconds(), TestContext.Current.CancellationToken); // heartbeat was bumped before the iteration call var frozen = theLoop.LastReceiveLoopActivityAt; frozen.ShouldNotBeNull(); // While the iteration is hung, the heartbeat stops advancing — this is exactly the "Accepting but not // consuming" signal an external monitor reads. - await Task.Delay(100); + await Task.Delay(100, TestContext.Current.CancellationToken); theLoop.LastReceiveLoopActivityAt.ShouldBe(frozen); // Cancellation unblocks the hung Task.Delay; the loop observes the OCE and stops cleanly. @@ -104,7 +104,7 @@ public async Task stop_async_cancels_and_marks_stopped() { var theLoop = loop(_ => Task.FromResult(false)); theLoop.Start(); - await Task.Delay(30); + await Task.Delay(30, TestContext.Current.CancellationToken); await theLoop.StopAsync(2.Seconds()); @@ -130,7 +130,7 @@ public async Task stop_async_returns_within_budget_when_iteration_ignores_cancel }); theLoop.Start(); - await entered.Task.WaitAsync(5.Seconds()); + await entered.Task.WaitAsync(5.Seconds(), TestContext.Current.CancellationToken); var stopwatch = Stopwatch.StartNew(); await theLoop.StopAsync(200.Milliseconds()); diff --git a/src/Testing/CoreTests/WolverineOptionsTests.cs b/src/Testing/CoreTests/WolverineOptionsTests.cs index d5db93103..b41d38e5c 100644 --- a/src/Testing/CoreTests/WolverineOptionsTests.cs +++ b/src/Testing/CoreTests/WolverineOptionsTests.cs @@ -129,7 +129,7 @@ public async Task durable_local_queue_is_indeed_durable() { using var runtime = await Host.CreateDefaultBuilder() .UseWolverine() - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); runtime.Services.GetRequiredService() .Endpoints.EndpointFor(TransportConstants.DurableLocalUri)! diff --git a/src/Testing/CoreTests/critterstack_defaults_usage.cs b/src/Testing/CoreTests/critterstack_defaults_usage.cs index 591c19ea5..f211fb103 100644 --- a/src/Testing/CoreTests/critterstack_defaults_usage.cs +++ b/src/Testing/CoreTests/critterstack_defaults_usage.cs @@ -24,7 +24,7 @@ public async Task running_in_development_mode() }); }) .UseEnvironment("Development") - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var options = host.Services.GetRequiredService(); @@ -49,7 +49,7 @@ public async Task set_the_application_assembly() }); }) .UseEnvironment("Development") - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); host.GetRuntime().Options.ApplicationAssembly.ShouldBe(typeof(IInterfaceMessage).Assembly); } @@ -63,7 +63,7 @@ public async Task use_the_default_application_assembly() }) .UseEnvironment("Development") - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); host.GetRuntime().Options.ApplicationAssembly.ShouldBe(GetType().Assembly); } @@ -82,7 +82,7 @@ public async Task running_in_production_mode_1() }); }) .UseEnvironment("Production") - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var options = host.Services.GetRequiredService(); @@ -105,7 +105,7 @@ public async Task running_in_production_mode_2() }); }) .UseEnvironment("Production") - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var options = host.Services.GetRequiredService(); diff --git a/src/Testing/CoreTests/envelope_id_generation.cs b/src/Testing/CoreTests/envelope_id_generation.cs index 22dafcf09..348f5a8ca 100644 --- a/src/Testing/CoreTests/envelope_id_generation.cs +++ b/src/Testing/CoreTests/envelope_id_generation.cs @@ -70,13 +70,16 @@ public async Task guid_v7_ids_are_unique_across_threads() // Simulate the scenario from the bug report: multiple threads generating IDs for (var t = 0; t < 10; t++) { + // xUnit's own fixer declines this shape (it cannot tell which Task.Run overload to bind), + // so the token is threaded by hand. It only governs scheduling here -- the loop below has + // nothing to cancel. tasks.Add(Task.Run(() => { for (var i = 0; i < 1000; i++) { ids.Add(new Envelope().Id); } - })); + }, TestContext.Current.CancellationToken)); } await Task.WhenAll(tasks); @@ -92,7 +95,7 @@ public async Task invoke_async_works_with_guid_v7() .UseWolverine(opts => { opts.EnvelopeIdGeneration = EnvelopeIdGeneration.GuidV7; - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var tracked = await host.InvokeMessageAndWaitAsync(new GuidV7TestMessage("hello")); diff --git a/src/Testing/CoreTests/respecting_jasper_fx_defaults.cs b/src/Testing/CoreTests/respecting_jasper_fx_defaults.cs index 5bbc7237f..cc8e5d082 100644 --- a/src/Testing/CoreTests/respecting_jasper_fx_defaults.cs +++ b/src/Testing/CoreTests/respecting_jasper_fx_defaults.cs @@ -14,7 +14,7 @@ public async Task use_defaults() using var host = await Host.CreateDefaultBuilder() .UseWolverine() .UseEnvironment("Development") - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.GetRuntime(); runtime.Options.CodeGeneration.TypeLoadMode.ShouldBe(TypeLoadMode.Dynamic); @@ -38,7 +38,7 @@ public async Task use_jasper_fx_defaults() }); }) .UseEnvironment("Development") - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.GetRuntime(); diff --git a/src/Testing/MessageRoutingTests/MessageRoutingTests.csproj b/src/Testing/MessageRoutingTests/MessageRoutingTests.csproj index 98194edb2..5a491df4c 100644 --- a/src/Testing/MessageRoutingTests/MessageRoutingTests.csproj +++ b/src/Testing/MessageRoutingTests/MessageRoutingTests.csproj @@ -1,6 +1,8 @@ + + true Exe enable false diff --git a/src/Testing/MetricsTests/MetricsTests.csproj b/src/Testing/MetricsTests/MetricsTests.csproj index 63e948479..6699085b2 100644 --- a/src/Testing/MetricsTests/MetricsTests.csproj +++ b/src/Testing/MetricsTests/MetricsTests.csproj @@ -1,6 +1,8 @@ + + true Exe net9.0 enable diff --git a/src/Testing/PolicyTests/PolicyTests.csproj b/src/Testing/PolicyTests/PolicyTests.csproj index 46bfd72f3..606d92943 100644 --- a/src/Testing/PolicyTests/PolicyTests.csproj +++ b/src/Testing/PolicyTests/PolicyTests.csproj @@ -1,6 +1,8 @@ + + true Exe false diff --git a/src/Testing/SlowTests/Bug_2580_tenant_partitioning_with_inferred_grouping.cs b/src/Testing/SlowTests/Bug_2580_tenant_partitioning_with_inferred_grouping.cs index f6c01aa3a..96a140f3f 100644 --- a/src/Testing/SlowTests/Bug_2580_tenant_partitioning_with_inferred_grouping.cs +++ b/src/Testing/SlowTests/Bug_2580_tenant_partitioning_with_inferred_grouping.cs @@ -54,7 +54,7 @@ public async Task issue_2580_same_tenant_messages_should_not_run_in_parallel_whe topology.MaxDegreeOfParallelism = PartitionSlots.Three; topology.ConfigureQueues(x => x.BufferedInMemory()); }); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var store = host.Services.GetRequiredService(); await using (var session = store.LightweightSession()) @@ -64,7 +64,7 @@ public async Task issue_2580_same_tenant_messages_should_not_run_in_parallel_whe session.Events.StartStream(aggregateId, new TenantPartitioningStarted()); } - await session.SaveChangesAsync(); + await session.SaveChangesAsync(TestContext.Current.CancellationToken); } var bus = host.Services.GetRequiredService(); diff --git a/src/Testing/SlowTests/Bug_concurrency_with_global_partitioning.cs b/src/Testing/SlowTests/Bug_concurrency_with_global_partitioning.cs index e66e660e0..098830a7c 100644 --- a/src/Testing/SlowTests/Bug_concurrency_with_global_partitioning.cs +++ b/src/Testing/SlowTests/Bug_concurrency_with_global_partitioning.cs @@ -87,10 +87,10 @@ public async Task should_not_have_concurrency_exceptions_with_global_partitionin // Clean up the soccer schema from previous test runs to avoid stale durable messages await using (var conn = new Npgsql.NpgsqlConnection(Servers.PostgresConnectionString)) { - await conn.OpenAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); await using var cmd = conn.CreateCommand(); cmd.CommandText = "DROP SCHEMA IF EXISTS soccer CASCADE;"; - await cmd.ExecuteNonQueryAsync(); + await cmd.ExecuteNonQueryAsync(TestContext.Current.CancellationToken); } var tracker = new ExceptionTracker(); @@ -98,14 +98,14 @@ public async Task should_not_have_concurrency_exceptions_with_global_partitionin // Stand up 3 SampleService hosts to simulate a multi-node cluster. // Start the first host alone so it creates the Marten schema without DDL races. - using var sampleService1 = await BuildSampleServiceHost("SampleService1", tracker, destinationTracker).StartAsync(); - using var sampleService2 = await BuildSampleServiceHost("SampleService2", tracker, destinationTracker).StartAsync(); - using var sampleService3 = await BuildSampleServiceHost("SampleService3", tracker, destinationTracker).StartAsync(); + using var sampleService1 = await BuildSampleServiceHost("SampleService1", tracker, destinationTracker).StartAsync(cancellationToken: TestContext.Current.CancellationToken); + using var sampleService2 = await BuildSampleServiceHost("SampleService2", tracker, destinationTracker).StartAsync(cancellationToken: TestContext.Current.CancellationToken); + using var sampleService3 = await BuildSampleServiceHost("SampleService3", tracker, destinationTracker).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var hosts = new[] { sampleService1, sampleService2, sampleService3 }; // Allow Kafka consumer group rebalancing to stabilize before sending messages - await Task.Delay(15.Seconds()); + await Task.Delay(15.Seconds(), TestContext.Current.CancellationToken); using var cts = new CancellationTokenSource(30.Seconds()); cts.CancelAfter(30.Seconds()); @@ -160,7 +160,7 @@ await bus.PublishAsync(new SoccerEventTypeTwo await Task.WhenAll(tasks); // Give time for in-flight messages to finish processing - await Task.Delay(10.Seconds()); + await Task.Delay(10.Seconds(), TestContext.Current.CancellationToken); // === Duplicate Envelope.Id analysis === Console.WriteLine("=== Duplicate Envelope.Id analysis ==="); diff --git a/src/Testing/SlowTests/RetryBlockTests.cs b/src/Testing/SlowTests/RetryBlockTests.cs index bfbf24cc7..eec0b30f9 100644 --- a/src/Testing/SlowTests/RetryBlockTests.cs +++ b/src/Testing/SlowTests/RetryBlockTests.cs @@ -68,7 +68,7 @@ public async Task disregard_after_too_many_failures() while (tries < 10 && !theLogger.Messages[LogLevel.Information].Any()) { tries++; - await Task.Delay(100.Milliseconds()); + await Task.Delay(100.Milliseconds(), TestContext.Current.CancellationToken); } theLogger.Messages[LogLevel.Information].Single() diff --git a/src/Testing/SlowTests/SharedMemory/inner_envelope_is_stamped_before_serialization.cs b/src/Testing/SlowTests/SharedMemory/inner_envelope_is_stamped_before_serialization.cs index 15f1ed254..09b671fff 100644 --- a/src/Testing/SlowTests/SharedMemory/inner_envelope_is_stamped_before_serialization.cs +++ b/src/Testing/SlowTests/SharedMemory/inner_envelope_is_stamped_before_serialization.cs @@ -52,7 +52,7 @@ public async Task scheduled_send_to_non_native_transport_preserves_context_field bus.PublishAsync(new Message1(), new DeliveryOptions { ScheduleDelay = 1.Minutes() }).AsTask()); await tracked.PlayScheduledMessagesAsync(2.Hours()); - await Task.Delay(2.Minutes()); + await Task.Delay(2.Minutes(), TestContext.Current.CancellationToken); var captured = await ScheduledEnvelopeCapture.WaitAsync(5.Seconds()); captured.TenantId.ShouldBe("red"); diff --git a/src/Testing/SlowTests/SlowTests.csproj b/src/Testing/SlowTests/SlowTests.csproj index 30160e90f..d62c878e5 100644 --- a/src/Testing/SlowTests/SlowTests.csproj +++ b/src/Testing/SlowTests/SlowTests.csproj @@ -1,5 +1,10 @@ + + + true + + diff --git a/src/Testing/SlowTests/delayed_message_end_to_end.cs b/src/Testing/SlowTests/delayed_message_end_to_end.cs index 8c927574d..89de8e0e5 100644 --- a/src/Testing/SlowTests/delayed_message_end_to_end.cs +++ b/src/Testing/SlowTests/delayed_message_end_to_end.cs @@ -13,7 +13,7 @@ public class delayed_message_end_to_end public async Task receive_timeout_message() { using var host = await Host.CreateDefaultBuilder() - .UseWolverine().StartAsync(); + .UseWolverine().StartAsync(cancellationToken: TestContext.Current.CancellationToken); var message = new KickOffMessage(23); diff --git a/src/Testing/SlowTests/dropped_messages_on_full_local_queue.cs b/src/Testing/SlowTests/dropped_messages_on_full_local_queue.cs index 0853123fe..35a66efed 100644 --- a/src/Testing/SlowTests/dropped_messages_on_full_local_queue.cs +++ b/src/Testing/SlowTests/dropped_messages_on_full_local_queue.cs @@ -49,7 +49,7 @@ public async Task all_cascaded_messages_reach_the_second_handler(int maxParallel opts.Policies.DisableConventionalLocalRouting(); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var bus = host.MessageBus(); await bus.PublishAsync(new StartPipeline()); diff --git a/src/Testing/SlowTests/in_memory_scheduled_messages.cs b/src/Testing/SlowTests/in_memory_scheduled_messages.cs index 91382d8ff..1321447da 100644 --- a/src/Testing/SlowTests/in_memory_scheduled_messages.cs +++ b/src/Testing/SlowTests/in_memory_scheduled_messages.cs @@ -79,7 +79,7 @@ public async Task empty_all() queue.Sent.ShouldBeEmpty(); - await Task.Delay(2000.Milliseconds()); + await Task.Delay(2000.Milliseconds(), TestContext.Current.CancellationToken); queue.Sent.ShouldBeEmpty(); } diff --git a/src/Testing/SlowTests/intrinsic_serialization_end_to_end.cs b/src/Testing/SlowTests/intrinsic_serialization_end_to_end.cs index c9261b385..0f3327e00 100644 --- a/src/Testing/SlowTests/intrinsic_serialization_end_to_end.cs +++ b/src/Testing/SlowTests/intrinsic_serialization_end_to_end.cs @@ -21,13 +21,13 @@ public async Task send_message_between_nodes() .UseWolverine(opts => { opts.PublishAllMessages().ToPort(port); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var receiver = await Host.CreateDefaultBuilder() .UseWolverine(opts => { opts.ListenAtPort(port); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var tracked = await sender.TrackActivity() .AlsoTrack(receiver) diff --git a/src/Testing/SlowTests/invoke_async_with_delivery_options.cs b/src/Testing/SlowTests/invoke_async_with_delivery_options.cs index 275767cd5..5ffc38370 100644 --- a/src/Testing/SlowTests/invoke_async_with_delivery_options.cs +++ b/src/Testing/SlowTests/invoke_async_with_delivery_options.cs @@ -48,17 +48,15 @@ public async ValueTask DisposeAsync() public async Task invoke_locally() { var bus = _receiver.MessageBus(); - await bus.InvokeAsync(new WithHeaders(), - new DeliveryOptions { TenantId = "millers" }.WithHeader("name", "Chewie") - .WithHeader("breed", "indeterminate")); + await bus.InvokeAsync(new WithHeaders(), new DeliveryOptions { TenantId = "millers" }.WithHeader("name", "Chewie") + .WithHeader("breed", "indeterminate"), TestContext.Current.CancellationToken); } [Fact] public async Task invoke_with_expected_outcome_locally() { var bus = _receiver.MessageBus(); - var answer = await bus.InvokeAsync(new DoMath(3, 4, "blue", "tom"), - new DeliveryOptions { TenantId = "blue" }.WithHeader("user-id", "tom")); + var answer = await bus.InvokeAsync(new DoMath(3, 4, "blue", "tom"), new DeliveryOptions { TenantId = "blue" }.WithHeader("user-id", "tom"), TestContext.Current.CancellationToken); answer.Sum.ShouldBe(7); } diff --git a/src/Testing/SlowTests/tracked_session_mechanics.cs b/src/Testing/SlowTests/tracked_session_mechanics.cs index 6ed6c4abc..901054559 100644 --- a/src/Testing/SlowTests/tracked_session_mechanics.cs +++ b/src/Testing/SlowTests/tracked_session_mechanics.cs @@ -27,13 +27,13 @@ public async Task failure_acks_show_up_in_tracked_session() opts.Discovery.DisableConventionalDiscovery(); opts.PublishAllMessages().ToPort(port2); opts.ListenAtPort(port1); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); using var receiver = await Host.CreateDefaultBuilder() .UseWolverine(opts => { opts.ListenAtPort(port2); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); await Should.ThrowAsync(async () => { @@ -51,7 +51,7 @@ public async Task deal_with_in_memory_scheduled_message() .UseWolverine(opts => { - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); // Should finish cleanly var tracked = await host.SendMessageAndWaitAsync(new TriggerScheduledMessage("Chiefs")); @@ -75,7 +75,7 @@ public async Task deal_with_locally_scheduled_execution() { opts.PersistMessagesWithPostgresql(Servers.PostgresConnectionString, "wolverine"); opts.Policies.UseDurableInboxOnAllListeners(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); // Should finish cleanly var tracked = await host.SendMessageAndWaitAsync(new TriggerScheduledMessage("Chiefs")); @@ -103,13 +103,13 @@ public async Task handle_scheduled_delivery_to_external_transport() { opts.PublishMessage().ToPort(port2); opts.ListenAtPort(port1); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); using var receiver = await Host.CreateDefaultBuilder() .UseWolverine(opts => { opts.ListenAtPort(port2); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); // Should finish cleanly var tracked = await sender diff --git a/src/Testing/Wolverine.Behavioural.FSharpTests/BehaviouralRunStep.cs b/src/Testing/Wolverine.Behavioural.FSharpTests/BehaviouralRunStep.cs index b4da19da5..aa9ca4ace 100644 --- a/src/Testing/Wolverine.Behavioural.FSharpTests/BehaviouralRunStep.cs +++ b/src/Testing/Wolverine.Behavioural.FSharpTests/BehaviouralRunStep.cs @@ -46,11 +46,11 @@ public async Task generated_fsharp_handler_runs_under_static_load() opts.ApplicationAssembly = appAssembly; opts.CodeGeneration.TypeLoadMode = TypeLoadMode.Static; }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); // The pre-generated F# MessageHandler is loaded by name and executed — no runtime compilation. var bus = host.MessageBus(); - await bus.InvokeAsync(new BehaviouralPing(42)); + await bus.InvokeAsync(new BehaviouralPing(42), TestContext.Current.CancellationToken); // end-snippet using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(10)); diff --git a/src/Testing/Wolverine.Behavioural.FSharpTests/CodegenWriteFSharpCli.cs b/src/Testing/Wolverine.Behavioural.FSharpTests/CodegenWriteFSharpCli.cs index ca05e5a60..6cac915ee 100644 --- a/src/Testing/Wolverine.Behavioural.FSharpTests/CodegenWriteFSharpCli.cs +++ b/src/Testing/Wolverine.Behavioural.FSharpTests/CodegenWriteFSharpCli.cs @@ -63,15 +63,15 @@ public async Task codegen_write_fsharp_generates_runnable_fsharp_for_a_wolverine // behavioural run-step compiles + executes under TypeLoadMode.Static. var adapterFile = generatedFiles.Single(f => Path.GetFileName(f).StartsWith("BehaviouralPingHandler", StringComparison.Ordinal)); - var generatedAdapter = Normalize(await File.ReadAllTextAsync(adapterFile)); - var committedAdapter = Normalize(await File.ReadAllTextAsync(BehaviouralCodegen.GeneratedFilePath())); + var generatedAdapter = Normalize(await File.ReadAllTextAsync(adapterFile, TestContext.Current.CancellationToken)); + var committedAdapter = Normalize(await File.ReadAllTextAsync(BehaviouralCodegen.GeneratedFilePath(), TestContext.Current.CancellationToken)); generatedAdapter.ShouldBe(committedAdapter); // The static HandlerRegistry was also emitted as valid F# (the Type[] accessors as F# // array literals) — this is what previously threw NotSupportedException. var registryFile = generatedFiles.Single(f => Path.GetFileName(f) == "GeneratedHandlerRegistry.fs"); - var registry = await File.ReadAllTextAsync(registryFile); + var registry = await File.ReadAllTextAsync(registryFile, TestContext.Current.CancellationToken); registry.ShouldContain("inherit Wolverine.Runtime.Handlers.HandlerRegistry()"); registry.ShouldContain("typeof"); } diff --git a/src/Testing/Wolverine.Behavioural.FSharpTests/Wolverine.Behavioural.FSharpTests.csproj b/src/Testing/Wolverine.Behavioural.FSharpTests/Wolverine.Behavioural.FSharpTests.csproj index 5370ca8a2..e159b4478 100644 --- a/src/Testing/Wolverine.Behavioural.FSharpTests/Wolverine.Behavioural.FSharpTests.csproj +++ b/src/Testing/Wolverine.Behavioural.FSharpTests/Wolverine.Behavioural.FSharpTests.csproj @@ -9,6 +9,8 @@ --> + + true Exe net9.0 false diff --git a/src/Testing/Wolverine.ComplianceTests/Wolverine.ComplianceTests.csproj b/src/Testing/Wolverine.ComplianceTests/Wolverine.ComplianceTests.csproj index 6382e9d4a..9a9281f5f 100644 --- a/src/Testing/Wolverine.ComplianceTests/Wolverine.ComplianceTests.csproj +++ b/src/Testing/Wolverine.ComplianceTests/Wolverine.ComplianceTests.csproj @@ -1,6 +1,8 @@ + + true Compliance test harnesses for adding persistence and transport options to Wolverine WolverineFx.ComplianceTests + + true Exe net9.0 false diff --git a/src/Testing/Wolverine.Cosmos.FSharpTests/Wolverine.Cosmos.FSharpTests.csproj b/src/Testing/Wolverine.Cosmos.FSharpTests/Wolverine.Cosmos.FSharpTests.csproj index 508364634..e5083f13e 100644 --- a/src/Testing/Wolverine.Cosmos.FSharpTests/Wolverine.Cosmos.FSharpTests.csproj +++ b/src/Testing/Wolverine.Cosmos.FSharpTests/Wolverine.Cosmos.FSharpTests.csproj @@ -9,6 +9,8 @@ --> + + true Exe net9.0 false diff --git a/src/Testing/Wolverine.EfCore.FSharpTests/Wolverine.EfCore.FSharpTests.csproj b/src/Testing/Wolverine.EfCore.FSharpTests/Wolverine.EfCore.FSharpTests.csproj index 608cf43db..7dd813d93 100644 --- a/src/Testing/Wolverine.EfCore.FSharpTests/Wolverine.EfCore.FSharpTests.csproj +++ b/src/Testing/Wolverine.EfCore.FSharpTests/Wolverine.EfCore.FSharpTests.csproj @@ -8,6 +8,8 @@ --> + + true Exe net9.0 false diff --git a/src/Testing/Wolverine.Http.FSharpTests/Wolverine.Http.FSharpTests.csproj b/src/Testing/Wolverine.Http.FSharpTests/Wolverine.Http.FSharpTests.csproj index e45ce98f1..64662da86 100644 --- a/src/Testing/Wolverine.Http.FSharpTests/Wolverine.Http.FSharpTests.csproj +++ b/src/Testing/Wolverine.Http.FSharpTests/Wolverine.Http.FSharpTests.csproj @@ -8,6 +8,8 @@ --> + + true Exe net9.0 false diff --git a/src/Testing/Wolverine.Marten.FSharpTests/Wolverine.Marten.FSharpTests.csproj b/src/Testing/Wolverine.Marten.FSharpTests/Wolverine.Marten.FSharpTests.csproj index 1e0e6e109..6d5eeeb43 100644 --- a/src/Testing/Wolverine.Marten.FSharpTests/Wolverine.Marten.FSharpTests.csproj +++ b/src/Testing/Wolverine.Marten.FSharpTests/Wolverine.Marten.FSharpTests.csproj @@ -8,6 +8,8 @@ --> + + true Exe net9.0 false diff --git a/src/Testing/Wolverine.MartenAggregate.FSharpTests/Wolverine.MartenAggregate.FSharpTests.csproj b/src/Testing/Wolverine.MartenAggregate.FSharpTests/Wolverine.MartenAggregate.FSharpTests.csproj index 722ac0287..e5083d990 100644 --- a/src/Testing/Wolverine.MartenAggregate.FSharpTests/Wolverine.MartenAggregate.FSharpTests.csproj +++ b/src/Testing/Wolverine.MartenAggregate.FSharpTests/Wolverine.MartenAggregate.FSharpTests.csproj @@ -8,6 +8,8 @@ --> + + true Exe net9.0 false diff --git a/src/Transports/AWS/Wolverine.AmazonSns.Tests/Internal/AmazonSnsTopicTests.cs b/src/Transports/AWS/Wolverine.AmazonSns.Tests/Internal/AmazonSnsTopicTests.cs index 698b0c4d2..85379929f 100644 --- a/src/Transports/AWS/Wolverine.AmazonSns.Tests/Internal/AmazonSnsTopicTests.cs +++ b/src/Transports/AWS/Wolverine.AmazonSns.Tests/Internal/AmazonSnsTopicTests.cs @@ -62,7 +62,7 @@ public async Task do_not_create_if_parent_is_not_auto_provision() theTopic.TopicArn.ShouldBe(theSnsTopicArn); - await theSnsClient.DidNotReceiveWithAnyArgs().CreateTopicAsync(theTopic.TopicName); + await theSnsClient.DidNotReceiveWithAnyArgs().CreateTopicAsync(theTopic.TopicName, Arg.Any()); } [Fact] @@ -72,8 +72,7 @@ public async Task do_create_topic_if_parent_is_auto_provision() const string theSnsTopicArn = "arn:aws:sns:us-east-2:123456789012:TheTopic"; - theSnsClient.CreateTopicAsync(Arg.Any()) - .Returns(new CreateTopicResponse + theSnsClient.CreateTopicAsync(Arg.Any(), TestContext.Current.CancellationToken).Returns(new CreateTopicResponse { TopicArn = theSnsTopicArn }); diff --git a/src/Transports/AWS/Wolverine.AmazonSns.Tests/Wolverine.AmazonSns.Tests.csproj b/src/Transports/AWS/Wolverine.AmazonSns.Tests/Wolverine.AmazonSns.Tests.csproj index 62bb09b57..1af4433be 100644 --- a/src/Transports/AWS/Wolverine.AmazonSns.Tests/Wolverine.AmazonSns.Tests.csproj +++ b/src/Transports/AWS/Wolverine.AmazonSns.Tests/Wolverine.AmazonSns.Tests.csproj @@ -1,6 +1,8 @@ + + true Exe false diff --git a/src/Transports/AWS/Wolverine.AmazonSns.Tests/bootstrapping.cs b/src/Transports/AWS/Wolverine.AmazonSns.Tests/bootstrapping.cs index 152d38170..f3cd55f7b 100644 --- a/src/Transports/AWS/Wolverine.AmazonSns.Tests/bootstrapping.cs +++ b/src/Transports/AWS/Wolverine.AmazonSns.Tests/bootstrapping.cs @@ -11,13 +11,13 @@ public class Bootstrapping public async Task create_an_open_client() { using var host = await Host.CreateDefaultBuilder() - .UseWolverine(opts => { opts.UseAmazonSnsTransportLocally(); }).StartAsync(); + .UseWolverine(opts => { opts.UseAmazonSnsTransportLocally(); }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var options = host.Services.GetRequiredService(); var transport = options.AmazonSnsTransport(); // Just a smoke test on configuration here - var topicNames = await transport.SnsClient!.ListTopicsAsync("0"); + var topicNames = await transport.SnsClient!.ListTopicsAsync("0", TestContext.Current.CancellationToken); } [Fact] @@ -31,7 +31,7 @@ public async Task create_new_topic_on_startup() opts.UseAmazonSnsTransportLocally().AutoProvision(); opts.PublishMessage().ToSnsTopic(topicName); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var options = host.Services.GetRequiredService(); var transport = options.AmazonSnsTransport(); @@ -41,7 +41,7 @@ public async Task create_new_topic_on_startup() topic.ShouldNotBeNull(); topic.TopicArn.ShouldNotBeNull(); - await transport.SnsClient.DeleteTopicAsync(topic.TopicArn); + await transport.SnsClient.DeleteTopicAsync(topic.TopicArn, TestContext.Current.CancellationToken); } [Fact] @@ -56,7 +56,7 @@ public async Task auto_purge_topic_on_startup_smoke_test() opts.UseAmazonSnsTransportLocally().AutoPurgeOnStartup().AutoProvision(); opts.PublishMessage().ToSnsTopic(topicName); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var options = host.Services.GetRequiredService(); var transport = options.AmazonSnsTransport(); @@ -65,6 +65,6 @@ public async Task auto_purge_topic_on_startup_smoke_test() topic.ShouldNotBeNull(); topic.TopicArn.ShouldNotBeNull(); - await transport.SnsClient.DeleteTopicAsync(topic.TopicArn); + await transport.SnsClient.DeleteTopicAsync(topic.TopicArn, TestContext.Current.CancellationToken); } } diff --git a/src/Transports/AWS/Wolverine.AmazonSns.Tests/end_to_end_with_named_broker.cs b/src/Transports/AWS/Wolverine.AmazonSns.Tests/end_to_end_with_named_broker.cs index c4e9e03a4..77b11a1e0 100644 --- a/src/Transports/AWS/Wolverine.AmazonSns.Tests/end_to_end_with_named_broker.cs +++ b/src/Transports/AWS/Wolverine.AmazonSns.Tests/end_to_end_with_named_broker.cs @@ -76,7 +76,7 @@ public async Task publish_to_named_sns_topic_and_receive_via_named_sqs_subscript opts.PublishMessage() .ToSnsTopicOnNamedBroker(theName, topic) .SubscribeSqsQueue(queue); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); await host.MessageBus().PublishAsync(new NamedBrokerMessage("blue")); diff --git a/src/Transports/AWS/Wolverine.AmazonSqs.Tests/AmazonSqsPerTenantConnectionTests.cs b/src/Transports/AWS/Wolverine.AmazonSqs.Tests/AmazonSqsPerTenantConnectionTests.cs index c2b184e96..693e700d6 100644 --- a/src/Transports/AWS/Wolverine.AmazonSqs.Tests/AmazonSqsPerTenantConnectionTests.cs +++ b/src/Transports/AWS/Wolverine.AmazonSqs.Tests/AmazonSqsPerTenantConnectionTests.cs @@ -85,7 +85,7 @@ public async Task tenant_message_is_consumed_and_stamped_with_the_tenant_id() opts.PublishMessage().ToSqsQueue(queue).SendInline(); opts.ListenToSqsQueue(queue); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); // The default listener polls the shared region and the tenant listener polls the tenant region; the message // only exists in the tenant region, so only the tenant listener consumes it and stamps the tenant id. @@ -132,7 +132,7 @@ public async Task per_tenant_queues_are_provisioned_on_the_tenant_region() // AutoProvision + ConnectAsync must have created the shared topology queue on the tenant's own region. using var tenantClient = rawClient(TenantRegion); - var url = await tenantClient.GetQueueUrlAsync(queue); + var url = await tenantClient.GetQueueUrlAsync(queue, TestContext.Current.CancellationToken); url.QueueUrl.ShouldNotBeNull(); url.QueueUrl.ShouldContain(TenantRegion); } diff --git a/src/Transports/AWS/Wolverine.AmazonSqs.Tests/BufferedSendingAndReceivingCompliance.cs b/src/Transports/AWS/Wolverine.AmazonSqs.Tests/BufferedSendingAndReceivingCompliance.cs index c8214d366..be7c0f215 100644 --- a/src/Transports/AWS/Wolverine.AmazonSqs.Tests/BufferedSendingAndReceivingCompliance.cs +++ b/src/Transports/AWS/Wolverine.AmazonSqs.Tests/BufferedSendingAndReceivingCompliance.cs @@ -60,7 +60,7 @@ public virtual async Task dlq_mechanics() var transport = runtime.Options.Transports.GetOrCreate(); var queue = transport.Queues[AmazonSqsTransport.DeadLetterQueueName]; await queue.InitializeAsync(NullLogger.Instance); - var messages = await transport.Client!.ReceiveMessageAsync(queue.QueueUrl); + var messages = await transport.Client!.ReceiveMessageAsync(queue.QueueUrl, TestContext.Current.CancellationToken); messages.Messages.Count.ShouldBeGreaterThan(0); } } \ No newline at end of file diff --git a/src/Transports/AWS/Wolverine.AmazonSqs.Tests/Bugs/disabling_dead_letter_queue.cs b/src/Transports/AWS/Wolverine.AmazonSqs.Tests/Bugs/disabling_dead_letter_queue.cs index f8f977ea5..18ab8de6d 100644 --- a/src/Transports/AWS/Wolverine.AmazonSqs.Tests/Bugs/disabling_dead_letter_queue.cs +++ b/src/Transports/AWS/Wolverine.AmazonSqs.Tests/Bugs/disabling_dead_letter_queue.cs @@ -24,7 +24,7 @@ public async Task do_not_create_dead_letter_queue() .AutoProvision(); opts.ListenToSqsQueue("incoming"); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); #endregion @@ -50,7 +50,7 @@ public async Task do_not_use_default_dlq_when_all_listener_dlqs_are_configured() opts.ListenToSqsQueue("product-shipped") .ConfigureDeadLetterQueue("product-shipped-error"); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var transport = host.Services.GetRequiredService().As() .Options.Transports.GetOrCreate(); @@ -72,7 +72,7 @@ public async Task no_seriously_do_not_create_dlq() options.ListenToSqsQueue("product-created") .ConfigureDeadLetterQueue("product-created-error"); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var transport = host.Services.GetRequiredService().As() .Options.Transports.GetOrCreate(); diff --git a/src/Transports/AWS/Wolverine.AmazonSqs.Tests/DurableSendingAndReceivingCompliance.cs b/src/Transports/AWS/Wolverine.AmazonSqs.Tests/DurableSendingAndReceivingCompliance.cs index d2959e867..4c9ce1f14 100644 --- a/src/Transports/AWS/Wolverine.AmazonSqs.Tests/DurableSendingAndReceivingCompliance.cs +++ b/src/Transports/AWS/Wolverine.AmazonSqs.Tests/DurableSendingAndReceivingCompliance.cs @@ -88,7 +88,7 @@ public virtual async Task dlq_mechanics() var transport = runtime.Options.Transports.GetOrCreate(); var queue = transport.Queues[AmazonSqsTransport.DeadLetterQueueName]; await queue.InitializeAsync(NullLogger.Instance); - var messages = await transport.Client!.ReceiveMessageAsync(queue.QueueUrl); + var messages = await transport.Client!.ReceiveMessageAsync(queue.QueueUrl, TestContext.Current.CancellationToken); messages.Messages.Count.ShouldBeGreaterThan(0); } } diff --git a/src/Transports/AWS/Wolverine.AmazonSqs.Tests/InlineSendingAndReceivingCompliance.cs b/src/Transports/AWS/Wolverine.AmazonSqs.Tests/InlineSendingAndReceivingCompliance.cs index e7e2ad4bc..989ad323e 100644 --- a/src/Transports/AWS/Wolverine.AmazonSqs.Tests/InlineSendingAndReceivingCompliance.cs +++ b/src/Transports/AWS/Wolverine.AmazonSqs.Tests/InlineSendingAndReceivingCompliance.cs @@ -66,7 +66,7 @@ public virtual async Task dlq_mechanics() var transport = runtime.Options.Transports.GetOrCreate(); var queue = transport.Queues[AmazonSqsTransport.DeadLetterQueueName]; await queue.InitializeAsync(NullLogger.Instance); - var messages = await transport.Client!.ReceiveMessageAsync(queue.QueueUrl); + var messages = await transport.Client!.ReceiveMessageAsync(queue.QueueUrl, TestContext.Current.CancellationToken); messages.Messages.Count.ShouldBeGreaterThan(0); } } \ No newline at end of file diff --git a/src/Transports/AWS/Wolverine.AmazonSqs.Tests/Internal/AmazonSqsQueueTests.cs b/src/Transports/AWS/Wolverine.AmazonSqs.Tests/Internal/AmazonSqsQueueTests.cs index 0198daa9e..267e6a791 100644 --- a/src/Transports/AWS/Wolverine.AmazonSqs.Tests/Internal/AmazonSqsQueueTests.cs +++ b/src/Transports/AWS/Wolverine.AmazonSqs.Tests/Internal/AmazonSqsQueueTests.cs @@ -132,7 +132,7 @@ public async Task do_not_create_if_parent_is_not_auto_provision() var theSqsQueueUrl = "https://someserver.com/foo"; - theClient.GetQueueUrlAsync(theQueue.QueueName).Returns(new GetQueueUrlResponse + theClient.GetQueueUrlAsync(theQueue.QueueName, TestContext.Current.CancellationToken).Returns(new GetQueueUrlResponse { QueueUrl = theSqsQueueUrl }); @@ -141,7 +141,7 @@ public async Task do_not_create_if_parent_is_not_auto_provision() theQueue.QueueUrl.ShouldBe(theSqsQueueUrl); - await theClient.DidNotReceiveWithAnyArgs().CreateQueueAsync(theQueue.QueueName); + await theClient.DidNotReceiveWithAnyArgs().CreateQueueAsync(theQueue.QueueName, Arg.Any()); } [Fact] @@ -151,8 +151,7 @@ public async Task do_create_queue_if_parent_is_autoprovision() var theSqsQueueUrl = "https://someserver.com/foo"; - theClient.CreateQueueAsync(Arg.Any()) - .Returns(new CreateQueueResponse + theClient.CreateQueueAsync(Arg.Any(), TestContext.Current.CancellationToken).Returns(new CreateQueueResponse { QueueUrl = theSqsQueueUrl }); @@ -170,14 +169,14 @@ public async Task do_not_purge_when_not_auto_purge() // Gotta set this up to make the test work var theSqsQueueUrl = "https://someserver.com/foo"; - theClient.GetQueueUrlAsync(theQueue.QueueName).Returns(new GetQueueUrlResponse + theClient.GetQueueUrlAsync(theQueue.QueueName, TestContext.Current.CancellationToken).Returns(new GetQueueUrlResponse { QueueUrl = theSqsQueueUrl }); await theQueue.InitializeAsync(NullLogger.Instance); - await theClient.DidNotReceiveWithAnyArgs().PurgeQueueAsync(theSqsQueueUrl); + await theClient.DidNotReceiveWithAnyArgs().PurgeQueueAsync(theSqsQueueUrl, Arg.Any()); } [Fact] @@ -188,14 +187,14 @@ public async Task should_purge_when_auto_purge() // Gotta set this up to make the test work var theSqsQueueUrl = "https://someserver.com/foo"; - theClient.GetQueueUrlAsync(theQueue.QueueName).Returns(new GetQueueUrlResponse + theClient.GetQueueUrlAsync(theQueue.QueueName, TestContext.Current.CancellationToken).Returns(new GetQueueUrlResponse { QueueUrl = theSqsQueueUrl }); await theQueue.InitializeAsync(NullLogger.Instance); - await theClient.Received().PurgeQueueAsync(theSqsQueueUrl); + await theClient.Received().PurgeQueueAsync(theSqsQueueUrl, Arg.Any()); } [Fact] diff --git a/src/Transports/AWS/Wolverine.AmazonSqs.Tests/Samples/Bootstrapping.cs b/src/Transports/AWS/Wolverine.AmazonSqs.Tests/Samples/Bootstrapping.cs index 4a41824ed..efa7513df 100644 --- a/src/Transports/AWS/Wolverine.AmazonSqs.Tests/Samples/Bootstrapping.cs +++ b/src/Transports/AWS/Wolverine.AmazonSqs.Tests/Samples/Bootstrapping.cs @@ -367,7 +367,7 @@ public async Task customize_mappers() .DisableAllNativeDeadLetterQueues() .ConfigureListeners(l => l.InteropWith(new CustomSqsMapper())) .ConfigureSenders(s => s.InteropWith(new CustomSqsMapper())); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); #endregion } diff --git a/src/Transports/AWS/Wolverine.AmazonSqs.Tests/Wolverine.AmazonSqs.Tests.csproj b/src/Transports/AWS/Wolverine.AmazonSqs.Tests/Wolverine.AmazonSqs.Tests.csproj index ee63c4b09..5cc0a3a7c 100644 --- a/src/Transports/AWS/Wolverine.AmazonSqs.Tests/Wolverine.AmazonSqs.Tests.csproj +++ b/src/Transports/AWS/Wolverine.AmazonSqs.Tests/Wolverine.AmazonSqs.Tests.csproj @@ -1,6 +1,8 @@ + + true Exe false diff --git a/src/Transports/AWS/Wolverine.AmazonSqs.Tests/bootstrapping.cs b/src/Transports/AWS/Wolverine.AmazonSqs.Tests/bootstrapping.cs index d850545f1..d38ac768d 100644 --- a/src/Transports/AWS/Wolverine.AmazonSqs.Tests/bootstrapping.cs +++ b/src/Transports/AWS/Wolverine.AmazonSqs.Tests/bootstrapping.cs @@ -11,13 +11,13 @@ public class Bootstrapping public async Task create_an_open_client() { using var host = await Host.CreateDefaultBuilder() - .UseWolverine(opts => { opts.UseAmazonSqsTransportLocally(); }).StartAsync(); + .UseWolverine(opts => { opts.UseAmazonSqsTransportLocally(); }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var options = host.Services.GetRequiredService(); var transport = options.AmazonSqsTransport(); // Just a smoke test on configuration here - var queueNames = await transport.Client!.ListQueuesAsync("wolverine"); + var queueNames = await transport.Client!.ListQueuesAsync("wolverine", TestContext.Current.CancellationToken); } [Fact] @@ -31,17 +31,17 @@ public async Task create_new_queue_on_startup() opts.UseAmazonSqsTransportLocally().AutoProvision(); opts.ListenToSqsQueue("wolverine-" + queueName); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var options = host.Services.GetRequiredService(); var transport = options.AmazonSqsTransport(); // Just a smoke test on configuration here - var queueNames = await transport.Client!.ListQueuesAsync("wolverine"); + var queueNames = await transport.Client!.ListQueuesAsync("wolverine", TestContext.Current.CancellationToken); var queueUrl = queueNames.QueueUrls.FirstOrDefault(x => x.Contains(queueName)); queueUrl.ShouldNotBeNull(); - await transport.Client!.DeleteQueueAsync(queueUrl); + await transport.Client!.DeleteQueueAsync(queueUrl, TestContext.Current.CancellationToken); } [Fact] @@ -56,16 +56,16 @@ public async Task auto_purge_queue_on_startup_smoke_test() opts.UseAmazonSqsTransportLocally().AutoPurgeOnStartup().AutoProvision(); opts.ListenToSqsQueue("wolverine-" + queueName); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var options = host.Services.GetRequiredService(); var transport = options.AmazonSqsTransport(); - var queueNames = await transport.Client!.ListQueuesAsync("wolverine"); + var queueNames = await transport.Client!.ListQueuesAsync("wolverine", TestContext.Current.CancellationToken); var queueUrl = queueNames.QueueUrls.FirstOrDefault(x => x.Contains(queueName)); queueUrl.ShouldNotBeNull(); - await transport.Client!.DeleteQueueAsync(queueUrl); + await transport.Client!.DeleteQueueAsync(queueUrl, TestContext.Current.CancellationToken); } [Fact] @@ -84,7 +84,7 @@ public async Task configure_listening() e.MaxNumberOfMessages = 5; e.WaitTimeSeconds = 6; }); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var options = host.Services.GetRequiredService(); diff --git a/src/Transports/AWS/Wolverine.AmazonSqs.Tests/concurrency_resilient_sharded_processing.cs b/src/Transports/AWS/Wolverine.AmazonSqs.Tests/concurrency_resilient_sharded_processing.cs index 72eeb6390..f75298905 100644 --- a/src/Transports/AWS/Wolverine.AmazonSqs.Tests/concurrency_resilient_sharded_processing.cs +++ b/src/Transports/AWS/Wolverine.AmazonSqs.Tests/concurrency_resilient_sharded_processing.cs @@ -84,7 +84,7 @@ public async Task hammer_it_with_lots_of_messages_against_buffered() }); #endregion - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var tracked = await host .TrackActivity() diff --git a/src/Transports/AWS/Wolverine.AmazonSqs.Tests/dead_letter_queue_recovery.cs b/src/Transports/AWS/Wolverine.AmazonSqs.Tests/dead_letter_queue_recovery.cs index 366534b0b..c928cc73b 100644 --- a/src/Transports/AWS/Wolverine.AmazonSqs.Tests/dead_letter_queue_recovery.cs +++ b/src/Transports/AWS/Wolverine.AmazonSqs.Tests/dead_letter_queue_recovery.cs @@ -83,7 +83,7 @@ await _host { results = await messageStore.DeadLetters.QueryAsync(query, CancellationToken.None); if (results.Envelopes.Any()) break; - await Task.Delay(500); + await Task.Delay(500, TestContext.Current.CancellationToken); } results.ShouldNotBeNull(); diff --git a/src/Transports/AWS/Wolverine.AmazonSqs.Tests/default_dead_letter_queue_name.cs b/src/Transports/AWS/Wolverine.AmazonSqs.Tests/default_dead_letter_queue_name.cs index 3bb0864d9..2ff49f52c 100644 --- a/src/Transports/AWS/Wolverine.AmazonSqs.Tests/default_dead_letter_queue_name.cs +++ b/src/Transports/AWS/Wolverine.AmazonSqs.Tests/default_dead_letter_queue_name.cs @@ -39,7 +39,7 @@ public async Task fallback_default_name_is_wolverine_dead_letter_queue_when_neit { opts.UseAmazonSqsTransportLocally().AutoProvision(); opts.ListenToSqsQueue("orders"); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var transport = TransportFor(host); @@ -59,7 +59,7 @@ public async Task transport_default_applies_to_listeners_with_no_per_endpoint_ov opts.ListenToSqsQueue("orders"); opts.ListenToSqsQueue("shipments"); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var transport = TransportFor(host); @@ -84,7 +84,7 @@ public async Task per_endpoint_override_wins_over_transport_default() // No override here — should still pick up the transport default. opts.ListenToSqsQueue("shipments"); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var transport = TransportFor(host); @@ -106,7 +106,7 @@ public async Task per_endpoint_disable_wins_over_transport_default() .DisableDeadLetterQueueing(); opts.ListenToSqsQueue("orders"); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var transport = TransportFor(host); @@ -128,7 +128,7 @@ public async Task global_disable_trumps_transport_default_during_provisioning() .DisableAllNativeDeadLetterQueues(); opts.ListenToSqsQueue("orders"); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var transport = TransportFor(host); @@ -160,7 +160,7 @@ public async Task transport_default_is_sanitized_consistently_with_per_listener_ .AutoProvision(); opts.ListenToSqsQueue("orders"); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var transport = TransportFor(host); @@ -180,7 +180,7 @@ public async Task transport_default_is_provisioned_when_listeners_inherit_it() opts.ListenToSqsQueue("orders"); opts.ListenToSqsQueue("shipments"); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var transport = TransportFor(host); @@ -207,7 +207,7 @@ public async Task mixed_inherit_and_override_provisions_both_dead_letter_queues( opts.ListenToSqsQueue("notifications") .DisableDeadLetterQueueing(); // disabled, no DLQ provisioned for this one - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var transport = TransportFor(host); @@ -249,7 +249,7 @@ public async Task system_queues_keep_their_explicit_no_dlq_setting_under_a_trans .AutoProvision(); opts.ListenToSqsQueue("orders"); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var transport = TransportFor(host); diff --git a/src/Transports/AWS/Wolverine.AmazonSqs.Tests/end_to_end_with_named_broker.cs b/src/Transports/AWS/Wolverine.AmazonSqs.Tests/end_to_end_with_named_broker.cs index 94f94cce8..57e7d60c8 100644 --- a/src/Transports/AWS/Wolverine.AmazonSqs.Tests/end_to_end_with_named_broker.cs +++ b/src/Transports/AWS/Wolverine.AmazonSqs.Tests/end_to_end_with_named_broker.cs @@ -46,7 +46,7 @@ public async Task send_message_to_and_receive_through_kafka_with_inline_receiver { await publisher.SendAsync(new ColorChosen { Name = "blue" }); } - }); + }, TestContext.Current.CancellationToken); diff --git a/src/Transports/AWS/Wolverine.AmazonSqs.Tests/global_partitioned_sharded_processing.cs b/src/Transports/AWS/Wolverine.AmazonSqs.Tests/global_partitioned_sharded_processing.cs index 50b6d3eee..93d202b78 100644 --- a/src/Transports/AWS/Wolverine.AmazonSqs.Tests/global_partitioned_sharded_processing.cs +++ b/src/Transports/AWS/Wolverine.AmazonSqs.Tests/global_partitioned_sharded_processing.cs @@ -70,7 +70,7 @@ public async Task hammer_it_with_lots_of_messages_global_partitioned() topology.UseShardedAmazonSqsQueues("gletters", 4); topology.MessagesImplementing(); }); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var tracked = await host .TrackActivity() diff --git a/src/Transports/Azure/Wolverine.AzureServiceBus.Tests/BufferedSendingAndReceivingCompliance.cs b/src/Transports/Azure/Wolverine.AzureServiceBus.Tests/BufferedSendingAndReceivingCompliance.cs index 1cf74c6cf..dd36b6f0c 100644 --- a/src/Transports/Azure/Wolverine.AzureServiceBus.Tests/BufferedSendingAndReceivingCompliance.cs +++ b/src/Transports/Azure/Wolverine.AzureServiceBus.Tests/BufferedSendingAndReceivingCompliance.cs @@ -67,7 +67,7 @@ public virtual async Task dlq_mechanics() await queue.InitializeAsync(NullLogger.Instance); await using var messageReceiver = transport.BusClient.CreateReceiver(AzureServiceBusTransport.DeadLetterQueueName); - var queued = await messageReceiver.ReceiveMessageAsync(); + var queued = await messageReceiver.ReceiveMessageAsync(cancellationToken: TestContext.Current.CancellationToken); queued.ShouldNotBeNull(); } } \ No newline at end of file diff --git a/src/Transports/Azure/Wolverine.AzureServiceBus.Tests/Bugs/Bug_1684_separated_handlers_and_conventional_routing.cs b/src/Transports/Azure/Wolverine.AzureServiceBus.Tests/Bugs/Bug_1684_separated_handlers_and_conventional_routing.cs index 0f93bbe47..d11ca3004 100644 --- a/src/Transports/Azure/Wolverine.AzureServiceBus.Tests/Bugs/Bug_1684_separated_handlers_and_conventional_routing.cs +++ b/src/Transports/Azure/Wolverine.AzureServiceBus.Tests/Bugs/Bug_1684_separated_handlers_and_conventional_routing.cs @@ -36,7 +36,7 @@ public async Task try_it_and_send_to_multiple_topic_subscriptions() //services.AddHostedService(); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var message = new Msg(Guid.NewGuid()); var tracked = await host.TrackActivity().IncludeExternalTransports().SendMessageAndWaitAsync(message); diff --git a/src/Transports/Azure/Wolverine.AzureServiceBus.Tests/Bugs/Bug_1933_multi_tenant_conventional_routing.cs b/src/Transports/Azure/Wolverine.AzureServiceBus.Tests/Bugs/Bug_1933_multi_tenant_conventional_routing.cs index bc0b5e935..6ec2d4cbd 100644 --- a/src/Transports/Azure/Wolverine.AzureServiceBus.Tests/Bugs/Bug_1933_multi_tenant_conventional_routing.cs +++ b/src/Transports/Azure/Wolverine.AzureServiceBus.Tests/Bugs/Bug_1933_multi_tenant_conventional_routing.cs @@ -54,7 +54,7 @@ public async Task should_receive_message_when_published_without_tenant_id() var transport = opts.Transports.GetOrCreate(); transport.Tenants["test"].Transport.ManagementConnectionString = Servers.AzureServiceBusConnectionString; - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var message = new Bug1933Message("Hello from default namespace"); @@ -81,7 +81,7 @@ public async Task baseline_without_tenants() opts.UseAzureServiceBusTesting() .AutoPurgeOnStartup() .UseConventionalRouting(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var message = new Bug1933Message("Hello from default namespace"); diff --git a/src/Transports/Azure/Wolverine.AzureServiceBus.Tests/Bugs/Bug_2283_purge_session_subscription.cs b/src/Transports/Azure/Wolverine.AzureServiceBus.Tests/Bugs/Bug_2283_purge_session_subscription.cs index 88095b732..cf5ba50d8 100644 --- a/src/Transports/Azure/Wolverine.AzureServiceBus.Tests/Bugs/Bug_2283_purge_session_subscription.cs +++ b/src/Transports/Azure/Wolverine.AzureServiceBus.Tests/Bugs/Bug_2283_purge_session_subscription.cs @@ -95,7 +95,7 @@ await _host.TrackActivity() .FromTopic("bug2283") .RequireSessions(1) .ProcessInline(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); // Send new messages through host2 and verify only the new ones arrive Func sendNew = async bus => @@ -111,7 +111,7 @@ await _host.TrackActivity() var received = session.Received.MessagesOf().Select(x => x.Name).ToArray(); received.ShouldContain("New1"); - await host2.StopAsync(); + await host2.StopAsync(TestContext.Current.CancellationToken); } } diff --git a/src/Transports/Azure/Wolverine.AzureServiceBus.Tests/Internal/AzureServiceBusSubscriptionTests.cs b/src/Transports/Azure/Wolverine.AzureServiceBus.Tests/Internal/AzureServiceBusSubscriptionTests.cs index c7c63e5aa..b7a73664e 100644 --- a/src/Transports/Azure/Wolverine.AzureServiceBus.Tests/Internal/AzureServiceBusSubscriptionTests.cs +++ b/src/Transports/Azure/Wolverine.AzureServiceBus.Tests/Internal/AzureServiceBusSubscriptionTests.cs @@ -39,7 +39,7 @@ public async Task initialize_with_no_auto_provision() await subscription.InitializeAsync(theManagementClient, NullLogger.Instance); - await theManagementClient.DidNotReceive().CreateSubscriptionAsync(Arg.Any()); + await theManagementClient.DidNotReceive().CreateSubscriptionAsync(Arg.Any(), Arg.Any()); } [Fact] @@ -52,9 +52,7 @@ public async Task initialize_with_auto_provision_and_default_rule() await subscription.InitializeAsync(theManagementClient, NullLogger.Instance); - await theManagementClient.Received().CreateSubscriptionAsync( - Arg.Is(x => x.TopicName == "foo" && x.SubscriptionName == "bar"), - Arg.Is(x => x.Equals(new CreateRuleOptions()))); + await theManagementClient.Received().CreateSubscriptionAsync(Arg.Is(x => x.TopicName == "foo" && x.SubscriptionName == "bar"), Arg.Is(x => x.Equals(new CreateRuleOptions())), Arg.Any()); } [Fact] @@ -74,11 +72,9 @@ public async Task initialize_with_auto_provision_with_custom_rule() await subscription.InitializeAsync(theManagementClient, NullLogger.Instance); - await theManagementClient.Received().CreateSubscriptionAsync( - Arg.Is(x => x.TopicName == "foo" && x.SubscriptionName == "bar"), - Arg.Is(x => + await theManagementClient.Received().CreateSubscriptionAsync(Arg.Is(x => x.TopicName == "foo" && x.SubscriptionName == "bar"), Arg.Is(x => x.Filter.Equals(new SqlRuleFilter("foo = 'bar'")) && - x.Action.Equals(new SqlRuleAction("SET foo = 'baz'")))); + x.Action.Equals(new SqlRuleAction("SET foo = 'baz'"))), TestContext.Current.CancellationToken); } } \ No newline at end of file diff --git a/src/Transports/Azure/Wolverine.AzureServiceBus.Tests/Internal/AzureServiceBusTopicTests.cs b/src/Transports/Azure/Wolverine.AzureServiceBus.Tests/Internal/AzureServiceBusTopicTests.cs index de1c3f33b..295bf62d9 100644 --- a/src/Transports/Azure/Wolverine.AzureServiceBus.Tests/Internal/AzureServiceBusTopicTests.cs +++ b/src/Transports/Azure/Wolverine.AzureServiceBus.Tests/Internal/AzureServiceBusTopicTests.cs @@ -35,7 +35,7 @@ public async Task initialize_with_no_auto_provision() await endpoint.InitializeAsync(theManagementClient, NullLogger.Instance); - await theManagementClient.DidNotReceive().CreateTopicAsync(Arg.Any()); + await theManagementClient.DidNotReceive().CreateTopicAsync(Arg.Any(), Arg.Any()); } [Fact] @@ -47,6 +47,6 @@ public async Task initialize_with_auto_provision() await endpoint.InitializeAsync(theManagementClient, NullLogger.Instance); - await theManagementClient.Received().CreateTopicAsync(Arg.Is(x => x.Name == "foo")); + await theManagementClient.Received().CreateTopicAsync(Arg.Is(x => x.Name == "foo"), Arg.Any()); } } \ No newline at end of file diff --git a/src/Transports/Azure/Wolverine.AzureServiceBus.Tests/Wolverine.AzureServiceBus.Tests.csproj b/src/Transports/Azure/Wolverine.AzureServiceBus.Tests/Wolverine.AzureServiceBus.Tests.csproj index 0bbac1068..e26f04984 100644 --- a/src/Transports/Azure/Wolverine.AzureServiceBus.Tests/Wolverine.AzureServiceBus.Tests.csproj +++ b/src/Transports/Azure/Wolverine.AzureServiceBus.Tests/Wolverine.AzureServiceBus.Tests.csproj @@ -1,6 +1,8 @@ + + true Exe false diff --git a/src/Transports/Azure/Wolverine.AzureServiceBus.Tests/connection_state_3237.cs b/src/Transports/Azure/Wolverine.AzureServiceBus.Tests/connection_state_3237.cs index 6d38d9604..3c4661fb3 100644 --- a/src/Transports/Azure/Wolverine.AzureServiceBus.Tests/connection_state_3237.cs +++ b/src/Transports/Azure/Wolverine.AzureServiceBus.Tests/connection_state_3237.cs @@ -68,7 +68,7 @@ public async Task healthy_listeners_rest_at_unknown_and_never_report_connected() opts.PublishMessage().ToAzureServiceBusQueue("connstate-batched"); opts.ListenToAzureServiceBusQueue("connstate-inline").ProcessInline(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); // Prove the pipe actually works... await host.TrackActivity().IncludeExternalTransports().Timeout(30.Seconds()) diff --git a/src/Transports/Azure/Wolverine.AzureServiceBus.Tests/dead_letter_queue_recovery.cs b/src/Transports/Azure/Wolverine.AzureServiceBus.Tests/dead_letter_queue_recovery.cs index 1abc6a4b0..24be1e44e 100644 --- a/src/Transports/Azure/Wolverine.AzureServiceBus.Tests/dead_letter_queue_recovery.cs +++ b/src/Transports/Azure/Wolverine.AzureServiceBus.Tests/dead_letter_queue_recovery.cs @@ -84,7 +84,7 @@ await _host { results = await messageStore.DeadLetters.QueryAsync(query, CancellationToken.None); if (results.Envelopes.Any()) break; - await Task.Delay(500); + await Task.Delay(500, TestContext.Current.CancellationToken); } results.ShouldNotBeNull(); diff --git a/src/Transports/Azure/Wolverine.AzureServiceBus.Tests/end_to_end.cs b/src/Transports/Azure/Wolverine.AzureServiceBus.Tests/end_to_end.cs index ee7e5274e..230dbebb2 100644 --- a/src/Transports/Azure/Wolverine.AzureServiceBus.Tests/end_to_end.cs +++ b/src/Transports/Azure/Wolverine.AzureServiceBus.Tests/end_to_end.cs @@ -89,7 +89,7 @@ public async Task disable_system_queues() opts.ListenToAzureServiceBusQueue("send_and_receive"); opts.PublishAllMessages().ToAzureServiceBusQueue("send_and_receive"); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var transport = host.GetRuntime().Options.Transports.GetOrCreate(); diff --git a/src/Transports/Azure/Wolverine.AzureServiceBus.Tests/end_to_end_with_named_broker.cs b/src/Transports/Azure/Wolverine.AzureServiceBus.Tests/end_to_end_with_named_broker.cs index 1f26af186..d1337982a 100644 --- a/src/Transports/Azure/Wolverine.AzureServiceBus.Tests/end_to_end_with_named_broker.cs +++ b/src/Transports/Azure/Wolverine.AzureServiceBus.Tests/end_to_end_with_named_broker.cs @@ -83,7 +83,7 @@ public async Task correct_scheme_on_reply_uri() opts.Services.AddResourceSetupOnStartup(StartupAction.ResetState); }); - await receiver.ResetResourceState(); + await receiver.ResetResourceState(cancellation: TestContext.Current.CancellationToken); var request = new RequestId(Guid.NewGuid()); var (tracked, response) = diff --git a/src/Transports/Azure/Wolverine.AzureServiceBus.Tests/session_id_pinning.cs b/src/Transports/Azure/Wolverine.AzureServiceBus.Tests/session_id_pinning.cs index facd46825..89899e95b 100644 --- a/src/Transports/Azure/Wolverine.AzureServiceBus.Tests/session_id_pinning.cs +++ b/src/Transports/Azure/Wolverine.AzureServiceBus.Tests/session_id_pinning.cs @@ -52,7 +52,7 @@ public async Task pinned_listener_only_receives_its_own_session() { SessionId = "B", MessageId = Guid.NewGuid().ToString() - }); + }, TestContext.Current.CancellationToken); // Drive three "A" messages through Wolverine and confirm ONLY those are received Func sendAll = async bus => @@ -73,8 +73,8 @@ public async Task pinned_listener_only_receives_its_own_session() // The "B" session message must still be sitting on the shared queue, never delivered to the // A-pinned listener. - await using var sessionReceiver = await client.AcceptSessionAsync("shared-pinned", "B"); - var leftover = await sessionReceiver.ReceiveMessageAsync(5.Seconds()); + await using var sessionReceiver = await client.AcceptSessionAsync("shared-pinned", "B", cancellationToken: TestContext.Current.CancellationToken); + var leftover = await sessionReceiver.ReceiveMessageAsync(5.Seconds(), TestContext.Current.CancellationToken); leftover.ShouldNotBeNull(); leftover.SessionId.ShouldBe("B"); } diff --git a/src/Transports/Azure/Wolverine.AzureServiceBus.Tests/using_native_scheduling.cs b/src/Transports/Azure/Wolverine.AzureServiceBus.Tests/using_native_scheduling.cs index 1434956c4..c3bbf65b0 100644 --- a/src/Transports/Azure/Wolverine.AzureServiceBus.Tests/using_native_scheduling.cs +++ b/src/Transports/Azure/Wolverine.AzureServiceBus.Tests/using_native_scheduling.cs @@ -21,7 +21,7 @@ public async Task with_inline_endpoint() opts.ListenToAzureServiceBusQueue("inline1").ProcessInline(); opts.PublishMessage().ToAzureServiceBusQueue("inline1"); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var session = await host.TrackActivity() .IncludeExternalTransports() @@ -31,7 +31,7 @@ public async Task with_inline_endpoint() session.Received.SingleMessage() .Name.ShouldBe("later"); - await host.StopAsync(); + await host.StopAsync(TestContext.Current.CancellationToken); } [Fact] @@ -45,7 +45,7 @@ public async Task with_inline_endpoint_cascaded_timeout() opts.ListenToAzureServiceBusQueue("inline1").ProcessInline(); opts.PublishAllMessages().ToAzureServiceBusQueue("inline1"); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var referenceTime = DateTimeOffset.UtcNow; var delay = TimeSpan.FromSeconds(1); @@ -61,7 +61,7 @@ public async Task with_inline_endpoint_cascaded_timeout() envelope.ShouldNotBeNull(); envelope.ScheduledTime!.Value.ShouldBeInRange(referenceTime.Add(delay - margin), referenceTime.Add(delay + margin)); - await host.StopAsync(); + await host.StopAsync(TestContext.Current.CancellationToken); } [Fact] @@ -75,7 +75,7 @@ public async Task with_inline_endpoint_explicit_scheduling() opts.ListenToAzureServiceBusQueue("inline1").ProcessInline(); opts.PublishAllMessages().ToAzureServiceBusQueue("inline1"); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var referenceTime = DateTimeOffset.UtcNow; var delay = TimeSpan.FromSeconds(1); @@ -91,7 +91,7 @@ public async Task with_inline_endpoint_explicit_scheduling() envelope.ShouldNotBeNull(); envelope.ScheduledTime!.Value.ShouldBeInRange(referenceTime.Add(delay - margin), referenceTime.Add(delay + margin)); - await host.StopAsync(); + await host.StopAsync(TestContext.Current.CancellationToken); } [Fact] @@ -107,7 +107,7 @@ public async Task schedule_to_topic_with_subscription_listener() opts.ListenToAzureServiceBusSubscription("scheduled-sub") .FromTopic("scheduled-topic") .ProcessInline(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var session = await host.TrackActivity() .IncludeExternalTransports() @@ -117,7 +117,7 @@ public async Task schedule_to_topic_with_subscription_listener() session.Received.SingleMessage() .Name.ShouldBe("topic scheduled"); - await host.StopAsync(); + await host.StopAsync(TestContext.Current.CancellationToken); } [Fact] @@ -131,7 +131,7 @@ public async Task with_buffered_endpoint() // durable would have similar mechani opts.ListenToAzureServiceBusQueue("buffered1").BufferedInMemory(); opts.PublishMessage().ToAzureServiceBusQueue("buffered1"); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var session = await host.TrackActivity() .IncludeExternalTransports() @@ -141,7 +141,7 @@ public async Task with_buffered_endpoint() // durable would have similar mechani session.Received.SingleMessage() .Name.ShouldBe("in a bit"); - await host.StopAsync(); + await host.StopAsync(TestContext.Current.CancellationToken); } } diff --git a/src/Transports/GCP/Wolverine.Pubsub.Tests/PubsubPerTenantBrokerTests.cs b/src/Transports/GCP/Wolverine.Pubsub.Tests/PubsubPerTenantBrokerTests.cs index 569195c3d..961f59e16 100644 --- a/src/Transports/GCP/Wolverine.Pubsub.Tests/PubsubPerTenantBrokerTests.cs +++ b/src/Transports/GCP/Wolverine.Pubsub.Tests/PubsubPerTenantBrokerTests.cs @@ -98,7 +98,7 @@ public async Task tenant_message_is_consumed_and_stamped_with_the_tenant_id() opts.PublishMessage().ToPubsubTopic(topic).SendInline(); opts.ListenToPubsubTopic(topic); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); // The default listener polls the default project and the tenant listener polls the tenant project; the // message only exists under the tenant project, so only the tenant listener consumes it and stamps the id. @@ -134,13 +134,13 @@ public async Task auto_provision_creates_the_topology_under_the_tenant_project() opts.PublishMessage().ToPubsubTopic(topic); opts.ListenToPubsubTopic(topic); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); // Prove the topic was actually created under the tenant project (GetTopicAsync throws when absent). var publisher = await new PublisherServiceApiClientBuilder { EmulatorDetection = EmulatorDetection.EmulatorOnly - }.BuildAsync(); + }.BuildAsync(TestContext.Current.CancellationToken); var tenantTopic = await publisher.GetTopicAsync(new TopicName(TenantProject, topic)); tenantTopic.ShouldNotBeNull(); diff --git a/src/Transports/GCP/Wolverine.Pubsub.Tests/Wolverine.Pubsub.Tests.csproj b/src/Transports/GCP/Wolverine.Pubsub.Tests/Wolverine.Pubsub.Tests.csproj index 913b17345..68ac07df7 100644 --- a/src/Transports/GCP/Wolverine.Pubsub.Tests/Wolverine.Pubsub.Tests.csproj +++ b/src/Transports/GCP/Wolverine.Pubsub.Tests/Wolverine.Pubsub.Tests.csproj @@ -1,6 +1,8 @@ + + true Exe false diff --git a/src/Transports/GCP/Wolverine.Pubsub.Tests/connection_state_3237.cs b/src/Transports/GCP/Wolverine.Pubsub.Tests/connection_state_3237.cs index a25fedb20..795a2531c 100644 --- a/src/Transports/GCP/Wolverine.Pubsub.Tests/connection_state_3237.cs +++ b/src/Transports/GCP/Wolverine.Pubsub.Tests/connection_state_3237.cs @@ -24,7 +24,7 @@ public async Task healthy_listener_rests_at_unknown_and_never_reports_connected( opts.PublishMessage().ToPubsubTopic("connstate"); opts.ListenToPubsubTopic("connstate"); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); // Prove the pipe actually works... await host.TrackActivity().IncludeExternalTransports().Timeout(30.Seconds()) @@ -60,7 +60,7 @@ public async Task unreachable_broker_degrades_to_disconnected_after_retries_are_ c.RetryPolicy.MaxRetryCount = 2; c.RetryPolicy.RetryDelay = 50; }); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var state = await ConnectionStateTestHelpers.WaitForListenerConnectionStateAsync( host, PubsubTransport.ProtocolName, TransportConnectionState.Disconnected); diff --git a/src/Transports/GCP/Wolverine.Pubsub.Tests/send_and_receive.cs b/src/Transports/GCP/Wolverine.Pubsub.Tests/send_and_receive.cs index b5be6badd..550af4894 100644 --- a/src/Transports/GCP/Wolverine.Pubsub.Tests/send_and_receive.cs +++ b/src/Transports/GCP/Wolverine.Pubsub.Tests/send_and_receive.cs @@ -62,7 +62,7 @@ public async Task builds_system_endpoints() opts .PublishAllMessages() .ToPubsubTopic("send_and_receive"); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var transport = host.GetRuntime().Options.Transports.GetOrCreate(); var endpoints = transport .Endpoints() diff --git a/src/Transports/Kafka/Wolverine.Kafka.Tests/Bugs/Bug_2537_autoprovision_creates_missing_topics.cs b/src/Transports/Kafka/Wolverine.Kafka.Tests/Bugs/Bug_2537_autoprovision_creates_missing_topics.cs index 5d6dd9630..1bcefab57 100644 --- a/src/Transports/Kafka/Wolverine.Kafka.Tests/Bugs/Bug_2537_autoprovision_creates_missing_topics.cs +++ b/src/Transports/Kafka/Wolverine.Kafka.Tests/Bugs/Bug_2537_autoprovision_creates_missing_topics.cs @@ -79,7 +79,7 @@ public async Task autoprovision_alone_creates_missing_topic_for_group_listener() opts.Discovery.DisableConventionalDiscovery(); opts.Services.AddSingleton(new OutputLoggerProvider(_output)); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); // AutoProvision should have created the topic during host startup. ListAllTopics().ShouldContain(_topicName, diff --git a/src/Transports/Kafka/Wolverine.Kafka.Tests/KafkaPerTenantConfigurationTests.cs b/src/Transports/Kafka/Wolverine.Kafka.Tests/KafkaPerTenantConfigurationTests.cs index 74d2f1d8b..eb96c4926 100644 --- a/src/Transports/Kafka/Wolverine.Kafka.Tests/KafkaPerTenantConfigurationTests.cs +++ b/src/Transports/Kafka/Wolverine.Kafka.Tests/KafkaPerTenantConfigurationTests.cs @@ -117,7 +117,7 @@ public async Task tenant_aware_endpoint_resolves_a_TenantedSender() opts.Policies.DisableConventionalLocalRouting(); opts.PublishMessage().ToKafkaTopic("tenant-colors"); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.GetRuntime(); var transport = runtime.Options.Transports.GetOrCreate(); diff --git a/src/Transports/Kafka/Wolverine.Kafka.Tests/KafkaPerTenantConnectionTests.cs b/src/Transports/Kafka/Wolverine.Kafka.Tests/KafkaPerTenantConnectionTests.cs index 1254927a2..0fb45df43 100644 --- a/src/Transports/Kafka/Wolverine.Kafka.Tests/KafkaPerTenantConnectionTests.cs +++ b/src/Transports/Kafka/Wolverine.Kafka.Tests/KafkaPerTenantConnectionTests.cs @@ -130,7 +130,7 @@ public async Task tenant_message_is_consumed_and_stamped_with_the_tenant_id() opts.Discovery.IncludeAssembly(GetType().Assembly); opts.Services.AddSingleton(new OutputLoggerProvider(_output)); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); // Single host both publishes (to the tenant cluster) and listens (on the tenant cluster), so the // message round-trips back stamped with the tenant id. diff --git a/src/Transports/Kafka/Wolverine.Kafka.Tests/Wolverine.Kafka.Tests.csproj b/src/Transports/Kafka/Wolverine.Kafka.Tests/Wolverine.Kafka.Tests.csproj index 28e6a45a4..945e66c2c 100644 --- a/src/Transports/Kafka/Wolverine.Kafka.Tests/Wolverine.Kafka.Tests.csproj +++ b/src/Transports/Kafka/Wolverine.Kafka.Tests/Wolverine.Kafka.Tests.csproj @@ -1,6 +1,8 @@ + + true Exe net9.0;net10.0 false diff --git a/src/Transports/Kafka/Wolverine.Kafka.Tests/cold_start_and_hot_tail.cs b/src/Transports/Kafka/Wolverine.Kafka.Tests/cold_start_and_hot_tail.cs index 65019954e..ebc877e1c 100644 --- a/src/Transports/Kafka/Wolverine.Kafka.Tests/cold_start_and_hot_tail.cs +++ b/src/Transports/Kafka/Wolverine.Kafka.Tests/cold_start_and_hot_tail.cs @@ -107,7 +107,7 @@ public async Task hot_tail_delivers_all_messages_to_every_node() // Latest means only messages published AFTER the consumers join are seen — give them a moment // to be assigned their partitions before publishing. - await Task.Delay(3000); + await Task.Delay(3000, TestContext.Current.CancellationToken); for (var i = 0; i < 5; i++) { diff --git a/src/Transports/Kafka/Wolverine.Kafka.Tests/commit_strategy_end_to_end.cs b/src/Transports/Kafka/Wolverine.Kafka.Tests/commit_strategy_end_to_end.cs index f886be073..cf5ae4d21 100644 --- a/src/Transports/Kafka/Wolverine.Kafka.Tests/commit_strategy_end_to_end.cs +++ b/src/Transports/Kafka/Wolverine.Kafka.Tests/commit_strategy_end_to_end.cs @@ -54,7 +54,7 @@ public async Task second_consumer_in_same_group_resumes_past_committed_offsets() await waitForCountAsync(firstBatch, 5); // Graceful shutdown flushes/commits the stored offsets (StoreThenAutoFlush + clean Close). - await first.StopAsync(); + await first.StopAsync(TestContext.Current.CancellationToken); first.Dispose(); // --- Phase 2: a fresh consumer in the SAME group should only see the new messages --- @@ -70,7 +70,7 @@ public async Task second_consumer_in_same_group_resumes_past_committed_offsets() await waitForCountAsync(secondBatch, 3); // Give any (incorrect) redelivery of the first batch a chance to show up before asserting. - await Task.Delay(1000); + await Task.Delay(1000, TestContext.Current.CancellationToken); secondBatch.ShouldNotContain(x => x.StartsWith("first-"), "The second consumer reprocessed already-committed messages — offsets were not committed/flushed"); diff --git a/src/Transports/Kafka/Wolverine.Kafka.Tests/configuration_precedence.cs b/src/Transports/Kafka/Wolverine.Kafka.Tests/configuration_precedence.cs index d0ca658f3..9d89b276a 100644 --- a/src/Transports/Kafka/Wolverine.Kafka.Tests/configuration_precedence.cs +++ b/src/Transports/Kafka/Wolverine.Kafka.Tests/configuration_precedence.cs @@ -33,7 +33,7 @@ public async Task explicit_configuration_wins() }).Named("Specific"); // Not working as expected opts.Services.AddResourceSetupOnStartup(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.GetRuntime(); diff --git a/src/Transports/Kafka/Wolverine.Kafka.Tests/connection_state_3454.cs b/src/Transports/Kafka/Wolverine.Kafka.Tests/connection_state_3454.cs index 9da7888f7..7b23f4462 100644 --- a/src/Transports/Kafka/Wolverine.Kafka.Tests/connection_state_3454.cs +++ b/src/Transports/Kafka/Wolverine.Kafka.Tests/connection_state_3454.cs @@ -85,7 +85,7 @@ public async Task healthy_listener_rests_at_unknown_and_never_reports_connected( opts.PublishMessage().ToKafkaTopic("connstate-3454"); // BeginAtEarliest so a record produced before the group finishes joining is still consumed opts.ListenToKafkaTopic("connstate-3454").BeginAtEarliest(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); // Prove records actually flow... await host.TrackActivity().IncludeExternalTransports().Timeout(60.Seconds()) @@ -109,7 +109,7 @@ public async Task unreachable_broker_degrades_to_disconnected() { opts.UseKafka("localhost:19092"); opts.ListenToKafkaTopic("connstate-dead"); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var state = await ConnectionStateTestHelpers.WaitForListenerConnectionStateAsync( host, "kafka", TransportConnectionState.Disconnected, 30000); @@ -132,7 +132,7 @@ public async Task user_claimed_error_handler_backs_off_instead_of_throwing() .ConfigureConsumerBuilders(b => b.SetErrorHandler((_, _) => Interlocked.Increment(ref userHandlerHits))); opts.ListenToKafkaTopic("connstate-user-handler"); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); // Poll for the state we must NOT reach; the helper returns the last observed state on timeout var state = await ConnectionStateTestHelpers.WaitForListenerConnectionStateAsync( diff --git a/src/Transports/Kafka/Wolverine.Kafka.Tests/disable_requeueing.cs b/src/Transports/Kafka/Wolverine.Kafka.Tests/disable_requeueing.cs index eb4470b8d..7dbf0dd42 100644 --- a/src/Transports/Kafka/Wolverine.Kafka.Tests/disable_requeueing.cs +++ b/src/Transports/Kafka/Wolverine.Kafka.Tests/disable_requeueing.cs @@ -14,7 +14,7 @@ public async Task can_disable() .UseWolverine(opts => { opts.UseKafka("").ConsumeOnly(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); host.GetRuntime().Options.Transports.GetOrCreate() .Usage.ShouldBe(KafkaUsage.ConsumeOnly); diff --git a/src/Transports/Kafka/Wolverine.Kafka.Tests/duplicate_message_handling_with_postgres_inbox.cs b/src/Transports/Kafka/Wolverine.Kafka.Tests/duplicate_message_handling_with_postgres_inbox.cs index 2fb17a769..f027ae05a 100644 --- a/src/Transports/Kafka/Wolverine.Kafka.Tests/duplicate_message_handling_with_postgres_inbox.cs +++ b/src/Transports/Kafka/Wolverine.Kafka.Tests/duplicate_message_handling_with_postgres_inbox.cs @@ -72,7 +72,7 @@ public async Task duplicate_message_is_discarded_and_partition_continues() await ProduceAsync(producer, _topicName, fixedId, new DupTestMessage("first")); await ProduceAsync(producer, _topicName, fixedId, new DupTestMessage("duplicate")); await ProduceAsync(producer, _topicName, freshId, new DupTestMessage("third")); - producer.Flush(); + producer.Flush(TestContext.Current.CancellationToken); // Wait until both unique envelope IDs have been processed by the handler. var deadline = DateTimeOffset.UtcNow.AddSeconds(30); @@ -84,7 +84,7 @@ public async Task duplicate_message_is_discarded_and_partition_continues() break; } - await Task.Delay(250); + await Task.Delay(250, TestContext.Current.CancellationToken); } DupTestHandler.HandledIds.ShouldContain(fixedId); diff --git a/src/Transports/Kafka/Wolverine.Kafka.Tests/global_partitioned_aggregate_concurrency.cs b/src/Transports/Kafka/Wolverine.Kafka.Tests/global_partitioned_aggregate_concurrency.cs index aba350c7f..57b174faf 100644 --- a/src/Transports/Kafka/Wolverine.Kafka.Tests/global_partitioned_aggregate_concurrency.cs +++ b/src/Transports/Kafka/Wolverine.Kafka.Tests/global_partitioned_aggregate_concurrency.cs @@ -150,7 +150,7 @@ public async ValueTask DisposeAsync() public async Task should_not_have_concurrency_exceptions_for_same_stream() { var store = _replica1.Services.GetRequiredService(); - await store.Advanced.Clean.DeleteAllEventDataAsync(); + await store.Advanced.Clean.DeleteAllEventDataAsync(TestContext.Current.CancellationToken); var bus = _publisher.Services.GetRequiredService(); @@ -166,6 +166,8 @@ public async Task should_not_have_concurrency_exceptions_for_same_stream() { var id = streamId; var iteration = i; + // xUnit's own fixer declines this shape (it cannot tell which Task.Run overload to + // bind), so the token is threaded by hand. tasks.Add(Task.Run(async () => { if (iteration % 2 == 0) @@ -178,7 +180,7 @@ public async Task should_not_have_concurrency_exceptions_for_same_stream() } Interlocked.Increment(ref messageCount); - })); + }, TestContext.Current.CancellationToken)); } } @@ -186,7 +188,7 @@ public async Task should_not_have_concurrency_exceptions_for_same_stream() _output.WriteLine($"Published {messageCount} messages across {streamIds.Length} streams"); // Wait for processing to complete across both replicas - await Task.Delay(45.Seconds()); + await Task.Delay(45.Seconds(), TestContext.Current.CancellationToken); var errors = ConcurrencyTracker.Errors.ToList(); var concurrentAccessCount = ConcurrencyTracker.ConcurrentAccessDetected; diff --git a/src/Transports/Kafka/Wolverine.Kafka.Tests/global_partitioned_sharded_processing.cs b/src/Transports/Kafka/Wolverine.Kafka.Tests/global_partitioned_sharded_processing.cs index 2f5a84c74..2d565dac5 100644 --- a/src/Transports/Kafka/Wolverine.Kafka.Tests/global_partitioned_sharded_processing.cs +++ b/src/Transports/Kafka/Wolverine.Kafka.Tests/global_partitioned_sharded_processing.cs @@ -74,7 +74,7 @@ public async Task hammer_it_with_lots_of_messages_global_partitioned() topology.UseShardedKafkaTopics("gletters", 4); topology.MessagesImplementing(); }); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var tracked = await host .TrackActivity() diff --git a/src/Transports/Kafka/Wolverine.Kafka.Tests/kafka_replay.cs b/src/Transports/Kafka/Wolverine.Kafka.Tests/kafka_replay.cs index de58e8e43..4fe2e90d8 100644 --- a/src/Transports/Kafka/Wolverine.Kafka.Tests/kafka_replay.cs +++ b/src/Transports/Kafka/Wolverine.Kafka.Tests/kafka_replay.cs @@ -54,12 +54,12 @@ public async Task replay_from_offset_reprocesses_the_window_without_touching_the await waitForCountAsync(sink.Received, 6); // Let the live group commit its progress through the topic. - await Task.Delay(2000); + await Task.Delay(2000, TestContext.Current.CancellationToken); var committedBefore = QueryCommittedOffset(liveGroup, topic); // Now replay just the tail of the window through the pipeline again. sink.Received.Clear(); - var result = await host.ReplayKafkaTopicAsync(new KafkaReplayRequest { Topic = topic, FromOffset = 2 }); + var result = await host.ReplayKafkaTopicAsync(new KafkaReplayRequest { Topic = topic, FromOffset = 2 }, token: TestContext.Current.CancellationToken); result.RecordsReplayed.ShouldBe(4); await waitForCountAsync(sink.Received, 4); @@ -82,9 +82,9 @@ public async Task replay_from_timestamp_reprocesses_only_records_after_it() await host.SendAsync(new HotTailMessage { Id = "old-1" }); await waitForCountAsync(sink.Received, 2); - await Task.Delay(1500); + await Task.Delay(1500, TestContext.Current.CancellationToken); var boundary = DateTimeOffset.UtcNow; - await Task.Delay(1500); + await Task.Delay(1500, TestContext.Current.CancellationToken); await host.SendAsync(new HotTailMessage { Id = "new-0" }); await host.SendAsync(new HotTailMessage { Id = "new-1" }); @@ -92,7 +92,7 @@ public async Task replay_from_timestamp_reprocesses_only_records_after_it() await waitForCountAsync(sink.Received, 5); sink.Received.Clear(); - var result = await host.ReplayKafkaTopicAsync(new KafkaReplayRequest { Topic = topic, FromTimestamp = boundary }); + var result = await host.ReplayKafkaTopicAsync(new KafkaReplayRequest { Topic = topic, FromTimestamp = boundary }, token: TestContext.Current.CancellationToken); result.RecordsReplayed.ShouldBe(3); await waitForCountAsync(sink.Received, 3); diff --git a/src/Transports/Kafka/Wolverine.Kafka.Tests/moving_unknown_cloudevents_type_to_dlq.cs b/src/Transports/Kafka/Wolverine.Kafka.Tests/moving_unknown_cloudevents_type_to_dlq.cs index fe6fd8665..0eef58826 100644 --- a/src/Transports/Kafka/Wolverine.Kafka.Tests/moving_unknown_cloudevents_type_to_dlq.cs +++ b/src/Transports/Kafka/Wolverine.Kafka.Tests/moving_unknown_cloudevents_type_to_dlq.cs @@ -73,8 +73,8 @@ public async Task cloudevents_message_with_unknown_type_should_be_dead_lettered( await producer.ProduceAsync(_topicName, new Message { Value = Encoding.UTF8.GetBytes(cloudEventsJson) - }); - producer.Flush(); + }, TestContext.Current.CancellationToken); + producer.Flush(TestContext.Current.CancellationToken); // Poll until the message appears in the dead letter queue var storage = _receiver.GetRuntime().Storage; @@ -89,7 +89,7 @@ public async Task cloudevents_message_with_unknown_type_should_be_dead_lettered( if (deadLetters.Envelopes.Any()) break; - await Task.Delay(1.Seconds()); + await Task.Delay(1.Seconds(), TestContext.Current.CancellationToken); } deadLetters.Envelopes.ShouldNotBeEmpty(); diff --git a/src/Transports/Kafka/Wolverine.Kafka.Tests/next_generation_rebalance_protocol.cs b/src/Transports/Kafka/Wolverine.Kafka.Tests/next_generation_rebalance_protocol.cs index d5bfe74c9..2183a0c62 100644 --- a/src/Transports/Kafka/Wolverine.Kafka.Tests/next_generation_rebalance_protocol.cs +++ b/src/Transports/Kafka/Wolverine.Kafka.Tests/next_generation_rebalance_protocol.cs @@ -169,7 +169,7 @@ public async Task end_to_end_round_trip_under_the_next_generation_protocol() opts.PublishMessage().ToKafkaTopic("kip848"); // BeginAtEarliest so a record produced before the group finishes joining is still consumed opts.ListenToKafkaTopic("kip848").BeginAtEarliest(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); await host.TrackActivity().IncludeExternalTransports().Timeout(60.Seconds()) .WaitForMessageToBeReceivedAt(host) @@ -223,7 +223,7 @@ public async Task conflicting_client_side_settings_are_cleared_at_bootstrap_and_ opts.ListenToKafkaTopic("kip848-override") .ConfigureConsumer(c => c.SessionTimeoutMs = 15000) .BeginAtEarliest(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); await host.TrackActivity().IncludeExternalTransports().Timeout(60.Seconds()) .WaitForMessageToBeReceivedAt(host) diff --git a/src/Transports/Kafka/Wolverine.Kafka.Tests/publish_and_receive_raw_json.cs b/src/Transports/Kafka/Wolverine.Kafka.Tests/publish_and_receive_raw_json.cs index 99e92f4ad..22d9118c6 100644 --- a/src/Transports/Kafka/Wolverine.Kafka.Tests/publish_and_receive_raw_json.cs +++ b/src/Transports/Kafka/Wolverine.Kafka.Tests/publish_and_receive_raw_json.cs @@ -149,13 +149,13 @@ public async Task do_not_go_into_infinite_loop_with_garbage_data() await producer.ProduceAsync("json", new Message { Value = "{garbage}" - }); - producer.Flush(); + }, TestContext.Current.CancellationToken); + producer.Flush(TestContext.Current.CancellationToken); // Wait long enough to detect any infinite retry loop, but not so long // it needlessly inflates CI run time. 30 seconds is sufficient — a tight // retry loop would exhaust resources well before then. - await Task.Delay(30.Seconds()); + await Task.Delay(30.Seconds(), TestContext.Current.CancellationToken); } public async ValueTask DisposeAsync() diff --git a/src/Transports/Kafka/Wolverine.Kafka.Tests/publish_raw_json_wire_format.cs b/src/Transports/Kafka/Wolverine.Kafka.Tests/publish_raw_json_wire_format.cs index 6b1a129eb..9f0a23941 100644 --- a/src/Transports/Kafka/Wolverine.Kafka.Tests/publish_raw_json_wire_format.cs +++ b/src/Transports/Kafka/Wolverine.Kafka.Tests/publish_raw_json_wire_format.cs @@ -29,7 +29,7 @@ public async Task raw_json_endpoints_actually_register_the_json_only_mapper() opts.PublishAllMessages().ToKafkaTopic("mapper-registration-out").PublishRawJson(); opts.Services.AddResourceSetupOnStartup(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.GetRuntime(); var transport = runtime.Options.Transports.GetOrCreate(); @@ -37,7 +37,7 @@ public async Task raw_json_endpoints_actually_register_the_json_only_mapper() transport.Topics["mapper-registration-in"].BuildMapper(runtime).ShouldBeOfType(); transport.Topics["mapper-registration-out"].BuildMapper(runtime).ShouldBeOfType(); - await host.StopAsync(); + await host.StopAsync(TestContext.Current.CancellationToken); } [Fact] @@ -55,7 +55,7 @@ public async Task published_records_carry_no_wolverine_headers_on_the_wire() opts.PublishAllMessages().ToKafkaTopic("clean-json").PublishRawJson(); opts.Services.AddResourceSetupOnStartup(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); // The topic may hold records from prior runs, so tag this run's message with a // unique color and scan for exactly that record. @@ -101,6 +101,6 @@ public async Task published_records_carry_no_wolverine_headers_on_the_wire() .Color.ShouldBe(color); consumer.Close(); - await host.StopAsync(); + await host.StopAsync(TestContext.Current.CancellationToken); } } diff --git a/src/Transports/Kafka/Wolverine.Kafka.Tests/raw_json_serializer_options.cs b/src/Transports/Kafka/Wolverine.Kafka.Tests/raw_json_serializer_options.cs index ef9d7d120..0bf9e683f 100644 --- a/src/Transports/Kafka/Wolverine.Kafka.Tests/raw_json_serializer_options.cs +++ b/src/Transports/Kafka/Wolverine.Kafka.Tests/raw_json_serializer_options.cs @@ -36,7 +36,7 @@ public async Task receive_raw_json_honors_the_supplied_options_for_deserializati opts.ListenToKafkaTopic(topic).ReceiveRawJson(options); opts.Services.AddResourceSetupOnStartup(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var transport = receiver.GetRuntime().Options.Transports.GetOrCreate(); var colorName = Guid.NewGuid().ToString(); @@ -59,7 +59,7 @@ public async Task receive_raw_json_honors_the_supplied_options_for_deserializati session.Received.SingleMessage() .ColorName.ShouldBe(colorName); - await receiver.StopAsync(); + await receiver.StopAsync(TestContext.Current.CancellationToken); } [Fact] @@ -79,7 +79,7 @@ public async Task publish_raw_json_honors_the_supplied_options_for_serialization .PublishRawJson(new JsonSerializerOptions()); opts.Services.AddResourceSetupOnStartup(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var colorName = Guid.NewGuid().ToString(); @@ -116,7 +116,7 @@ public async Task publish_raw_json_honors_the_supplied_options_for_serialization body.ShouldContain($"\"ColorName\":\"{colorName}\""); consumer.Close(); - await sender.StopAsync(); + await sender.StopAsync(TestContext.Current.CancellationToken); } } diff --git a/src/Transports/Kafka/Wolverine.Kafka.Tests/send_kafka_tombstone.cs b/src/Transports/Kafka/Wolverine.Kafka.Tests/send_kafka_tombstone.cs index 52f4ee725..6f850c0ee 100644 --- a/src/Transports/Kafka/Wolverine.Kafka.Tests/send_kafka_tombstone.cs +++ b/src/Transports/Kafka/Wolverine.Kafka.Tests/send_kafka_tombstone.cs @@ -38,7 +38,7 @@ public async Task send_tombstone_produces_message_with_null_value() await bus.BroadcastToTopicAsync(topicName, new KafkaTombstone(tombstoneKey)); // Give the batched sender time to flush - await Task.Delay(5.Seconds()); + await Task.Delay(5.Seconds(), TestContext.Current.CancellationToken); var consumerConfig = new ConsumerConfig { diff --git a/src/Transports/Kafka/Wolverine.Kafka.Tests/sticky_handlers_with_global_partitioning.cs b/src/Transports/Kafka/Wolverine.Kafka.Tests/sticky_handlers_with_global_partitioning.cs index b91c7c7db..901c2cfee 100644 --- a/src/Transports/Kafka/Wolverine.Kafka.Tests/sticky_handlers_with_global_partitioning.cs +++ b/src/Transports/Kafka/Wolverine.Kafka.Tests/sticky_handlers_with_global_partitioning.cs @@ -63,7 +63,7 @@ public async Task each_sticky_handler_executes_exactly_once_per_message() opts.Policies.PropagateGroupIdToPartitionKey(); opts.Services.AddResourceSetupOnStartup(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); // Publish a single message var message = new KafkaStickyCommand("group-1", "payload-1"); @@ -138,7 +138,7 @@ public async Task dual_publish_to_kafka_and_local_sticky_should_not_double_execu opts.Policies.PropagateGroupIdToPartitionKey(); opts.Services.AddResourceSetupOnStartup(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var message = new KafkaStickyCommand("group-1", "dual-payload"); @@ -148,7 +148,7 @@ public async Task dual_publish_to_kafka_and_local_sticky_should_not_double_execu await bus.PublishAsync(message); // Wait for handlers to process - await Task.Delay(10.Seconds()); + await Task.Delay(10.Seconds(), TestContext.Current.CancellationToken); _output.WriteLine($"Handler A executed {KafkaStickyHandlerA.ExecutionCount} times"); _output.WriteLine($"Handler B executed {KafkaStickyHandlerB.ExecutionCount} times"); @@ -202,7 +202,7 @@ public async Task multiple_messages_each_handled_exactly_once_per_handler() opts.Policies.PropagateGroupIdToPartitionKey(); opts.Services.AddResourceSetupOnStartup(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); // Send 3 messages for (int i = 0; i < 3; i++) diff --git a/src/Transports/MQTT/Wolverine.MQTT.Tests/Bugs/Bug_1634_not_using_default_serializer_correctly.cs b/src/Transports/MQTT/Wolverine.MQTT.Tests/Bugs/Bug_1634_not_using_default_serializer_correctly.cs index 5d41401f1..fc7acd870 100644 --- a/src/Transports/MQTT/Wolverine.MQTT.Tests/Bugs/Bug_1634_not_using_default_serializer_correctly.cs +++ b/src/Transports/MQTT/Wolverine.MQTT.Tests/Bugs/Bug_1634_not_using_default_serializer_correctly.cs @@ -20,7 +20,7 @@ public async Task try_it_out() opts.UseMqttWithLocalBroker() .ConfigureSenders(sub => sub.DefaultSerializer(new Serializer())); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.GetRuntime(); var topic = runtime.Options.Transports.GetOrCreate().Topics["One"]; diff --git a/src/Transports/MQTT/Wolverine.MQTT.Tests/Bugs/Bug_mapper_exception_routes_to_dlq.cs b/src/Transports/MQTT/Wolverine.MQTT.Tests/Bugs/Bug_mapper_exception_routes_to_dlq.cs index c9d4c1b2d..6fba265d1 100644 --- a/src/Transports/MQTT/Wolverine.MQTT.Tests/Bugs/Bug_mapper_exception_routes_to_dlq.cs +++ b/src/Transports/MQTT/Wolverine.MQTT.Tests/Bugs/Bug_mapper_exception_routes_to_dlq.cs @@ -58,8 +58,8 @@ public async Task unmappable_message_is_persisted_to_wolverine_dead_letters() .WithTcpServer(MosquittoContainerFixture.Host, MosquittoContainerFixture.Port) .Build(); - await client.ConnectAsync(options); - await client.PublishStringAsync(_topic, "hello"); + await client.ConnectAsync(options, TestContext.Current.CancellationToken); + await client.PublishStringAsync(_topic, "hello", cancellationToken: TestContext.Current.CancellationToken); var storage = _host.GetRuntime().Storage; @@ -77,7 +77,7 @@ public async Task unmappable_message_is_persisted_to_wolverine_dead_letters() } attempts++; - await Task.Delay(250.Milliseconds()); + await Task.Delay(250.Milliseconds(), TestContext.Current.CancellationToken); } throw new Exception( diff --git a/src/Transports/MQTT/Wolverine.MQTT.Tests/Wolverine.MQTT.Tests.csproj b/src/Transports/MQTT/Wolverine.MQTT.Tests/Wolverine.MQTT.Tests.csproj index 5f799b865..ab8c7f37d 100644 --- a/src/Transports/MQTT/Wolverine.MQTT.Tests/Wolverine.MQTT.Tests.csproj +++ b/src/Transports/MQTT/Wolverine.MQTT.Tests/Wolverine.MQTT.Tests.csproj @@ -1,6 +1,8 @@ + + true Exe false true diff --git a/src/Transports/MQTT/Wolverine.MQTT.Tests/ack_smoke_tests.cs b/src/Transports/MQTT/Wolverine.MQTT.Tests/ack_smoke_tests.cs index c5dd693b1..65f7949d8 100644 --- a/src/Transports/MQTT/Wolverine.MQTT.Tests/ack_smoke_tests.cs +++ b/src/Transports/MQTT/Wolverine.MQTT.Tests/ack_smoke_tests.cs @@ -56,7 +56,7 @@ public async Task send_zero_message() var bus = _sender.MessageBus(); await bus.BroadcastToTopicAsync("red", new ZeroMessage("Zero")); - await Task.Delay(2.Seconds()); + await Task.Delay(2.Seconds(), TestContext.Current.CancellationToken); } [Fact] @@ -65,7 +65,7 @@ public async Task send_ack_message() var bus = _sender.MessageBus(); await bus.BroadcastToTopicAsync("red", new TriggerZero("red")); - await Task.Delay(2.Seconds()); + await Task.Delay(2.Seconds(), TestContext.Current.CancellationToken); } public async ValueTask DisposeAsync() diff --git a/src/Transports/MQTT/Wolverine.MQTT.Tests/connectivity.cs b/src/Transports/MQTT/Wolverine.MQTT.Tests/connectivity.cs index 10979780d..281dff273 100644 --- a/src/Transports/MQTT/Wolverine.MQTT.Tests/connectivity.cs +++ b/src/Transports/MQTT/Wolverine.MQTT.Tests/connectivity.cs @@ -47,7 +47,7 @@ public async Task can_connect_to_a_local_broker() await managedClient.EnqueueAsync(topic: "Step", payload: "1", MqttQualityOfServiceLevel.AtLeastOnce, retain: true); await managedClient.EnqueueAsync(topic: "Step", payload: "2", MqttQualityOfServiceLevel.AtLeastOnce, retain: true); - await Task.Delay(3.Seconds()); + await Task.Delay(3.Seconds(), TestContext.Current.CancellationToken); await managedClient.SubscribeAsync(topic: "xyz", qualityOfServiceLevel: MqttQualityOfServiceLevel.AtMostOnce); await managedClient.SubscribeAsync(topic: "abc", qualityOfServiceLevel: MqttQualityOfServiceLevel.AtMostOnce); @@ -55,7 +55,7 @@ public async Task can_connect_to_a_local_broker() await managedClient.EnqueueAsync(topic: "Step", payload: "3"); - await Task.Delay(3.Seconds()); + await Task.Delay(3.Seconds(), TestContext.Current.CancellationToken); // var transport = new MqttTransport(); // transport.Configuration = builder => diff --git a/src/Transports/MQTT/Wolverine.MQTT.Tests/mqtt_per_tenant_broker_tests.cs b/src/Transports/MQTT/Wolverine.MQTT.Tests/mqtt_per_tenant_broker_tests.cs index 1f9c8e01e..d41aebd05 100644 --- a/src/Transports/MQTT/Wolverine.MQTT.Tests/mqtt_per_tenant_broker_tests.cs +++ b/src/Transports/MQTT/Wolverine.MQTT.Tests/mqtt_per_tenant_broker_tests.cs @@ -100,7 +100,7 @@ public async Task tenant_message_is_consumed_and_stamped_with_the_tenant_id() opts.Policies.DisableConventionalLocalRouting(); opts.PublishMessage().ToMqttTopic(topic).SendInline(); opts.ListenToMqttTopic(topic); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); // The default listener consumes broker A and the tenant listener consumes broker B; the message only // exists on broker B, so only the tenant listener consumes it and stamps the tenant id. diff --git a/src/Transports/MQTT/Wolverine.MQTT.Tests/named_broker_tests.cs b/src/Transports/MQTT/Wolverine.MQTT.Tests/named_broker_tests.cs index 07868358f..f2bd071c9 100644 --- a/src/Transports/MQTT/Wolverine.MQTT.Tests/named_broker_tests.cs +++ b/src/Transports/MQTT/Wolverine.MQTT.Tests/named_broker_tests.cs @@ -160,7 +160,7 @@ public async Task round_trips_a_message_over_the_named_broker() opts.Policies.DisableConventionalLocalRouting(); opts.PublishMessage().ToMqttTopicOnNamedBroker(theName, topic).SendInline(); opts.ListenToMqttTopicOnNamedBroker(theName, topic); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var session = await host .TrackActivity() @@ -192,7 +192,7 @@ public async Task request_reply_round_trips_over_the_named_broker() opts.Policies.DisableConventionalLocalRouting(); opts.PublishMessage().ToMqttTopicOnNamedBroker(theName, topic); opts.ListenToMqttTopicOnNamedBroker(theName, topic); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var (_, response) = await host .TrackActivity() diff --git a/src/Transports/MQTT/Wolverine.Mqtt5.Tests/Bugs/Bug_1634_not_using_default_serializer_correctly.cs b/src/Transports/MQTT/Wolverine.Mqtt5.Tests/Bugs/Bug_1634_not_using_default_serializer_correctly.cs index 5d41401f1..fc7acd870 100644 --- a/src/Transports/MQTT/Wolverine.Mqtt5.Tests/Bugs/Bug_1634_not_using_default_serializer_correctly.cs +++ b/src/Transports/MQTT/Wolverine.Mqtt5.Tests/Bugs/Bug_1634_not_using_default_serializer_correctly.cs @@ -20,7 +20,7 @@ public async Task try_it_out() opts.UseMqttWithLocalBroker() .ConfigureSenders(sub => sub.DefaultSerializer(new Serializer())); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.GetRuntime(); var topic = runtime.Options.Transports.GetOrCreate().Topics["One"]; diff --git a/src/Transports/MQTT/Wolverine.Mqtt5.Tests/Bugs/Bug_mapper_exception_routes_to_dlq.cs b/src/Transports/MQTT/Wolverine.Mqtt5.Tests/Bugs/Bug_mapper_exception_routes_to_dlq.cs index 75a854637..8b536b42b 100644 --- a/src/Transports/MQTT/Wolverine.Mqtt5.Tests/Bugs/Bug_mapper_exception_routes_to_dlq.cs +++ b/src/Transports/MQTT/Wolverine.Mqtt5.Tests/Bugs/Bug_mapper_exception_routes_to_dlq.cs @@ -57,8 +57,8 @@ public async Task unmappable_message_is_persisted_to_wolverine_dead_letters() .WithTcpServer(MosquittoContainerFixture.Host, MosquittoContainerFixture.Port) .Build(); - await client.ConnectAsync(options); - await client.PublishStringAsync(_topic, "hello"); + await client.ConnectAsync(options, TestContext.Current.CancellationToken); + await client.PublishStringAsync(_topic, "hello", cancellationToken: TestContext.Current.CancellationToken); var storage = _host.GetRuntime().Storage; @@ -76,7 +76,7 @@ public async Task unmappable_message_is_persisted_to_wolverine_dead_letters() } attempts++; - await Task.Delay(250.Milliseconds()); + await Task.Delay(250.Milliseconds(), TestContext.Current.CancellationToken); } throw new Exception( diff --git a/src/Transports/MQTT/Wolverine.Mqtt5.Tests/Wolverine.Mqtt5.Tests.csproj b/src/Transports/MQTT/Wolverine.Mqtt5.Tests/Wolverine.Mqtt5.Tests.csproj index dd1c17126..0d3e168c4 100644 --- a/src/Transports/MQTT/Wolverine.Mqtt5.Tests/Wolverine.Mqtt5.Tests.csproj +++ b/src/Transports/MQTT/Wolverine.Mqtt5.Tests/Wolverine.Mqtt5.Tests.csproj @@ -1,6 +1,8 @@ + + true Exe false true diff --git a/src/Transports/MQTT/Wolverine.Mqtt5.Tests/ack_smoke_tests.cs b/src/Transports/MQTT/Wolverine.Mqtt5.Tests/ack_smoke_tests.cs index c5dd693b1..65f7949d8 100644 --- a/src/Transports/MQTT/Wolverine.Mqtt5.Tests/ack_smoke_tests.cs +++ b/src/Transports/MQTT/Wolverine.Mqtt5.Tests/ack_smoke_tests.cs @@ -56,7 +56,7 @@ public async Task send_zero_message() var bus = _sender.MessageBus(); await bus.BroadcastToTopicAsync("red", new ZeroMessage("Zero")); - await Task.Delay(2.Seconds()); + await Task.Delay(2.Seconds(), TestContext.Current.CancellationToken); } [Fact] @@ -65,7 +65,7 @@ public async Task send_ack_message() var bus = _sender.MessageBus(); await bus.BroadcastToTopicAsync("red", new TriggerZero("red")); - await Task.Delay(2.Seconds()); + await Task.Delay(2.Seconds(), TestContext.Current.CancellationToken); } public async ValueTask DisposeAsync() diff --git a/src/Transports/MQTT/Wolverine.Mqtt5.Tests/connectivity.cs b/src/Transports/MQTT/Wolverine.Mqtt5.Tests/connectivity.cs index 95b4ee3d9..ba8f53c79 100644 --- a/src/Transports/MQTT/Wolverine.Mqtt5.Tests/connectivity.cs +++ b/src/Transports/MQTT/Wolverine.Mqtt5.Tests/connectivity.cs @@ -60,7 +60,7 @@ await managedClient.StartAsync(new ManagedMqttClientOptionsBuilder() await broker.StartAsync(); await waitUntilAsync(() => managedClient.IsConnected, 10.Seconds()); - var completed = await Task.WhenAny(received.Task, Task.Delay(10.Seconds())); + var completed = await Task.WhenAny(received.Task, Task.Delay(10.Seconds(), TestContext.Current.CancellationToken)); completed.ShouldBe(received.Task); } @@ -92,7 +92,7 @@ public async Task can_connect_to_a_local_broker() await managedClient.EnqueueAsync(topic: "Step", payload: "1", MqttQualityOfServiceLevel.AtLeastOnce, retain: true); await managedClient.EnqueueAsync(topic: "Step", payload: "2", MqttQualityOfServiceLevel.AtLeastOnce, retain: true); - await Task.Delay(3.Seconds()); + await Task.Delay(3.Seconds(), TestContext.Current.CancellationToken); await managedClient.SubscribeAsync(topic: "xyz", qualityOfServiceLevel: MqttQualityOfServiceLevel.AtMostOnce); await managedClient.SubscribeAsync(topic: "abc", qualityOfServiceLevel: MqttQualityOfServiceLevel.AtMostOnce); @@ -100,7 +100,7 @@ public async Task can_connect_to_a_local_broker() await managedClient.EnqueueAsync(topic: "Step", payload: "3"); - await Task.Delay(3.Seconds()); + await Task.Delay(3.Seconds(), TestContext.Current.CancellationToken); // var transport = new MqttTransport(); // transport.Configuration = builder => diff --git a/src/Transports/MQTT/Wolverine.Mqtt5.Tests/mqtt_per_tenant_broker_tests.cs b/src/Transports/MQTT/Wolverine.Mqtt5.Tests/mqtt_per_tenant_broker_tests.cs index 1f9c8e01e..d41aebd05 100644 --- a/src/Transports/MQTT/Wolverine.Mqtt5.Tests/mqtt_per_tenant_broker_tests.cs +++ b/src/Transports/MQTT/Wolverine.Mqtt5.Tests/mqtt_per_tenant_broker_tests.cs @@ -100,7 +100,7 @@ public async Task tenant_message_is_consumed_and_stamped_with_the_tenant_id() opts.Policies.DisableConventionalLocalRouting(); opts.PublishMessage().ToMqttTopic(topic).SendInline(); opts.ListenToMqttTopic(topic); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); // The default listener consumes broker A and the tenant listener consumes broker B; the message only // exists on broker B, so only the tenant listener consumes it and stamps the tenant id. diff --git a/src/Transports/MQTT/Wolverine.Mqtt5.Tests/named_broker_tests.cs b/src/Transports/MQTT/Wolverine.Mqtt5.Tests/named_broker_tests.cs index 6118479bc..97bfeb4c6 100644 --- a/src/Transports/MQTT/Wolverine.Mqtt5.Tests/named_broker_tests.cs +++ b/src/Transports/MQTT/Wolverine.Mqtt5.Tests/named_broker_tests.cs @@ -161,7 +161,7 @@ public async Task round_trips_a_message_over_the_named_broker() opts.Policies.DisableConventionalLocalRouting(); opts.PublishMessage().ToMqttTopicOnNamedBroker(theName, topic).SendInline(); opts.ListenToMqttTopicOnNamedBroker(theName, topic); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var session = await host .TrackActivity() @@ -193,7 +193,7 @@ public async Task request_reply_round_trips_over_the_named_broker() opts.Policies.DisableConventionalLocalRouting(); opts.PublishMessage().ToMqttTopicOnNamedBroker(theName, topic); opts.ListenToMqttTopicOnNamedBroker(theName, topic); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var (_, response) = await host .TrackActivity() diff --git a/src/Transports/NATS/Wolverine.Nats.Tests/NatsDynamicSubjectTenancyTests.cs b/src/Transports/NATS/Wolverine.Nats.Tests/NatsDynamicSubjectTenancyTests.cs index 10de1d10e..1dbab4096 100644 --- a/src/Transports/NATS/Wolverine.Nats.Tests/NatsDynamicSubjectTenancyTests.cs +++ b/src/Transports/NATS/Wolverine.Nats.Tests/NatsDynamicSubjectTenancyTests.cs @@ -53,7 +53,7 @@ public async Task dynamic_subject_is_tenant_qualified_for_subject_isolation_tena opts.Policies.DisableConventionalLocalRouting(); opts.PublishMessagesToNatsSubject(m => $"{root}.{m.OrderId}").SendInline(); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); // Each tenant's dynamic subject must be tenant-qualified: {tenantId}.{computed subject}. await using var subA = await NatsTestHelpers.SubscribeRawAsync(url, $"tenantA.{root}.{orderId}"); diff --git a/src/Transports/NATS/Wolverine.Nats.Tests/NatsDynamicSubjectTests.cs b/src/Transports/NATS/Wolverine.Nats.Tests/NatsDynamicSubjectTests.cs index ac85077cb..96b49aaa2 100644 --- a/src/Transports/NATS/Wolverine.Nats.Tests/NatsDynamicSubjectTests.cs +++ b/src/Transports/NATS/Wolverine.Nats.Tests/NatsDynamicSubjectTests.cs @@ -200,7 +200,7 @@ public async Task subject_resolver_escape_hatch_rewrites_the_subject_from_envelo opts.UseNats(_natsUrl).AutoProvision(); opts.ListenToNatsSubject($"{root}.>").Named("resolver-wildcard"); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); using var sender = await Host.CreateDefaultBuilder() .ConfigureLogging(logging => logging.AddXunitLogging(_output)) @@ -218,7 +218,7 @@ public async Task subject_resolver_escape_hatch_rewrites_the_subject_from_envelo opts.Policies.DisableConventionalLocalRouting(); opts.PublishMessage().ToNatsSubject(baseSubject).SendInline(); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); await using var raw = await NatsTestHelpers.SubscribeRawAsync(_natsUrl, expectedSubject); @@ -259,7 +259,7 @@ public async Task subject_resolver_output_is_normalized() opts.UseNats(_natsUrl).AutoProvision(); opts.ListenToNatsSubject($"{root}.>").Named("normalize-wildcard"); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); using var sender = await Host.CreateDefaultBuilder() .ConfigureLogging(logging => logging.AddXunitLogging(_output)) @@ -275,7 +275,7 @@ public async Task subject_resolver_output_is_normalized() opts.Policies.DisableConventionalLocalRouting(); opts.PublishMessage().ToNatsSubject(baseSubject).SendInline(); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); await using var raw = await NatsTestHelpers.SubscribeRawAsync(_natsUrl, expectedSubject); diff --git a/src/Transports/NATS/Wolverine.Nats.Tests/NatsJetStreamConsumerFilterTests.cs b/src/Transports/NATS/Wolverine.Nats.Tests/NatsJetStreamConsumerFilterTests.cs index 097d6584c..bb19440d6 100644 --- a/src/Transports/NATS/Wolverine.Nats.Tests/NatsJetStreamConsumerFilterTests.cs +++ b/src/Transports/NATS/Wolverine.Nats.Tests/NatsJetStreamConsumerFilterTests.cs @@ -54,7 +54,7 @@ public async Task auto_provisioned_durable_consumers_are_filtered_to_their_own_s opts.ListenToNatsSubject(subjectA).UseJetStream(stream, $"consumer-a-{id}"); opts.ListenToNatsSubject(subjectB).UseJetStream(stream, $"consumer-b-{id}"); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); await using var connection = new NatsConnection(new NatsOpts { Url = natsUrl }); await connection.ConnectAsync(); @@ -62,10 +62,10 @@ public async Task auto_provisioned_durable_consumers_are_filtered_to_their_own_s // Each durable consumer must be scoped to the subject its listener was bound to. // Before the fix both came back with a null FilterSubject - var consumerA = await js.GetConsumerAsync(stream, $"consumer-a-{id}"); + var consumerA = await js.GetConsumerAsync(stream, $"consumer-a-{id}", TestContext.Current.CancellationToken); consumerA.Info.Config.FilterSubject.ShouldBe(subjectA); - var consumerB = await js.GetConsumerAsync(stream, $"consumer-b-{id}"); + var consumerB = await js.GetConsumerAsync(stream, $"consumer-b-{id}", TestContext.Current.CancellationToken); consumerB.Info.Config.FilterSubject.ShouldBe(subjectB); } @@ -91,7 +91,7 @@ public async Task a_scheduling_enabled_consumer_also_owns_its_schedule_subject() opts.Policies.DisableConventionalLocalRouting(); opts.ListenToNatsSubject(subject).UseJetStream(stream, $"sched-consumer-{id}"); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var transport = host.Services.GetRequiredService() .Options.Transports.GetOrCreate(); @@ -105,7 +105,7 @@ public async Task a_scheduling_enabled_consumer_also_owns_its_schedule_subject() // filter covers both that and "{subject}", and on a work queue stream a control message no // consumer covers is discarded, so the scheduled send silently never arrives. The consumer // therefore has to carry both subjects - var consumer = await js.GetConsumerAsync(stream, $"sched-consumer-{id}"); + var consumer = await js.GetConsumerAsync(stream, $"sched-consumer-{id}", TestContext.Current.CancellationToken); consumer.Info.Config.FilterSubjects.ShouldBe([subject, $"{subject}.scheduled"]); } @@ -141,7 +141,7 @@ public async Task a_message_only_reaches_the_consumer_whose_subject_matches() opts.PublishMessage().ToNatsSubject(subjectA).UseJetStream(stream) .SendInline(); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); await host.MessageBus().SendAsync(new FilteredMessage(id)); diff --git a/src/Transports/NATS/Wolverine.Nats.Tests/NatsJetStreamDedupTests.cs b/src/Transports/NATS/Wolverine.Nats.Tests/NatsJetStreamDedupTests.cs index 1284fc204..6b7869cd5 100644 --- a/src/Transports/NATS/Wolverine.Nats.Tests/NatsJetStreamDedupTests.cs +++ b/src/Transports/NATS/Wolverine.Nats.Tests/NatsJetStreamDedupTests.cs @@ -55,7 +55,7 @@ public async Task same_domain_msg_id_is_deduplicated_by_the_stream() opts.Policies.DisableConventionalLocalRouting(); opts.PublishMessage().ToNatsSubject(subject).UseJetStream(stream).SendInline(); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var bus = host.MessageBus(); var orderId = Guid.NewGuid().ToString("N"); @@ -90,7 +90,7 @@ public async Task explicit_nats_msg_id_header_is_honored_for_dedup() opts.Policies.DisableConventionalLocalRouting(); opts.PublishMessage().ToNatsSubject(subject).UseJetStream(stream).SendInline(); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var bus = host.MessageBus(); var fixedMsgId = Guid.NewGuid().ToString("N"); @@ -128,7 +128,7 @@ public async Task distinct_messages_are_not_deduplicated_with_default_envelope_i opts.Policies.DisableConventionalLocalRouting(); opts.PublishMessage().ToNatsSubject(subject).UseJetStream(stream).SendInline(); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var bus = host.MessageBus(); diff --git a/src/Transports/NATS/Wolverine.Nats.Tests/NatsNamedBrokerTests.cs b/src/Transports/NATS/Wolverine.Nats.Tests/NatsNamedBrokerTests.cs index 25fc8cb13..d527e9d67 100644 --- a/src/Transports/NATS/Wolverine.Nats.Tests/NatsNamedBrokerTests.cs +++ b/src/Transports/NATS/Wolverine.Nats.Tests/NatsNamedBrokerTests.cs @@ -183,7 +183,7 @@ public async Task round_trips_a_message_over_the_named_broker() opts.PublishMessage().ToNatsSubjectOnNamedBroker(theName, subject).SendInline(); opts.ListenToNatsSubjectOnNamedBroker(theName, subject); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var session = await host .TrackActivity() @@ -219,7 +219,7 @@ public async Task request_reply_round_trips_over_the_named_broker() opts.PublishMessage().ToNatsSubjectOnNamedBroker(theName, subject); opts.ListenToNatsSubjectOnNamedBroker(theName, subject); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var (_, response) = await host .TrackActivity() diff --git a/src/Transports/NATS/Wolverine.Nats.Tests/NatsPerTenantConnectionTests.cs b/src/Transports/NATS/Wolverine.Nats.Tests/NatsPerTenantConnectionTests.cs index 748bf9c4d..7b52059bb 100644 --- a/src/Transports/NATS/Wolverine.Nats.Tests/NatsPerTenantConnectionTests.cs +++ b/src/Transports/NATS/Wolverine.Nats.Tests/NatsPerTenantConnectionTests.cs @@ -138,7 +138,7 @@ public async Task tenant_message_is_consumed_over_the_tenants_own_connection() opts.PublishMessage().ToNatsSubject(baseSubject).SendInline(); opts.ListenToNatsSubject(baseSubject); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); // Single host both sends and receives via the broker, so explicitly wait for the round-trip receipt // rather than just the send settling. @@ -177,13 +177,13 @@ public async Task streams_are_auto_provisioned_over_a_tenants_own_connection() .DefineStream(streamName, s => s.WithSubjects($"{subject}.>")) .AddTenant("tenantB", cfg => cfg.ConnectionString = _serverBUrl); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); // Prove the stream was actually created on server B (the tenant's own server), not just server A. // GetStreamAsync throws if the stream is absent, so a broken provisioning path fails the test. await using var connToB = new NatsConnection(new NatsOpts { Url = _serverBUrl }); await connToB.ConnectAsync(); - var streamOnB = await connToB.CreateJetStreamContext().GetStreamAsync(streamName); + var streamOnB = await connToB.CreateJetStreamContext().GetStreamAsync(streamName, cancellationToken: TestContext.Current.CancellationToken); streamOnB.ShouldNotBeNull(); } diff --git a/src/Transports/NATS/Wolverine.Nats.Tests/NatsTransportIntegrationTests.cs b/src/Transports/NATS/Wolverine.Nats.Tests/NatsTransportIntegrationTests.cs index f278ca87a..6be69ede2 100644 --- a/src/Transports/NATS/Wolverine.Nats.Tests/NatsTransportIntegrationTests.cs +++ b/src/Transports/NATS/Wolverine.Nats.Tests/NatsTransportIntegrationTests.cs @@ -202,7 +202,7 @@ public async Task receive_message_without_type_header_using_default_incoming_mes .DefaultIncomingMessage() .BufferedInMemory(); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); await using var nats = new NatsConnection(new NatsOpts { Url = natsUrl }); await nats.ConnectAsync(); diff --git a/src/Transports/NATS/Wolverine.Nats.Tests/RequestReplyTests.cs b/src/Transports/NATS/Wolverine.Nats.Tests/RequestReplyTests.cs index aa52c21da..85840cbec 100644 --- a/src/Transports/NATS/Wolverine.Nats.Tests/RequestReplyTests.cs +++ b/src/Transports/NATS/Wolverine.Nats.Tests/RequestReplyTests.cs @@ -103,10 +103,8 @@ public async Task throws_unknown_endpoint_exception_for_invalid_endpoint() await Assert.ThrowsAsync(async () => { await bus.EndpointFor("nats://nonexistent.subject") - .InvokeAsync( - new PingMessage { Name = "NoEndpoint" }, - timeout: TimeSpan.FromSeconds(1) - ); + .InvokeAsync(new PingMessage { Name = "NoEndpoint" }, + cancellation: TestContext.Current.CancellationToken); }); } } diff --git a/src/Transports/NATS/Wolverine.Nats.Tests/Wolverine.Nats.Tests.csproj b/src/Transports/NATS/Wolverine.Nats.Tests/Wolverine.Nats.Tests.csproj index e4161bffc..52a3966fc 100644 --- a/src/Transports/NATS/Wolverine.Nats.Tests/Wolverine.Nats.Tests.csproj +++ b/src/Transports/NATS/Wolverine.Nats.Tests/Wolverine.Nats.Tests.csproj @@ -1,6 +1,8 @@  + + true Exe false true diff --git a/src/Transports/NATS/Wolverine.Nats.Tests/connection_state_3231.cs b/src/Transports/NATS/Wolverine.Nats.Tests/connection_state_3231.cs index a1182704d..c6d45dfa8 100644 --- a/src/Transports/NATS/Wolverine.Nats.Tests/connection_state_3231.cs +++ b/src/Transports/NATS/Wolverine.Nats.Tests/connection_state_3231.cs @@ -24,7 +24,7 @@ public async Task healthy_nats_listener_reports_connected() { opts.UseNats(_fixture.ConnectionString); opts.ListenToNatsSubject(subject); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var state = await ConnectionStateTestHelpers.WaitForListenerConnectionStateAsync( host, "nats", TransportConnectionState.Connected); diff --git a/src/Transports/Pulsar/Wolverine.Pulsar.Tests/PulsarListenerTests.cs b/src/Transports/Pulsar/Wolverine.Pulsar.Tests/PulsarListenerTests.cs index ca49799b4..f175ed20a 100644 --- a/src/Transports/Pulsar/Wolverine.Pulsar.Tests/PulsarListenerTests.cs +++ b/src/Transports/Pulsar/Wolverine.Pulsar.Tests/PulsarListenerTests.cs @@ -20,11 +20,11 @@ public async Task UnsubscribeOnClose() var topic = "persistent://public/default/test"; opts.PublishMessage().ToPulsarTopic(topic); opts.ListenToPulsarTopic(topic).SubscriptionName("test"); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); await host.MessageBus().PublishAsync(new PulsarListenerTestMessage()); - await host.StopAsync(); + await host.StopAsync(TestContext.Current.CancellationToken); host.Dispose(); var subscriptionExists = await SubscriptionExists(); @@ -43,11 +43,11 @@ public async Task KeepSubscriptionOnClose() var topic = "persistent://public/default/test"; opts.PublishMessage().ToPulsarTopic(topic); opts.ListenToPulsarTopic(topic).SubscriptionName("test"); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); await host.MessageBus()!.PublishAsync(new PulsarListenerTestMessage()); - await host.StopAsync(); + await host.StopAsync(TestContext.Current.CancellationToken); host.Dispose(); var subscriptionExists = await SubscriptionExists(); diff --git a/src/Transports/Pulsar/Wolverine.Pulsar.Tests/PulsarNamedBrokerIntegrationTests.cs b/src/Transports/Pulsar/Wolverine.Pulsar.Tests/PulsarNamedBrokerIntegrationTests.cs index 8113639fb..f88ac3aa8 100644 --- a/src/Transports/Pulsar/Wolverine.Pulsar.Tests/PulsarNamedBrokerIntegrationTests.cs +++ b/src/Transports/Pulsar/Wolverine.Pulsar.Tests/PulsarNamedBrokerIntegrationTests.cs @@ -42,7 +42,7 @@ public async Task round_trips_a_message_over_the_named_broker() opts.Discovery.DisableConventionalDiscovery().IncludeType(); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var session = await host .TrackActivity() diff --git a/src/Transports/Pulsar/Wolverine.Pulsar.Tests/PulsarPerTenantConfigurationTests.cs b/src/Transports/Pulsar/Wolverine.Pulsar.Tests/PulsarPerTenantConfigurationTests.cs index 05bdb58ce..04ac4e738 100644 --- a/src/Transports/Pulsar/Wolverine.Pulsar.Tests/PulsarPerTenantConfigurationTests.cs +++ b/src/Transports/Pulsar/Wolverine.Pulsar.Tests/PulsarPerTenantConfigurationTests.cs @@ -93,7 +93,7 @@ public async Task tenant_aware_endpoint_resolves_a_TenantedSender() opts.PublishMessage() .ToPulsarTopic("persistent://public/default/tenant-colors"); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.GetRuntime(); var transport = runtime.Options.Transports.GetOrCreate(); diff --git a/src/Transports/Pulsar/Wolverine.Pulsar.Tests/PulsarPerTenantConnectionTests.cs b/src/Transports/Pulsar/Wolverine.Pulsar.Tests/PulsarPerTenantConnectionTests.cs index 5040ae0fe..ca24878b4 100644 --- a/src/Transports/Pulsar/Wolverine.Pulsar.Tests/PulsarPerTenantConnectionTests.cs +++ b/src/Transports/Pulsar/Wolverine.Pulsar.Tests/PulsarPerTenantConnectionTests.cs @@ -89,7 +89,7 @@ public async Task tenant_message_is_consumed_and_stamped_with_the_tenant_id() opts.Discovery.DisableConventionalDiscovery().IncludeType(); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var session = await host .TrackActivity() diff --git a/src/Transports/Pulsar/Wolverine.Pulsar.Tests/Wolverine.Pulsar.Tests.csproj b/src/Transports/Pulsar/Wolverine.Pulsar.Tests/Wolverine.Pulsar.Tests.csproj index 824973369..6b654c508 100644 --- a/src/Transports/Pulsar/Wolverine.Pulsar.Tests/Wolverine.Pulsar.Tests.csproj +++ b/src/Transports/Pulsar/Wolverine.Pulsar.Tests/Wolverine.Pulsar.Tests.csproj @@ -1,6 +1,8 @@ + + true Exe false diff --git a/src/Transports/Pulsar/Wolverine.Pulsar.Tests/acknowledgment_strategy.cs b/src/Transports/Pulsar/Wolverine.Pulsar.Tests/acknowledgment_strategy.cs index 6687bf6ed..23686a9a2 100644 --- a/src/Transports/Pulsar/Wolverine.Pulsar.Tests/acknowledgment_strategy.cs +++ b/src/Transports/Pulsar/Wolverine.Pulsar.Tests/acknowledgment_strategy.cs @@ -185,7 +185,7 @@ public async Task batched_acknowledgment_delivers_all_messages() var cutoff = DateTimeOffset.UtcNow.AddSeconds(30); while (DateTimeOffset.UtcNow < cutoff && sink.Received.Count < 5) { - await Task.Delay(100); + await Task.Delay(100, TestContext.Current.CancellationToken); } sink.Received.OrderBy(x => x).ShouldBe(["m-0", "m-1", "m-2", "m-3", "m-4"]); diff --git a/src/Transports/Pulsar/Wolverine.Pulsar.Tests/connection_state_3231.cs b/src/Transports/Pulsar/Wolverine.Pulsar.Tests/connection_state_3231.cs index e46738043..52d6c25f0 100644 --- a/src/Transports/Pulsar/Wolverine.Pulsar.Tests/connection_state_3231.cs +++ b/src/Transports/Pulsar/Wolverine.Pulsar.Tests/connection_state_3231.cs @@ -21,7 +21,7 @@ public async Task healthy_pulsar_listener_reports_connected() { opts.UsePulsar(b => b.ServiceUrl(PulsarContainerFixture.ServiceUrl)); opts.ListenToPulsarTopic(topic); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var state = await ConnectionStateTestHelpers.WaitForListenerConnectionStateAsync( host, "pulsar", TransportConnectionState.Connected); diff --git a/src/Transports/Pulsar/Wolverine.Pulsar.Tests/pulsar_hot_tail.cs b/src/Transports/Pulsar/Wolverine.Pulsar.Tests/pulsar_hot_tail.cs index 4930fe23d..272fc71a8 100644 --- a/src/Transports/Pulsar/Wolverine.Pulsar.Tests/pulsar_hot_tail.cs +++ b/src/Transports/Pulsar/Wolverine.Pulsar.Tests/pulsar_hot_tail.cs @@ -65,7 +65,7 @@ public async Task hot_tail_delivers_all_tail_messages_to_every_node_and_never_re using var nodeB = await hotTailNodeAsync(topic); // Latest means only messages published AFTER the readers attach are seen — give them a moment. - await Task.Delay(3.Seconds()); + await Task.Delay(3.Seconds(), TestContext.Current.CancellationToken); for (var i = 0; i < 5; i++) { diff --git a/src/Transports/Pulsar/Wolverine.Pulsar.Tests/pulsar_replay.cs b/src/Transports/Pulsar/Wolverine.Pulsar.Tests/pulsar_replay.cs index a14cba371..1fffcd353 100644 --- a/src/Transports/Pulsar/Wolverine.Pulsar.Tests/pulsar_replay.cs +++ b/src/Transports/Pulsar/Wolverine.Pulsar.Tests/pulsar_replay.cs @@ -60,7 +60,7 @@ public async Task replay_reprocesses_the_whole_topic_without_touching_the_live_s using var replayer = await replayerAsync(); var replaySink = replayer.Services.GetRequiredService(); - var result = await replayer.ReplayPulsarTopicAsync(new PulsarReplayRequest { Topic = topic }); + var result = await replayer.ReplayPulsarTopicAsync(new PulsarReplayRequest { Topic = topic }, token: TestContext.Current.CancellationToken); result.MessagesReplayed.ShouldBe(6); await waitForCountAsync(replaySink.Received, 6); @@ -85,9 +85,9 @@ public async Task replay_from_timestamp_reprocesses_only_messages_after_it() await publisher.SendAsync(new ReplayMessage { Id = "old-0" }); await publisher.SendAsync(new ReplayMessage { Id = "old-1" }); - await Task.Delay(1500); + await Task.Delay(1500, TestContext.Current.CancellationToken); var boundary = DateTimeOffset.UtcNow; - await Task.Delay(1500); + await Task.Delay(1500, TestContext.Current.CancellationToken); await publisher.SendAsync(new ReplayMessage { Id = "new-0" }); await publisher.SendAsync(new ReplayMessage { Id = "new-1" }); @@ -100,7 +100,7 @@ public async Task replay_from_timestamp_reprocesses_only_messages_after_it() { Topic = topic, FromTimestamp = boundary - }); + }, token: TestContext.Current.CancellationToken); result.MessagesReplayed.ShouldBe(3); await waitForCountAsync(replaySink.Received, 3); @@ -116,7 +116,7 @@ public async Task replay_of_empty_topic_returns_zero() using var publisher = await publisherAsync(topic); using var replayer = await replayerAsync(); - var result = await replayer.ReplayPulsarTopicAsync(new PulsarReplayRequest { Topic = topic }); + var result = await replayer.ReplayPulsarTopicAsync(new PulsarReplayRequest { Topic = topic }, token: TestContext.Current.CancellationToken); result.MessagesReplayed.ShouldBe(0); } diff --git a/src/Transports/Pulsar/Wolverine.Pulsar.Tests/subscription_initial_position.cs b/src/Transports/Pulsar/Wolverine.Pulsar.Tests/subscription_initial_position.cs index b24909638..bfcbfb3b0 100644 --- a/src/Transports/Pulsar/Wolverine.Pulsar.Tests/subscription_initial_position.cs +++ b/src/Transports/Pulsar/Wolverine.Pulsar.Tests/subscription_initial_position.cs @@ -120,7 +120,7 @@ public async Task latest_consumes_only_messages_published_after_the_subscription }); // Give the subscription time to be established before publishing the "post" messages. - await Task.Delay(3.Seconds()); + await Task.Delay(3.Seconds(), TestContext.Current.CancellationToken); for (var i = 0; i < 3; i++) { diff --git a/src/Transports/RabbitMQ/ChaosTesting/ChaosTesting.csproj b/src/Transports/RabbitMQ/ChaosTesting/ChaosTesting.csproj index 1e135cb18..37896db75 100644 --- a/src/Transports/RabbitMQ/ChaosTesting/ChaosTesting.csproj +++ b/src/Transports/RabbitMQ/ChaosTesting/ChaosTesting.csproj @@ -1,6 +1,8 @@ + + true Exe false diff --git a/src/Transports/RabbitMQ/CircuitBreakingTests/CircuitBreakerIntegrationContext.cs b/src/Transports/RabbitMQ/CircuitBreakingTests/CircuitBreakerIntegrationContext.cs index 51c4f3747..f818190ae 100644 --- a/src/Transports/RabbitMQ/CircuitBreakingTests/CircuitBreakerIntegrationContext.cs +++ b/src/Transports/RabbitMQ/CircuitBreakingTests/CircuitBreakerIntegrationContext.cs @@ -183,7 +183,7 @@ public virtual async Task the_circuit_breaker_should_trip_and_restart() { await Task.Delay(10.Seconds()); _recorder.NeverFail = true; - }); + }, TestContext.Current.CancellationToken); delayPublishHundredMessages(5.Seconds(), 5); delayPublishHundredMessages(10.Seconds(), 5); diff --git a/src/Transports/RabbitMQ/CircuitBreakingTests/CircuitBreakingTests.csproj b/src/Transports/RabbitMQ/CircuitBreakingTests/CircuitBreakingTests.csproj index f3708b6b6..130226c5a 100644 --- a/src/Transports/RabbitMQ/CircuitBreakingTests/CircuitBreakingTests.csproj +++ b/src/Transports/RabbitMQ/CircuitBreakingTests/CircuitBreakingTests.csproj @@ -1,6 +1,8 @@  + + true Exe false diff --git a/src/Transports/RabbitMQ/CircuitBreakingTests/RabbitMq/back_pressure_tripping_off.cs b/src/Transports/RabbitMQ/CircuitBreakingTests/RabbitMq/back_pressure_tripping_off.cs index f5ccf5948..e7d4ee729 100644 --- a/src/Transports/RabbitMQ/CircuitBreakingTests/RabbitMq/back_pressure_tripping_off.cs +++ b/src/Transports/RabbitMQ/CircuitBreakingTests/RabbitMq/back_pressure_tripping_off.cs @@ -76,7 +76,7 @@ await publisher.EndpointFor("incoming") .SendAsync(message); recorder.TrackPublished(message.Id); } - }); + }, TestContext.Current.CancellationToken); await waitForTooBusy; diff --git a/src/Transports/RabbitMQ/CircuitBreakingTests/stopping_and_starting_listeners.cs b/src/Transports/RabbitMQ/CircuitBreakingTests/stopping_and_starting_listeners.cs index f0694fedb..f79a6f191 100644 --- a/src/Transports/RabbitMQ/CircuitBreakingTests/stopping_and_starting_listeners.cs +++ b/src/Transports/RabbitMQ/CircuitBreakingTests/stopping_and_starting_listeners.cs @@ -154,7 +154,7 @@ public async Task pause_listener_on_matching_error_condition() { opts.Durability.Mode = DurabilityMode.Solo; opts.PublishAllMessages().ToPort(_port1).Named("one"); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = theListener.GetRuntime(); diff --git a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_1594_ReplayDeadLetterQueue.cs b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_1594_ReplayDeadLetterQueue.cs index 534d0d083..0bdc8a0cb 100644 --- a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_1594_ReplayDeadLetterQueue.cs +++ b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_1594_ReplayDeadLetterQueue.cs @@ -50,13 +50,13 @@ public async Task can_replay_dead_letter_message(EndpointMode mode) opts.ListenToRabbitQueue(queueName, q => q.As().Mode = mode); opts.Services.AddResourceSetupOnStartup(StartupAction.ResetState); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); - await host.ResetResourceState(); + await host.ResetResourceState(cancellation: TestContext.Current.CancellationToken); await host.MessageBus().PublishAsync(new ReplayTestMessage()); - await Task.Delay(1000); + await Task.Delay(1000, TestContext.Current.CancellationToken); var messageStore = host.Services.GetRequiredService(); var deadLetterQuery = new DeadLetterEnvelopeQuery { PageSize = 10 }; @@ -70,7 +70,7 @@ public async Task can_replay_dead_letter_message(EndpointMode mode) deadLetterId = deadLetterResults.Envelopes.First().Id; break; } - await Task.Delay(100); + await Task.Delay(100, TestContext.Current.CancellationToken); } deadLetterId.ShouldNotBeNull("Message should be in DLQ after failure"); diff --git a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_1684_separated_handlers_and_conventional_routing.cs b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_1684_separated_handlers_and_conventional_routing.cs index d5c3799a8..ffaf01afa 100644 --- a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_1684_separated_handlers_and_conventional_routing.cs +++ b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_1684_separated_handlers_and_conventional_routing.cs @@ -31,7 +31,7 @@ public async Task try_it_and_send_to_multiple_topic_subscriptions() //services.AddHostedService(); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var message = new Msg(Guid.NewGuid()); var tracked = await host.TrackActivity().IncludeExternalTransports().SendMessageAndWaitAsync(message); diff --git a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_1716_weird_serialization_issue.cs b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_1716_weird_serialization_issue.cs index 78f467d82..5999d783c 100644 --- a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_1716_weird_serialization_issue.cs +++ b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_1716_weird_serialization_issue.cs @@ -16,10 +16,10 @@ public async Task try_to_reproduce() var bus = host1.MessageBus(); await bus.ScheduleAsync(new Bug1716("what"), DateTimeOffset.UtcNow.AddSeconds(15)); - await host1.StopAsync(); + await host1.StopAsync(TestContext.Current.CancellationToken); using var host2 = await startHost(); - await Task.Delay(2.Minutes()); + await Task.Delay(2.Minutes(), TestContext.Current.CancellationToken); } [Fact] diff --git a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_1801_not_acking_on_consumer_failure.cs b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_1801_not_acking_on_consumer_failure.cs index 4ddaec763..7b57801e2 100644 --- a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_1801_not_acking_on_consumer_failure.cs +++ b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_1801_not_acking_on_consumer_failure.cs @@ -17,7 +17,7 @@ public async Task try_it() opts.ListenToRabbitQueue("will_error"); opts.PublishMessage().ToRabbitQueue("will_error"); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var tracked = await host.TrackActivity() .IncludeExternalTransports() diff --git a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_189_fails_if_there_are_many_messages_in_queue_on_startup.cs b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_189_fails_if_there_are_many_messages_in_queue_on_startup.cs index 150ec0251..4389f71b7 100644 --- a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_189_fails_if_there_are_many_messages_in_queue_on_startup.cs +++ b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_189_fails_if_there_are_many_messages_in_queue_on_startup.cs @@ -33,7 +33,7 @@ await Host.CreateDefaultBuilder() #endregion - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var bus = sender.MessageBus(); @@ -42,7 +42,7 @@ await Host.CreateDefaultBuilder() await bus.PublishAsync(new Bug189(Guid.NewGuid())); } - await sender.StopAsync(); + await sender.StopAsync(TestContext.Current.CancellationToken); var waiter = Bug189Handler.WaitForCompletion(500, 120000); @@ -55,7 +55,7 @@ await Host.CreateDefaultBuilder() // TODO -- take in the parallel listener count within ProcessInline()? Just sugar, but still? opts.ListenToRabbitQueue(queueName).ProcessInline().ListenerCount(5); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); try { @@ -66,7 +66,7 @@ await Host.CreateDefaultBuilder() if (receiverTask.IsCompletedSuccessfully) { var host = await receiverTask; - await host.StopAsync(); + await host.StopAsync(TestContext.Current.CancellationToken); } } } diff --git a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_1921_order_of_operations.cs b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_1921_order_of_operations.cs index fb108d2e1..bcfaea76f 100644 --- a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_1921_order_of_operations.cs +++ b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_1921_order_of_operations.cs @@ -17,6 +17,6 @@ public async Task start_up_should_succeed() .CustomizeDeadLetterQueueing( new($"my-awesome-dead-letter-queue", DeadLetterQueueMode.Native) ); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); } } \ No newline at end of file diff --git a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_2155_ancillary_store_inbox_persistence.cs b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_2155_ancillary_store_inbox_persistence.cs index 3b475f1bf..7f825bb56 100644 --- a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_2155_ancillary_store_inbox_persistence.cs +++ b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_2155_ancillary_store_inbox_persistence.cs @@ -95,7 +95,7 @@ await _host .SendMessageAndWaitAsync(message); // Give a moment for the async mark-as-handled to complete - await Task.Delay(500); + await Task.Delay(500, TestContext.Current.CancellationToken); // The main store should have the envelope marked as Handled (not stuck as Incoming) var runtime = _host.GetRuntime(); diff --git a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_2360_publish_with_require_response.cs b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_2360_publish_with_require_response.cs index 6bb48ea0d..628b597bf 100644 --- a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_2360_publish_with_require_response.cs +++ b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_2360_publish_with_require_response.cs @@ -42,7 +42,7 @@ public async Task publish_with_require_response_should_invoke_handler() opts.Discovery.DisableConventionalDiscovery() .IncludeType(typeof(Bug2360InitHandler)) .IncludeType(typeof(Bug2360ResponseHandler)); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); // The "server" service that handles the request and returns a response using var receiver = await Host.CreateDefaultBuilder() @@ -57,7 +57,7 @@ public async Task publish_with_require_response_should_invoke_handler() opts.Discovery.DisableConventionalDiscovery() .IncludeType(typeof(Bug2360RequestHandler)); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); // Send the initial message that triggers PublishAsync with RequireResponse var session = await sender @@ -91,7 +91,7 @@ public async Task invoke_async_still_works_for_request_reply() opts.PublishMessage().ToRabbitQueue(receiverQueue); opts.Discovery.DisableConventionalDiscovery(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); // The "server" service using var receiver = await Host.CreateDefaultBuilder() @@ -106,11 +106,11 @@ public async Task invoke_async_still_works_for_request_reply() opts.Discovery.DisableConventionalDiscovery() .IncludeType(typeof(Bug2360RequestHandler)); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); // InvokeAsync should still work as a synchronous request/reply var bus = sender.MessageBus(); - var response = await bus.InvokeAsync(new Bug2360Request("InvokeTest"), timeout: 30.Seconds()); + var response = await bus.InvokeAsync(new Bug2360Request("InvokeTest"), cancellation: TestContext.Current.CancellationToken); response.ShouldNotBeNull(); response.Reply.ShouldBe("Handled: InvokeTest"); diff --git a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_2361_outbox_stuck_with_tenanted_broker.cs b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_2361_outbox_stuck_with_tenanted_broker.cs index 9cccbb982..c78bc8351 100644 --- a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_2361_outbox_stuck_with_tenanted_broker.cs +++ b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_2361_outbox_stuck_with_tenanted_broker.cs @@ -69,10 +69,10 @@ public async Task messages_sent_to_tenanted_broker_should_be_removed_from_outbox // Listen on the tenant's queue opts.ListenToRabbitQueue(queueName); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); // Clean up any stale outbox data from previous runs - await host.ResetResourceState(); + await host.ResetResourceState(cancellation: TestContext.Current.CancellationToken); // Send a message targeted at the tenant var session = await host @@ -90,15 +90,15 @@ await bus.PublishAsync(new Bug2361Message("Hello from tenant"), .ShouldNotBeNull(); // Wait for async outbox cleanup to complete - await Task.Delay(3.Seconds()); + await Task.Delay(3.Seconds(), TestContext.Current.CancellationToken); // Verify the outbox is empty - no stuck messages await using var conn = new NpgsqlConnection(Servers.PostgresConnectionString); - await conn.OpenAsync(); + await conn.OpenAsync(TestContext.Current.CancellationToken); await using var cmd = conn.CreateCommand(); cmd.CommandText = "SELECT count(*) FROM bug2361.wolverine_outgoing_envelopes"; - var stuckCount = (long)(await cmd.ExecuteScalarAsync())!; + var stuckCount = (long)(await cmd.ExecuteScalarAsync(TestContext.Current.CancellationToken))!; _output.WriteLine($"Outbox messages remaining: {stuckCount}"); stuckCount.ShouldBe(0, "Messages should not be stuck in the outbox after successful send to tenanted broker"); diff --git a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_2944_interop_ancillary_inbox.cs b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_2944_interop_ancillary_inbox.cs index 9c9b09939..1aeaf649c 100644 --- a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_2944_interop_ancillary_inbox.cs +++ b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_2944_interop_ancillary_inbox.cs @@ -132,7 +132,7 @@ await transport.WithAdminChannelAsync(async channel => // Brief settle so the inbox row commits before we query - the tracker fires on Received, // not on inbox commit. - await Task.Delay(1000); + await Task.Delay(1000, TestContext.Current.CancellationToken); var ancillaryStore = runtime.Stores.FindAncillaryStore(typeof(IAncillaryStore2944)); diff --git a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_3171_channel_only_shutdown_recovery.cs b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_3171_channel_only_shutdown_recovery.cs index c4e5c7312..a2ac4aea0 100644 --- a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_3171_channel_only_shutdown_recovery.cs +++ b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_3171_channel_only_shutdown_recovery.cs @@ -145,7 +145,7 @@ public async Task listener_resumes_consuming_after_an_unexpected_channel_shutdow // of #3171 — the listener sits blocked and will not self-heal on its own. try { - await originalChannel.QueueDeclarePassiveAsync($"missing-{Guid.NewGuid():N}"); + await originalChannel.QueueDeclarePassiveAsync($"missing-{Guid.NewGuid():N}", TestContext.Current.CancellationToken); } catch { diff --git a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_3391_callback_exception_restart.cs b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_3391_callback_exception_restart.cs index 344b87b74..f45fdf80f 100644 --- a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_3391_callback_exception_restart.cs +++ b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_3391_callback_exception_restart.cs @@ -173,7 +173,7 @@ public async Task listener_still_consumes_after_a_successful_eager_restart() uint consumers; while ((consumers = await consumerCountAsync()) != 1u && DateTimeOffset.UtcNow < deadline) { - await Task.Delay(250); + await Task.Delay(250, TestContext.Current.CancellationToken); } consumers.ShouldBe(1u, "The restarted listener should be consuming from the queue again"); diff --git a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_3687_settling_a_delivery_from_a_dead_channel.cs b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_3687_settling_a_delivery_from_a_dead_channel.cs index 41807d065..439c1736f 100644 --- a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_3687_settling_a_delivery_from_a_dead_channel.cs +++ b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_3687_settling_a_delivery_from_a_dead_channel.cs @@ -118,7 +118,7 @@ public async Task a_stale_delivery_tag_is_never_settled_against_a_replaced_chann // against a queue that does not exist returns 404 NOT_FOUND and takes the channel down. try { - await originalChannel.QueueDeclarePassiveAsync($"missing-{Guid.NewGuid():N}"); + await originalChannel.QueueDeclarePassiveAsync($"missing-{Guid.NewGuid():N}", TestContext.Current.CancellationToken); } catch { diff --git a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_475_durable_outbox_sending_out_of_order.cs b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_475_durable_outbox_sending_out_of_order.cs index c85e9ce04..da3f17146 100644 --- a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_475_durable_outbox_sending_out_of_order.cs +++ b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_475_durable_outbox_sending_out_of_order.cs @@ -35,9 +35,9 @@ public async Task try_messages() opts.Policies.UseDurableInboxOnAllListeners(); opts.Policies.UseDurableOutboxOnAllSendingEndpoints(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); - await host.ResetResourceState(); + await host.ResetResourceState(cancellation: TestContext.Current.CancellationToken); Func publishing = async bus => { diff --git a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_710_rabbit_exchange_errorneously_used_for_system_queues.cs b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_710_rabbit_exchange_errorneously_used_for_system_queues.cs index d7142fc58..e230d8eb1 100644 --- a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_710_rabbit_exchange_errorneously_used_for_system_queues.cs +++ b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_710_rabbit_exchange_errorneously_used_for_system_queues.cs @@ -29,7 +29,7 @@ public async Task start_system_with_declared_exchange() opts.Services.AddMarten(Servers.PostgresConnectionString) .IntegrateWithWolverine(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var options = host.Services.GetRequiredService().Options; diff --git a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_DLQ_NotSavedToDatabase.cs b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_DLQ_NotSavedToDatabase.cs index 9976d969c..ac8acf13f 100644 --- a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_DLQ_NotSavedToDatabase.cs +++ b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_DLQ_NotSavedToDatabase.cs @@ -71,9 +71,9 @@ public async Task test_1_durable_inbox_should_save_failed_messages_to_sql_dlq() opts.ListenToRabbitQueue(queueName).UseDurableInbox(); opts.PublishMessage().ToRabbitQueue(queueName); opts.Services.AddResourceSetupOnStartup(StartupAction.ResetState); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); - await _host.ResetResourceState(); + await _host.ResetResourceState(cancellation: TestContext.Current.CancellationToken); // Debug print: check DeadLetterQueue and Mode var runtime = _host.Services.GetRequiredService(); @@ -101,9 +101,9 @@ public async Task test_2_non_durable_inbox_should_save_failed_messages_to_sql_dl opts.ListenToRabbitQueue(queueName); // No UseDurableInbox() opts.PublishMessage().ToRabbitQueue(queueName); opts.Services.AddResourceSetupOnStartup(StartupAction.ResetState); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); - await _host.ResetResourceState(); + await _host.ResetResourceState(cancellation: TestContext.Current.CancellationToken); // Debug print: check DeadLetterQueue and Mode var runtime = _host.Services.GetRequiredService(); @@ -137,9 +137,9 @@ public async Task test_3_global_durable_configs_should_save_failed_messages_to_s opts.ListenToRabbitQueue(queueName); opts.PublishMessage().ToRabbitQueue(queueName); opts.Services.AddResourceSetupOnStartup(StartupAction.ResetState); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); - await _host.ResetResourceState(); + await _host.ResetResourceState(cancellation: TestContext.Current.CancellationToken); // Debug print: check DeadLetterQueue and Mode var runtime = _host.Services.GetRequiredService(); @@ -202,9 +202,9 @@ public async Task test_5_verify_try_build_dead_letter_sender_behavior() opts.EnableAutomaticFailureAcks = false; opts.UseRabbitMq().DisableDeadLetterQueueing().AutoProvision().AutoPurgeOnStartup(); opts.Services.AddResourceSetupOnStartup(StartupAction.ResetState); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); - await _host.ResetResourceState(); + await _host.ResetResourceState(cancellation: TestContext.Current.CancellationToken); var runtime = _host.Services.GetRequiredService(); var transport = runtime.Options.RabbitMqTransport(); @@ -270,9 +270,9 @@ public async Task test_6_demonstrate_durable_receiver_decision_logic_issue() opts.ListenToRabbitQueue(queueName); opts.PublishMessage().ToRabbitQueue(queueName); opts.Services.AddResourceSetupOnStartup(StartupAction.ResetState); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); - await _host.ResetResourceState(); + await _host.ResetResourceState(cancellation: TestContext.Current.CancellationToken); var runtime = _host.Services.GetRequiredService(); var transport = runtime.Options.RabbitMqTransport(); diff --git a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_mapper_exception_routes_to_dlq.cs b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_mapper_exception_routes_to_dlq.cs index 9e42ff98e..481aa041f 100644 --- a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_mapper_exception_routes_to_dlq.cs +++ b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Bugs/Bug_mapper_exception_routes_to_dlq.cs @@ -33,7 +33,7 @@ public async Task unmappable_message_is_routed_to_broker_dlq_not_silently_acked( opts.ListenToRabbitQueue(_queueName) .UseInterop(new AlwaysThrowingMapper()); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var transport = _host.Services .GetRequiredService() @@ -64,7 +64,7 @@ await channel.BasicPublishAsync( var count = await deadLetterQueue.QueuedCountAsync(); if (count > 0) return; attempts++; - await Task.Delay(250.Milliseconds()); + await Task.Delay(250.Milliseconds(), TestContext.Current.CancellationToken); } throw new Exception( diff --git a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Internals/RabbitMqExchangeTests.cs b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Internals/RabbitMqExchangeTests.cs index cac5931ad..0091e6edd 100644 --- a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Internals/RabbitMqExchangeTests.cs +++ b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Internals/RabbitMqExchangeTests.cs @@ -51,7 +51,7 @@ public async Task exchange_declare() await exchange.DeclareAsync(channel, NullLogger.Instance); - await channel.Received().ExchangeDeclareAsync("foo", "fanout", false, true, (IDictionary)exchange.Arguments); + await channel.Received().ExchangeDeclareAsync("foo", "fanout", false, true, (IDictionary)exchange.Arguments, cancellationToken: Arg.Any()); exchange.HasDeclared.ShouldBeTrue(); } @@ -67,7 +67,7 @@ public async Task exchange_declare_passive() await exchange.DeclareAsync(channel, NullLogger.Instance); - await channel.Received().ExchangeDeclarePassiveAsync("foo"); + await channel.Received().ExchangeDeclarePassiveAsync("foo", Arg.Any()); exchange.HasDeclared.ShouldBeTrue(); } @@ -85,7 +85,7 @@ public async Task exchange_declare_headers() await exchange.DeclareAsync(channel, NullLogger.Instance); - await channel.Received().ExchangeDeclareAsync("foo", "headers", false, true, (IDictionary)exchange.Arguments); + await channel.Received().ExchangeDeclareAsync("foo", "headers", false, true, (IDictionary)exchange.Arguments, cancellationToken: Arg.Any()); exchange.HasDeclared.ShouldBeTrue(); } diff --git a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Internals/RabbitMqQueueTests.cs b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Internals/RabbitMqQueueTests.cs index a28ef8263..fff7f7f5a 100644 --- a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Internals/RabbitMqQueueTests.cs +++ b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Internals/RabbitMqQueueTests.cs @@ -66,19 +66,13 @@ public async Task publish_queue_dead_letter_queueing_sets_a_specific_dlq() queue.DeadLetterQueue.ExchangeName.ShouldBe("publish-dlx-exchange"); var channel = Substitute.For(); - channel.QueueDeclareAsync(default!, default, default, default, default!) - .ReturnsForAnyArgs(Task.FromResult(new QueueDeclareOk("publish-queue", 0, 0))); + channel.QueueDeclareAsync(default!, default, default, default, default!, cancellationToken: TestContext.Current.CancellationToken).ReturnsForAnyArgs(Task.FromResult(new QueueDeclareOk("publish-queue", 0, 0))); await queue.DeclareAsync(channel, NullLogger.Instance); - await channel.Received().QueueDeclareAsync( - "publish-queue", - queue.IsDurable, - queue.IsExclusive, - queue.AutoDelete, - Arg.Is>(args => + await channel.Received().QueueDeclareAsync("publish-queue", queue.IsDurable, queue.IsExclusive, queue.AutoDelete, Arg.Is>(args => args.ContainsKey(RabbitMqTransport.DeadLetterQueueHeader) && - Equals(args[RabbitMqTransport.DeadLetterQueueHeader], "publish-dlx-exchange"))); + Equals(args[RabbitMqTransport.DeadLetterQueueHeader], "publish-dlx-exchange")), cancellationToken: TestContext.Current.CancellationToken); } [Fact] @@ -103,18 +97,12 @@ public async Task publish_queue_disable_dead_letter_queueing_clears_the_dlq() queue.DeadLetterQueue.ShouldBeNull(); var channel = Substitute.For(); - channel.QueueDeclareAsync(default!, default, default, default, default!) - .ReturnsForAnyArgs(Task.FromResult(new QueueDeclareOk("publish-queue", 0, 0))); + channel.QueueDeclareAsync(default!, default, default, default, default!, cancellationToken: TestContext.Current.CancellationToken).ReturnsForAnyArgs(Task.FromResult(new QueueDeclareOk("publish-queue", 0, 0))); await queue.DeclareAsync(channel, NullLogger.Instance); - await channel.Received().QueueDeclareAsync( - "publish-queue", - queue.IsDurable, - queue.IsExclusive, - queue.AutoDelete, - Arg.Is>(args => - !args.ContainsKey(RabbitMqTransport.DeadLetterQueueHeader))); + await channel.Received().QueueDeclareAsync("publish-queue", queue.IsDurable, queue.IsExclusive, queue.AutoDelete, Arg.Is>(args => + !args.ContainsKey(RabbitMqTransport.DeadLetterQueueHeader)), cancellationToken: TestContext.Current.CancellationToken); } [Fact] @@ -151,7 +139,7 @@ public async Task declare(bool autoDelete, bool isExclusive, bool isDurable) await queue.DeclareAsync(channel, NullLogger.Instance); await channel.Received() - .QueueDeclareAsync("foo", queue.IsDurable, queue.IsExclusive, queue.AutoDelete, (IDictionary)queue.Arguments); + .QueueDeclareAsync("foo", queue.IsDurable, queue.IsExclusive, queue.AutoDelete, (IDictionary)queue.Arguments, cancellationToken: TestContext.Current.CancellationToken); queue.HasDeclared.ShouldBeTrue(); } @@ -167,8 +155,8 @@ public async Task initialize_with_no_auto_provision_or_auto_purge() await queue.InitializeAsync(theChannel, NullLogger.Instance); - await theChannel.DidNotReceiveWithAnyArgs().QueueDeclareAsync("foo", true, true, true, null); - await theChannel.DidNotReceiveWithAnyArgs().QueuePurgeAsync("foo"); + await theChannel.DidNotReceiveWithAnyArgs().QueueDeclareAsync("foo", true, true, true, null, cancellationToken: Arg.Any()); + await theChannel.DidNotReceiveWithAnyArgs().QueuePurgeAsync("foo", Arg.Any()); } public record PublishOverrideMessage; @@ -184,8 +172,8 @@ public async Task initialize_with_no_auto_provision_but_auto_purge_on_endpoint_o await endpoint.InitializeAsync(theChannel, NullLogger.Instance); - await theChannel.DidNotReceiveWithAnyArgs().QueueDeclareAsync("foo", true, true, true, null); - await theChannel.Received().QueuePurgeAsync("foo"); + await theChannel.DidNotReceiveWithAnyArgs().QueueDeclareAsync("foo", true, true, true, null, cancellationToken: Arg.Any()); + await theChannel.Received().QueuePurgeAsync("foo", Arg.Any()); } [Fact] @@ -200,8 +188,8 @@ public async Task initialize_with_no_auto_provision_but_global_auto_purge() await endpoint.InitializeAsync(theChannel, NullLogger.Instance); - await theChannel.DidNotReceiveWithAnyArgs().QueueDeclareAsync("foo", true, true, true, null); - await theChannel.Received().QueuePurgeAsync("foo"); + await theChannel.DidNotReceiveWithAnyArgs().QueueDeclareAsync("foo", true, true, true, null, cancellationToken: Arg.Any()); + await theChannel.Received().QueuePurgeAsync("foo", Arg.Any()); } [Fact] @@ -216,8 +204,8 @@ public async Task initialize_with_auto_provision_and_global_auto_purge() await endpoint.InitializeAsync(theChannel, NullLogger.Instance); - await theChannel.Received().QueueDeclareAsync("foo", true, false, false, (IDictionary)endpoint.Arguments); - await theChannel.Received().QueuePurgeAsync("foo"); + await theChannel.Received().QueueDeclareAsync("foo", true, false, false, (IDictionary)endpoint.Arguments, cancellationToken: Arg.Any()); + await theChannel.Received().QueuePurgeAsync("foo", Arg.Any()); } [Fact] @@ -231,7 +219,7 @@ public async Task initialize_with_auto_provision_and_local_auto_purge() await endpoint.InitializeAsync(theChannel, NullLogger.Instance); - await theChannel.Received().QueueDeclareAsync("foo", true, false, false, (IDictionary)endpoint.Arguments); - await theChannel.Received().QueuePurgeAsync("foo"); + await theChannel.Received().QueueDeclareAsync("foo", true, false, false, (IDictionary)endpoint.Arguments, cancellationToken: Arg.Any()); + await theChannel.Received().QueuePurgeAsync("foo", Arg.Any()); } } diff --git a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/RabbitMqBrokerHealthProbe_tests.cs b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/RabbitMqBrokerHealthProbe_tests.cs index 24a7c5b17..6c4f5752d 100644 --- a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/RabbitMqBrokerHealthProbe_tests.cs +++ b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/RabbitMqBrokerHealthProbe_tests.cs @@ -79,7 +79,7 @@ await sendingConnection.CloseAsync( } // Give the connection-shutdown event a moment to fire on the client. - await Task.Delay(500); + await Task.Delay(500, TestContext.Current.CancellationToken); var snapshot = await ((IBrokerHealthProbe)transport).ProbeAsync(CancellationToken.None); diff --git a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/RabbitMqExchangeBindingTests.cs b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/RabbitMqExchangeBindingTests.cs index b0aeb348a..3bf305082 100644 --- a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/RabbitMqExchangeBindingTests.cs +++ b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/RabbitMqExchangeBindingTests.cs @@ -17,7 +17,7 @@ public async Task declare_calls_exchange_bind() await binding.DeclareAsync(channel, NullLogger.Instance); - await channel.Received().ExchangeBindAsync("destination", "source", "routing.key", (IDictionary)binding.Arguments); + await channel.Received().ExchangeBindAsync("destination", "source", "routing.key", (IDictionary)binding.Arguments, cancellationToken: Arg.Any()); binding.HasDeclared.ShouldBeTrue(); } @@ -29,7 +29,7 @@ public async Task teardown_calls_exchange_unbind() await binding.TeardownAsync(channel); - await channel.Received().ExchangeUnbindAsync("destination", "source", "routing.key", (IDictionary)binding.Arguments); + await channel.Received().ExchangeUnbindAsync("destination", "source", "routing.key", (IDictionary)binding.Arguments, cancellationToken: Arg.Any()); } public class when_adding_exchange_to_exchange_bindings @@ -197,9 +197,8 @@ public async Task declare_async_also_declares_exchange_bindings() await exchange.DeclareAsync(channel, NullLogger.Instance); - await channel.Received().ExchangeDeclareAsync("dest", "topic", true, false, (IDictionary)exchange.Arguments); - await channel.Received().ExchangeBindAsync("dest", "source", "routing.key", - Arg.Any>()); + await channel.Received().ExchangeDeclareAsync("dest", "topic", true, false, (IDictionary)exchange.Arguments, cancellationToken: Arg.Any()); + await channel.Received().ExchangeBindAsync("dest", "source", "routing.key", Arg.Any>(), cancellationToken: Arg.Any()); } } } diff --git a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Wolverine.RabbitMQ.Tests.csproj b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Wolverine.RabbitMQ.Tests.csproj index a98633820..a70a83e95 100644 --- a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Wolverine.RabbitMQ.Tests.csproj +++ b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Wolverine.RabbitMQ.Tests.csproj @@ -1,6 +1,8 @@ + + true Exe false diff --git a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/application_does_not_fail_without_rabbit_mq_transport_initialized.cs b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/application_does_not_fail_without_rabbit_mq_transport_initialized.cs index 1b0dea06c..556e7d12a 100644 --- a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/application_does_not_fail_without_rabbit_mq_transport_initialized.cs +++ b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/application_does_not_fail_without_rabbit_mq_transport_initialized.cs @@ -9,6 +9,6 @@ public class application_does_not_fail_without_rabbit_mq_transport_initialized public async Task do_not_fail() { using var host = await Host.CreateDefaultBuilder() - .UseWolverine().StartAsync(); + .UseWolverine().StartAsync(cancellationToken: TestContext.Current.CancellationToken); } } \ No newline at end of file diff --git a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/cluster_endpoints.cs b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/cluster_endpoints.cs index da82ec5e6..e19b66fff 100644 --- a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/cluster_endpoints.cs +++ b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/cluster_endpoints.cs @@ -208,7 +208,7 @@ public async Task can_publish_and_receive_through_cluster_code_path() opts.ListenToRabbitQueue(queueName); opts.Services.AddResourceSetupOnStartup(StartupAction.ResetState); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var session = await host .TrackActivity() diff --git a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/dead_letter_queue_recovery_listener.cs b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/dead_letter_queue_recovery_listener.cs index 9d3203575..7afc18be0 100644 --- a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/dead_letter_queue_recovery_listener.cs +++ b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/dead_letter_queue_recovery_listener.cs @@ -93,7 +93,7 @@ await _host { results = await messageStore.DeadLetters.QueryAsync(query, CancellationToken.None); if (results.Envelopes.Any()) break; - await Task.Delay(500); + await Task.Delay(500, TestContext.Current.CancellationToken); } results.ShouldNotBeNull(); @@ -127,7 +127,7 @@ public async Task recovers_multiple_messages() { results = await messageStore.DeadLetters.QueryAsync(query, CancellationToken.None); if (results.Envelopes.Count() >= 3) break; - await Task.Delay(2.Seconds()); + await Task.Delay(2.Seconds(), TestContext.Current.CancellationToken); } results.ShouldNotBeNull(); @@ -202,7 +202,7 @@ await _host { results = await messageStore.DeadLetters.QueryAsync(query, CancellationToken.None); if (results.Envelopes.Any()) break; - await Task.Delay(500); + await Task.Delay(500, TestContext.Current.CancellationToken); } results.ShouldNotBeNull(); diff --git a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/disable_external_listeners.cs b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/disable_external_listeners.cs index 3018f3fe8..26b25c8a3 100644 --- a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/disable_external_listeners.cs +++ b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/disable_external_listeners.cs @@ -25,7 +25,7 @@ public async Task listeners_are_not_active() // This could never, ever work opts.UseRabbitMq().AutoProvision(); opts.ListenToRabbitQueue("incoming"); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); #endregion diff --git a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/disabling_external_transports_does_not_try_to_connect_to_rabbit.cs b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/disabling_external_transports_does_not_try_to_connect_to_rabbit.cs index bec42bf7a..edb332814 100644 --- a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/disabling_external_transports_does_not_try_to_connect_to_rabbit.cs +++ b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/disabling_external_transports_does_not_try_to_connect_to_rabbit.cs @@ -21,7 +21,7 @@ public async Task can_execute_locally() opts.PublishMessage().ToRabbitQueue("name"); opts.StubAllExternalTransports(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var session = await host.SendMessageAndWaitAsync(new SayName("Jennifer Coolidge")); diff --git a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/end_to_end.cs b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/end_to_end.cs index eb6b24686..0f5d7f997 100644 --- a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/end_to_end.cs +++ b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/end_to_end.cs @@ -174,7 +174,7 @@ public async Task send_message_to_and_receive_through_rabbitmq_with_durable_tran opts.Services.AddResourceSetupOnStartup(StartupAction.ResetState); }); - await receiver.ResetResourceState(); + await receiver.ResetResourceState(cancellation: TestContext.Current.CancellationToken); await publisher .TrackActivity() @@ -216,7 +216,7 @@ public async Task send_message_to_and_receive_through_rabbitmq_with_inline_recei opts.Services.AddResourceSetupOnStartup(StartupAction.ResetState); }); - await receiver.ResetResourceState(); + await receiver.ResetResourceState(cancellation: TestContext.Current.CancellationToken); for (int i = 0; i < 10000; i++) { @@ -263,7 +263,7 @@ public async Task send_message_to_and_receive_through_rabbitmq_with_inline_recei opts.Services.AddResourceSetupOnStartup(StartupAction.ResetState); }); - await receiver.ResetResourceState(); + await receiver.ResetResourceState(cancellation: TestContext.Current.CancellationToken); for (int i = 0; i < 10000; i++) { @@ -298,7 +298,7 @@ public async Task send_message_to_and_receive_through_rabbitmq_with_inline_recei opts.Services.AddResourceSetupOnStartup(StartupAction.ResetState); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); using var receiver = await Host.CreateDefaultBuilder() .UseWolverine(opts => @@ -310,9 +310,9 @@ public async Task send_message_to_and_receive_through_rabbitmq_with_inline_recei opts.Services.AddResourceSetupOnStartup(StartupAction.ResetState); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); - await receiver.ResetResourceState(); + await receiver.ResetResourceState(cancellation: TestContext.Current.CancellationToken); for (int i = 0; i < 10000; i++) { @@ -346,7 +346,7 @@ public async Task send_message_to_and_receive_through_rabbitmq_with_inline_recei .SendInline(); opts.Services.AddResourceSetupOnStartup(StartupAction.ResetState); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); using var receiver = await Host.CreateDefaultBuilder().UseWolverine(opts => { @@ -359,7 +359,7 @@ public async Task send_message_to_and_receive_through_rabbitmq_with_inline_recei opts.Services.AddResourceSetupOnStartup(StartupAction.ResetState); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); Func publishing = async c => { @@ -405,7 +405,7 @@ public async Task reply_uri_mechanics() }).IntegrateWithWolverine(); opts.Services.AddResourceSetupOnStartup(StartupAction.ResetState); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); using var receiver = await Host.CreateDefaultBuilder().UseWolverine(opts => { @@ -424,7 +424,7 @@ public async Task reply_uri_mechanics() }).IntegrateWithWolverine(); opts.Services.AddResourceSetupOnStartup(StartupAction.ResetState); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var session = await publisher .TrackActivity() @@ -510,7 +510,7 @@ public async Task schedule_send_message_to_and_receive_through_rabbitmq_with_dur }).IntegrateWithWolverine(); }); - await publisher.ResetResourceState(); + await publisher.ResetResourceState(cancellation: TestContext.Current.CancellationToken); var receiver = await WolverineHost.ForAsync(opts => { @@ -529,7 +529,7 @@ public async Task schedule_send_message_to_and_receive_through_rabbitmq_with_dur }).IntegrateWithWolverine(); }); - await receiver.ResetResourceState(); + await receiver.ResetResourceState(cancellation: TestContext.Current.CancellationToken); try { @@ -864,7 +864,7 @@ public async Task request_reply_from_within_handler() opts.ListenToRabbitQueue(queueName); }); - await receiver.ResetResourceState(); + await receiver.ResetResourceState(cancellation: TestContext.Current.CancellationToken); await publisher .TrackActivity() diff --git a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/end_to_end_with_named_broker.cs b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/end_to_end_with_named_broker.cs index 48630a362..a191f6a9b 100644 --- a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/end_to_end_with_named_broker.cs +++ b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/end_to_end_with_named_broker.cs @@ -45,7 +45,7 @@ public async Task send_message_to_and_receive_through_rabbitmq_with_inline_recei opts.Services.AddResourceSetupOnStartup(StartupAction.ResetState); }); - await receiver.ResetResourceState(); + await receiver.ResetResourceState(cancellation: TestContext.Current.CancellationToken); for (int i = 0; i < 10000; i++) { @@ -94,7 +94,7 @@ public async Task correct_scheme_on_reply_uri() opts.Services.AddResourceSetupOnStartup(StartupAction.ResetState); }); - await receiver.ResetResourceState(); + await receiver.ResetResourceState(cancellation: TestContext.Current.CancellationToken); var request = new RequestId(Guid.NewGuid()); var (tracked, response) = diff --git a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/endpoint_health_connection_state_3231.cs b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/endpoint_health_connection_state_3231.cs index e58c4c372..acc44e9cb 100644 --- a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/endpoint_health_connection_state_3231.cs +++ b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/endpoint_health_connection_state_3231.cs @@ -87,7 +87,7 @@ await sendingConnection.CloseAsync( } // Give the connection-shutdown callback a moment to flip the agent state. - await Task.Delay(500); + await Task.Delay(500, TestContext.Current.CancellationToken); var snapshots = runtime.Endpoints.CollectEndpointHealth(); var rabbitSender = snapshots.First(s => s.Direction == EndpointDirection.Sending && s.Uri.Scheme == "rabbitmq"); diff --git a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/exclusive_listeners.cs b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/exclusive_listeners.cs index 915ccccb6..7c049e64d 100644 --- a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/exclusive_listeners.cs +++ b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/exclusive_listeners.cs @@ -56,7 +56,7 @@ public async Task exclusive_listeners_are_automatically_started_in_solo_mode() opts.ListenAtPort(PortFinder.GetAvailablePort()).ListenWithStrictOrdering().Named("one"); opts.ListenAtPort(PortFinder.GetAvailablePort()).ListenWithStrictOrdering().Named("two"); opts.ListenAtPort(PortFinder.GetAvailablePort()).Named("three"); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.GetRuntime(); runtime.Endpoints.ActiveListeners().Where(x => x.Uri.Scheme != "stub" ).Select(x => x.Endpoint.EndpointName) diff --git a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/fanout_from_external_to_separated_local_handlers.cs b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/fanout_from_external_to_separated_local_handlers.cs index 9e81d6a6f..ea6598366 100644 --- a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/fanout_from_external_to_separated_local_handlers.cs +++ b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/fanout_from_external_to_separated_local_handlers.cs @@ -30,7 +30,7 @@ public async Task should_fanout_to_all_local_handlers_from_external_endpoint() opts.MultipleHandlerBehavior = MultipleHandlerBehavior.Separated; }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var message = new FanoutTestMessage(Guid.NewGuid()); diff --git a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/global_partitioned_sharded_processing.cs b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/global_partitioned_sharded_processing.cs index 7e634da1c..e5be82ad4 100644 --- a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/global_partitioned_sharded_processing.cs +++ b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/global_partitioned_sharded_processing.cs @@ -70,7 +70,7 @@ public async Task hammer_it_with_lots_of_messages_global_partitioned() topology.UseShardedRabbitQueues("gletters", 4); topology.MessagesImplementing(); }); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var tracked = await host .TrackActivity() diff --git a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/interop_friendly_dead_letter_queue_mechanics.cs b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/interop_friendly_dead_letter_queue_mechanics.cs index b053ea8cd..eb2dc751b 100644 --- a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/interop_friendly_dead_letter_queue_mechanics.cs +++ b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/interop_friendly_dead_letter_queue_mechanics.cs @@ -99,7 +99,7 @@ public async Task move_failed_messages_to_the_dlq() var queuedCount = await deadLetterQueue.QueuedCountAsync(); if (queuedCount > 0) return; - await Task.Delay(250.Milliseconds()); + await Task.Delay(250.Milliseconds(), TestContext.Current.CancellationToken); } throw new Exception("Never got a message in the dead letter queue"); diff --git a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/leader_pinned_listener.cs b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/leader_pinned_listener.cs index a8fa962c0..81a5777a7 100644 --- a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/leader_pinned_listener.cs +++ b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/leader_pinned_listener.cs @@ -102,7 +102,7 @@ await host.WaitUntilAssignmentsChangeTo(w => host3.GetRuntime().Endpoints.ActiveListeners().Where(x => x.Endpoint.Role == EndpointRole.Application).Any(x => x.Uri.Scheme == "rabbitmq").ShouldBeFalse(); host4.GetRuntime().Endpoints.ActiveListeners().Where(x => x.Endpoint.Role == EndpointRole.Application).Any(x => x.Uri.Scheme == "rabbitmq").ShouldBeFalse(); - await host.StopAsync(); + await host.StopAsync(TestContext.Current.CancellationToken); host.Dispose(); _hosts.Remove(host); diff --git a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/masstransit_interop_map_tenant_id.cs b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/masstransit_interop_map_tenant_id.cs index 2f0a3fc36..c62bfb4a7 100644 --- a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/masstransit_interop_map_tenant_id.cs +++ b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/masstransit_interop_map_tenant_id.cs @@ -30,7 +30,7 @@ public async Task map_tenant_id_from_is_applied_on_the_rabbitmq_listener() .UseMassTransitInterop(mt => mt.MapTenantIdFrom(env => env.Message?.Tenant)); opts.StubAllExternalTransports(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.GetRuntime(); diff --git a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/masstransit_interop_serializer_on_retry.cs b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/masstransit_interop_serializer_on_retry.cs index c7efb60ab..154e80f62 100644 --- a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/masstransit_interop_serializer_on_retry.cs +++ b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/masstransit_interop_serializer_on_retry.cs @@ -35,7 +35,7 @@ public async Task replayed_masstransit_envelope_is_unwrapped_on_the_retry_path() opts.ListenToRabbitQueue("orders").UseMassTransitInterop(); opts.StubAllExternalTransports(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.GetRuntime(); diff --git a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/multi_node_exclusive_listener_recovery.cs b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/multi_node_exclusive_listener_recovery.cs index 9f1b6bfad..3270a9579 100644 --- a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/multi_node_exclusive_listener_recovery.cs +++ b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/multi_node_exclusive_listener_recovery.cs @@ -327,7 +327,7 @@ public async Task rows_released_after_the_listener_is_already_running_are_still_ // Several recovery sweeps go by with nothing to find. This is the window a one-shot recovery would // have spent its single look in. - await Task.Delay(2.Seconds()); + await Task.Delay(2.Seconds(), TestContext.Current.CancellationToken); tracking.Count.ShouldBe(0, "The listener must not touch inbox rows that are still owned by another node"); diff --git a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/native_dead_letter_queue_mechanics.cs b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/native_dead_letter_queue_mechanics.cs index 4d5389214..bc2a1adb5 100644 --- a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/native_dead_letter_queue_mechanics.cs +++ b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/native_dead_letter_queue_mechanics.cs @@ -104,7 +104,7 @@ public async Task publish_side_queue_keeps_its_custom_dead_letter_exchange_durin }); opts.LocalRoutingConventionDisabled = true; - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); theTransport = _host .Services @@ -141,7 +141,7 @@ public async Task publish_side_queue_can_disable_dead_letter_queueing_during_aut .DisableDeadLetterQueueing(); opts.LocalRoutingConventionDisabled = true; - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); theTransport = _host .Services @@ -167,7 +167,7 @@ public async Task no_dead_letter_queue_if_disabled() opts.ListenToRabbitQueue(queueName); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var transport = host.Services.GetRequiredService().Options.RabbitMqTransport(); @@ -192,7 +192,7 @@ public async Task customize_dead_letter_queueing() opts.ListenToRabbitQueue(QueueName); opts.LocalRoutingConventionDisabled = true; - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); theTransport = _host .Services @@ -226,7 +226,7 @@ public async Task move_failed_messages_to_the_dlq() var queuedCount = await deadLetterQueue.QueuedCountAsync(); if (queuedCount > 0) return; - await Task.Delay(250.Milliseconds()); + await Task.Delay(250.Milliseconds(), TestContext.Current.CancellationToken); } throw new Exception("Never got a message in the dead letter queue"); @@ -259,9 +259,7 @@ public async Task uses_overridden_dead_letter_exchange_per_queue_when_transport_ queue.Compile(runtime); var channel = Substitute.For(); - channel.QueueDeclareAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), - Arg.Any>()) - .Returns(Task.FromResult(new QueueDeclareOk(queue.QueueName, 0, 0))); + channel.QueueDeclareAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any>(), cancellationToken: TestContext.Current.CancellationToken).Returns(Task.FromResult(new QueueDeclareOk(queue.QueueName, 0, 0))); await queue.DeclareAsync(channel, NullLogger.Instance); @@ -335,9 +333,7 @@ public async Task default_and_override_queues_keep_their_own_dlx_exchange_on_dec overrideEndpoint.Compile(runtime); var channel = Substitute.For(); - channel.QueueDeclareAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), - Arg.Any>()) - .Returns(Task.FromResult(new QueueDeclareOk(defaultQueue, 0, 0))); + channel.QueueDeclareAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any>(), cancellationToken: TestContext.Current.CancellationToken).Returns(Task.FromResult(new QueueDeclareOk(defaultQueue, 0, 0))); await defaultEndpoint.DeclareAsync(channel, NullLogger.Instance); await overrideEndpoint.DeclareAsync(channel, NullLogger.Instance); @@ -362,7 +358,7 @@ public async Task overriding_dead_letter_queue_for_specific_queue() opts.LocalRoutingConventionDisabled = true; opts.ListenToRabbitQueue(QueueName + "Different").DeadLetterQueueing(new DeadLetterQueue(deadLetterQueueName)); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); theTransport = _host .Services @@ -384,7 +380,7 @@ public async Task overriding_dead_letter_queue_for_specific_queue() var queuedCount = await deadLetterQueue.QueuedCountAsync(); if (queuedCount > 0) return; - await Task.Delay(250.Milliseconds()); + await Task.Delay(250.Milliseconds(), TestContext.Current.CancellationToken); } throw new Exception("Never got a message in the dead letter queue"); diff --git a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/rate_limiting_end_to_end.cs b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/rate_limiting_end_to_end.cs index b63fcf6e1..aaae8ec2c 100644 --- a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/rate_limiting_end_to_end.cs +++ b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/rate_limiting_end_to_end.cs @@ -39,7 +39,7 @@ public async Task rate_limited_messages_are_delayed_over_rabbitmq() opts.UseRabbitMq().DisableDeadLetterQueueing().AutoProvision().AutoPurgeOnStartup(); opts.PublishAllMessages().ToRabbitQueue(queueName); opts.Services.AddResourceSetupOnStartup(StartupAction.ResetState); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); receiver = await Host.CreateDefaultBuilder() .UseWolverine(opts => @@ -55,18 +55,18 @@ public async Task rate_limited_messages_are_delayed_over_rabbitmq() .RateLimit("rabbitmq-rate-limit", new RateLimit(1, window)); opts.Services.AddResourceSetupOnStartup(StartupAction.ResetState); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); - await publisher.ResetResourceState(); - await receiver.ResetResourceState(); + await publisher.ResetResourceState(cancellation: TestContext.Current.CancellationToken); + await receiver.ResetResourceState(cancellation: TestContext.Current.CancellationToken); await alignToWindowStart(window); var bus = publisher.MessageBus(); await bus.PublishAsync(new RateLimitedMessage()); await bus.PublishAsync(new RateLimitedMessage()); - var first = await tracker.FirstHandled.Task.WaitAsync(10.Seconds()); - var second = await tracker.SecondHandled.Task.WaitAsync(10.Seconds()); + var first = await tracker.FirstHandled.Task.WaitAsync(10.Seconds(), TestContext.Current.CancellationToken); + var second = await tracker.SecondHandled.Task.WaitAsync(10.Seconds(), TestContext.Current.CancellationToken); (second - first).ShouldBeGreaterThanOrEqualTo(700.Milliseconds()); } @@ -117,7 +117,7 @@ public async Task rate_limited_messages_do_not_throw_when_rescheduled() .RateLimit("pause-test", new RateLimit(1, window)); opts.Services.AddResourceSetupOnStartup(StartupAction.ResetState); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); publisher = await Host.CreateDefaultBuilder() .UseWolverine(opts => @@ -125,11 +125,11 @@ public async Task rate_limited_messages_do_not_throw_when_rescheduled() opts.UseRabbitMq().DisableDeadLetterQueueing().AutoProvision(); opts.PublishAllMessages().ToRabbitQueue(queueName); opts.Services.AddResourceSetupOnStartup(StartupAction.ResetState); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); - await publisher.ResetResourceState(); - await receiver.ResetResourceState(); - await Task.Delay(500.Milliseconds()); + await publisher.ResetResourceState(cancellation: TestContext.Current.CancellationToken); + await receiver.ResetResourceState(cancellation: TestContext.Current.CancellationToken); + await Task.Delay(500.Milliseconds(), TestContext.Current.CancellationToken); var bus = publisher.MessageBus(); for (var i = 0; i < 10; i++) @@ -138,7 +138,7 @@ public async Task rate_limited_messages_do_not_throw_when_rescheduled() } // Wait long enough for rescheduling to occur - await Task.Delay(8.Seconds()); + await Task.Delay(8.Seconds(), TestContext.Current.CancellationToken); // The critical assertion: no NullReferenceException during pause/resume exceptions.Any(ContainsNullRef).ShouldBeFalse( diff --git a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/scheduled_saga_timeout_preserves_tenant.cs b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/scheduled_saga_timeout_preserves_tenant.cs index 8183f3f54..c9e2a1871 100644 --- a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/scheduled_saga_timeout_preserves_tenant.cs +++ b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/scheduled_saga_timeout_preserves_tenant.cs @@ -64,7 +64,7 @@ public async Task saga_timeout_delivered_through_rabbit_is_handled_under_origina { var sagaId = Guid.NewGuid(); - await _host.MessageBus().InvokeForTenantAsync("red", new StartSaga(sagaId)); + await _host.MessageBus().InvokeForTenantAsync("red", new StartSaga(sagaId), TestContext.Current.CancellationToken); SagaTimeoutCapture.Snapshot captured; try @@ -78,7 +78,7 @@ public async Task saga_timeout_delivered_through_rabbit_is_handled_under_origina foreach (var tenant in new[] { "red", "*DEFAULT*" }) { await using var diag = store.QuerySession(tenant); - var row = await diag.LoadAsync(sagaId); + var row = await diag.LoadAsync(sagaId, TestContext.Current.CancellationToken); if (row != null) { snapshots.Add($"tenant={tenant}, storedTenant={row.StoredTenantId ?? "null"}, timedOut={row.TimedOut}"); @@ -101,7 +101,7 @@ public async Task saga_timeout_delivered_through_rabbit_is_handled_under_origina await using var session = store2.QuerySession(); var remaining = await session.Query() .Where(x => x.Id == sagaId) - .ToListAsync(); + .ToListAsync(token: TestContext.Current.CancellationToken); remaining.ShouldBeEmpty(); } diff --git a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/sending_raw_messages.cs b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/sending_raw_messages.cs index 29e42335d..2324e0788 100644 --- a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/sending_raw_messages.cs +++ b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/sending_raw_messages.cs @@ -31,7 +31,7 @@ public async Task send_end_to_end_with_default_message_type_name() opts.PublishAllMessages() .ToRabbitQueue(theQueueName).SendInline(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); using var receiver = await WolverineHost.ForAsync(opts => @@ -69,7 +69,7 @@ public async Task send_end_to_end_with_supplied_message_type_name() opts.PublishAllMessages() .ToRabbitQueue(theQueueName).SendInline(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); using var receiver = await WolverineHost.ForAsync(opts => @@ -105,7 +105,7 @@ public async Task send_end_to_end_customize_envelope() opts.PublishAllMessages() .ToRabbitQueue(theQueueName).SendInline(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); using var receiver = await WolverineHost.ForAsync(opts => diff --git a/src/Transports/Redis/Wolverine.Redis.Tests/BasicPubSubTests.cs b/src/Transports/Redis/Wolverine.Redis.Tests/BasicPubSubTests.cs index 93a8a30eb..bef3bc345 100644 --- a/src/Transports/Redis/Wolverine.Redis.Tests/BasicPubSubTests.cs +++ b/src/Transports/Redis/Wolverine.Redis.Tests/BasicPubSubTests.cs @@ -49,14 +49,14 @@ public async Task publish_and_listen_end_to_end() opts.PublishAllMessages().ToRedisStream(streamKey); opts.Services.AddSingleton(tcs); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var bus = host.MessageBus(); // Send directly to the Redis stream endpoint to avoid route misconfiguration var uri = new Uri($"redis://stream/0/{streamKey}"); await bus.EndpointFor(uri).SendAsync(new PubMessage("123")); - var completed = await Task.WhenAny(tcs.Task, Task.Delay(TimeSpan.FromSeconds(10))); + var completed = await Task.WhenAny(tcs.Task, Task.Delay(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken)); completed.ShouldBe(tcs.Task); var result = await tcs.Task; result.ShouldBeTrue(); diff --git a/src/Transports/Redis/Wolverine.Redis.Tests/Bugs/Bug_1970_issue_with_scheduling.cs b/src/Transports/Redis/Wolverine.Redis.Tests/Bugs/Bug_1970_issue_with_scheduling.cs index e347c8251..bfc058a17 100644 --- a/src/Transports/Redis/Wolverine.Redis.Tests/Bugs/Bug_1970_issue_with_scheduling.cs +++ b/src/Transports/Redis/Wolverine.Redis.Tests/Bugs/Bug_1970_issue_with_scheduling.cs @@ -19,7 +19,7 @@ public async Task send_scheduled_message() opts.PublishAllMessages().ToRedisStream("wolverine-messages"); opts.ListenToRedisStream("wolverine-messages", "test-consumers") .StartFromNewMessages(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var bus = host.MessageBus(); diff --git a/src/Transports/Redis/Wolverine.Redis.Tests/DatabaseBackedEndpointTests.cs b/src/Transports/Redis/Wolverine.Redis.Tests/DatabaseBackedEndpointTests.cs index 43cccbed3..aca089624 100644 --- a/src/Transports/Redis/Wolverine.Redis.Tests/DatabaseBackedEndpointTests.cs +++ b/src/Transports/Redis/Wolverine.Redis.Tests/DatabaseBackedEndpointTests.cs @@ -32,7 +32,7 @@ public async Task redis_endpoint_implements_idatabase_backed_endpoint() opts.UseRedisTransport(RedisContainerFixture.ConnectionString).AutoProvision(); opts.PublishMessage().ToRedisStream(streamKey).SendInline(); opts.ListenToRedisStream(streamKey, "dbe-test-group").StartFromBeginning(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.Services.GetRequiredService(); var transport = runtime.Options.Transports.GetOrCreate(); @@ -55,7 +55,7 @@ public async Task schedule_retry_should_add_message_to_scheduled_set() opts.UseRedisTransport(RedisContainerFixture.ConnectionString).AutoProvision(); opts.PublishMessage().ToRedisStream(streamKey).SendInline(); opts.ListenToRedisStream(streamKey, "dbe-test-group").StartFromBeginning(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.Services.GetRequiredService(); var transport = runtime.Options.Transports.GetOrCreate(); @@ -84,7 +84,7 @@ public async Task schedule_retry_should_add_message_to_scheduled_set() await endpoint!.ScheduleRetryAsync(envelope, CancellationToken.None); // Wait a moment for Redis to persist - await Task.Delay(200); + await Task.Delay(200, TestContext.Current.CancellationToken); // Verify the message is in the scheduled set var scheduledCount = await database.SortedSetLengthAsync(scheduledKey); @@ -119,7 +119,7 @@ public async Task schedule_retry_without_scheduled_time_uses_default_delay() opts.UseRedisTransport(RedisContainerFixture.ConnectionString).AutoProvision(); opts.PublishMessage().ToRedisStream(streamKey).SendInline(); opts.ListenToRedisStream(streamKey, "dbe-test-group").StartFromBeginning(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.Services.GetRequiredService(); var transport = runtime.Options.Transports.GetOrCreate(); @@ -146,7 +146,7 @@ public async Task schedule_retry_without_scheduled_time_uses_default_delay() await endpoint!.ScheduleRetryAsync(envelope, CancellationToken.None); var afterSchedule = DateTimeOffset.UtcNow; - await Task.Delay(200); + await Task.Delay(200, TestContext.Current.CancellationToken); var entries = await database.SortedSetRangeByScoreWithScoresAsync(scheduledKey); entries.Length.ShouldBe(1); @@ -179,7 +179,7 @@ public async Task scheduled_retry_should_be_picked_up_by_polling() opts.UseRedisTransport(RedisContainerFixture.ConnectionString).AutoProvision(); opts.PublishMessage().ToRedisStream(streamKey).SendInline(); opts.ListenToRedisStream(streamKey, "dbe-test-group").StartFromBeginning(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.Services.GetRequiredService(); var transport = runtime.Options.Transports.GetOrCreate(); @@ -204,14 +204,14 @@ public async Task scheduled_retry_should_be_picked_up_by_polling() envelope.ContentType = writer.ContentType; await endpoint!.ScheduleRetryAsync(envelope, CancellationToken.None); - await Task.Delay(200); + await Task.Delay(200, TestContext.Current.CancellationToken); // Verify it's in scheduled set var initialCount = await database.SortedSetLengthAsync(scheduledKey); initialCount.ShouldBe(1); // Wait for polling to move it to the stream - await Task.Delay(3000); + await Task.Delay(3000, TestContext.Current.CancellationToken); // Verify it's been removed from scheduled set var finalCount = await database.SortedSetLengthAsync(scheduledKey); diff --git a/src/Transports/Redis/Wolverine.Redis.Tests/DeadLetterQueueTests.cs b/src/Transports/Redis/Wolverine.Redis.Tests/DeadLetterQueueTests.cs index 3906f3565..0022a1176 100644 --- a/src/Transports/Redis/Wolverine.Redis.Tests/DeadLetterQueueTests.cs +++ b/src/Transports/Redis/Wolverine.Redis.Tests/DeadLetterQueueTests.cs @@ -79,7 +79,7 @@ public async Task failed_message_should_move_to_dead_letter_queue() await bus.PublishAsync(command); // Wait for processing and failure - need more time for retries to exhaust - await Task.Delay(5000); + await Task.Delay(5000, TestContext.Current.CancellationToken); var tracker = host.Services.GetRequiredService(); _output.WriteLine($"Handler was called {tracker.Attempts.Count} times"); @@ -129,7 +129,7 @@ public async Task dead_letter_queue_should_contain_exception_details() var command = new FailingCommand(Guid.NewGuid().ToString(), "Test error message"); await bus.PublishAsync(command); - await Task.Delay(2000); + await Task.Delay(2000, TestContext.Current.CancellationToken); // Read dead letter entry var deadLetterEntries = await database.StreamReadAsync(deadLetterKey, "0-0", count: 1); @@ -199,7 +199,7 @@ public async Task multiple_failed_messages_should_all_be_in_dead_letter_queue() } // Wait for all to fail - await Task.Delay(3000); + await Task.Delay(3000, TestContext.Current.CancellationToken); // Verify all are in dead letter queue var deadLetterLength = await database.StreamLengthAsync(deadLetterKey); diff --git a/src/Transports/Redis/Wolverine.Redis.Tests/NativeSchedulingRetryTests.cs b/src/Transports/Redis/Wolverine.Redis.Tests/NativeSchedulingRetryTests.cs index 2609a93c2..49b4d762f 100644 --- a/src/Transports/Redis/Wolverine.Redis.Tests/NativeSchedulingRetryTests.cs +++ b/src/Transports/Redis/Wolverine.Redis.Tests/NativeSchedulingRetryTests.cs @@ -61,7 +61,7 @@ public async Task endpoint_schedule_retry_async_should_save_to_redis() { opts.ServiceName = "RetryTestService"; opts.UseRedisTransport(RedisContainerFixture.ConnectionString).AutoProvision(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.Services.GetRequiredService(); var transport = runtime.Options.Transports.GetOrCreate(); @@ -92,7 +92,7 @@ public async Task endpoint_schedule_retry_async_should_save_to_redis() await endpoint!.ScheduleRetryAsync(envelope, CancellationToken.None); // Wait for Redis to persist - await Task.Delay(200); + await Task.Delay(200, TestContext.Current.CancellationToken); // Verify the message is in the scheduled set var scheduledCount = await database.SortedSetLengthAsync(scheduledKey); diff --git a/src/Transports/Redis/Wolverine.Redis.Tests/NonDefaultDatabaseTests.cs b/src/Transports/Redis/Wolverine.Redis.Tests/NonDefaultDatabaseTests.cs index 59085f677..6327dd80c 100644 --- a/src/Transports/Redis/Wolverine.Redis.Tests/NonDefaultDatabaseTests.cs +++ b/src/Transports/Redis/Wolverine.Redis.Tests/NonDefaultDatabaseTests.cs @@ -52,13 +52,13 @@ public async Task listener_should_consume_from_non_default_database() opts.Services.AddSingleton(tcs); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var bus = host.MessageBus(); var uri = new Uri($"redis://stream/{databaseId}/{streamKey}"); await bus.EndpointFor(uri).SendAsync(new NonDefaultDbMessage("db1-test")); - var completed = await Task.WhenAny(tcs.Task, Task.Delay(TimeSpan.FromSeconds(10))); + var completed = await Task.WhenAny(tcs.Task, Task.Delay(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken)); completed.ShouldBe(tcs.Task, "Message on non-default database was never consumed — listener likely fell back to db0"); var result = await tcs.Task; diff --git a/src/Transports/Redis/Wolverine.Redis.Tests/RedisAutoClaimIntegrationTests.cs b/src/Transports/Redis/Wolverine.Redis.Tests/RedisAutoClaimIntegrationTests.cs index 52acd6986..eeb87578e 100644 --- a/src/Transports/Redis/Wolverine.Redis.Tests/RedisAutoClaimIntegrationTests.cs +++ b/src/Transports/Redis/Wolverine.Redis.Tests/RedisAutoClaimIntegrationTests.cs @@ -46,7 +46,7 @@ await db.StreamAddAsync(streamKey, new[] // Read with consumer A but do not ack, to create a pending entry await db.StreamReadGroupAsync(streamKey, group, consumerA, ">", 1, false); // Give the message a little idle time to satisfy minIdle - await Task.Delay(250); + await Task.Delay(250, TestContext.Current.CancellationToken); var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); @@ -68,10 +68,10 @@ await db.StreamAddAsync(streamKey, new[] opts.Services.AddSingleton(tcs); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); // Wait up to 10 seconds for message to be handled via auto-claim - var completed = await Task.WhenAny(tcs.Task, Task.Delay(TimeSpan.FromSeconds(10))); + var completed = await Task.WhenAny(tcs.Task, Task.Delay(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken)); completed.ShouldBe(tcs.Task); var result = await tcs.Task; result.ShouldBeTrue(); @@ -105,9 +105,9 @@ public async Task autoclaim_disabled_by_default() endpoint.AutoClaimEnabled.ShouldBeFalse(); endpoint.AutoClaimPeriod.ShouldBe(TimeSpan.FromSeconds(30)); // Default period }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); - await Task.Delay(100); // Brief delay to let host start + await Task.Delay(100, TestContext.Current.CancellationToken); // Brief delay to let host start } [Fact] diff --git a/src/Transports/Redis/Wolverine.Redis.Tests/RedisClaimingTests.cs b/src/Transports/Redis/Wolverine.Redis.Tests/RedisClaimingTests.cs index f1aebdf4d..49e037a4d 100644 --- a/src/Transports/Redis/Wolverine.Redis.Tests/RedisClaimingTests.cs +++ b/src/Transports/Redis/Wolverine.Redis.Tests/RedisClaimingTests.cs @@ -41,7 +41,7 @@ await db.StreamAddAsync(streamKey, new[] // Read with consumer A but do not ack, to create a pending entry await db.StreamReadGroupAsync(streamKey, group, consumerA, ">", 1, false); // Give the message a little idle time to satisfy minIdle - await Task.Delay(250); + await Task.Delay(250, TestContext.Current.CancellationToken); var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); @@ -64,10 +64,10 @@ await db.StreamAddAsync(streamKey, new[] opts.Services.AddSingleton(tcs); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); // Wait up to 10 seconds for message to be handled via claim loop - var completed = await Task.WhenAny(tcs.Task, Task.Delay(TimeSpan.FromSeconds(10))); + var completed = await Task.WhenAny(tcs.Task, Task.Delay(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken)); completed.ShouldBe(tcs.Task); var result = await tcs.Task; result.ShouldBeTrue(); diff --git a/src/Transports/Redis/Wolverine.Redis.Tests/RedisNamedBrokerTests.cs b/src/Transports/Redis/Wolverine.Redis.Tests/RedisNamedBrokerTests.cs index 706025d04..6e3791f75 100644 --- a/src/Transports/Redis/Wolverine.Redis.Tests/RedisNamedBrokerTests.cs +++ b/src/Transports/Redis/Wolverine.Redis.Tests/RedisNamedBrokerTests.cs @@ -141,7 +141,7 @@ public async Task round_trips_a_message_over_the_named_broker() opts.PublishMessage().ToRedisStreamOnNamedBroker(theName, streamKey).SendInline(); opts.ListenToRedisStreamOnNamedBroker(theName, streamKey, "named-group"); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var session = await host .TrackActivity() diff --git a/src/Transports/Redis/Wolverine.Redis.Tests/RedisPerTenantConnectionTests.cs b/src/Transports/Redis/Wolverine.Redis.Tests/RedisPerTenantConnectionTests.cs index c37e1c6b0..3828d9cd7 100644 --- a/src/Transports/Redis/Wolverine.Redis.Tests/RedisPerTenantConnectionTests.cs +++ b/src/Transports/Redis/Wolverine.Redis.Tests/RedisPerTenantConnectionTests.cs @@ -98,7 +98,7 @@ public async Task tenant_message_is_consumed_over_the_tenants_own_connection() opts.PublishMessage().ToRedisStream(streamKey).SendInline(); opts.ListenToRedisStream(streamKey, "tenant-group"); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var session = await host .TrackActivity() diff --git a/src/Transports/Redis/Wolverine.Redis.Tests/RetryLimitTests.cs b/src/Transports/Redis/Wolverine.Redis.Tests/RetryLimitTests.cs index 27c6b18e4..30d4c3469 100644 --- a/src/Transports/Redis/Wolverine.Redis.Tests/RetryLimitTests.cs +++ b/src/Transports/Redis/Wolverine.Redis.Tests/RetryLimitTests.cs @@ -50,7 +50,7 @@ public async Task retries_should_stop_after_configured_limit() opts.Discovery.IncludeType(); opts.Services.AddSingleton(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.Services.GetRequiredService(); var transport = runtime.Options.Transports.GetOrCreate(); @@ -67,7 +67,7 @@ public async Task retries_should_stop_after_configured_limit() var tracker = host.Services.GetRequiredService(); // Wait for listener to fully initialize - await Task.Delay(500); + await Task.Delay(500, TestContext.Current.CancellationToken); // Send a message that will ALWAYS fail var bus = host.MessageBus(); @@ -77,7 +77,7 @@ public async Task retries_should_stop_after_configured_limit() await bus.PublishAsync(command); // Wait for first attempt and first retry - await Task.Delay(1500); + await Task.Delay(1500, TestContext.Current.CancellationToken); _output.WriteLine($"After 1.5s - Handler calls: {tracker.AttemptCount}"); // Check scheduled set @@ -85,7 +85,7 @@ public async Task retries_should_stop_after_configured_limit() _output.WriteLine($" Scheduled messages: {scheduledCount1}"); // Wait for second retry - await Task.Delay(1500); + await Task.Delay(1500, TestContext.Current.CancellationToken); _output.WriteLine($"After 3s - Handler calls: {tracker.AttemptCount}"); var scheduledCount2 = await database.SortedSetLengthAsync(scheduledKey); @@ -105,7 +105,7 @@ public async Task retries_should_stop_after_configured_limit() } // Wait longer for any remaining retries - await Task.Delay(3000); + await Task.Delay(3000, TestContext.Current.CancellationToken); var finalAttemptCount = tracker.AttemptCount; _output.WriteLine($"After 6s - Handler calls: {finalAttemptCount}"); diff --git a/src/Transports/Redis/Wolverine.Redis.Tests/ScheduledMessageIntegrationTests.cs b/src/Transports/Redis/Wolverine.Redis.Tests/ScheduledMessageIntegrationTests.cs index 28ed36b89..c6ac20908 100644 --- a/src/Transports/Redis/Wolverine.Redis.Tests/ScheduledMessageIntegrationTests.cs +++ b/src/Transports/Redis/Wolverine.Redis.Tests/ScheduledMessageIntegrationTests.cs @@ -37,7 +37,7 @@ public async Task verify_scheduled_messages_use_sorted_set() opts.PublishAllMessages().ToRedisStream(streamKey).SendInline(); opts.ListenToRedisStream(streamKey, "integration-test-group") .StartFromBeginning(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); // Verify scheduled messages are stored in Redis sorted set var runtime = host.Services.GetRequiredService(); @@ -53,7 +53,7 @@ public async Task verify_scheduled_messages_use_sorted_set() await bus.ScheduleAsync(command, DateTimeOffset.UtcNow.AddSeconds(10)); // Wait a bit - await Task.Delay(500); + await Task.Delay(500, TestContext.Current.CancellationToken); // Verify it's in a sorted set var keyType = await database.KeyTypeAsync(scheduledKey); @@ -71,7 +71,7 @@ public async Task verify_scheduled_messages_key_format() { opts.UseRedisTransport(RedisContainerFixture.ConnectionString).AutoProvision(); opts.PublishAllMessages().ToRedisStream(streamKey).SendInline(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.Services.GetRequiredService(); var transport = runtime.Options.Transports.GetOrCreate(); @@ -99,7 +99,7 @@ public async Task verify_message_moves_from_scheduled_to_stream() opts.PublishAllMessages().ToRedisStream(streamKey).SendInline(); opts.ListenToRedisStream(streamKey, "integration-test-group") .StartFromBeginning(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.Services.GetRequiredService(); var transport = runtime.Options.Transports.GetOrCreate(); @@ -114,13 +114,13 @@ public async Task verify_message_moves_from_scheduled_to_stream() await bus.ScheduleAsync(command, DateTimeOffset.UtcNow.AddSeconds(1)); // Check it's in the scheduled set - await Task.Delay(300); + await Task.Delay(300, TestContext.Current.CancellationToken); var scheduledCount = await database.SortedSetLengthAsync(scheduledKey); scheduledCount.ShouldBeGreaterThan(0); _output.WriteLine($"Message added to scheduled set (count: {scheduledCount})"); // Wait for it to be moved - await Task.Delay(2000); + await Task.Delay(2000, TestContext.Current.CancellationToken); // Should be removed from scheduled set var remainingScheduled = await database.SortedSetLengthAsync(scheduledKey); @@ -149,7 +149,7 @@ public async Task verify_score_represents_execution_time() opts.PublishAllMessages().ToRedisStream(streamKey).SendInline(); opts.ListenToRedisStream(streamKey, "integration-test-group") .StartFromBeginning(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var runtime = host.Services.GetRequiredService(); var transport = runtime.Options.Transports.GetOrCreate(); @@ -164,7 +164,7 @@ public async Task verify_score_represents_execution_time() var command = new IntegrationTestCommand(Guid.NewGuid().ToString()); await bus.ScheduleAsync(command, scheduledTime); - await Task.Delay(300); + await Task.Delay(300, TestContext.Current.CancellationToken); // Get the score from Redis var entries = await database.SortedSetRangeByScoreWithScoresAsync(scheduledKey); diff --git a/src/Transports/Redis/Wolverine.Redis.Tests/ScheduledMessageTests.cs b/src/Transports/Redis/Wolverine.Redis.Tests/ScheduledMessageTests.cs index 2678e4497..56a6261e5 100644 --- a/src/Transports/Redis/Wolverine.Redis.Tests/ScheduledMessageTests.cs +++ b/src/Transports/Redis/Wolverine.Redis.Tests/ScheduledMessageTests.cs @@ -47,7 +47,7 @@ public async Task should_send_scheduled_message_immediately_when_schedule_time_i await bus.ScheduleAsync(command, DateTimeOffset.UtcNow.AddSeconds(-1)); // Wait for message to be processed - await Task.Delay(2000); + await Task.Delay(2000, TestContext.Current.CancellationToken); tracker.ReceivedMessages.ShouldContain(command.Id); } @@ -66,11 +66,11 @@ public async Task should_delay_execution_of_scheduled_message() await bus.ScheduleAsync(command, scheduledTime); // Wait a bit less than scheduled time - should not be processed yet - await Task.Delay(1500); + await Task.Delay(1500, TestContext.Current.CancellationToken); tracker.ReceivedMessages.ShouldNotContain(command.Id); // Wait for the message to be processed after the scheduled time - await Task.Delay(7000); + await Task.Delay(7000, TestContext.Current.CancellationToken); tracker.ReceivedMessages.ShouldContain(command.Id); var executionTime = tracker.GetExecutionTime(command.Id); @@ -96,7 +96,7 @@ public async Task should_handle_multiple_scheduled_messages_at_different_times() await bus.ScheduleAsync(command3, DateTimeOffset.UtcNow.AddSeconds(1)); // Wait for all messages to be processed - await Task.Delay(6000); + await Task.Delay(6000, TestContext.Current.CancellationToken); tracker.ReceivedMessages.ShouldContain(command1.Id); tracker.ReceivedMessages.ShouldContain(command2.Id); @@ -123,7 +123,7 @@ public async Task scheduled_messages_are_stored_in_redis_sorted_set() .StartFromBeginning(); opts.Services.AddSingleton(); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); // This test verifies that scheduled messages use Redis sorted sets var runtime = host.Services.GetRequiredService(); @@ -140,7 +140,7 @@ public async Task scheduled_messages_are_stored_in_redis_sorted_set() await bus.ScheduleAsync(command, DateTimeOffset.UtcNow.AddSeconds(10)); // Wait a bit for it to be persisted - await Task.Delay(500); + await Task.Delay(500, TestContext.Current.CancellationToken); // Verify it's in the scheduled sorted set var count = await database.SortedSetLengthAsync(scheduledKey); diff --git a/src/Transports/Redis/Wolverine.Redis.Tests/StartFromBehaviorTests.cs b/src/Transports/Redis/Wolverine.Redis.Tests/StartFromBehaviorTests.cs index 266f5aa7f..8f7ed4f54 100644 --- a/src/Transports/Redis/Wolverine.Redis.Tests/StartFromBehaviorTests.cs +++ b/src/Transports/Redis/Wolverine.Redis.Tests/StartFromBehaviorTests.cs @@ -73,7 +73,7 @@ public async Task StartFromNewMessages_should_only_process_messages_after_group_ { opts.UseRedisTransport(RedisContainerFixture.ConnectionString).AutoProvision(); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var bus = publisherHost.MessageBus(); @@ -82,7 +82,7 @@ public async Task StartFromNewMessages_should_only_process_messages_after_group_ await bus.EndpointFor(new Uri($"redis://stream/0/{streamKey}")).SendAsync(new TestMessage("before-2")); await bus.EndpointFor(new Uri($"redis://stream/0/{streamKey}")).SendAsync(new TestMessage("before-3")); - await publisherHost.StopAsync(); + await publisherHost.StopAsync(TestContext.Current.CancellationToken); // Now create a listener with StartFromNewMessages (default behavior) using var listenerHost = await Host.CreateDefaultBuilder() @@ -104,17 +104,17 @@ public async Task StartFromNewMessages_should_only_process_messages_after_group_ opts.Services.AddSingleton(tcs); opts.Discovery.IncludeAssembly(typeof(StartFromBehaviorTests).Assembly); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); // Give listener time to start - await Task.Delay(200); + await Task.Delay(200, TestContext.Current.CancellationToken); // Send a message after the listener is active var listenerBus = listenerHost.MessageBus(); await listenerBus.EndpointFor(new Uri($"redis://stream/0/{streamKey}")).SendAsync(new TestMessage("after-1")); // Wait for completion or timeout - var completed = await Task.WhenAny(tcs.Task, Task.Delay(TimeSpan.FromSeconds(5))); + var completed = await Task.WhenAny(tcs.Task, Task.Delay(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)); if (completed == tcs.Task) { // Should only have received the message sent after listener creation @@ -131,7 +131,7 @@ public async Task StartFromNewMessages_should_only_process_messages_after_group_ tracker.ReceivedMessages.ShouldContain("after-1"); } - await listenerHost.StopAsync(); + await listenerHost.StopAsync(TestContext.Current.CancellationToken); } [Fact] @@ -149,7 +149,7 @@ public async Task StartFromBeginning_should_process_existing_messages() opts.PublishMessage().To(new Uri($"redis://stream/0/{streamKey}")) .SendInline(); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var bus = publisherHost.MessageBus(); @@ -158,7 +158,7 @@ public async Task StartFromBeginning_should_process_existing_messages() await bus.PublishAsync(new TestMessage("existing-1")); await bus.PublishAsync(new TestMessage("existing-2")); - await publisherHost.StopAsync(); + await publisherHost.StopAsync(TestContext.Current.CancellationToken); var waiter = tracker.WaitForNumberOfMessages(2, 10000); @@ -181,7 +181,7 @@ public async Task StartFromBeginning_should_process_existing_messages() opts.Services.AddSingleton(tracker); opts.Discovery.IncludeAssembly(typeof(StartFromBehaviorTests).Assembly); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); // Give time for message processing await waiter; @@ -191,6 +191,6 @@ public async Task StartFromBeginning_should_process_existing_messages() tracker.ReceivedMessages.ShouldContain("existing-1"); tracker.ReceivedMessages.ShouldContain("existing-2"); - await listenerHost.StopAsync(); + await listenerHost.StopAsync(TestContext.Current.CancellationToken); } } diff --git a/src/Transports/Redis/Wolverine.Redis.Tests/Wolverine.Redis.Tests.csproj b/src/Transports/Redis/Wolverine.Redis.Tests/Wolverine.Redis.Tests.csproj index 6eb3a1ed0..3e1dd1149 100644 --- a/src/Transports/Redis/Wolverine.Redis.Tests/Wolverine.Redis.Tests.csproj +++ b/src/Transports/Redis/Wolverine.Redis.Tests/Wolverine.Redis.Tests.csproj @@ -1,6 +1,8 @@ + + true Exe false true diff --git a/src/Transports/Redis/Wolverine.Redis.Tests/connection_state_3231.cs b/src/Transports/Redis/Wolverine.Redis.Tests/connection_state_3231.cs index 360231249..60d536c74 100644 --- a/src/Transports/Redis/Wolverine.Redis.Tests/connection_state_3231.cs +++ b/src/Transports/Redis/Wolverine.Redis.Tests/connection_state_3231.cs @@ -21,7 +21,7 @@ public async Task healthy_redis_listener_reports_connected() { opts.UseRedisTransport(RedisContainerFixture.ConnectionString).AutoProvision(); opts.ListenToRedisStream(streamKey, "g1").BlockTimeout(100.Milliseconds()); - }).StartAsync(); + }).StartAsync(cancellationToken: TestContext.Current.CancellationToken); var state = await ConnectionStateTestHelpers.WaitForListenerConnectionStateAsync( host, "redis", TransportConnectionState.Connected); diff --git a/src/Transports/Redis/Wolverine.Redis.Tests/redis_connection_source_configuration.cs b/src/Transports/Redis/Wolverine.Redis.Tests/redis_connection_source_configuration.cs index adab67cde..88403f54b 100644 --- a/src/Transports/Redis/Wolverine.Redis.Tests/redis_connection_source_configuration.cs +++ b/src/Transports/Redis/Wolverine.Redis.Tests/redis_connection_source_configuration.cs @@ -107,13 +107,13 @@ public async Task bootstrapping_with_a_caller_managed_multiplexer_round_trips_an opts.PublishAllMessages().ToRedisStream(streamKey); opts.Services.AddSingleton(tcs); }) - .StartAsync()) + .StartAsync(cancellationToken: TestContext.Current.CancellationToken)) { var bus = host.MessageBus(); await bus.EndpointFor(new Uri($"redis://stream/0/{streamKey}")) .SendAsync(new ByoMuxMessage("123")); - var completed = await Task.WhenAny(tcs.Task, Task.Delay(TimeSpan.FromSeconds(10))); + var completed = await Task.WhenAny(tcs.Task, Task.Delay(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken)); completed.ShouldBe(tcs.Task); } @@ -151,7 +151,7 @@ public async Task connection_factory_overload_round_trips_and_is_not_disposed_by opts.PublishAllMessages().ToRedisStream(streamKey); opts.Services.AddSingleton(tcs); }) - .StartAsync()) + .StartAsync(cancellationToken: TestContext.Current.CancellationToken)) { // The transport resolved its connection from the factory. var transport = host.Services.GetRequiredService() @@ -162,7 +162,7 @@ public async Task connection_factory_overload_round_trips_and_is_not_disposed_by await bus.EndpointFor(new Uri($"redis://stream/0/{streamKey}")) .SendAsync(new ByoMuxMessage("123")); - var completed = await Task.WhenAny(tcs.Task, Task.Delay(TimeSpan.FromSeconds(10))); + var completed = await Task.WhenAny(tcs.Task, Task.Delay(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken)); completed.ShouldBe(tcs.Task); } @@ -188,7 +188,7 @@ public async Task connection_factory_resolves_the_multiplexer_from_the_ioc_conta opts.ListenToRedisStream(streamKey, "g1").DefaultIncomingMessage(); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var transport = host.Services.GetRequiredService() .Options.Transports.GetOrCreate(); diff --git a/src/Transports/SignalR/Wolverine.SignalR.Tests/Wolverine.SignalR.Tests.csproj b/src/Transports/SignalR/Wolverine.SignalR.Tests/Wolverine.SignalR.Tests.csproj index b9d0eeb58..d7d6cafc5 100644 --- a/src/Transports/SignalR/Wolverine.SignalR.Tests/Wolverine.SignalR.Tests.csproj +++ b/src/Transports/SignalR/Wolverine.SignalR.Tests/Wolverine.SignalR.Tests.csproj @@ -1,6 +1,8 @@ + + true Exe + true Exe false net9.0 diff --git a/src/Wolverine.Grpc.Tests/code_first_grpc_tests.cs b/src/Wolverine.Grpc.Tests/code_first_grpc_tests.cs index 3e9af0a88..0b5490da8 100644 --- a/src/Wolverine.Grpc.Tests/code_first_grpc_tests.cs +++ b/src/Wolverine.Grpc.Tests/code_first_grpc_tests.cs @@ -138,8 +138,8 @@ public async Task map_wolverine_grpc_services_discovers_and_maps_grpc_service_ty // This should discover PingGrpcService via the "GrpcService" suffix convention app.MapWolverineGrpcServices(); - await app.StartAsync(); - await app.StopAsync(); + await app.StartAsync(TestContext.Current.CancellationToken); + await app.StopAsync(TestContext.Current.CancellationToken); await app.DisposeAsync(); } } diff --git a/src/Wolverine.Grpc.Tests/codegen_preview_grpc_tests.cs b/src/Wolverine.Grpc.Tests/codegen_preview_grpc_tests.cs index 5ca1fa957..9a3351056 100644 --- a/src/Wolverine.Grpc.Tests/codegen_preview_grpc_tests.cs +++ b/src/Wolverine.Grpc.Tests/codegen_preview_grpc_tests.cs @@ -37,7 +37,7 @@ public async Task codegen_preview_generates_code_for_grpc_service() { services.AddWolverineGrpc(); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); // Mimic MapProtoFirstServices() without needing a WebApplication: discover the // stubs, then push the graph into the supplemental code-file collection so that @@ -112,7 +112,7 @@ public async Task codegen_preview_reports_no_match_for_unknown_grpc_input() { services.AddWolverineGrpc(); }) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var graph = host.Services.GetRequiredService(); var grpcOptions = host.Services.GetRequiredService(); diff --git a/src/Wolverine.Grpc.Tests/grpc_and_http_coexistence_3591.cs b/src/Wolverine.Grpc.Tests/grpc_and_http_coexistence_3591.cs index 6789891d7..0eae3103a 100644 --- a/src/Wolverine.Grpc.Tests/grpc_and_http_coexistence_3591.cs +++ b/src/Wolverine.Grpc.Tests/grpc_and_http_coexistence_3591.cs @@ -64,24 +64,24 @@ public async ValueTask DisposeAsync() [Fact] public async Task http_get_still_responds_when_grpc_services_are_mapped() { - var response = await _client.GetAsync("/api/coexist/check"); + var response = await _client.GetAsync("/api/coexist/check", TestContext.Current.CancellationToken); response.StatusCode.ShouldNotBe(System.Net.HttpStatusCode.NotFound); response.EnsureSuccessStatusCode(); - (await response.Content.ReadAsStringAsync()).ShouldContain("ok"); + (await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken)).ShouldContain("ok"); } [Fact] public async Task http_get_with_asparameters_and_invoke_still_responds_when_grpc_is_mapped() { // The issue's exact endpoint shape: [AsParameters] request forwarded through the message bus. - var response = await _client.GetAsync("/api/coexist/invoke?Name=bob"); + var response = await _client.GetAsync("/api/coexist/invoke?Name=bob", TestContext.Current.CancellationToken); response.StatusCode.ShouldNotBe(System.Net.HttpStatusCode.NotFound); response.EnsureSuccessStatusCode(); - (await response.Content.ReadAsStringAsync()).ShouldContain("bob"); + (await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken)).ShouldContain("bob"); } } diff --git a/src/Wolverine.Grpc.Tests/grpc_and_http_coexistence_3630.cs b/src/Wolverine.Grpc.Tests/grpc_and_http_coexistence_3630.cs index 83698517c..616e30d71 100644 --- a/src/Wolverine.Grpc.Tests/grpc_and_http_coexistence_3630.cs +++ b/src/Wolverine.Grpc.Tests/grpc_and_http_coexistence_3630.cs @@ -62,24 +62,24 @@ public async ValueTask DisposeAsync() [Fact] public async Task http_get_still_responds_when_grpc_services_are_mapped() { - var response = await _client.GetAsync("/gh3630/check"); + var response = await _client.GetAsync("/gh3630/check", TestContext.Current.CancellationToken); response.StatusCode.ShouldNotBe(System.Net.HttpStatusCode.NotFound); response.EnsureSuccessStatusCode(); - (await response.Content.ReadAsStringAsync()).ShouldContain("ok"); + (await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken)).ShouldContain("ok"); } [Fact] public async Task http_get_with_asparameters_and_invoke_still_responds_when_grpc_is_mapped() { // The issue's exact endpoint shape: an [AsParameters] request forwarded through the message bus. - var response = await _client.GetAsync("/gh3630/invoke?Name=bob&Pin=1111"); + var response = await _client.GetAsync("/gh3630/invoke?Name=bob&Pin=1111", TestContext.Current.CancellationToken); response.StatusCode.ShouldNotBe(System.Net.HttpStatusCode.NotFound); response.EnsureSuccessStatusCode(); - (await response.Content.ReadAsStringAsync()).ShouldContain("bob"); + (await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken)).ShouldContain("bob"); } } diff --git a/src/Wolverine.Grpc.Tests/grpc_capabilities_descriptor_source_3267.cs b/src/Wolverine.Grpc.Tests/grpc_capabilities_descriptor_source_3267.cs index 207d5c7ad..2d5c2424f 100644 --- a/src/Wolverine.Grpc.Tests/grpc_capabilities_descriptor_source_3267.cs +++ b/src/Wolverine.Grpc.Tests/grpc_capabilities_descriptor_source_3267.cs @@ -249,7 +249,7 @@ public async Task no_grpc_means_empty_capabilities_and_no_registered_source() { using var host = await Host.CreateDefaultBuilder() .UseWolverine() - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); host.Services.GetService().ShouldBeNull(); diff --git a/src/Wolverine.Grpc.Tests/grpc_endpoint_manifest_3235.cs b/src/Wolverine.Grpc.Tests/grpc_endpoint_manifest_3235.cs index 32f5029de..8c3df25fe 100644 --- a/src/Wolverine.Grpc.Tests/grpc_endpoint_manifest_3235.cs +++ b/src/Wolverine.Grpc.Tests/grpc_endpoint_manifest_3235.cs @@ -27,7 +27,7 @@ public async Task projects_proto_first_and_code_first_unary_endpoints() opts.Discovery.IncludeAssembly(typeof(IGreeterCodeFirstService).Assembly); }) .ConfigureServices(services => services.AddWolverineGrpc()) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var manifest = host.Services.GetRequiredService(); @@ -77,7 +77,7 @@ public async Task manifest_is_not_registered_without_grpc() { using var host = await Host.CreateDefaultBuilder() .UseWolverine() - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); host.Services.GetService().ShouldBeNull(); } diff --git a/src/Wolverine.Grpc.Tests/grpc_service_manifest.cs b/src/Wolverine.Grpc.Tests/grpc_service_manifest.cs index 0a225e301..5c2084930 100644 --- a/src/Wolverine.Grpc.Tests/grpc_service_manifest.cs +++ b/src/Wolverine.Grpc.Tests/grpc_service_manifest.cs @@ -32,7 +32,7 @@ public async Task generated_registry_captures_discovered_service_types() opts.ApplicationAssembly = typeof(GreeterGrpcService).Assembly; }) .ConfigureServices(services => services.AddWolverineGrpc()) - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); var graph = host.Services.GetRequiredService(); var grpcOptions = host.Services.GetRequiredService(); diff --git a/src/Wolverine.Grpc.Tests/inline_request_reply_grpc.cs b/src/Wolverine.Grpc.Tests/inline_request_reply_grpc.cs index aa591de40..982652183 100644 --- a/src/Wolverine.Grpc.Tests/inline_request_reply_grpc.cs +++ b/src/Wolverine.Grpc.Tests/inline_request_reply_grpc.cs @@ -44,7 +44,7 @@ public async Task invoke_reads_reply_from_the_grpc_response_slot() using var receiver = await startReceiverAsync(); using var sender = await startSenderAsync(); - var response = await sender.MessageBus().InvokeAsync(new GrpcInlinePing("Rand")); + var response = await sender.MessageBus().InvokeAsync(new GrpcInlinePing("Rand"), TestContext.Current.CancellationToken); response.ShouldNotBeNull(); response.Name.ShouldBe("Rand"); diff --git a/src/Wolverine.HealthChecks.Tests/EndToEndIntegrationTests.cs b/src/Wolverine.HealthChecks.Tests/EndToEndIntegrationTests.cs index ebff56a10..ac5af0420 100644 --- a/src/Wolverine.HealthChecks.Tests/EndToEndIntegrationTests.cs +++ b/src/Wolverine.HealthChecks.Tests/EndToEndIntegrationTests.cs @@ -54,10 +54,10 @@ private static IHostBuilder BuildHostBuilder() [Fact] public async Task health_endpoint_reports_healthy_after_startup() { - using var host = await BuildHostBuilder().StartAsync(); + using var host = await BuildHostBuilder().StartAsync(cancellationToken: TestContext.Current.CancellationToken); var client = host.GetTestClient(); - var response = await client.GetAsync("/health"); + var response = await client.GetAsync("/health", TestContext.Current.CancellationToken); response.StatusCode.ShouldBe(HttpStatusCode.OK); } @@ -93,18 +93,18 @@ public async Task tag_scoping_separates_liveness_and_readiness() }); }) .UseWolverine() - .StartAsync(); + .StartAsync(cancellationToken: TestContext.Current.CancellationToken); try { var client = host.GetTestClient(); - (await client.GetAsync("/health/ready")).StatusCode.ShouldBe(HttpStatusCode.OK); - (await client.GetAsync("/health/live")).StatusCode.ShouldBe(HttpStatusCode.OK); + (await client.GetAsync("/health/ready", TestContext.Current.CancellationToken)).StatusCode.ShouldBe(HttpStatusCode.OK); + (await client.GetAsync("/health/live", TestContext.Current.CancellationToken)).StatusCode.ShouldBe(HttpStatusCode.OK); } finally { - await host.StopAsync(); + await host.StopAsync(TestContext.Current.CancellationToken); host.Dispose(); } } diff --git a/src/Wolverine.HealthChecks.Tests/Wolverine.HealthChecks.Tests.csproj b/src/Wolverine.HealthChecks.Tests/Wolverine.HealthChecks.Tests.csproj index ff03ad340..76ec1df01 100644 --- a/src/Wolverine.HealthChecks.Tests/Wolverine.HealthChecks.Tests.csproj +++ b/src/Wolverine.HealthChecks.Tests/Wolverine.HealthChecks.Tests.csproj @@ -1,6 +1,8 @@ + + true Exe false net9.0 diff --git a/src/Wolverine.HealthChecks.Tests/WolverineBusHealthCheckTests.cs b/src/Wolverine.HealthChecks.Tests/WolverineBusHealthCheckTests.cs index aad09fe5b..2ea684d49 100644 --- a/src/Wolverine.HealthChecks.Tests/WolverineBusHealthCheckTests.cs +++ b/src/Wolverine.HealthChecks.Tests/WolverineBusHealthCheckTests.cs @@ -41,7 +41,7 @@ public async Task healthy_when_started_and_not_cancelling() var runtime = BuildRuntime(started: true, cancellationRequested: false); var check = new WolverineBusHealthCheck(runtime); - var result = await check.CheckHealthAsync(ContextFor()); + var result = await check.CheckHealthAsync(ContextFor(), TestContext.Current.CancellationToken); result.Status.ShouldBe(HealthStatus.Healthy); result.Data.ShouldContainKey("started"); @@ -56,7 +56,7 @@ public async Task unhealthy_when_not_yet_started() var runtime = BuildRuntime(started: false, cancellationRequested: false); var check = new WolverineBusHealthCheck(runtime); - var result = await check.CheckHealthAsync(ContextFor()); + var result = await check.CheckHealthAsync(ContextFor(), TestContext.Current.CancellationToken); result.Status.ShouldBe(HealthStatus.Unhealthy); result.Data["started"].ShouldBe(false); @@ -69,7 +69,7 @@ public async Task uses_failure_status_from_registration() var runtime = BuildRuntime(started: false, cancellationRequested: false); var check = new WolverineBusHealthCheck(runtime); - var result = await check.CheckHealthAsync(ContextFor(failureStatus: HealthStatus.Degraded)); + var result = await check.CheckHealthAsync(ContextFor(failureStatus: HealthStatus.Degraded), TestContext.Current.CancellationToken); result.Status.ShouldBe(HealthStatus.Degraded); } @@ -80,7 +80,7 @@ public async Task unhealthy_when_runtime_cancellation_requested() var runtime = BuildRuntime(started: true, cancellationRequested: true); var check = new WolverineBusHealthCheck(runtime); - var result = await check.CheckHealthAsync(ContextFor()); + var result = await check.CheckHealthAsync(ContextFor(), TestContext.Current.CancellationToken); result.Status.ShouldBe(HealthStatus.Unhealthy); result.Data["cancellationRequested"].ShouldBe(true); diff --git a/src/Wolverine.HealthChecks.Tests/WolverineListenerHealthCheckTests.cs b/src/Wolverine.HealthChecks.Tests/WolverineListenerHealthCheckTests.cs index 0ac17580b..1023891ad 100644 --- a/src/Wolverine.HealthChecks.Tests/WolverineListenerHealthCheckTests.cs +++ b/src/Wolverine.HealthChecks.Tests/WolverineListenerHealthCheckTests.cs @@ -45,7 +45,7 @@ public async Task healthy_when_all_listeners_accepting() FakeListener(ListeningStatus.Accepting, "local://default") ); - var result = await new WolverineListenerHealthCheck(runtime).CheckHealthAsync(ContextFor()); + var result = await new WolverineListenerHealthCheck(runtime).CheckHealthAsync(ContextFor(), TestContext.Current.CancellationToken); result.Status.ShouldBe(HealthStatus.Healthy); result.Data["accepting"].ShouldBe(2); @@ -62,7 +62,7 @@ public async Task degraded_when_any_listener_too_busy() FakeListener(ListeningStatus.TooBusy, "rabbitmq://orders") ); - var result = await new WolverineListenerHealthCheck(runtime).CheckHealthAsync(ContextFor()); + var result = await new WolverineListenerHealthCheck(runtime).CheckHealthAsync(ContextFor(), TestContext.Current.CancellationToken); result.Status.ShouldBe(HealthStatus.Degraded); result.Data["tooBusy"].ShouldBe(1); @@ -76,7 +76,7 @@ public async Task degraded_when_any_listener_globally_latched() FakeListener(ListeningStatus.GloballyLatched, "rabbitmq://orders") ); - var result = await new WolverineListenerHealthCheck(runtime).CheckHealthAsync(ContextFor()); + var result = await new WolverineListenerHealthCheck(runtime).CheckHealthAsync(ContextFor(), TestContext.Current.CancellationToken); result.Status.ShouldBe(HealthStatus.Degraded); result.Data["globallyLatched"].ShouldBe(1); @@ -90,7 +90,7 @@ public async Task unhealthy_when_all_listeners_stopped() FakeListener(ListeningStatus.Stopped, "local://default") ); - var result = await new WolverineListenerHealthCheck(runtime).CheckHealthAsync(ContextFor()); + var result = await new WolverineListenerHealthCheck(runtime).CheckHealthAsync(ContextFor(), TestContext.Current.CancellationToken); result.Status.ShouldBe(HealthStatus.Unhealthy); result.Data["stopped"].ShouldBe(2); @@ -103,7 +103,7 @@ public async Task healthy_with_note_when_no_listeners_match() // who want a missing listener to fail can register a separate check. var runtime = RuntimeWithListeners(); - var result = await new WolverineListenerHealthCheck(runtime).CheckHealthAsync(ContextFor()); + var result = await new WolverineListenerHealthCheck(runtime).CheckHealthAsync(ContextFor(), TestContext.Current.CancellationToken); result.Status.ShouldBe(HealthStatus.Healthy); result.Data["listenerCount"].ShouldBe(0); @@ -122,7 +122,7 @@ public async Task filter_scopes_listeners() var check = new WolverineListenerHealthCheck(runtime, agent => agent.Uri.Scheme == "rabbitmq"); - var result = await check.CheckHealthAsync(ContextFor()); + var result = await check.CheckHealthAsync(ContextFor(), TestContext.Current.CancellationToken); result.Status.ShouldBe(HealthStatus.Unhealthy); result.Data["listenerCount"].ShouldBe(1); @@ -137,7 +137,7 @@ public async Task uses_failure_status_from_registration() ); var result = await new WolverineListenerHealthCheck(runtime) - .CheckHealthAsync(ContextFor(failureStatus: HealthStatus.Degraded)); + .CheckHealthAsync(ContextFor(failureStatus: HealthStatus.Degraded), TestContext.Current.CancellationToken); result.Status.ShouldBe(HealthStatus.Degraded); } From 511673236e2295173e64ca8b1ed5ad2c34285d24 Mon Sep 17 00:00:00 2001 From: "Jeremy D. Miller" Date: Wed, 29 Jul 2026 16:34:32 -0500 Subject: [PATCH 2/2] fix(tests): match any CancellationToken in NSubstitute arranges, not the test's (GH-3702) The xUnit1051 sweep threaded `TestContext.Current.CancellationToken` into NSubstitute mock interactions. On a verification that is merely narrowing, and on an arrange it is worse than narrowing: it makes the stub match only that exact token. Production code passes its own token -- `default` in every one of these paths -- so the arranged call never matches, NSubstitute hands back `null`, and the test dies dereferencing it. That is the 11 consistently-failing tests on this PR's last CI run, all of them `NullReferenceException` under a transport's endpoint-initialization unit tests: Wolverine.AmazonSns.Tests when_initializing_the_endpoint (1) Wolverine.AmazonSqs.Tests when_initializing_the_endpoint (4) Wolverine.AzureServiceBus.Tests AzureServiceSubscriptionTests (1) Wolverine.RabbitMQ.Tests Internals.RabbitMqQueueTests (5) The original commit already knew verifications had to use `Arg.Any()` and converted 25 of them; it just did not carry the same rule to the arrange side. The rule is simply: NSubstitute interactions match on arguments, so a mock call -- arrange or assert -- takes `Arg.Any()`. Never the ambient test token. 13 sites across 5 files. Found by tokenizing every file into statements and flagging any `TestContext.Current.CancellationToken` inside a statement carrying an NSubstitute marker (`.Returns`/`.Received`/`Arg.*`/...). A second, independent pass -- flag the token whenever it is an argument to a call on a variable the file builds with `Substitute.For<>` -- now reports zero, so this clears the class and not just the failures CI happened to surface. Verified: red baseline reproduced locally before the fix (Wolverine.AmazonSqs.Tests `when_initializing_the_endpoint` = 4 failed / 4 passed, same 4 as CI), then 0 failed / 8 passed after. All four projects build with xUnit1051 at error severity, 0 warnings. SNS 2/2, SQS 8/8, ASB 5/5, RabbitMQ 25/25 (includes native_dead_letter_queue_mechanics against a live broker, whose two sites were latent -- they had not yet failed on CI). Co-Authored-By: Claude Opus 5 (1M context) --- .../Internal/AmazonSnsTopicTests.cs | 2 +- .../Internal/AmazonSqsQueueTests.cs | 8 ++--- .../AzureServiceBusSubscriptionTests.cs | 12 ++++++-- .../Internals/RabbitMqQueueTests.cs | 30 ++++++++++++++----- .../native_dead_letter_queue_mechanics.cs | 4 +-- 5 files changed, 39 insertions(+), 17 deletions(-) diff --git a/src/Transports/AWS/Wolverine.AmazonSns.Tests/Internal/AmazonSnsTopicTests.cs b/src/Transports/AWS/Wolverine.AmazonSns.Tests/Internal/AmazonSnsTopicTests.cs index 85379929f..8d2cf4f56 100644 --- a/src/Transports/AWS/Wolverine.AmazonSns.Tests/Internal/AmazonSnsTopicTests.cs +++ b/src/Transports/AWS/Wolverine.AmazonSns.Tests/Internal/AmazonSnsTopicTests.cs @@ -72,7 +72,7 @@ public async Task do_create_topic_if_parent_is_auto_provision() const string theSnsTopicArn = "arn:aws:sns:us-east-2:123456789012:TheTopic"; - theSnsClient.CreateTopicAsync(Arg.Any(), TestContext.Current.CancellationToken).Returns(new CreateTopicResponse + theSnsClient.CreateTopicAsync(Arg.Any(), Arg.Any()).Returns(new CreateTopicResponse { TopicArn = theSnsTopicArn }); diff --git a/src/Transports/AWS/Wolverine.AmazonSqs.Tests/Internal/AmazonSqsQueueTests.cs b/src/Transports/AWS/Wolverine.AmazonSqs.Tests/Internal/AmazonSqsQueueTests.cs index 267e6a791..407e9e909 100644 --- a/src/Transports/AWS/Wolverine.AmazonSqs.Tests/Internal/AmazonSqsQueueTests.cs +++ b/src/Transports/AWS/Wolverine.AmazonSqs.Tests/Internal/AmazonSqsQueueTests.cs @@ -132,7 +132,7 @@ public async Task do_not_create_if_parent_is_not_auto_provision() var theSqsQueueUrl = "https://someserver.com/foo"; - theClient.GetQueueUrlAsync(theQueue.QueueName, TestContext.Current.CancellationToken).Returns(new GetQueueUrlResponse + theClient.GetQueueUrlAsync(theQueue.QueueName, Arg.Any()).Returns(new GetQueueUrlResponse { QueueUrl = theSqsQueueUrl }); @@ -151,7 +151,7 @@ public async Task do_create_queue_if_parent_is_autoprovision() var theSqsQueueUrl = "https://someserver.com/foo"; - theClient.CreateQueueAsync(Arg.Any(), TestContext.Current.CancellationToken).Returns(new CreateQueueResponse + theClient.CreateQueueAsync(Arg.Any(), Arg.Any()).Returns(new CreateQueueResponse { QueueUrl = theSqsQueueUrl }); @@ -169,7 +169,7 @@ public async Task do_not_purge_when_not_auto_purge() // Gotta set this up to make the test work var theSqsQueueUrl = "https://someserver.com/foo"; - theClient.GetQueueUrlAsync(theQueue.QueueName, TestContext.Current.CancellationToken).Returns(new GetQueueUrlResponse + theClient.GetQueueUrlAsync(theQueue.QueueName, Arg.Any()).Returns(new GetQueueUrlResponse { QueueUrl = theSqsQueueUrl }); @@ -187,7 +187,7 @@ public async Task should_purge_when_auto_purge() // Gotta set this up to make the test work var theSqsQueueUrl = "https://someserver.com/foo"; - theClient.GetQueueUrlAsync(theQueue.QueueName, TestContext.Current.CancellationToken).Returns(new GetQueueUrlResponse + theClient.GetQueueUrlAsync(theQueue.QueueName, Arg.Any()).Returns(new GetQueueUrlResponse { QueueUrl = theSqsQueueUrl }); diff --git a/src/Transports/Azure/Wolverine.AzureServiceBus.Tests/Internal/AzureServiceBusSubscriptionTests.cs b/src/Transports/Azure/Wolverine.AzureServiceBus.Tests/Internal/AzureServiceBusSubscriptionTests.cs index b7a73664e..75ffbda5f 100644 --- a/src/Transports/Azure/Wolverine.AzureServiceBus.Tests/Internal/AzureServiceBusSubscriptionTests.cs +++ b/src/Transports/Azure/Wolverine.AzureServiceBus.Tests/Internal/AzureServiceBusSubscriptionTests.cs @@ -52,7 +52,10 @@ public async Task initialize_with_auto_provision_and_default_rule() await subscription.InitializeAsync(theManagementClient, NullLogger.Instance); - await theManagementClient.Received().CreateSubscriptionAsync(Arg.Is(x => x.TopicName == "foo" && x.SubscriptionName == "bar"), Arg.Is(x => x.Equals(new CreateRuleOptions())), Arg.Any()); + await theManagementClient.Received().CreateSubscriptionAsync( + Arg.Is(x => x.TopicName == "foo" && x.SubscriptionName == "bar"), + Arg.Is(x => x.Equals(new CreateRuleOptions())), + Arg.Any()); } [Fact] @@ -72,9 +75,12 @@ public async Task initialize_with_auto_provision_with_custom_rule() await subscription.InitializeAsync(theManagementClient, NullLogger.Instance); - await theManagementClient.Received().CreateSubscriptionAsync(Arg.Is(x => x.TopicName == "foo" && x.SubscriptionName == "bar"), Arg.Is(x => + await theManagementClient.Received().CreateSubscriptionAsync( + Arg.Is(x => x.TopicName == "foo" && x.SubscriptionName == "bar"), + Arg.Is(x => x.Filter.Equals(new SqlRuleFilter("foo = 'bar'")) && - x.Action.Equals(new SqlRuleAction("SET foo = 'baz'"))), TestContext.Current.CancellationToken); + x.Action.Equals(new SqlRuleAction("SET foo = 'baz'"))), + Arg.Any()); } } \ No newline at end of file diff --git a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Internals/RabbitMqQueueTests.cs b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Internals/RabbitMqQueueTests.cs index fff7f7f5a..bc4767877 100644 --- a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Internals/RabbitMqQueueTests.cs +++ b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/Internals/RabbitMqQueueTests.cs @@ -66,13 +66,21 @@ public async Task publish_queue_dead_letter_queueing_sets_a_specific_dlq() queue.DeadLetterQueue.ExchangeName.ShouldBe("publish-dlx-exchange"); var channel = Substitute.For(); - channel.QueueDeclareAsync(default!, default, default, default, default!, cancellationToken: TestContext.Current.CancellationToken).ReturnsForAnyArgs(Task.FromResult(new QueueDeclareOk("publish-queue", 0, 0))); + channel.QueueDeclareAsync(default!, default, default, default, default!, + cancellationToken: Arg.Any()) + .ReturnsForAnyArgs(Task.FromResult(new QueueDeclareOk("publish-queue", 0, 0))); await queue.DeclareAsync(channel, NullLogger.Instance); - await channel.Received().QueueDeclareAsync("publish-queue", queue.IsDurable, queue.IsExclusive, queue.AutoDelete, Arg.Is>(args => + await channel.Received().QueueDeclareAsync( + "publish-queue", + queue.IsDurable, + queue.IsExclusive, + queue.AutoDelete, + Arg.Is>(args => args.ContainsKey(RabbitMqTransport.DeadLetterQueueHeader) && - Equals(args[RabbitMqTransport.DeadLetterQueueHeader], "publish-dlx-exchange")), cancellationToken: TestContext.Current.CancellationToken); + Equals(args[RabbitMqTransport.DeadLetterQueueHeader], "publish-dlx-exchange")), + cancellationToken: Arg.Any()); } [Fact] @@ -97,12 +105,20 @@ public async Task publish_queue_disable_dead_letter_queueing_clears_the_dlq() queue.DeadLetterQueue.ShouldBeNull(); var channel = Substitute.For(); - channel.QueueDeclareAsync(default!, default, default, default, default!, cancellationToken: TestContext.Current.CancellationToken).ReturnsForAnyArgs(Task.FromResult(new QueueDeclareOk("publish-queue", 0, 0))); + channel.QueueDeclareAsync(default!, default, default, default, default!, + cancellationToken: Arg.Any()) + .ReturnsForAnyArgs(Task.FromResult(new QueueDeclareOk("publish-queue", 0, 0))); await queue.DeclareAsync(channel, NullLogger.Instance); - await channel.Received().QueueDeclareAsync("publish-queue", queue.IsDurable, queue.IsExclusive, queue.AutoDelete, Arg.Is>(args => - !args.ContainsKey(RabbitMqTransport.DeadLetterQueueHeader)), cancellationToken: TestContext.Current.CancellationToken); + await channel.Received().QueueDeclareAsync( + "publish-queue", + queue.IsDurable, + queue.IsExclusive, + queue.AutoDelete, + Arg.Is>(args => + !args.ContainsKey(RabbitMqTransport.DeadLetterQueueHeader)), + cancellationToken: Arg.Any()); } [Fact] @@ -139,7 +155,7 @@ public async Task declare(bool autoDelete, bool isExclusive, bool isDurable) await queue.DeclareAsync(channel, NullLogger.Instance); await channel.Received() - .QueueDeclareAsync("foo", queue.IsDurable, queue.IsExclusive, queue.AutoDelete, (IDictionary)queue.Arguments, cancellationToken: TestContext.Current.CancellationToken); + .QueueDeclareAsync("foo", queue.IsDurable, queue.IsExclusive, queue.AutoDelete, (IDictionary)queue.Arguments, cancellationToken: Arg.Any()); queue.HasDeclared.ShouldBeTrue(); } diff --git a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/native_dead_letter_queue_mechanics.cs b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/native_dead_letter_queue_mechanics.cs index bc2a1adb5..711628dfb 100644 --- a/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/native_dead_letter_queue_mechanics.cs +++ b/src/Transports/RabbitMQ/Wolverine.RabbitMQ.Tests/native_dead_letter_queue_mechanics.cs @@ -259,7 +259,7 @@ public async Task uses_overridden_dead_letter_exchange_per_queue_when_transport_ queue.Compile(runtime); var channel = Substitute.For(); - channel.QueueDeclareAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any>(), cancellationToken: TestContext.Current.CancellationToken).Returns(Task.FromResult(new QueueDeclareOk(queue.QueueName, 0, 0))); + channel.QueueDeclareAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any>(), cancellationToken: Arg.Any()).Returns(Task.FromResult(new QueueDeclareOk(queue.QueueName, 0, 0))); await queue.DeclareAsync(channel, NullLogger.Instance); @@ -333,7 +333,7 @@ public async Task default_and_override_queues_keep_their_own_dlx_exchange_on_dec overrideEndpoint.Compile(runtime); var channel = Substitute.For(); - channel.QueueDeclareAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any>(), cancellationToken: TestContext.Current.CancellationToken).Returns(Task.FromResult(new QueueDeclareOk(defaultQueue, 0, 0))); + channel.QueueDeclareAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any>(), cancellationToken: Arg.Any()).Returns(Task.FromResult(new QueueDeclareOk(defaultQueue, 0, 0))); await defaultEndpoint.DeclareAsync(channel, NullLogger.Instance); await overrideEndpoint.DeclareAsync(channel, NullLogger.Instance);