language
stringclasses
4 values
source_code
stringlengths
2
986k
test_code
stringlengths
125
758k
repo_name
stringclasses
97 values
instruction
stringlengths
156
643
industrial
namespace Polly.CircuitBreaker; internal sealed class CircuitBreakerResilienceStrategy<T> : ResilienceStrategy<T>, IDisposable { private readonly Func<CircuitBreakerPredicateArguments<T>, ValueTask<bool>> _handler; private readonly CircuitStateController<T> _controller; private readonly IDisposable? _manualControlRegistration; public CircuitBreakerResilienceStrategy( Func<CircuitBreakerPredicateArguments<T>, ValueTask<bool>> handler, CircuitStateController<T> controller, CircuitBreakerStateProvider? stateProvider, CircuitBreakerManualControl? manualControl) { _handler = handler; _controller = controller; stateProvider?.Initialize(() => _controller.CircuitState); _manualControlRegistration = manualControl?.Initialize( _controller.IsolateCircuitAsync, _controller.CloseCircuitAsync); } public void Dispose() { _manualControlRegistration?.Dispose(); _controller.Dispose(); } protected internal override async ValueTask<Outcome<T>> ExecuteCore<TState>(Func<ResilienceContext, TState, ValueTask<Outcome<T>>> callback, ResilienceContext context, TState state) { if (await _controller.OnActionPreExecuteAsync(context).ConfigureAwait(context.ContinueOnCapturedContext) is Outcome<T> outcome) { return outcome; } try { context.CancellationToken.ThrowIfCancellationRequested(); outcome = await callback(context, state).ConfigureAwait(context.ContinueOnCapturedContext); } #pragma warning disable CA1031 catch (Exception ex) { outcome = new(ex); } #pragma warning restore CA1031 var args = new CircuitBreakerPredicateArguments<T>(context, outcome); if (await _handler(args).ConfigureAwait(context.ContinueOnCapturedContext)) { await _controller.OnHandledOutcomeAsync(outcome, context).ConfigureAwait(context.ContinueOnCapturedContext); } else { await _controller.OnUnhandledOutcomeAsync(outcome, context).ConfigureAwait(context.ContinueOnCapturedContext); } return outcome; } }
using Microsoft.Extensions.Time.Testing; using NSubstitute; using Polly.CircuitBreaker; using Polly.Telemetry; namespace Polly.Core.Tests.CircuitBreaker; public class CircuitBreakerResilienceStrategyTests : IDisposable { private readonly FakeTimeProvider _timeProvider; private readonly CircuitBehavior _behavior; private readonly ResilienceStrategyTelemetry _telemetry; private readonly CircuitBreakerStrategyOptions<int> _options; private readonly CircuitStateController<int> _controller; public CircuitBreakerResilienceStrategyTests() { _timeProvider = new FakeTimeProvider(); _behavior = Substitute.For<CircuitBehavior>(); _telemetry = TestUtilities.CreateResilienceTelemetry(_ => { }); _options = new CircuitBreakerStrategyOptions<int>(); _controller = new CircuitStateController<int>( CircuitBreakerConstants.DefaultBreakDuration, null, null, null, _behavior, _timeProvider, _telemetry, null); } private static CancellationToken CancellationToken => TestCancellation.Token; [Fact] public void Ctor_Ok() => Should.NotThrow(Create); [Fact] public void Ctor_StateProvider_EnsureAttached() { _options.StateProvider = new CircuitBreakerStateProvider(); Create(); _options.StateProvider.IsInitialized.ShouldBeTrue(); _options.StateProvider.CircuitState.ShouldBe(CircuitState.Closed); } [Fact] public async Task Ctor_ManualControl_EnsureAttached() { _options.ShouldHandle = args => new ValueTask<bool>(args.Outcome.Exception is InvalidOperationException); _options.ManualControl = new CircuitBreakerManualControl(); var strategy = Create(); await _options.ManualControl.IsolateAsync(CancellationToken); Should.Throw<IsolatedCircuitException>(() => strategy.Execute(_ => 0)).RetryAfter.ShouldBeNull(); await _options.ManualControl.CloseAsync(CancellationToken); Should.NotThrow(() => strategy.Execute(_ => 0)); _behavior.Received().OnCircuitClosed(); _behavior.Received().OnActionSuccess(CircuitState.Closed); } [Fact] public void Execute_HandledResult_OnFailureCalled() { _options.ShouldHandle = args => new ValueTask<bool>(args.Outcome.Result is -1); var strategy = Create(); var shouldBreak = false; _behavior.When(v => v.OnActionFailure(CircuitState.Closed, out Arg.Any<bool>())) .Do(x => x[1] = shouldBreak); strategy.Execute(_ => -1, CancellationToken).ShouldBe(-1); _behavior.Received().OnActionFailure(CircuitState.Closed, out Arg.Any<bool>()); } [Fact] public void Execute_UnhandledResult_OnActionSuccess() { _options.ShouldHandle = args => new ValueTask<bool>(args.Outcome.Result is -1); var strategy = Create(); strategy.Execute(_ => 0, CancellationToken).ShouldBe(0); _behavior.Received(1).OnActionSuccess(CircuitState.Closed); } [Fact] public void Execute_HandledException_OnFailureCalled() { _options.ShouldHandle = args => new ValueTask<bool>(args.Outcome.Exception is InvalidOperationException); var strategy = Create(); var shouldBreak = false; _behavior.When(v => v.OnActionFailure(CircuitState.Closed, out Arg.Any<bool>())) .Do(x => x[1] = shouldBreak); Should.Throw<InvalidOperationException>(() => strategy.Execute<int>(_ => throw new InvalidOperationException())); _behavior.Received().OnActionFailure(CircuitState.Closed, out Arg.Any<bool>()); } [Fact] public void Execute_UnhandledException_OnActionSuccess() { _options.ShouldHandle = args => new ValueTask<bool>(args.Outcome.Exception is InvalidOperationException); var strategy = Create(); Should.Throw<ArgumentException>(() => strategy.Execute<int>(_ => throw new ArgumentException())); _behavior.Received(1).OnActionSuccess(CircuitState.Closed); } [Fact] public async Task ExecuteOutcomeAsync_UnhandledException_OnActionSuccess() { _options.ShouldHandle = args => new ValueTask<bool>(args.Outcome.Exception is InvalidOperationException); var strategy = Create(); var outcome = await strategy.ExecuteOutcomeAsync<int, string>((_, _) => throw new ArgumentException(), new(), "dummy-state"); outcome.Exception.ShouldBeOfType<ArgumentException>(); _behavior.Received(1).OnActionSuccess(CircuitState.Closed); } public void Dispose() => _controller.Dispose(); [Fact] public void Execute_Ok() { _options.ShouldHandle = _ => PredicateResult.False(); Should.NotThrow(() => Create().Execute(_ => 0)); _behavior.Received(1).OnActionSuccess(CircuitState.Closed); } private ResiliencePipeline<int> Create() #pragma warning disable CA2000 // Dispose objects before losing scope => new CircuitBreakerResilienceStrategy<int>(_options.ShouldHandle!, _controller, _options.StateProvider, _options.ManualControl).AsPipeline(); #pragma warning restore CA2000 // Dispose objects before losing scope }
Polly
You are an expert C++ developer. Task: Write a unit test for 'CircuitBreakerResilienceStrategy' using GoogleTest (gtest) and GoogleMock (gmock). Context: - Class: CircuitBreakerResilienceStrategy Requirements: Use EXPECT_CALL for virtual methods.
industrial
#if !NETCOREAPP using System.Runtime.Serialization; #endif namespace Polly.CircuitBreaker; #pragma warning disable CA1032 // Implement standard exception constructors /// <summary> /// Exception thrown when a circuit is broken. /// </summary> /// <typeparam name="TResult">The type of returned results being handled by the policy.</typeparam> #if !NETCOREAPP [Serializable] #endif public class BrokenCircuitException<TResult> : BrokenCircuitException { /// <summary> /// Initializes a new instance of the <see cref="BrokenCircuitException{TResult}"/> class. /// </summary> /// <param name="result">The result which caused the circuit to break.</param> public BrokenCircuitException(TResult result) => Result = result; /// <summary> /// Initializes a new instance of the <see cref="BrokenCircuitException{TResult}"/> class. /// </summary> /// <param name="message">The message that describes the error.</param> /// <param name="result">The result which caused the circuit to break.</param> public BrokenCircuitException(string message, TResult result) : base(message) => Result = result; /// <summary> /// Initializes a new instance of the <see cref="BrokenCircuitException{TResult}"/> class. /// </summary> /// <param name="message">The message that describes the error.</param> /// <param name="inner">The inner exception.</param> /// <param name="result">The result which caused the circuit to break.</param> public BrokenCircuitException(string message, Exception inner, TResult result) : base(message, inner) => Result = result; /// <summary> /// Gets the result value which was considered a handled fault, by the policy. /// </summary> public TResult Result { get; } #pragma warning disable RS0016 // Add public types and members to the declared API #if !NETCOREAPP /// <summary> /// Initializes a new instance of the <see cref="BrokenCircuitException{TResult}"/> class. /// </summary> /// <param name="info">The <see cref="SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="StreamingContext" /> that contains contextual information about the source or destination.</param> protected BrokenCircuitException(SerializationInfo info, StreamingContext context) : base(info, context) => Result = default!; #endif #pragma warning restore RS0016 // Add public types and members to the declared API }
using Polly.CircuitBreaker; namespace Polly.Core.Tests.CircuitBreaker; public class BrokenCircuitExceptionTests { [Fact] public void Ctor_Default_Ok() { var exception = new BrokenCircuitException(); exception.Message.ShouldBe("The circuit is now open and is not allowing calls."); exception.RetryAfter.ShouldBeNull(); } [Fact] public void Ctor_Message_Ok() { var exception = new BrokenCircuitException(TestMessage); exception.Message.ShouldBe(TestMessage); exception.RetryAfter.ShouldBeNull(); } [Fact] public void Ctor_RetryAfter_Ok() { var exception = new BrokenCircuitException(TestRetryAfter); exception.Message.ShouldBe($"The circuit is now open and is not allowing calls. It can be retried after '{TestRetryAfter}'."); exception.RetryAfter.ShouldBe(TestRetryAfter); } [Fact] public void Ctor_Message_RetryAfter_Ok() { var exception = new BrokenCircuitException(TestMessage, TestRetryAfter); exception.Message.ShouldBe(TestMessage); exception.RetryAfter.ShouldBe(TestRetryAfter); } [Fact] public void Ctor_Message_InnerException_Ok() { var exception = new BrokenCircuitException(TestMessage, new InvalidOperationException()); exception.Message.ShouldBe(TestMessage); exception.InnerException.ShouldBeOfType<InvalidOperationException>(); exception.RetryAfter.ShouldBeNull(); } [Fact] public void Ctor_Message_RetryAfter_InnerException_Ok() { var exception = new BrokenCircuitException(TestMessage, TestRetryAfter, new InvalidOperationException()); exception.Message.ShouldBe(TestMessage); exception.InnerException.ShouldBeOfType<InvalidOperationException>(); exception.RetryAfter.ShouldBe(TestRetryAfter); } #if NETFRAMEWORK [Fact] public void BinarySerialization_NonNullRetryAfter_Ok() { var exception = new BrokenCircuitException(TestMessage, TestRetryAfter, new InvalidOperationException()); BrokenCircuitException roundtripResult = BinarySerializationUtil.SerializeAndDeserializeException(exception); roundtripResult.ShouldNotBeNull(); roundtripResult.Message.ShouldBe(TestMessage); roundtripResult.InnerException.ShouldBeOfType<InvalidOperationException>(); roundtripResult.RetryAfter.ShouldBe(TestRetryAfter); } [Fact] public void BinarySerialization_NullRetryAfter_Ok() { var exception = new BrokenCircuitException(TestMessage, new InvalidOperationException()); BrokenCircuitException roundtripResult = BinarySerializationUtil.SerializeAndDeserializeException(exception); roundtripResult.ShouldNotBeNull(); roundtripResult.Message.ShouldBe(TestMessage); roundtripResult.InnerException.ShouldBeOfType<InvalidOperationException>(); roundtripResult.RetryAfter.ShouldBeNull(); } #endif private const string TestMessage = "Dummy."; private static readonly TimeSpan TestRetryAfter = TimeSpan.FromHours(1); }
Polly
You are an expert .NET (C#) developer. Task: Write a unit test for 'BrokenCircuitException' using XUnit and Moq. Context: - Class: BrokenCircuitException Requirements: Use Mock<T> interface mocking.
industrial
namespace Polly.CircuitBreaker; #pragma warning disable CA1815 // Override equals and operator equals on value types /// <summary> /// Arguments used by <see cref="CircuitBreakerStrategyOptions{TResult}.OnHalfOpened"/> event. /// </summary> /// <remarks> /// Always use the constructor when creating this struct, otherwise we do not guarantee binary compatibility. /// </remarks> public readonly struct OnCircuitHalfOpenedArguments { /// <summary> /// Initializes a new instance of the <see cref="OnCircuitHalfOpenedArguments"/> struct. /// </summary> /// <param name="context">The context instance.</param> public OnCircuitHalfOpenedArguments(ResilienceContext context) => Context = context; /// <summary> /// Gets the context associated with the execution of a user-provided callback. /// </summary> public ResilienceContext Context { get; } }
using Polly.CircuitBreaker; namespace Polly.Core.Tests.CircuitBreaker; public static class OnCircuitHalfOpenedArgumentsTests { [Fact] public static void Ctor_Ok() { // Arrange var context = ResilienceContextPool.Shared.Get(TestCancellation.Token); // Act var target = new OnCircuitHalfOpenedArguments(context); // Assert target.Context.ShouldBe(context); } }
Polly
You are an expert C++ developer. Task: Write a unit test for 'TargetModule' using GoogleTest (gtest) and GoogleMock (gmock). Context: - Class: TargetModule Requirements: Use EXPECT_CALL for virtual methods.
industrial
namespace Polly.CircuitBreaker; #pragma warning disable CA1815 // Override equals and operator equals on value types /// <summary> /// Arguments used by <see cref="CircuitBreakerStrategyOptions{TResult}.ShouldHandle"/> predicate. /// </summary> /// <typeparam name="TResult">The type of result.</typeparam> /// <remarks> /// Always use the constructor when creating this struct, otherwise we do not guarantee binary compatibility. /// </remarks> public readonly struct CircuitBreakerPredicateArguments<TResult> : IOutcomeArguments<TResult> { /// <summary> /// Initializes a new instance of the <see cref="CircuitBreakerPredicateArguments{TResult}"/> struct. /// </summary> /// <param name="outcome">The context in which the resilience operation or event occurred.</param> /// <param name="context">The outcome of the resilience operation or event.</param> public CircuitBreakerPredicateArguments(ResilienceContext context, Outcome<TResult> outcome) { Context = context; Outcome = outcome; } /// <summary> /// Gets the outcome of the user-specified callback. /// </summary> public Outcome<TResult> Outcome { get; } /// <summary> /// Gets the context of this event. /// </summary> public ResilienceContext Context { get; } }
using Polly.CircuitBreaker; namespace Polly.Core.Tests.CircuitBreaker; public static class CircuitBreakerPredicateArgumentsTests { [Fact] public static void Ctor_Ok() { var args = new CircuitBreakerPredicateArguments<int>( ResilienceContextPool.Shared.Get(TestCancellation.Token), Outcome.FromResult(1)); args.Context.ShouldNotBeNull(); args.Outcome.Result.ShouldBe(1); } }
Polly
You are an expert C++ developer. Task: Write a unit test for 'TargetModule' using GoogleTest (gtest) and GoogleMock (gmock). Context: - Class: TargetModule Requirements: Use EXPECT_CALL for virtual methods.
industrial
using System.ComponentModel.DataAnnotations; using System.Diagnostics.CodeAnalysis; using Polly.CircuitBreaker; using Polly.CircuitBreaker.Health; namespace Polly; /// <summary> /// Circuit breaker extensions for <see cref="ResiliencePipelineBuilder"/>. /// </summary> public static class CircuitBreakerResiliencePipelineBuilderExtensions { /// <summary> /// Adds circuit breaker to the builder. /// </summary> /// <param name="builder">The builder instance.</param> /// <param name="options">The options instance.</param> /// <returns>A builder with the circuit breaker added.</returns> /// <remarks> /// See <see cref="CircuitBreakerStrategyOptions{TResult}"/> for more details about the circuit breaker. /// <para> /// If you are discarding the circuit breaker by this call make sure to use <see cref="CircuitBreakerManualControl"/> /// and dispose the manual control instance when the circuit breaker is no longer used. /// </para> /// </remarks> /// <exception cref="ArgumentNullException">Thrown when <paramref name="builder"/> or <paramref name="options"/> is <see langword="null"/>.</exception> /// <exception cref="ValidationException">Thrown when <paramref name="options"/> are invalid.</exception> [UnconditionalSuppressMessage( "Trimming", "IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code", Justification = "All options members preserved.")] [DynamicDependency(DynamicallyAccessedMemberTypes.All, typeof(CircuitBreakerStrategyOptions))] public static ResiliencePipelineBuilder AddCircuitBreaker(this ResiliencePipelineBuilder builder, CircuitBreakerStrategyOptions options) { Guard.NotNull(builder); Guard.NotNull(options); return builder.AddStrategy(context => CreateStrategy(context, options), options); } /// <summary> /// Adds circuit breaker to the builder. /// </summary> /// <typeparam name="TResult">The type of result the circuit breaker handles.</typeparam> /// <param name="builder">The builder instance.</param> /// <param name="options">The options instance.</param> /// <returns>A builder with the circuit breaker added.</returns> /// <remarks> /// See <see cref="CircuitBreakerStrategyOptions{TResult}"/> for more details about the circuit breaker. /// <para> /// If you are discarding the circuit breaker by this call make sure to use <see cref="CircuitBreakerManualControl"/> /// and dispose the manual control instance when the circuit breaker is no longer used. /// </para> /// </remarks> /// <exception cref="ArgumentNullException">Thrown when <paramref name="builder"/> or <paramref name="options"/> is <see langword="null"/>.</exception> /// <exception cref="ValidationException">Thrown when <paramref name="options"/> are invalid.</exception> [UnconditionalSuppressMessage( "Trimming", "IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code", Justification = "All options members preserved.")] public static ResiliencePipelineBuilder<TResult> AddCircuitBreaker<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] TResult>( this ResiliencePipelineBuilder<TResult> builder, CircuitBreakerStrategyOptions<TResult> options) { Guard.NotNull(builder); Guard.NotNull(options); return builder.AddStrategy(context => CreateStrategy(context, options), options); } internal static CircuitBreakerResilienceStrategy<TResult> CreateStrategy<TResult>( StrategyBuilderContext context, CircuitBreakerStrategyOptions<TResult> options) { var behavior = new AdvancedCircuitBehavior( options.FailureRatio, options.MinimumThroughput, HealthMetrics.Create(options.SamplingDuration, context.TimeProvider)); var controller = new CircuitStateController<TResult>( options.BreakDuration, options.OnOpened, options.OnClosed, options.OnHalfOpened, behavior, context.TimeProvider, context.Telemetry, options.BreakDurationGenerator); return new CircuitBreakerResilienceStrategy<TResult>( options.ShouldHandle!, controller, options.StateProvider, options.ManualControl); } }
using System.ComponentModel.DataAnnotations; using Microsoft.Extensions.Time.Testing; using Polly.CircuitBreaker; using Polly.Testing; namespace Polly.Core.Tests.CircuitBreaker; public class CircuitBreakerResiliencePipelineBuilderTests { #pragma warning disable IDE0028 public static TheoryData<Action<ResiliencePipelineBuilder>> ConfigureData = new() { builder => builder.AddCircuitBreaker(new CircuitBreakerStrategyOptions { ShouldHandle = _ => PredicateResult.True() }), }; public static TheoryData<Action<ResiliencePipelineBuilder<int>>> ConfigureDataGeneric = new() { builder => builder.AddCircuitBreaker(new CircuitBreakerStrategyOptions<int> { ShouldHandle = _ => PredicateResult.True() }), }; #pragma warning restore IDE0028 [MemberData(nameof(ConfigureData))] [Theory] public void AddCircuitBreaker_Configure(Action<ResiliencePipelineBuilder> builderAction) { var builder = new ResiliencePipelineBuilder(); builderAction(builder); builder.Build().GetPipelineDescriptor().FirstStrategy.StrategyInstance.ShouldBeOfType<CircuitBreakerResilienceStrategy<object>>(); } [MemberData(nameof(ConfigureDataGeneric))] [Theory] public void AddCircuitBreaker_Generic_Configure(Action<ResiliencePipelineBuilder<int>> builderAction) { var builder = new ResiliencePipelineBuilder<int>(); builderAction(builder); builder.Build().GetPipelineDescriptor().FirstStrategy.StrategyInstance.ShouldBeOfType<CircuitBreakerResilienceStrategy<int>>(); } [Fact] public void AddCircuitBreaker_Validation() { Should.Throw<ValidationException>(() => new ResiliencePipelineBuilder<int>().AddCircuitBreaker(new CircuitBreakerStrategyOptions<int> { BreakDuration = TimeSpan.MinValue })); Should.Throw<ValidationException>(() => new ResiliencePipelineBuilder().AddCircuitBreaker(new CircuitBreakerStrategyOptions { BreakDuration = TimeSpan.MinValue })); } [Fact] public void AddCircuitBreaker_IntegrationTest() { var cancellationToken = TestCancellation.Token; int opened = 0; int closed = 0; int halfOpened = 0; var halfBreakDuration = TimeSpan.FromMilliseconds(500); var breakDuration = halfBreakDuration + halfBreakDuration; var options = new CircuitBreakerStrategyOptions { FailureRatio = 0.5, MinimumThroughput = 10, SamplingDuration = TimeSpan.FromSeconds(10), BreakDuration = breakDuration, ShouldHandle = args => new ValueTask<bool>(args.Outcome.Result is -1), OnOpened = _ => { opened++; return default; }, OnClosed = _ => { closed++; return default; }, OnHalfOpened = (_) => { halfOpened++; return default; } }; var timeProvider = new FakeTimeProvider(); var strategy = new ResiliencePipelineBuilder { TimeProvider = timeProvider }.AddCircuitBreaker(options).Build(); for (int i = 0; i < 10; i++) { strategy.Execute(_ => -1, cancellationToken); } // Circuit opened opened.ShouldBe(1); halfOpened.ShouldBe(0); closed.ShouldBe(0); BrokenCircuitException exception = Assert.Throws<BrokenCircuitException>(() => strategy.Execute(_ => 0, cancellationToken)); exception.RetryAfter.ShouldBe(breakDuration); // Circuit still open after some time timeProvider.Advance(halfBreakDuration); opened.ShouldBe(1); halfOpened.ShouldBe(0); closed.ShouldBe(0); exception = Assert.Throws<BrokenCircuitException>(() => strategy.Execute(_ => 0, cancellationToken)); exception.RetryAfter.ShouldBe(halfBreakDuration); // Circuit Half Opened timeProvider.Advance(halfBreakDuration); strategy.Execute(_ => -1, cancellationToken); exception = Assert.Throws<BrokenCircuitException>(() => strategy.Execute(_ => 0, cancellationToken)); opened.ShouldBe(2); halfOpened.ShouldBe(1); closed.ShouldBe(0); exception.RetryAfter.ShouldBe(breakDuration); // Now close it timeProvider.Advance(breakDuration); strategy.Execute(_ => 0, cancellationToken); opened.ShouldBe(2); halfOpened.ShouldBe(2); closed.ShouldBe(1); } [Fact] public void AddCircuitBreaker_IntegrationTest_WithBreakDurationGenerator() { var cancellationToken = TestCancellation.Token; int opened = 0; int closed = 0; int halfOpened = 0; var halfBreakDuration = TimeSpan.FromMilliseconds(500); var breakDuration = halfBreakDuration + halfBreakDuration; var options = new CircuitBreakerStrategyOptions { FailureRatio = 0.5, MinimumThroughput = 10, SamplingDuration = TimeSpan.FromSeconds(10), BreakDuration = TimeSpan.FromSeconds(30), // Intentionally long to check it isn't used BreakDurationGenerator = (_) => new ValueTask<TimeSpan>(breakDuration), ShouldHandle = args => new ValueTask<bool>(args.Outcome.Result is -1), OnOpened = _ => { opened++; return default; }, OnClosed = _ => { closed++; return default; }, OnHalfOpened = (_) => { halfOpened++; return default; } }; var timeProvider = new FakeTimeProvider(); var strategy = new ResiliencePipelineBuilder { TimeProvider = timeProvider }.AddCircuitBreaker(options).Build(); for (int i = 0; i < 10; i++) { strategy.Execute(_ => -1, cancellationToken); } // Circuit opened opened.ShouldBe(1); halfOpened.ShouldBe(0); closed.ShouldBe(0); BrokenCircuitException exception = Assert.Throws<BrokenCircuitException>(() => strategy.Execute(_ => 0, cancellationToken)); exception.RetryAfter.ShouldBe(breakDuration); // Circuit still open after some time timeProvider.Advance(halfBreakDuration); opened.ShouldBe(1); halfOpened.ShouldBe(0); closed.ShouldBe(0); exception = Assert.Throws<BrokenCircuitException>(() => strategy.Execute(_ => 0, cancellationToken)); exception.RetryAfter.ShouldBe(halfBreakDuration); // Circuit Half Opened timeProvider.Advance(halfBreakDuration); strategy.Execute(_ => -1, cancellationToken); exception = Assert.Throws<BrokenCircuitException>(() => strategy.Execute(_ => 0, cancellationToken)); opened.ShouldBe(2); halfOpened.ShouldBe(1); closed.ShouldBe(0); exception.RetryAfter.ShouldBe(breakDuration); // Now close it timeProvider.Advance(breakDuration); strategy.Execute(_ => 0, cancellationToken); opened.ShouldBe(2); halfOpened.ShouldBe(2); closed.ShouldBe(1); } [Fact] public async Task AddCircuitBreakers_WithIsolatedManualControl_ShouldBeIsolated() { var cancellationToken = TestCancellation.Token; var manualControl = new CircuitBreakerManualControl(); await manualControl.IsolateAsync(cancellationToken); var strategy1 = new ResiliencePipelineBuilder() .AddCircuitBreaker(new() { ManualControl = manualControl }) .Build(); var strategy2 = new ResiliencePipelineBuilder() .AddCircuitBreaker(new() { ManualControl = manualControl }) .Build(); Should.Throw<IsolatedCircuitException>(() => strategy1.Execute(() => { })).RetryAfter.ShouldBeNull(); Should.Throw<IsolatedCircuitException>(() => strategy2.Execute(() => { })).RetryAfter.ShouldBeNull(); await manualControl.CloseAsync(cancellationToken); strategy1.Execute(() => { }); strategy2.Execute(() => { }); } [InlineData(false)] [InlineData(true)] [Theory] public async Task DisposePipeline_EnsureCircuitBreakerDisposed(bool attachManualControl) { var manualControl = attachManualControl ? new CircuitBreakerManualControl() : null; var pipeline = new ResiliencePipelineBuilder() .AddCircuitBreaker(new() { ManualControl = manualControl }) .Build(); if (attachManualControl) { manualControl!.IsEmpty.ShouldBeFalse(); } var strategy = (ResilienceStrategy<object>)pipeline.GetPipelineDescriptor().FirstStrategy.StrategyInstance; await pipeline.DisposeHelper.DisposeAsync(); Should.Throw<ObjectDisposedException>(() => strategy.AsPipeline().Execute(() => 1)); if (attachManualControl) { manualControl!.IsEmpty.ShouldBeTrue(); } } }
Polly
You are an expert .NET (C#) developer. Task: Write a unit test for 'CircuitBreakerResiliencePipelineBuilderExtensions' using XUnit and Moq. Context: - Class: CircuitBreakerResiliencePipelineBuilderExtensions Requirements: Use Mock<T> interface mocking.
industrial
namespace Polly.CircuitBreaker; #pragma warning disable CA1031 // Do not catch general exception types /// <summary> /// The scheduled task executor makes sure that tasks are executed in the order they were scheduled and not concurrently. /// </summary> internal sealed class ScheduledTaskExecutor : IDisposable { private readonly ConcurrentQueue<Entry> _tasks = new(); private readonly SemaphoreSlim _semaphore = new(0); private bool _disposed; public ScheduledTaskExecutor() => ProcessingTask = Task.Run(StartProcessingAsync); public Task ProcessingTask { get; } public Task ScheduleTask(Func<Task> taskFactory) { #if NET8_0_OR_GREATER ObjectDisposedException.ThrowIf(_disposed, this); #else if (_disposed) { throw new ObjectDisposedException(nameof(ScheduledTaskExecutor)); } #endif var source = new TaskCompletionSource<object>(); _tasks.Enqueue(new Entry(taskFactory, source)); _semaphore.Release(); return source.Task; } public void Dispose() { if (_disposed) { return; } _disposed = true; _semaphore.Release(); while (_tasks.TryDequeue(out var e)) { e.TaskCompletion.TrySetCanceled(); } _semaphore.Dispose(); } private async Task StartProcessingAsync() { while (!_disposed) { await _semaphore.WaitAsync().ConfigureAwait(false); if (_disposed || !_tasks.TryDequeue(out var entry)) { return; } try { await entry.TaskFactory().ConfigureAwait(false); entry.TaskCompletion.TrySetResult(null!); } catch (OperationCanceledException) { entry.TaskCompletion.TrySetCanceled(); } catch (Exception e) { entry.TaskCompletion.TrySetException(e); } } } private sealed record Entry(Func<Task> TaskFactory, TaskCompletionSource<object> TaskCompletion); }
using Polly.CircuitBreaker; namespace Polly.Core.Tests.CircuitBreaker.Controller; public class ScheduledTaskExecutorTests { private static CancellationToken CancellationToken => TestCancellation.Token; [Fact] public async Task ScheduleTask_Success_EnsureExecuted() { using var scheduler = new ScheduledTaskExecutor(); var executed = false; var task = scheduler.ScheduleTask( () => { executed = true; return Task.CompletedTask; }); await task; executed.ShouldBeTrue(); } [Fact] public async Task ScheduleTask_OperationCanceledException_EnsureExecuted() { using var scheduler = new ScheduledTaskExecutor(); var task = scheduler.ScheduleTask( () => throw new OperationCanceledException()); await Should.ThrowAsync<OperationCanceledException>(() => task); } [Fact] public async Task ScheduleTask_Exception_EnsureExecuted() { using var scheduler = new ScheduledTaskExecutor(); var task = scheduler.ScheduleTask( () => throw new InvalidOperationException()); await Should.ThrowAsync<InvalidOperationException>(() => task); } [Fact] public async Task ScheduleTask_Multiple_EnsureExecutionSerialized() { using var executing = new ManualResetEvent(false); using var verified = new ManualResetEvent(false); using var scheduler = new ScheduledTaskExecutor(); var task = scheduler.ScheduleTask( () => { executing.Set(); verified.WaitOne(); return Task.CompletedTask; }); executing.WaitOne(); var otherTask = scheduler.ScheduleTask(() => Task.CompletedTask); #pragma warning disable xUnit1031 // Do not use blocking task operations in test method otherTask.Wait(50, CancellationToken).ShouldBeFalse(); #pragma warning restore xUnit1031 // Do not use blocking task operations in test method verified.Set(); await task; await otherTask; } [Fact] public async Task Dispose_ScheduledTaskCancelled() { using var executing = new ManualResetEvent(false); using var verified = new ManualResetEvent(false); var scheduler = new ScheduledTaskExecutor(); var task = scheduler.ScheduleTask( () => { executing.Set(); verified.WaitOne(); return Task.CompletedTask; }); executing.WaitOne(); var otherTask = scheduler.ScheduleTask(() => Task.CompletedTask); scheduler.Dispose(); verified.Set(); await task; await Should.ThrowAsync<OperationCanceledException>(() => otherTask); Should.Throw<ObjectDisposedException>( () => scheduler.ScheduleTask(() => Task.CompletedTask)); } [Fact] public void Dispose_WhenScheduledTaskExecuting() { var timeout = TimeSpan.FromSeconds(10); using var disposed = new ManualResetEvent(false); using var ready = new ManualResetEvent(false); var scheduler = new ScheduledTaskExecutor(); var task = scheduler.ScheduleTask( () => { ready.Set(); disposed.WaitOne(); return Task.CompletedTask; }); ready.WaitOne(timeout).ShouldBeTrue(); scheduler.Dispose(); disposed.Set(); #pragma warning disable xUnit1031 #if NET scheduler.ProcessingTask.Wait(timeout, CancellationToken).ShouldBeTrue(); #else scheduler.ProcessingTask.Wait(timeout).ShouldBeTrue(); #endif #pragma warning restore xUnit1031 } [Fact] public async Task Dispose_EnsureNoBackgroundProcessing() { var scheduler = new ScheduledTaskExecutor(); var otherTask = scheduler.ScheduleTask(() => Task.CompletedTask); await otherTask; scheduler.Dispose(); #pragma warning disable S3966 // Objects should not be disposed more than once scheduler.Dispose(); #pragma warning restore S3966 // Objects should not be disposed more than once await scheduler.ProcessingTask; scheduler.ProcessingTask.IsCompleted.ShouldBeTrue(); } }
Polly
You are an expert C++ developer. Task: Write a unit test for 'ScheduledTaskExecutor' using GoogleTest (gtest) and GoogleMock (gmock). Context: - Class: ScheduledTaskExecutor Requirements: Use EXPECT_CALL for virtual methods.
industrial
using Polly.CircuitBreaker.Health; namespace Polly.CircuitBreaker; internal sealed class AdvancedCircuitBehavior : CircuitBehavior { private readonly HealthMetrics _metrics; private readonly double _failureRatio; private readonly int _minimumThroughput; public AdvancedCircuitBehavior(double failureRatio, int minimumThroughput, HealthMetrics metrics) { _metrics = metrics; _failureRatio = failureRatio; _minimumThroughput = minimumThroughput; } public override void OnActionSuccess(CircuitState currentState) => _metrics.IncrementSuccess(); public override void OnActionFailure(CircuitState currentState, out bool shouldBreak) { switch (currentState) { case CircuitState.Closed: _metrics.IncrementFailure(); var info = _metrics.GetHealthInfo(); shouldBreak = info.Throughput >= _minimumThroughput && info.FailureRate >= _failureRatio; break; case CircuitState.Open: case CircuitState.Isolated: // A failure call result may arrive when the circuit is open, if it was placed before the circuit broke. // We take no action beyond tracking the metric // We do not want to duplicate-signal onBreak // We do not want to extend time for which the circuit is broken. // We do not want to mask the fact that the call executed (as replacing its result with a Broken/IsolatedCircuitException would do). _metrics.IncrementFailure(); shouldBreak = false; break; default: shouldBreak = false; break; } } public override void OnCircuitClosed() => _metrics.Reset(); public override int FailureCount => _metrics.GetHealthInfo().FailureCount; public override double FailureRate => _metrics.GetHealthInfo().FailureRate; }
using NSubstitute; using Polly.CircuitBreaker; using Polly.CircuitBreaker.Health; namespace Polly.Core.Tests.CircuitBreaker.Controller; public class AdvancedCircuitBehaviorTests { private HealthMetrics _metrics = Substitute.For<HealthMetrics>(TimeProvider.System); [InlineData(10, 10, 0.0, 0.1, 0, false)] [InlineData(10, 10, 0.1, 0.1, 1, true)] [InlineData(10, 10, 0.2, 0.1, 2, true)] [InlineData(11, 10, 0.2, 0.1, 3, true)] [InlineData(9, 10, 0.1, 0.1, 4, false)] [Theory] public void OnActionFailure_WhenClosed_EnsureCorrectBehavior( int throughput, int minimumThruput, double failureRate, double failureThreshold, int failureCount, bool expectedShouldBreak) { _metrics.GetHealthInfo().Returns(new HealthInfo(throughput, failureRate, failureCount)); var behavior = new AdvancedCircuitBehavior(failureThreshold, minimumThruput, _metrics); behavior.OnActionFailure(CircuitState.Closed, out var shouldBreak); shouldBreak.ShouldBe(expectedShouldBreak); _metrics.Received(1).IncrementFailure(); } [InlineData(CircuitState.Closed, true)] [InlineData(CircuitState.Open, true)] [InlineData(CircuitState.Isolated, true)] [InlineData(CircuitState.HalfOpen, false)] [Theory] public void OnActionFailure_State_EnsureCorrectCalls(CircuitState state, bool shouldIncrementFailure) { _metrics = Substitute.For<HealthMetrics>(TimeProvider.System); var sut = Create(); sut.OnActionFailure(state, out var shouldBreak); shouldBreak.ShouldBeFalse(); if (shouldIncrementFailure) { _metrics.Received(1).IncrementFailure(); } else { _metrics.DidNotReceive().IncrementFailure(); } } [Fact] public void OnCircuitClosed_Ok() { _metrics = Substitute.For<HealthMetrics>(TimeProvider.System); var sut = Create(); sut.OnCircuitClosed(); _metrics.Received(1).Reset(); } [Theory] [InlineData(10, 0.0, 0)] [InlineData(10, 0.1, 1)] [InlineData(10, 0.2, 2)] [InlineData(11, 0.2, 3)] [InlineData(9, 0.1, 4)] public void BehaviorProperties_ShouldReflectHealthInfoValues( int throughput, double failureRate, int failureCount) { var anyFailureThreshold = 10; var anyMinimumThruput = 100; _metrics.GetHealthInfo().Returns(new HealthInfo(throughput, failureRate, failureCount)); var behavior = new AdvancedCircuitBehavior(anyFailureThreshold, anyMinimumThruput, _metrics); behavior.FailureCount.ShouldBe(failureCount, "because the FailureCount should match the HealthInfo"); behavior.FailureRate.ShouldBe(failureRate, "because the FailureRate should match the HealthInfo"); } private AdvancedCircuitBehavior Create() => new(CircuitBreakerConstants.DefaultFailureRatio, CircuitBreakerConstants.DefaultMinimumThroughput, _metrics); }
Polly
You are an expert C++ developer. Task: Write a unit test for 'AdvancedCircuitBehavior' using GoogleTest (gtest) and GoogleMock (gmock). Context: - Class: AdvancedCircuitBehavior Requirements: Use EXPECT_CALL for virtual methods.
industrial
namespace Polly.CircuitBreaker; internal abstract class CircuitStateController<TResult> : ICircuitController<TResult> { protected readonly TimeSpan DurationOfBreak; protected readonly Action<DelegateResult<TResult>, CircuitState, TimeSpan, Context> OnBreak; protected readonly Action<Context> OnReset; protected readonly Action OnHalfOpen; protected readonly object Lock = new(); protected long BlockedTill; protected CircuitState InternalCircuitState; protected DelegateResult<TResult> LastOutcome; protected CircuitStateController( TimeSpan durationOfBreak, Action<DelegateResult<TResult>, CircuitState, TimeSpan, Context> onBreak, Action<Context> onReset, Action onHalfOpen) { DurationOfBreak = durationOfBreak; OnBreak = onBreak; OnReset = onReset; OnHalfOpen = onHalfOpen; InternalCircuitState = CircuitState.Closed; Reset(); } public CircuitState CircuitState { get { if (InternalCircuitState != CircuitState.Open) { return InternalCircuitState; } using var _ = TimedLock.Lock(Lock); #pragma warning disable CA1508 // Avoid dead conditional code. _circuitState is checked again in the lock if (InternalCircuitState == CircuitState.Open && !IsInAutomatedBreak_NeedsLock) { InternalCircuitState = CircuitState.HalfOpen; OnHalfOpen(); } #pragma warning restore CA1508 // Avoid dead conditional code. _circuitState is checked again in the lock return InternalCircuitState; } } public Exception LastException { get { using var _ = TimedLock.Lock(Lock); return LastOutcome?.Exception; } } public TResult LastHandledResult { get { using var _ = TimedLock.Lock(Lock); return LastOutcome != null ? LastOutcome.Result : default; } } protected bool IsInAutomatedBreak_NeedsLock => SystemClock.UtcNow().Ticks < BlockedTill; public void Isolate() { using var _ = TimedLock.Lock(Lock); LastOutcome = new DelegateResult<TResult>(new IsolatedCircuitException("The circuit is manually held open and is not allowing calls.")); BreakFor_NeedsLock(TimeSpan.MaxValue, Context.None()); InternalCircuitState = CircuitState.Isolated; } protected void Break_NeedsLock(Context context) => BreakFor_NeedsLock(DurationOfBreak, context); private void BreakFor_NeedsLock(TimeSpan durationOfBreak, Context context) { // Prevent overflow if DurationOfBreak goes beyond the maximum possible DateTime ulong utcNowTicks = (ulong)SystemClock.UtcNow().Ticks; ulong durationOfBreakTicks = (ulong)durationOfBreak.Ticks; BlockedTill = (long)Math.Min(utcNowTicks + durationOfBreakTicks, (ulong)DateTime.MaxValue.Ticks); var transitionedState = InternalCircuitState; InternalCircuitState = CircuitState.Open; OnBreak(LastOutcome, transitionedState, durationOfBreak, context); } public void Reset() => OnCircuitReset(Context.None()); protected void ResetInternal_NeedsLock(Context context) { BlockedTill = DateTime.MinValue.Ticks; LastOutcome = null; CircuitState priorState = InternalCircuitState; InternalCircuitState = CircuitState.Closed; if (priorState != CircuitState.Closed) { OnReset(context); } } protected bool PermitHalfOpenCircuitTest() { long currentlyBlockedUntil = BlockedTill; if (SystemClock.UtcNow().Ticks < currentlyBlockedUntil) { return false; } // It's time to permit a / another trial call in the half-open state ... // ... but to prevent race conditions/multiple calls, we have to ensure only _one_ thread wins the race to own this next call. return Interlocked.CompareExchange(ref BlockedTill, SystemClock.UtcNow().Ticks + DurationOfBreak.Ticks, currentlyBlockedUntil) == currentlyBlockedUntil; } private BrokenCircuitException GetBreakingException() { const string BrokenCircuitMessage = "The circuit is now open and is not allowing calls."; var lastOutcome = LastOutcome; if (lastOutcome == null) { return new BrokenCircuitException(BrokenCircuitMessage); } if (lastOutcome.Exception != null) { return new BrokenCircuitException(BrokenCircuitMessage, lastOutcome.Exception); } return new BrokenCircuitException<TResult>(BrokenCircuitMessage, lastOutcome.Result); } public void OnActionPreExecute() { switch (CircuitState) { case CircuitState.Closed: break; case CircuitState.HalfOpen: if (!PermitHalfOpenCircuitTest()) { throw GetBreakingException(); } break; case CircuitState.Open: throw GetBreakingException(); case CircuitState.Isolated: throw new IsolatedCircuitException("The circuit is manually held open and is not allowing calls."); default: throw new InvalidOperationException("Unhandled CircuitState."); } } public abstract void OnActionSuccess(Context context); public abstract void OnActionFailure(DelegateResult<TResult> outcome, Context context); public abstract void OnCircuitReset(Context context); }
using Microsoft.Extensions.Time.Testing; using NSubstitute; using Polly.CircuitBreaker; namespace Polly.Core.Tests.CircuitBreaker.Controller; public class CircuitStateControllerTests { private readonly FakeTimeProvider _timeProvider = new(); private readonly CircuitBreakerStrategyOptions<int> _options = new(); private readonly CircuitBehavior _circuitBehavior = Substitute.For<CircuitBehavior>(); private readonly FakeTelemetryListener _telemetryListener = new(); [Fact] public void Ctor_EnsureDefaults() { using var controller = CreateController(); controller.CircuitState.ShouldBe(CircuitState.Closed); controller.LastException.ShouldBeNull(); controller.LastHandledOutcome.ShouldBeNull(); } [Fact] public async Task IsolateAsync_Ok() { // arrange var cancellationToken = TestCancellation.Token; bool called = false; _options.OnOpened = args => { args.BreakDuration.ShouldBe(TimeSpan.MaxValue); args.Context.IsSynchronous.ShouldBeFalse(); args.Context.IsVoid.ShouldBeFalse(); args.Context.ResultType.ShouldBe(typeof(int)); args.IsManual.ShouldBeTrue(); args.Outcome.IsVoidResult.ShouldBeFalse(); args.Outcome.Result.ShouldBe(0); called = true; return default; }; _timeProvider.Advance(TimeSpan.FromSeconds(1)); using var controller = CreateController(); var context = ResilienceContextPool.Shared.Get(cancellationToken); // act await controller.IsolateCircuitAsync(context); // assert controller.CircuitState.ShouldBe(CircuitState.Isolated); called.ShouldBeTrue(); var outcome = await controller.OnActionPreExecuteAsync(context); var exception = outcome.Value.Exception.ShouldBeOfType<IsolatedCircuitException>(); exception.RetryAfter.ShouldBeNull(); exception.TelemetrySource.ShouldNotBeNull(); // now close it await controller.CloseCircuitAsync(context); await controller.OnActionPreExecuteAsync(context); _circuitBehavior.Received().OnCircuitClosed(); _telemetryListener.GetArgs<OnCircuitOpenedArguments<int>>().ShouldNotBeEmpty(); } [Fact] public async Task BreakAsync_Ok() { // arrange var cancellationToken = TestCancellation.Token; bool called = false; _options.OnClosed = args => { args.Context.IsSynchronous.ShouldBeFalse(); args.Context.IsVoid.ShouldBeFalse(); args.Context.ResultType.ShouldBe(typeof(int)); args.IsManual.ShouldBeTrue(); args.Outcome.IsVoidResult.ShouldBeFalse(); args.Outcome.Result.ShouldBe(0); called = true; return default; }; _timeProvider.Advance(TimeSpan.FromSeconds(1)); using var controller = CreateController(); await controller.IsolateCircuitAsync(ResilienceContextPool.Shared.Get(cancellationToken)); var context = ResilienceContextPool.Shared.Get(cancellationToken); // act await controller.CloseCircuitAsync(context); // assert called.ShouldBeTrue(); await controller.OnActionPreExecuteAsync(ResilienceContextPool.Shared.Get(cancellationToken)); _circuitBehavior.Received().OnCircuitClosed(); _telemetryListener.GetArgs<OnCircuitClosedArguments<int>>().ShouldNotBeEmpty(); } [Fact] public async Task Disposed_EnsureThrows() { var context = ResilienceContextPool.Shared.Get(TestCancellation.Token); var controller = CreateController(); controller.Dispose(); Assert.Throws<ObjectDisposedException>(() => controller.CircuitState); Assert.Throws<ObjectDisposedException>(() => controller.LastException); Assert.Throws<ObjectDisposedException>(() => controller.LastHandledOutcome); await Assert.ThrowsAsync<ObjectDisposedException>(async () => await controller.CloseCircuitAsync(context)); await Assert.ThrowsAsync<ObjectDisposedException>(async () => await controller.IsolateCircuitAsync(context)); await Assert.ThrowsAsync<ObjectDisposedException>(async () => await controller.OnActionPreExecuteAsync(context)); await Assert.ThrowsAsync<ObjectDisposedException>(async () => await controller.OnUnhandledOutcomeAsync(Outcome.FromResult(10), context)); await Assert.ThrowsAsync<ObjectDisposedException>(async () => await controller.OnHandledOutcomeAsync(Outcome.FromResult(10), context)); } [Fact] public async Task OnActionPreExecute_CircuitOpenedByValue() { var context = ResilienceContextPool.Shared.Get(TestCancellation.Token); using var controller = CreateController(); await OpenCircuit(controller, Outcome.FromResult(99)); var exception = (BrokenCircuitException)(await controller.OnActionPreExecuteAsync(context)).Value.Exception!; exception.RetryAfter.ShouldNotBeNull(); exception.TelemetrySource.ShouldNotBeNull(); GetBlockedTill(controller).ShouldBe(_timeProvider.GetUtcNow() + _options.BreakDuration); } [InlineData(true)] [InlineData(false)] [Theory] public async Task OnActionPreExecute_CircuitOpened_EnsureExceptionStackTraceDoesNotGrow(bool innerException) { var stacks = new List<string>(); var context = ResilienceContextPool.Shared.Get(TestCancellation.Token); using var controller = CreateController(); await OpenCircuit( controller, innerException ? Outcome.FromException<int>(new InvalidOperationException()) : Outcome.FromResult(99)); for (int i = 0; i < 100; i++) { try { (await controller.OnActionPreExecuteAsync(context)).Value.ThrowIfException(); } catch (BrokenCircuitException e) { stacks.Add(e.StackTrace!); e.Message.ShouldBe("The circuit is now open and is not allowing calls."); e.RetryAfter.ShouldNotBeNull(); e.TelemetrySource.ShouldNotBeNull(); if (innerException) { e.InnerException.ShouldBeOfType<InvalidOperationException>(); } else { e.InnerException.ShouldBeNull(); } } } stacks.Distinct().Count().ShouldBe(1); } [Fact] public async Task HalfOpen_EnsureBreakDuration() { var context = ResilienceContextPool.Shared.Get(TestCancellation.Token); using var controller = CreateController(); await TransitionToState(controller, CircuitState.HalfOpen, context); GetBlockedTill(controller).ShouldBe(_timeProvider.GetUtcNow() + _options.BreakDuration); } [InlineData(true)] [InlineData(false)] [Theory] public async Task HalfOpen_EnsureCorrectStateTransitionAfterExecution(bool success) { var context = ResilienceContextPool.Shared.Get(TestCancellation.Token); using var controller = CreateController(); await TransitionToState(controller, CircuitState.HalfOpen, context); if (success) { await controller.OnUnhandledOutcomeAsync(Outcome.FromResult(0), context); controller.CircuitState.ShouldBe(CircuitState.Closed); _circuitBehavior.Received().OnActionSuccess(CircuitState.HalfOpen); _circuitBehavior.Received().OnCircuitClosed(); } else { await controller.OnHandledOutcomeAsync(Outcome.FromResult(0), context); controller.CircuitState.ShouldBe(CircuitState.Open); _circuitBehavior.DidNotReceiveWithAnyArgs().OnActionSuccess(default); _circuitBehavior.Received().OnActionFailure(CircuitState.HalfOpen, out _); } } [Fact] public async Task OnActionPreExecute_CircuitOpenedByException() { var context = ResilienceContextPool.Shared.Get(TestCancellation.Token); using var controller = CreateController(); await OpenCircuit(controller, Outcome.FromException<int>(new InvalidOperationException())); var exception = (BrokenCircuitException)(await controller.OnActionPreExecuteAsync(context)).Value.Exception!; exception.InnerException.ShouldBeOfType<InvalidOperationException>(); exception.RetryAfter.ShouldNotBeNull(); exception.TelemetrySource.ShouldNotBeNull(); } [Fact] public async Task OnActionFailure_EnsureLock() { // arrange var cancellationToken = TestCancellation.Token; var context = ResilienceContextPool.Shared.Get(cancellationToken); using var executing = new ManualResetEvent(false); using var verified = new ManualResetEvent(false); AdvanceTime(_options.BreakDuration); bool shouldBreak = false; _circuitBehavior.When(v => v.OnActionFailure(CircuitState.Closed, out shouldBreak)).Do((_) => { executing.Set(); verified.WaitOne(); }); using var controller = CreateController(); // act var executeAction = Task.Run(() => controller.OnHandledOutcomeAsync(Outcome.FromResult(0), context), cancellationToken); executing.WaitOne(); var executeAction2 = Task.Run(() => controller.OnHandledOutcomeAsync(Outcome.FromResult(0), context), cancellationToken); // assert #pragma warning disable xUnit1031 // Do not use blocking task operations in test method executeAction.Wait(50, cancellationToken).ShouldBeFalse(); #pragma warning restore xUnit1031 // Do not use blocking task operations in test method verified.Set(); await executeAction; await executeAction2; } [Fact] public async Task OnActionPreExecute_HalfOpen() { // arrange var context = ResilienceContextPool.Shared.Get(TestCancellation.Token); var called = false; _options.OnHalfOpened = _ => { called = true; return default; }; using var controller = CreateController(); await OpenCircuit(controller, Outcome.FromResult(10)); AdvanceTime(_options.BreakDuration); // act await controller.OnActionPreExecuteAsync(context); var error = (await controller.OnActionPreExecuteAsync(context)).Value.Exception; // assert var exception = error.ShouldBeOfType<BrokenCircuitException>(); exception.RetryAfter.ShouldNotBeNull(); exception.TelemetrySource.ShouldNotBeNull(); controller.CircuitState.ShouldBe(CircuitState.HalfOpen); called.ShouldBeTrue(); } [InlineData(CircuitState.HalfOpen, CircuitState.Closed)] [InlineData(CircuitState.Isolated, CircuitState.Isolated)] [InlineData(CircuitState.Closed, CircuitState.Closed)] [Theory] public async Task OnActionSuccess_EnsureCorrectBehavior(CircuitState state, CircuitState expectedState) { // arrange var context = ResilienceContextPool.Shared.Get(TestCancellation.Token); var called = false; _options.OnClosed = args => { args.IsManual.ShouldBeFalse(); called = true; return default; }; using var controller = CreateController(); await TransitionToState(controller, state, context); // act await controller.OnUnhandledOutcomeAsync(Outcome.FromResult(10), context); // assert controller.CircuitState.ShouldBe(expectedState); _circuitBehavior.Received().OnActionSuccess(state); if (expectedState == CircuitState.Closed && state != CircuitState.Closed) { _circuitBehavior.Received().OnCircuitClosed(); called.ShouldBeTrue(); } } [InlineData(CircuitState.HalfOpen, CircuitState.Open, true)] [InlineData(CircuitState.Closed, CircuitState.Open, true)] [InlineData(CircuitState.Closed, CircuitState.Closed, false)] [InlineData(CircuitState.Open, CircuitState.Open, false)] [InlineData(CircuitState.Isolated, CircuitState.Isolated, false)] [Theory] public async Task OnActionFailureAsync_EnsureCorrectBehavior(CircuitState state, CircuitState expectedState, bool shouldBreak) { // arrange var context = ResilienceContextPool.Shared.Get(TestCancellation.Token); var called = false; _options.OnOpened = args => { if (state == CircuitState.Isolated) { args.IsManual.ShouldBeTrue(); } else { args.IsManual.ShouldBeFalse(); } called = true; return default; }; using var controller = CreateController(); await TransitionToState(controller, state, context); _circuitBehavior.When(x => x.OnActionFailure(state, out Arg.Any<bool>())) .Do(x => x[1] = shouldBreak); // act await controller.OnHandledOutcomeAsync(Outcome.FromResult(99), context); // assert controller.LastHandledOutcome!.Value.Result.ShouldBe(99); controller.CircuitState.ShouldBe(expectedState); _circuitBehavior.Received().OnActionFailure(state, out Arg.Any<bool>()); if (expectedState == CircuitState.Open && state != CircuitState.Open) { called.ShouldBeTrue(); } } [Fact] public async Task OnActionFailureAsync_EnsureBreakDurationGeneration() { // arrange var context = ResilienceContextPool.Shared.Get(TestCancellation.Token); _options.BreakDurationGenerator = static args => { args.FailureCount.ShouldBe(1); args.FailureRate.ShouldBe(0.5); return new ValueTask<TimeSpan>(TimeSpan.FromMinutes(42)); }; using var controller = CreateController(); await TransitionToState(controller, CircuitState.Closed, context); var utcNow = new DateTimeOffset(2023, 12, 12, 12, 34, 56, TimeSpan.Zero); _timeProvider.SetUtcNow(utcNow); _circuitBehavior.FailureCount.Returns(1); _circuitBehavior.FailureRate.Returns(0.5); _circuitBehavior.When(v => v.OnActionFailure(CircuitState.Closed, out Arg.Any<bool>())) .Do(x => x[1] = true); // act await controller.OnHandledOutcomeAsync(Outcome.FromResult(99), context); // assert var blockedTill = GetBlockedTill(controller); blockedTill.ShouldBe(utcNow + TimeSpan.FromMinutes(42)); } [Fact] public async Task BreakDurationGenerator_EnsureHalfOpenAttempts() { // arrange var context = ResilienceContextPool.Shared.Get(TestCancellation.Token); var halfOpenAttempts = new List<int>(); _options.BreakDurationGenerator = args => { halfOpenAttempts.Add(args.HalfOpenAttempts); return new ValueTask<TimeSpan>(TimeSpan.Zero); }; using var controller = CreateController(); // act await TransitionToState(controller, CircuitState.Closed, context); for (int i = 0; i < 5; i++) { await TransitionToState(controller, CircuitState.Open, context); await TransitionToState(controller, CircuitState.HalfOpen, context); } await TransitionToState(controller, CircuitState.Closed, context); for (int i = 0; i < 3; i++) { await TransitionToState(controller, CircuitState.Open, context); await TransitionToState(controller, CircuitState.HalfOpen, context); } // assert halfOpenAttempts.ShouldBe([0, 1, 2, 3, 4, 0, 1, 2]); } [InlineData(true)] [InlineData(false)] [Theory] public async Task OnActionFailureAsync_EnsureBreakDurationNotOverflow(bool overflow) { // arrange var context = ResilienceContextPool.Shared.Get(TestCancellation.Token); using var controller = CreateController(); var shouldBreak = true; await TransitionToState(controller, CircuitState.HalfOpen, context); var utcNow = DateTimeOffset.MaxValue - _options.BreakDuration; if (overflow) { utcNow += TimeSpan.FromMilliseconds(10); } _timeProvider.SetUtcNow(utcNow); _circuitBehavior.When(v => v.OnActionFailure(CircuitState.HalfOpen, out Arg.Any<bool>())) .Do(x => x[1] = shouldBreak); // act await controller.OnHandledOutcomeAsync(Outcome.FromResult(99), context); // assert var blockedTill = GetBlockedTill(controller); if (overflow) { blockedTill.ShouldBe(DateTimeOffset.MaxValue); } else { blockedTill.ShouldBe(utcNow + _options.BreakDuration); } } [Fact] public async Task OnActionFailureAsync_VoidResult_EnsureBreakingExceptionNotSet() { // arrange var context = ResilienceContextPool.Shared.Get(TestCancellation.Token); using var controller = CreateController(); bool shouldBreak = true; await TransitionToState(controller, CircuitState.Open, context); _circuitBehavior.When(v => v.OnActionFailure(CircuitState.Open, out Arg.Any<bool>())) .Do(x => x[1] = shouldBreak); // act await controller.OnHandledOutcomeAsync(Outcome.FromResult(99), context); // assert controller.LastException.ShouldBeNull(); var outcome = await controller.OnActionPreExecuteAsync(context); var exception = outcome.Value.Exception.ShouldBeOfType<BrokenCircuitException>(); exception.RetryAfter.ShouldNotBeNull(); exception.TelemetrySource.ShouldNotBeNull(); } [Fact] public async Task Flow_Closed_HalfOpen_Closed() { var context = ResilienceContextPool.Shared.Get(TestCancellation.Token); using var controller = CreateController(); await TransitionToState(controller, CircuitState.HalfOpen, context); await controller.OnUnhandledOutcomeAsync(Outcome.FromResult(0), context); controller.CircuitState.ShouldBe(CircuitState.Closed); _circuitBehavior.Received().OnActionSuccess(CircuitState.HalfOpen); _circuitBehavior.Received().OnCircuitClosed(); } [Fact] public async Task Flow_Closed_HalfOpen_Open_HalfOpen_Closed() { var cancellationToken = TestCancellation.Token; var context = ResilienceContextPool.Shared.Get(cancellationToken); using var controller = CreateController(); bool shouldBreak = true; await TransitionToState(controller, CircuitState.HalfOpen, context); _circuitBehavior.When(v => v.OnActionFailure(CircuitState.HalfOpen, out Arg.Any<bool>())) .Do(x => x[1] = shouldBreak); await controller.OnHandledOutcomeAsync(Outcome.FromResult(0), context); controller.CircuitState.ShouldBe(CircuitState.Open); // execution rejected TimeSpan advanceTimeRejected = TimeSpan.FromMilliseconds(1); AdvanceTime(advanceTimeRejected); var outcome = await controller.OnActionPreExecuteAsync(context); var exception = outcome.Value.Exception.ShouldBeOfType<BrokenCircuitException>(); exception.RetryAfter.ShouldBe(_options.BreakDuration - advanceTimeRejected); exception.TelemetrySource.ShouldNotBeNull(); // wait and try, transition to half open AdvanceTime(_options.BreakDuration + _options.BreakDuration); await controller.OnActionPreExecuteAsync(context); controller.CircuitState.ShouldBe(CircuitState.HalfOpen); // close circuit await controller.OnUnhandledOutcomeAsync(Outcome.FromResult(0), context); controller.CircuitState.ShouldBe(CircuitState.Closed); _circuitBehavior.Received().OnActionSuccess(CircuitState.HalfOpen); _circuitBehavior.Received().OnCircuitClosed(); } [Fact] public async Task ExecuteScheduledTask_Async_Ok() { var cancellationToken = TestCancellation.Token; var context = ResilienceContextPool.Shared.Get(cancellationToken); var source = new TaskCompletionSource<string>(); var task = CircuitStateController<string>.ExecuteScheduledTaskAsync(source.Task, context.Initialize<string>(isSynchronous: false)); #pragma warning disable xUnit1031 // Do not use blocking task operations in test method task.Wait(3, cancellationToken).ShouldBeFalse(); #pragma warning restore xUnit1031 // Do not use blocking task operations in test method task.IsCompleted.ShouldBeFalse(); source.SetResult("ok"); await task; task.IsCompleted.ShouldBeTrue(); } private static DateTimeOffset? GetBlockedTill(CircuitStateController<int> controller) => (DateTimeOffset?)controller.GetType().GetField("_blockedUntil", BindingFlags.Instance | BindingFlags.NonPublic)!.GetValue(controller)!; private async Task TransitionToState( CircuitStateController<int> controller, CircuitState state, ResilienceContext context) { switch (state) { case CircuitState.Closed: await controller.CloseCircuitAsync(context); break; case CircuitState.Open: await OpenCircuit(controller); break; case CircuitState.HalfOpen: await OpenCircuit(controller); AdvanceTime(_options.BreakDuration); await controller.OnActionPreExecuteAsync(context); break; case CircuitState.Isolated: await controller.IsolateCircuitAsync(context); break; } controller.CircuitState.ShouldBe(state); } private async Task OpenCircuit(CircuitStateController<int> controller, Outcome<int>? outcome = null) { bool breakCircuit = true; _circuitBehavior.When(v => v.OnActionFailure(CircuitState.Closed, out Arg.Any<bool>())) .Do(x => x[1] = breakCircuit); await controller.OnHandledOutcomeAsync( outcome ?? Outcome.FromResult(10), ResilienceContextPool.Shared.Get(TestCancellation.Token).Initialize<int>(true)); } private void AdvanceTime(TimeSpan timespan) => _timeProvider.Advance(timespan); private CircuitStateController<int> CreateController() => new( _options.BreakDuration, _options.OnOpened, _options.OnClosed, _options.OnHalfOpened, _circuitBehavior, _timeProvider, TestUtilities.CreateResilienceTelemetry(_telemetryListener), _options.BreakDurationGenerator); }
Polly
You are an expert C++ developer. Task: Write a unit test for 'CircuitStateController' using GoogleTest (gtest) and GoogleMock (gmock). Context: - Class: CircuitStateController Requirements: Use EXPECT_CALL for virtual methods.
industrial
#nullable enable namespace Polly.CircuitBreaker; internal sealed class RollingHealthMetrics : IHealthMetrics { internal const short WindowCount = 10; private readonly long _samplingDuration; private readonly long _windowDuration; private readonly Queue<HealthCount> _windows; private HealthCount? _currentWindow; public RollingHealthMetrics(TimeSpan samplingDuration) { _samplingDuration = samplingDuration.Ticks; _windowDuration = _samplingDuration / WindowCount; // stryker disable once all : only affects capacity and not logic _windows = new(WindowCount + 1); } public void IncrementSuccess_NeedsLock() { var currentWindow = ActualiseCurrentMetric_NeedsLock(); currentWindow.Successes++; } public void IncrementFailure_NeedsLock() { var currentWindow = ActualiseCurrentMetric_NeedsLock(); currentWindow.Failures++; } public void Reset_NeedsLock() { _currentWindow = null; _windows.Clear(); } public HealthCount GetHealthCount_NeedsLock() { ActualiseCurrentMetric_NeedsLock(); int successes = 0; int failures = 0; foreach (var window in _windows) { successes += window.Successes; failures += window.Failures; } return new() { Successes = successes, Failures = failures, StartedAt = _windows.Peek().StartedAt }; } private HealthCount ActualiseCurrentMetric_NeedsLock() { var now = SystemClock.UtcNow().Ticks; var currentWindow = _currentWindow; // stryker disable once all : no means to test this if (currentWindow == null || now - currentWindow.StartedAt >= _windowDuration) { _currentWindow = currentWindow = new() { StartedAt = now }; _windows.Enqueue(currentWindow); } // stryker disable once all : no means to test this while (_windows.Count > 0 && now - _windows.Peek().StartedAt >= _samplingDuration) { _windows.Dequeue(); } return currentWindow; } }
using Microsoft.Extensions.Time.Testing; using Polly.CircuitBreaker.Health; namespace Polly.Core.Tests.CircuitBreaker.Health; public class RollingHealthMetricsTests { private readonly FakeTimeProvider _timeProvider; private readonly TimeSpan _samplingDuration = TimeSpan.FromSeconds(10); private readonly short _windows = 10; public RollingHealthMetricsTests() => _timeProvider = new FakeTimeProvider(); [Fact] public void Ctor_EnsureDefaults() { var metrics = Create(); var health = metrics.GetHealthInfo(); health.FailureRate.ShouldBe(0); health.Throughput.ShouldBe(0); } [Fact] public void Increment_Ok() { var metrics = Create(); metrics.IncrementFailure(); metrics.IncrementSuccess(); metrics.IncrementSuccess(); metrics.IncrementSuccess(); metrics.IncrementSuccess(); var health = metrics.GetHealthInfo(); health.FailureRate.ShouldBe(0.2); health.Throughput.ShouldBe(5); } [Fact] public void GetHealthInfo_EnsureWindowRespected() { var metrics = Create(); var health = new List<HealthInfo>(); for (int i = 0; i < 5; i++) { if (i < 2) { metrics.IncrementFailure(); } else { metrics.IncrementSuccess(); } metrics.IncrementSuccess(); _timeProvider.Advance(TimeSpan.FromSeconds(2)); health.Add(metrics.GetHealthInfo()); } _timeProvider.Advance(TimeSpan.FromSeconds(2)); health.Add(metrics.GetHealthInfo()); health[0].ShouldBe(new HealthInfo(2, 0.5, 1)); health[1].ShouldBe(new HealthInfo(4, 0.5, 2)); health[3].ShouldBe(new HealthInfo(8, 0.25, 2)); health[4].ShouldBe(new HealthInfo(8, 0.125, 1)); health[5].ShouldBe(new HealthInfo(6, 0.0, 0)); } [Fact] public void GetHealthInfo_EnsureWindowCapacityRespected() { var delay = TimeSpan.FromSeconds(1); var metrics = Create(); for (int i = 0; i < _windows; i++) { metrics.IncrementSuccess(); _timeProvider.Advance(delay); } metrics.GetHealthInfo().Throughput.ShouldBe(9); _timeProvider.Advance(delay); metrics.GetHealthInfo().Throughput.ShouldBe(8); } [Fact] public void Reset_Ok() { var metrics = Create(); metrics.IncrementSuccess(); metrics.Reset(); metrics.GetHealthInfo().Throughput.ShouldBe(0); } [InlineData(true)] [InlineData(false)] [Theory] public void GetHealthInfo_SamplingDurationRespected(bool variance) { var metrics = Create(); metrics.IncrementSuccess(); metrics.IncrementSuccess(); _timeProvider.Advance(_samplingDuration + (variance ? TimeSpan.FromMilliseconds(1) : TimeSpan.Zero)); metrics.GetHealthInfo().ShouldBe(new HealthInfo(0, 0, 0)); } private RollingHealthMetrics Create() => new(_samplingDuration, _windows, _timeProvider); }
Polly
You are an expert C++ developer. Task: Write a unit test for 'RollingHealthMetrics' using GoogleTest (gtest) and GoogleMock (gmock). Context: - Class: RollingHealthMetrics Requirements: Use EXPECT_CALL for virtual methods.
industrial
#nullable enable namespace Polly.CircuitBreaker; internal sealed class SingleHealthMetrics : IHealthMetrics { private readonly long _samplingDuration; private HealthCount? _current; public SingleHealthMetrics(TimeSpan samplingDuration) => _samplingDuration = samplingDuration.Ticks; public void IncrementSuccess_NeedsLock() => ActualiseCurrentMetric_NeedsLock().Successes++; public void IncrementFailure_NeedsLock() => ActualiseCurrentMetric_NeedsLock().Failures++; public void Reset_NeedsLock() => _current = null; public HealthCount GetHealthCount_NeedsLock() => ActualiseCurrentMetric_NeedsLock(); private HealthCount ActualiseCurrentMetric_NeedsLock() { long now = SystemClock.UtcNow().Ticks; if (_current == null || now - _current.StartedAt >= _samplingDuration) { _current = new() { StartedAt = now }; } return _current; } }
using Polly.CircuitBreaker.Health; namespace Polly.Core.Tests.CircuitBreaker.Health; public class HealthMetricsTests { [InlineData(100, typeof(SingleHealthMetrics))] [InlineData(199, typeof(SingleHealthMetrics))] [InlineData(200, typeof(RollingHealthMetrics))] [InlineData(201, typeof(RollingHealthMetrics))] [Theory] public void Create_Ok(int samplingDurationMs, Type expectedType) => HealthMetrics.Create( TimeSpan.FromMilliseconds(samplingDurationMs), TimeProvider.System) .ShouldBeOfType(expectedType); [Fact] public void HealthInfo_WithZeroTotal_ShouldSetValuesCorrectly() { // Arrange & Act var result = HealthInfo.Create(0, 0); // Assert result.Throughput.ShouldBe(0); result.FailureRate.ShouldBe(0); result.FailureCount.ShouldBe(0); } [Fact] public void HealthInfo_ParameterizedConstructor_ShouldSetProperties() { // Arrange int expectedThroughput = 100; double expectedFailureRate = 0.25; int expectedFailureCount = 25; // Act var result = new HealthInfo(expectedThroughput, expectedFailureRate, expectedFailureCount); // Assert result.Throughput.ShouldBe(expectedThroughput); result.FailureRate.ShouldBe(expectedFailureRate); result.FailureCount.ShouldBe(expectedFailureCount); } [Fact] public void HealthInfo_Constructor_ShouldSetValuesCorrectly() { // Arrange int throughput = 10; double failureRate = 0.2; int failureCount = 2; // Act var result = new HealthInfo(throughput, failureRate, failureCount); // Assert result.Throughput.ShouldBe(throughput); result.FailureRate.ShouldBe(failureRate); result.FailureCount.ShouldBe(failureCount); } }
Polly
You are an expert C++ developer. Task: Write a unit test for 'SingleHealthMetrics' using GoogleTest (gtest) and GoogleMock (gmock). Context: - Class: SingleHealthMetrics Requirements: Use EXPECT_CALL for virtual methods.
industrial
#nullable enable namespace Polly.CircuitBreaker; internal sealed class SingleHealthMetrics : IHealthMetrics { private readonly long _samplingDuration; private HealthCount? _current; public SingleHealthMetrics(TimeSpan samplingDuration) => _samplingDuration = samplingDuration.Ticks; public void IncrementSuccess_NeedsLock() => ActualiseCurrentMetric_NeedsLock().Successes++; public void IncrementFailure_NeedsLock() => ActualiseCurrentMetric_NeedsLock().Failures++; public void Reset_NeedsLock() => _current = null; public HealthCount GetHealthCount_NeedsLock() => ActualiseCurrentMetric_NeedsLock(); private HealthCount ActualiseCurrentMetric_NeedsLock() { long now = SystemClock.UtcNow().Ticks; if (_current == null || now - _current.StartedAt >= _samplingDuration) { _current = new() { StartedAt = now }; } return _current; } }
using Microsoft.Extensions.Time.Testing; using Polly.CircuitBreaker.Health; namespace Polly.Core.Tests.CircuitBreaker.Health; public class SingleHealthMetricsTests { private readonly FakeTimeProvider _timeProvider; public SingleHealthMetricsTests() => _timeProvider = new FakeTimeProvider(); [Fact] public void Ctor_EnsureDefaults() { var metrics = new SingleHealthMetrics(TimeSpan.FromMilliseconds(100), _timeProvider); var health = metrics.GetHealthInfo(); health.FailureRate.ShouldBe(0); health.Throughput.ShouldBe(0); } [Fact] public void Increment_Ok() { var metrics = new SingleHealthMetrics(TimeSpan.FromMilliseconds(100), _timeProvider); metrics.IncrementFailure(); metrics.IncrementSuccess(); metrics.IncrementSuccess(); metrics.IncrementSuccess(); metrics.IncrementSuccess(); var health = metrics.GetHealthInfo(); health.FailureRate.ShouldBe(0.2); health.Throughput.ShouldBe(5); } [Fact] public void Reset_Ok() { var metrics = new SingleHealthMetrics(TimeSpan.FromMilliseconds(100), _timeProvider); metrics.IncrementSuccess(); metrics.Reset(); metrics.GetHealthInfo().Throughput.ShouldBe(0); } [Fact] public void SamplingDurationRespected_Ok() { var metrics = new SingleHealthMetrics(TimeSpan.FromMilliseconds(100), _timeProvider); metrics.IncrementSuccess(); metrics.IncrementSuccess(); _timeProvider.Advance(TimeSpan.FromMilliseconds(100)); metrics.GetHealthInfo().Throughput.ShouldBe(0); } }
Polly
You are an expert C++ developer. Task: Write a unit test for 'SingleHealthMetrics' using GoogleTest (gtest) and GoogleMock (gmock). Context: - Class: SingleHealthMetrics Requirements: Use EXPECT_CALL for virtual methods.
industrial
using Polly.Telemetry; namespace Polly.Fallback; #pragma warning disable CA1031 // Do not catch general exception types internal sealed class FallbackResilienceStrategy<T> : ResilienceStrategy<T> { private readonly FallbackHandler<T> _handler; private readonly Func<OnFallbackArguments<T>, ValueTask>? _onFallback; private readonly ResilienceStrategyTelemetry _telemetry; public FallbackResilienceStrategy(FallbackHandler<T> handler, Func<OnFallbackArguments<T>, ValueTask>? onFallback, ResilienceStrategyTelemetry telemetry) { _handler = handler; _onFallback = onFallback; _telemetry = telemetry; } protected internal override async ValueTask<Outcome<T>> ExecuteCore<TState>(Func<ResilienceContext, TState, ValueTask<Outcome<T>>> callback, ResilienceContext context, TState state) { Outcome<T> outcome; try { outcome = await callback(context, state).ConfigureAwait(context.ContinueOnCapturedContext); } catch (Exception ex) { outcome = new(ex); } var handleFallbackArgs = new FallbackPredicateArguments<T>(context, outcome); if (!await _handler.ShouldHandle(handleFallbackArgs).ConfigureAwait(context.ContinueOnCapturedContext)) { return outcome; } var onFallbackArgs = new OnFallbackArguments<T>(context, outcome); _telemetry.Report<OnFallbackArguments<T>, T>(new(ResilienceEventSeverity.Warning, FallbackConstants.OnFallback), onFallbackArgs); if (_onFallback is not null) { await _onFallback(onFallbackArgs).ConfigureAwait(context.ContinueOnCapturedContext); } try { return await _handler.ActionGenerator(new FallbackActionArguments<T>(context, outcome)).ConfigureAwait(context.ContinueOnCapturedContext); } catch (Exception e) { return Outcome.FromException<T>(e); } } }
using Polly.Fallback; using Polly.Telemetry; namespace Polly.Core.Tests.Fallback; public class FallbackResilienceStrategyTests { private readonly FallbackStrategyOptions<string> _options = new(); private readonly List<TelemetryEventArguments<object, object>> _args = []; private readonly ResilienceStrategyTelemetry _telemetry; private FallbackHandler<string>? _handler; public FallbackResilienceStrategyTests() => _telemetry = TestUtilities.CreateResilienceTelemetry(_args.Add); [Fact] public void Ctor_Ok() => Create().ShouldNotBeNull(); [Fact] public void Handle_Result_Ok() { var called = false; _options.OnFallback = _ => { called = true; return default; }; SetHandler(outcome => outcome.Result == "error", () => Outcome.FromResult("success")); Create().Execute(_ => "error", TestCancellation.Token).ShouldBe("success"); _args.Count(v => v.Arguments is OnFallbackArguments<string>).ShouldBe(1); called.ShouldBeTrue(); } [InlineData(true)] [InlineData(false)] [Theory] public void ShouldHandle_ArgumentsSetCorrectly(bool handle) { var called = 0; _handler = new FallbackHandler<string>( args => { args.Outcome.Result.ShouldBe("ok"); args.Context.ShouldNotBeNull(); called++; return new ValueTask<bool>(handle); }, args => { args.Outcome.Result.ShouldBe("ok"); args.Context.ShouldNotBeNull(); called++; return Outcome.FromResultAsValueTask("fallback"); }); var result = Create().Execute(_ => "ok", TestCancellation.Token); if (handle) { result.ShouldBe("fallback"); called.ShouldBe(2); } else { result.ShouldBe("ok"); called.ShouldBe(1); } } [Fact] public void Handle_Result_FallbackActionThrows() { SetHandler(_ => true, () => throw new InvalidOperationException()); Should.Throw<InvalidOperationException>(() => Create().Execute(_ => "dummy")); } [Fact] public void Handle_Exception_Ok() { var called = false; _options.OnFallback = _ => { called = true; return default; }; SetHandler(outcome => outcome.Exception is InvalidOperationException, () => Outcome.FromResult("secondary")); Create().Execute<string>(_ => throw new InvalidOperationException(), TestCancellation.Token).ShouldBe("secondary"); _args.Count(v => v.Arguments is OnFallbackArguments<string>).ShouldBe(1); called.ShouldBeTrue(); } [Fact] public void Handle_UnhandledException_Ok() { var called = false; var fallbackActionCalled = false; _options.OnFallback = _ => { called = true; return default; }; SetHandler(outcome => outcome.Exception is InvalidOperationException, () => { fallbackActionCalled = true; return Outcome.FromResult("secondary"); }); Should.Throw<ArgumentException>(() => Create().Execute<string>(_ => throw new ArgumentException())); _args.ShouldBeEmpty(); called.ShouldBeFalse(); fallbackActionCalled.ShouldBeFalse(); } [Fact] public void Handle_UnhandledResult_Ok() { var called = false; var fallbackActionCalled = false; _options.OnFallback = _ => { called = true; return default; }; SetHandler(outcome => false, () => Outcome.FromResult("secondary")); Create().Execute(_ => "primary", TestCancellation.Token).ShouldBe("primary"); _args.ShouldBeEmpty(); called.ShouldBeFalse(); fallbackActionCalled.ShouldBeFalse(); } [Fact] public async Task ExecuteOutcomeAsync_UnhandledException_Ok() { var called = false; var fallbackActionCalled = false; _options.OnFallback = _ => { called = true; return default; }; SetHandler(outcome => outcome.Exception is InvalidOperationException, () => { fallbackActionCalled = true; return Outcome.FromResult("secondary"); }); var outcome = await Create().ExecuteOutcomeAsync<string, string>((_, _) => throw new ArgumentException(), new(), "dummy-state"); outcome.Exception.ShouldBeOfType<ArgumentException>(); _args.ShouldBeEmpty(); called.ShouldBeFalse(); fallbackActionCalled.ShouldBeFalse(); } private void SetHandler( Func<Outcome<string>, bool> shouldHandle, Func<Outcome<string>> fallback) => _handler = FallbackHelper.CreateHandler(shouldHandle, fallback); private ResiliencePipeline<string> Create() => new FallbackResilienceStrategy<string>(_handler!, _options.OnFallback, _telemetry).AsPipeline(); }
Polly
You are an expert C++ developer. Task: Write a unit test for 'FallbackResilienceStrategy' using GoogleTest (gtest) and GoogleMock (gmock). Context: - Class: FallbackResilienceStrategy Requirements: Use EXPECT_CALL for virtual methods.
industrial
using System.ComponentModel.DataAnnotations; namespace Polly.Fallback; /// <summary> /// Represents the options for configuring a fallback resilience strategy with a specific result type. /// </summary> /// <typeparam name="TResult">The result type.</typeparam> public class FallbackStrategyOptions<TResult> : ResilienceStrategyOptions { /// <summary> /// Initializes a new instance of the <see cref="FallbackStrategyOptions{TResult}"/> class. /// </summary> public FallbackStrategyOptions() => Name = FallbackConstants.DefaultName; /// <summary> /// Gets or sets a predicate that determines whether the fallback should be executed for a given outcome. /// </summary> /// <value> /// The default value is a predicate that falls back on any exception except <see cref="OperationCanceledException"/>. This property is required. /// </value> [Required] public Func<FallbackPredicateArguments<TResult>, ValueTask<bool>> ShouldHandle { get; set; } = DefaultPredicates<FallbackPredicateArguments<TResult>, TResult>.HandleOutcome; /// <summary> /// Gets or sets the fallback action to be executed when the <see cref="ShouldHandle"/> predicate evaluates as true. /// </summary> /// <value> /// The default value is <see langword="null"/>. This property is required. /// </value> [Required] public Func<FallbackActionArguments<TResult>, ValueTask<Outcome<TResult>>>? FallbackAction { get; set; } /// <summary> /// Gets or sets event delegate that is raised when fallback happens. /// </summary> /// <value> /// The default value is <see langword="null"/> instance. /// </value> public Func<OnFallbackArguments<TResult>, ValueTask>? OnFallback { get; set; } }
using System.ComponentModel.DataAnnotations; using Polly.Fallback; using Polly.Utils; namespace Polly.Core.Tests.Fallback; public class FallbackStrategyOptionsTests { [Fact] public void Ctor_EnsureDefaults() { var options = new FallbackStrategyOptions<int>(); options.ShouldHandle.ShouldNotBeNull(); options.OnFallback.ShouldBeNull(); options.FallbackAction.ShouldBeNull(); options.Name.ShouldBe("Fallback"); } [Fact] public async Task ShouldHandle_EnsureDefaults() { var options = new FallbackStrategyOptions<int>(); var context = ResilienceContextPool.Shared.Get(TestCancellation.Token); (await options.ShouldHandle(new FallbackPredicateArguments<int>(context, Outcome.FromResult(0)))).ShouldBe(false); (await options.ShouldHandle(new FallbackPredicateArguments<int>(context, Outcome.FromException<int>(new OperationCanceledException())))).ShouldBe(false); (await options.ShouldHandle(new FallbackPredicateArguments<int>(context, Outcome.FromException<int>(new InvalidOperationException())))).ShouldBe(true); } [Fact] public void Validation() { var options = new FallbackStrategyOptions<int> { ShouldHandle = null! }; var exception = Should.Throw<ValidationException>(() => ValidationHelper.ValidateObject(new(options, "Invalid."))); exception.Message.Trim().ShouldBe(""" Invalid. Validation Errors: The ShouldHandle field is required. The FallbackAction field is required. """, StringCompareShould.IgnoreLineEndings); } }
Polly
You are an expert .NET (C#) developer. Task: Write a unit test for 'FallbackStrategyOptions' using XUnit and Moq. Context: - Class: FallbackStrategyOptions Requirements: Use Mock<T> interface mocking.
industrial
using System.ComponentModel.DataAnnotations; using System.Diagnostics.CodeAnalysis; using Polly.Fallback; namespace Polly; /// <summary> /// Extensions for adding fallback to <see cref="ResiliencePipelineBuilder"/>. /// </summary> public static class FallbackResiliencePipelineBuilderExtensions { /// <summary> /// Adds a fallback resilience strategy with the provided options to the builder. /// </summary> /// <typeparam name="TResult">The result type.</typeparam> /// <param name="builder">The resilience pipeline builder.</param> /// <param name="options">The options to configure the fallback resilience strategy.</param> /// <returns>The builder instance with the fallback strategy added.</returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="builder"/> or <paramref name="options"/> is <see langword="null"/>.</exception> /// <exception cref="ValidationException">Thrown when <paramref name="options"/> are invalid.</exception> [UnconditionalSuppressMessage( "Trimming", "IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code", Justification = "All options members preserved.")] public static ResiliencePipelineBuilder<TResult> AddFallback<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] TResult>( this ResiliencePipelineBuilder<TResult> builder, FallbackStrategyOptions<TResult> options) { Guard.NotNull(builder); Guard.NotNull(options); return builder.AddStrategy(context => CreateFallback(context, options), options); } private static ResilienceStrategy<TResult> CreateFallback<TResult>( StrategyBuilderContext context, FallbackStrategyOptions<TResult> options) { var handler = new FallbackHandler<TResult>( options.ShouldHandle!, options.FallbackAction!); return new FallbackResilienceStrategy<TResult>( handler, options.OnFallback, context.Telemetry); } }
using System.ComponentModel.DataAnnotations; using Polly.Fallback; using Polly.Testing; namespace Polly.Core.Tests.Fallback; public class FallbackResiliencePipelineBuilderExtensionsTests { #pragma warning disable IDE0028 public static readonly TheoryData<Action<ResiliencePipelineBuilder<int>>> FallbackOverloadsGeneric = new() { builder => { builder.AddFallback(new FallbackStrategyOptions<int> { FallbackAction = _ => Outcome.FromResultAsValueTask(0), ShouldHandle = _ => PredicateResult.False(), }); } }; #pragma warning restore IDE0028 [MemberData(nameof(FallbackOverloadsGeneric))] [Theory] public void AddFallback_Generic_Ok(Action<ResiliencePipelineBuilder<int>> configure) { var builder = new ResiliencePipelineBuilder<int>(); configure(builder); builder.Build().GetPipelineDescriptor().FirstStrategy.StrategyInstance.ShouldBeOfType<FallbackResilienceStrategy<int>>(); } [Fact] public void AddFallbackT_InvalidOptions_Throws() => Should.Throw<ValidationException>(() => new ResiliencePipelineBuilder<double>().AddFallback(new FallbackStrategyOptions<double>())); }
Polly
You are an expert .NET (C#) developer. Task: Write a unit test for 'FallbackResiliencePipelineBuilderExtensions' using XUnit and Moq. Context: - Class: FallbackResiliencePipelineBuilderExtensions Requirements: Use Mock<T> interface mocking.
industrial
namespace Polly.Fallback; internal sealed record class FallbackHandler<T>( Func<FallbackPredicateArguments<T>, ValueTask<bool>> ShouldHandle, Func<FallbackActionArguments<T>, ValueTask<Outcome<T>>> ActionGenerator);
using Polly.Fallback; namespace Polly.Core.Tests.Fallback; public class FallbackHandlerTests { [Fact] public async Task GenerateAction_Generic_Ok() { var handler = FallbackHelper.CreateHandler(_ => true, () => Outcome.FromResult("secondary")); var context = ResilienceContextPool.Shared.Get(TestCancellation.Token); var outcome = await handler.ActionGenerator(new FallbackActionArguments<string>(context, Outcome.FromResult("primary")))!; outcome.Result.ShouldBe("secondary"); } }
Polly
You are an expert C++ developer. Task: Write a unit test for 'TargetModule' using GoogleTest (gtest) and GoogleMock (gmock). Context: - Class: TargetModule Requirements: Use EXPECT_CALL for virtual methods.
industrial
using System.ComponentModel.DataAnnotations; using System.Diagnostics.CodeAnalysis; using Polly.Timeout; namespace Polly; /// <summary> /// Extensions for adding timeout to <see cref="ResiliencePipelineBuilder"/>. /// </summary> public static class TimeoutResiliencePipelineBuilderExtensions { /// <summary> /// Adds a timeout to the builder. /// </summary> /// <typeparam name="TBuilder">The builder type.</typeparam> /// <param name="builder">The builder instance.</param> /// <param name="timeout">The timeout value. This value should be greater than <see cref="TimeSpan.Zero"/>.</param> /// <returns>The same builder instance.</returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="builder"/> is <see langword="null"/>.</exception> /// <exception cref="ValidationException">Thrown when the options produced from the arguments are invalid.</exception> public static TBuilder AddTimeout<TBuilder>(this TBuilder builder, TimeSpan timeout) where TBuilder : ResiliencePipelineBuilderBase => builder.AddTimeout(new TimeoutStrategyOptions { Timeout = timeout }); /// <summary> /// Adds a timeout to the builder. /// </summary> /// <typeparam name="TBuilder">The builder type.</typeparam> /// <param name="builder">The builder instance.</param> /// <param name="options">The timeout options.</param> /// <returns>The same builder instance.</returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="builder"/> or <paramref name="options"/> is <see langword="null"/>.</exception> /// <exception cref="ValidationException">Thrown when <paramref name="options"/> are invalid.</exception> [DynamicDependency(DynamicallyAccessedMemberTypes.All, typeof(TimeoutStrategyOptions))] [UnconditionalSuppressMessage( "Trimming", "IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code", Justification = "All options members preserved.")] public static TBuilder AddTimeout<TBuilder>(this TBuilder builder, TimeoutStrategyOptions options) where TBuilder : ResiliencePipelineBuilderBase { Guard.NotNull(builder); Guard.NotNull(options); builder.AddStrategy(context => new TimeoutResilienceStrategy(options, context.TimeProvider, context.Telemetry), options); return builder; } }
using System.ComponentModel.DataAnnotations; using Polly.Testing; using Polly.Timeout; namespace Polly.Core.Tests.Timeout; public class TimeoutResiliencePipelineBuilderExtensionsTests { public static IEnumerable<object[]> AddTimeout_Ok_Data() { var timeout = TimeSpan.FromSeconds(4); yield return new object[] { timeout, (ResiliencePipelineBuilder<int> builder) => { builder.AddTimeout(timeout); }, (TimeoutResilienceStrategy strategy) => { GetTimeout(strategy).ShouldBe(timeout); } }; } [Theory] [MemberData(nameof(TimeoutTestUtils.InvalidTimeouts), MemberType = typeof(TimeoutTestUtils))] public void AddTimeout_InvalidTimeout_EnsureValidated(TimeSpan timeout) { var builder = new ResiliencePipelineBuilder<int>(); Assert.Throws<ValidationException>(() => builder.AddTimeout(timeout)); } [Theory] #pragma warning disable xUnit1042 // The member referenced by the MemberData attribute returns untyped data rows [MemberData(nameof(AddTimeout_Ok_Data))] #pragma warning restore xUnit1042 // The member referenced by the MemberData attribute returns untyped data rows internal void AddTimeout_Ok(TimeSpan timeout, Action<ResiliencePipelineBuilder<int>> configure, Action<TimeoutResilienceStrategy> assert) { var builder = new ResiliencePipelineBuilder<int>(); configure(builder); var strategy = builder.Build().GetPipelineDescriptor().FirstStrategy.StrategyInstance.ShouldBeOfType<TimeoutResilienceStrategy>(); assert(strategy); GetTimeout(strategy).ShouldBe(timeout); } [Fact] public void AddTimeout_Options_Ok() { var strategy = new ResiliencePipelineBuilder().AddTimeout(new TimeoutStrategyOptions()).Build(); strategy.GetPipelineDescriptor().FirstStrategy.StrategyInstance.ShouldBeOfType<TimeoutResilienceStrategy>(); } [Fact] public void AddTimeout_InvalidOptions_Throws() => Should.Throw<ValidationException>( () => new ResiliencePipelineBuilder().AddTimeout(new TimeoutStrategyOptions { Timeout = TimeSpan.Zero })); private static TimeSpan GetTimeout(TimeoutResilienceStrategy strategy) { if (strategy.TimeoutGenerator is null) { return strategy.DefaultTimeout; } return strategy.TimeoutGenerator( new TimeoutGeneratorArguments( ResilienceContextPool.Shared.Get(TestCancellation.Token))).Preserve().GetAwaiter().GetResult(); } }
Polly
You are an expert .NET (C#) developer. Task: Write a unit test for 'TimeoutResiliencePipelineBuilderExtensions' using XUnit and Moq. Context: - Class: TimeoutResiliencePipelineBuilderExtensions Requirements: Use Mock<T> interface mocking.
industrial
#if !NETCOREAPP using System.Runtime.Serialization; #endif namespace Polly.Timeout; /// <summary> /// Exception thrown when a delegate executed through a timeout resilience strategy does not complete, before the configured timeout. /// </summary> #if !NETCOREAPP [Serializable] #endif public class TimeoutRejectedException : ExecutionRejectedException { /// <summary> /// Initializes a new instance of the <see cref="TimeoutRejectedException" /> class. /// </summary> public TimeoutRejectedException() : base("The operation didn't complete within the allowed timeout.") { } /// <summary> /// Initializes a new instance of the <see cref="TimeoutRejectedException"/> class. /// </summary> /// <param name="message">The message.</param> public TimeoutRejectedException(string message) : base(message) { } /// <summary> /// Initializes a new instance of the <see cref="TimeoutRejectedException"/> class. /// </summary> /// <param name="message">The message.</param> /// <param name="innerException">The inner exception.</param> public TimeoutRejectedException(string message, Exception innerException) : base(message, innerException) { } /// <summary> /// Initializes a new instance of the <see cref="TimeoutRejectedException" /> class. /// </summary> /// <param name="timeout">The timeout value that caused this exception.</param> public TimeoutRejectedException(TimeSpan timeout) : base("The operation didn't complete within the allowed timeout.") => Timeout = timeout; /// <summary> /// Initializes a new instance of the <see cref="TimeoutRejectedException"/> class. /// </summary> /// <param name="timeout">The timeout value that caused this exception.</param> /// <param name="message">The message.</param> public TimeoutRejectedException(string message, TimeSpan timeout) : base(message) => Timeout = timeout; /// <summary> /// Initializes a new instance of the <see cref="TimeoutRejectedException"/> class. /// </summary> /// <param name="message">The message.</param> /// <param name="timeout">The timeout value that caused this exception.</param> /// <param name="innerException">The inner exception.</param> public TimeoutRejectedException(string message, TimeSpan timeout, Exception innerException) : base(message, innerException) => Timeout = timeout; /// <summary> /// Gets the timeout value that caused this exception. /// </summary> public TimeSpan Timeout { get; private set; } = System.Threading.Timeout.InfiniteTimeSpan; #pragma warning disable RS0016 // Add public types and members to the declared API #if !NETCOREAPP /// <summary> /// Initializes a new instance of the <see cref="TimeoutRejectedException"/> class. /// </summary> /// <param name="info">The information.</param> /// <param name="context">The context.</param> private TimeoutRejectedException(SerializationInfo info, StreamingContext context) : base(info, context) => Timeout = TimeSpan.FromSeconds(info.GetDouble("Timeout")); /// <inheritdoc/> public override void GetObjectData(SerializationInfo info, StreamingContext context) { Guard.NotNull(info); info.AddValue("Timeout", Timeout.TotalSeconds); base.GetObjectData(info, context); } #endif #pragma warning restore RS0016 // Add public types and members to the declared API }
using Polly.Timeout; namespace Polly.Core.Tests.Timeout; public class TimeoutRejectedExceptionTests { [Fact] public void Ctor_Ok() { var delay = TimeSpan.FromSeconds(4); new TimeoutRejectedException().Message.ShouldBe("The operation didn't complete within the allowed timeout."); new TimeoutRejectedException("dummy").Message.ShouldBe("dummy"); new TimeoutRejectedException("dummy", new InvalidOperationException()).Message.ShouldBe("dummy"); new TimeoutRejectedException(delay).Timeout.ShouldBe(delay); new TimeoutRejectedException(delay).Message.ShouldBe("The operation didn't complete within the allowed timeout."); new TimeoutRejectedException("dummy", delay).Timeout.ShouldBe(delay); new TimeoutRejectedException("dummy", delay, new InvalidOperationException()).Timeout.ShouldBe(delay); } #if NETFRAMEWORK [Fact] public void BinaryDeserialization_Ok() { var timeout = TimeSpan.FromSeconds(4); var result = BinarySerializationUtil.SerializeAndDeserializeException(new TimeoutRejectedException(timeout)); result.Timeout.ShouldBe(timeout); } #endif }
Polly
You are an expert .NET (C#) developer. Task: Write a unit test for 'TimeoutRejectedException' using XUnit and Moq. Context: - Class: TimeoutRejectedException Requirements: Use Mock<T> interface mocking.
industrial
using Polly.Telemetry; namespace Polly.Timeout; internal sealed class TimeoutResilienceStrategy : ResilienceStrategy { private readonly ResilienceStrategyTelemetry _telemetry; private readonly CancellationTokenSourcePool _cancellationTokenSourcePool; public TimeoutResilienceStrategy(TimeoutStrategyOptions options, TimeProvider timeProvider, ResilienceStrategyTelemetry telemetry) { DefaultTimeout = options.Timeout; TimeoutGenerator = options.TimeoutGenerator; OnTimeout = options.OnTimeout; _telemetry = telemetry; _cancellationTokenSourcePool = CancellationTokenSourcePool.Create(timeProvider); } public TimeSpan DefaultTimeout { get; } public Func<TimeoutGeneratorArguments, ValueTask<TimeSpan>>? TimeoutGenerator { get; } public Func<OnTimeoutArguments, ValueTask>? OnTimeout { get; } protected internal override async ValueTask<Outcome<TResult>> ExecuteCore<TResult, TState>( Func<ResilienceContext, TState, ValueTask<Outcome<TResult>>> callback, ResilienceContext context, TState state) { var timeout = DefaultTimeout; if (TimeoutGenerator is not null) { timeout = await TimeoutGenerator!(new TimeoutGeneratorArguments(context)).ConfigureAwait(context.ContinueOnCapturedContext); } if (!TimeoutUtil.ShouldApplyTimeout(timeout)) { // do nothing return await callback(context, state).ConfigureAwait(context.ContinueOnCapturedContext); } var previousToken = context.CancellationToken; var cancellationSource = _cancellationTokenSourcePool.Get(timeout); context.CancellationToken = cancellationSource.Token; var registration = CreateRegistration(cancellationSource, previousToken); Outcome<TResult> outcome; try { outcome = await callback(context, state).ConfigureAwait(context.ContinueOnCapturedContext); } #pragma warning disable CA1031 catch (Exception ex) { outcome = new(ex); } #pragma warning restore CA1031 var isCancellationRequested = cancellationSource.IsCancellationRequested; // execution is finished, clean up context.CancellationToken = previousToken; #pragma warning disable CA1849 // Call async methods when in an async method, OK here as the callback is synchronous #pragma warning disable S6966 registration.Dispose(); #pragma warning restore S6966 #pragma warning restore CA1849 // Call async methods when in an async method _cancellationTokenSourcePool.Return(cancellationSource); // check the outcome if (isCancellationRequested && outcome.Exception is OperationCanceledException e && !previousToken.IsCancellationRequested) { var args = new OnTimeoutArguments(context, timeout); _telemetry.Report(new(ResilienceEventSeverity.Error, TimeoutConstants.OnTimeoutEvent), context, args); if (OnTimeout is not null) { await OnTimeout(args).ConfigureAwait(context.ContinueOnCapturedContext); } var timeoutException = new TimeoutRejectedException( $"The operation didn't complete within the allowed timeout of '{timeout}'.", timeout, e); _telemetry.SetTelemetrySource(timeoutException); return Outcome.FromException<TResult>(timeoutException.TrySetStackTrace()); } return outcome; } private static CancellationTokenRegistration CreateRegistration(CancellationTokenSource cancellationSource, CancellationToken previousToken) { #if NET return previousToken.UnsafeRegister(static state => ((CancellationTokenSource)state!).Cancel(), cancellationSource); #else return previousToken.Register(static state => ((CancellationTokenSource)state!).Cancel(), cancellationSource); #endif } }
using System.Runtime.InteropServices; using Microsoft.Extensions.Time.Testing; using NSubstitute; using Polly.Telemetry; using Polly.Timeout; namespace Polly.Core.Tests.Timeout; public class TimeoutResilienceStrategyTests : IDisposable { private readonly ResilienceStrategyTelemetry _telemetry; private readonly FakeTimeProvider _timeProvider = new(); private readonly TimeoutStrategyOptions _options; private readonly CancellationTokenSource _cancellationSource; private readonly TimeSpan _delay = TimeSpan.FromSeconds(12); private readonly List<TelemetryEventArguments<object, object>> _args = []; public TimeoutResilienceStrategyTests() { _telemetry = TestUtilities.CreateResilienceTelemetry(_args.Add); _options = new TimeoutStrategyOptions(); _cancellationSource = new CancellationTokenSource(); } #pragma warning disable IDE0028 // Simplify collection initialization public static TheoryData<Func<TimeSpan>> Execute_NoTimeout_Data() => new() { () => TimeSpan.Zero, () => TimeSpan.FromMilliseconds(-1), () => System.Threading.Timeout.InfiniteTimeSpan, }; #pragma warning restore IDE0028 // Simplify collection initialization public void Dispose() => _cancellationSource.Dispose(); [Fact] public void Execute_EnsureTimeoutGeneratorCalled() { var called = false; _options.TimeoutGenerator = args => { args.Context.ShouldNotBeNull(); called = true; return new ValueTask<TimeSpan>(TimeSpan.Zero); }; var sut = CreateSut(); sut.Execute(_ => { }, TestCancellation.Token); called.ShouldBeTrue(); } [Fact] public async Task Execute_EnsureOnTimeoutCalled() { var called = false; SetTimeout(_delay); var executionTime = _delay + TimeSpan.FromSeconds(1); _options.OnTimeout = args => { args.Timeout.ShouldBe(_delay); args.Context.ShouldNotBeNull(); args.Context.CancellationToken.IsCancellationRequested.ShouldBeFalse(); called = true; return default; }; var sut = CreateSut(); await Should.ThrowAsync<TimeoutRejectedException>( () => sut.ExecuteAsync(async token => { var delay = _timeProvider.Delay(executionTime, token); _timeProvider.Advance(_delay); await delay; }) .AsTask()); called.ShouldBeTrue(); _args.Count.ShouldBe(1); _args[0].Arguments.ShouldBeOfType<OnTimeoutArguments>(); } [MemberData(nameof(Execute_NoTimeout_Data))] [Theory] public void Execute_NoTimeout(Func<TimeSpan> timeout) { var called = false; SetTimeout(timeout()); var sut = CreateSut(); sut.Execute(_ => { }, TestCancellation.Token); called.ShouldBeFalse(); } [InlineData(true)] [InlineData(false)] [Theory] public async Task Execute_Timeout(bool defaultCancellationToken) { using var cts = new CancellationTokenSource(); CancellationToken token = defaultCancellationToken ? default : cts.Token; SetTimeout(TimeSpan.FromSeconds(2)); var sut = CreateSut(); var exception = await Should.ThrowAsync<TimeoutRejectedException>( () => sut.ExecuteAsync(async token => { var delay = _timeProvider.Delay(TimeSpan.FromSeconds(4), token); _timeProvider.Advance(TimeSpan.FromSeconds(2)); await delay; }, token) .AsTask()); exception.Message.ShouldBe("The operation didn't complete within the allowed timeout of '00:00:02'."); } [Fact] public async Task Execute_TimeoutGeneratorIsNull_FallsBackToTimeout() { var called = false; var timeout = TimeSpan.FromMilliseconds(10); _options.TimeoutGenerator = null; _options.Timeout = timeout; _options.OnTimeout = args => { called = true; args.Timeout.ShouldBe(timeout); return default; }; var sut = CreateSut(); await Should.ThrowAsync<TimeoutRejectedException>( () => sut.ExecuteAsync(async token => { var delay = _timeProvider.Delay(TimeSpan.FromMilliseconds(50), token); _timeProvider.Advance(timeout); await delay; }, _cancellationSource.Token) .AsTask()); called.ShouldBeTrue(); } [Fact] public async Task Execute_Timeout_EnsureStackTrace() { SetTimeout(TimeSpan.FromSeconds(2)); var sut = CreateSut(); var outcome = await sut.ExecuteOutcomeAsync( async (c, _) => { var delay = _timeProvider.Delay(TimeSpan.FromSeconds(4), c.CancellationToken); _timeProvider.Advance(TimeSpan.FromSeconds(2)); await delay; return Outcome.FromResult("dummy"); }, ResilienceContextPool.Shared.Get(_cancellationSource.Token), "state"); outcome.Exception.ShouldBeOfType<TimeoutRejectedException>(); if (!RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { outcome.Exception!.StackTrace.ShouldNotBeEmpty(); } } [Fact] public async Task Execute_Timeout_EnsureTelemetrySource() { SetTimeout(TimeSpan.FromSeconds(2)); var sut = CreateSut(); var outcome = await sut.ExecuteOutcomeAsync( async (c, _) => { var delay = _timeProvider.Delay(TimeSpan.FromSeconds(4), c.CancellationToken); _timeProvider.Advance(TimeSpan.FromSeconds(2)); await delay; return Outcome.FromResult("dummy"); }, ResilienceContextPool.Shared.Get(_cancellationSource.Token), "state"); outcome.Exception.ShouldBeOfType<TimeoutRejectedException>().TelemetrySource.ShouldNotBeNull(); } [Fact] public async Task Execute_Cancelled_EnsureNoTimeout() { var delay = TimeSpan.FromSeconds(10); var onTimeoutCalled = false; using var cts = new CancellationTokenSource(); SetTimeout(TimeSpan.FromSeconds(10)); _options.OnTimeout = args => { onTimeoutCalled = true; return default; }; var sut = CreateSut(); await Should.ThrowAsync<OperationCanceledException>( () => sut.ExecuteAsync(async token => { var task = _timeProvider.Delay(delay, token); cts.Cancel(); await task; }, cts.Token).AsTask()); onTimeoutCalled.ShouldBeFalse(); _args.ShouldBeEmpty(); } [Fact] public async Task Execute_NoTimeoutOrCancellation_EnsureCancellationTokenRestored() { var delay = TimeSpan.FromSeconds(10); using var cts = new CancellationTokenSource(); SetTimeout(TimeSpan.FromSeconds(10)); _timeProvider.Advance(delay); var sut = CreateSut(); var context = ResilienceContextPool.Shared.Get(cts.Token); await sut.ExecuteAsync( (r, _) => { r.CancellationToken.ShouldNotBe(cts.Token); return default; }, context, string.Empty); context.CancellationToken.ShouldBe(cts.Token); } [Fact] public async Task Execute_EnsureCancellationTokenRegistrationNotExecutedOnSynchronizationContext() { // Arrange using var cts = new CancellationTokenSource(); SetTimeout(TimeSpan.FromSeconds(10)); var sut = CreateSut(); var mockSynchronizationContext = Substitute.For<SynchronizationContext>(); mockSynchronizationContext .When(x => x.Post(Arg.Any<SendOrPostCallback>(), Arg.Any<object>())) .Do((p) => ((SendOrPostCallback)p[1])(p[2])); mockSynchronizationContext.CreateCopy() .Returns(mockSynchronizationContext); SynchronizationContext.SetSynchronizationContext(mockSynchronizationContext); // Act try { await sut.ExecuteAsync(async token => { Task delayTask = Task.Delay(TimeSpan.FromSeconds(10), token); cts.Cancel(); await delayTask; }, cts.Token); } catch (OperationCanceledException) { // ok } // Assert mockSynchronizationContext.DidNotReceiveWithAnyArgs().Post(default!, default); } private void SetTimeout(TimeSpan timeout) => _options.TimeoutGenerator = args => new ValueTask<TimeSpan>(timeout); private ResiliencePipeline CreateSut() => new TimeoutResilienceStrategy(_options, _timeProvider, _telemetry).AsPipeline(); }
Polly
You are an expert C++ developer. Task: Write a unit test for 'TimeoutResilienceStrategy' using GoogleTest (gtest) and GoogleMock (gmock). Context: - Class: TimeoutResilienceStrategy Requirements: Use EXPECT_CALL for virtual methods.
industrial
using System.ComponentModel.DataAnnotations; using System.Diagnostics.CodeAnalysis; namespace Polly.Timeout; /// <summary> /// Represents the options for the timeout strategy. /// </summary> public class TimeoutStrategyOptions : ResilienceStrategyOptions { /// <summary> /// Initializes a new instance of the <see cref="TimeoutStrategyOptions"/> class. /// </summary> public TimeoutStrategyOptions() => Name = TimeoutConstants.DefaultName; /// <summary> /// Gets or sets the default timeout. /// </summary> /// <value> /// This value must be greater than 10 milliseconds and less than 24 hours. The default value is 30 seconds. /// </value> [Range(typeof(TimeSpan), "00:00:00.010", "1.00:00:00")] [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Addressed with DynamicDependency on ValidationHelper.Validate method")] public TimeSpan Timeout { get; set; } = TimeSpan.FromSeconds(30); /// <summary> /// Gets or sets a timeout generator that generates the timeout for a given execution. /// </summary> /// <remarks> /// When generator is <see langword="null"/> then the <see cref="Timeout"/> property's value is used instead. /// When generator returns a <see cref="TimeSpan"/> value that is less than or equal to <see cref="TimeSpan.Zero"/> /// then the strategy will do nothing. /// <para> /// Return <see cref="System.Threading.Timeout.InfiniteTimeSpan"/> to disable the timeout for the given execution. /// </para> /// </remarks> /// <value> /// The default value is <see langword="null"/>. /// </value> public Func<TimeoutGeneratorArguments, ValueTask<TimeSpan>>? TimeoutGenerator { get; set; } /// <summary> /// Gets or sets the timeout delegate that raised when timeout occurs. /// </summary> /// <value> /// The default value is <see langword="null"/>. /// </value> public Func<OnTimeoutArguments, ValueTask>? OnTimeout { get; set; } }
using System.ComponentModel.DataAnnotations; using Polly.Timeout; using Polly.Utils; namespace Polly.Core.Tests.Timeout; public class TimeoutStrategyOptionsTests { [Fact] public void Ctor_EnsureDefaultValues() { var options = new TimeoutStrategyOptions(); options.TimeoutGenerator.ShouldBeNull(); options.OnTimeout.ShouldBeNull(); options.Name.ShouldBe("Timeout"); } [MemberData(nameof(TimeoutTestUtils.InvalidTimeouts), MemberType = typeof(TimeoutTestUtils))] [Theory] public void Timeout_Invalid_EnsureValidationError(TimeSpan value) { var options = new TimeoutStrategyOptions { Timeout = value }; Should.Throw<ValidationException>( () => ValidationHelper.ValidateObject(new(options, "Dummy message"))); } [MemberData(nameof(TimeoutTestUtils.ValidTimeouts), MemberType = typeof(TimeoutTestUtils))] [Theory] public void Timeout_Valid(TimeSpan value) { var options = new TimeoutStrategyOptions { Timeout = value }; Should.NotThrow( () => ValidationHelper.ValidateObject(new(options, "Dummy message"))); } }
Polly
You are an expert .NET (C#) developer. Task: Write a unit test for 'TimeoutStrategyOptions' using XUnit and Moq. Context: - Class: TimeoutStrategyOptions Requirements: Use Mock<T> interface mocking.
industrial
namespace Polly.Timeout; internal static class TimeoutConstants { public const string DefaultName = "Timeout"; public const string OnTimeoutEvent = "OnTimeout"; }
using Polly.Timeout; namespace Polly.Core.Tests.Timeout; public class TimeoutConstantsTests { [Fact] public void EnsureDefaultValues() => TimeoutConstants.OnTimeoutEvent.ShouldBe("OnTimeout"); }
Polly
You are an expert C++ developer. Task: Write a unit test for 'TimeoutConstants' using GoogleTest (gtest) and GoogleMock (gmock). Context: - Class: TimeoutConstants Requirements: Use EXPECT_CALL for virtual methods.
industrial
namespace Polly.Retry; #pragma warning disable CA1815 // Override equals and operator equals on value types /// <summary> /// Represents the arguments used by <see cref="RetryStrategyOptions{TResult}.DelayGenerator"/> for generating the next retry delay. /// </summary> /// <typeparam name="TResult">The type of result.</typeparam> /// <remarks> /// Always use the constructor when creating this struct, otherwise we do not guarantee binary compatibility. /// </remarks> public readonly struct RetryDelayGeneratorArguments<TResult> { /// <summary> /// Initializes a new instance of the <see cref="RetryDelayGeneratorArguments{TResult}"/> struct. /// </summary> /// <param name="outcome">The context in which the resilience operation or event occurred.</param> /// <param name="context">The outcome of the resilience operation or event.</param> /// <param name="attemptNumber">The zero-based attempt number.</param> public RetryDelayGeneratorArguments(ResilienceContext context, Outcome<TResult> outcome, int attemptNumber) { Context = context; Outcome = outcome; AttemptNumber = attemptNumber; } /// <summary> /// Gets the outcome of the resilience operation or event. /// </summary> public Outcome<TResult> Outcome { get; } /// <summary> /// Gets the context in which the resilience operation or event occurred. /// </summary> public ResilienceContext Context { get; } /// <summary> /// Gets The zero-based attempt number. /// </summary> public int AttemptNumber { get; } }
using Polly.Retry; namespace Polly.Core.Tests.Retry; public static class RetryDelayGeneratorArgumentsTests { [Fact] public static void Ctor_Ok() { // Arrange var context = ResilienceContextPool.Shared.Get(TestCancellation.Token); // Act var args = new RetryDelayGeneratorArguments<int>(context, Outcome.FromResult(1), 2); // Assert args.Context.ShouldBe(context); args.Outcome.Result.ShouldBe(1); args.AttemptNumber.ShouldBe(2); } }
Polly
You are an expert C++ developer. Task: Write a unit test for 'TargetModule' using GoogleTest (gtest) and GoogleMock (gmock). Context: - Class: TargetModule Requirements: Use EXPECT_CALL for virtual methods.
industrial
using System.ComponentModel.DataAnnotations; using System.Diagnostics.CodeAnalysis; using Polly.Retry; namespace Polly; /// <summary> /// Extensions for adding retries to <see cref="ResiliencePipelineBuilder"/>. /// </summary> public static class RetryResiliencePipelineBuilderExtensions { /// <summary> /// Adds a retry to the builder. /// </summary> /// <param name="builder">The builder instance.</param> /// <param name="options">The retry options.</param> /// <returns>The builder instance with the retry strategy added.</returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="builder"/> or <paramref name="options"/> is <see langword="null"/>.</exception> /// <exception cref="ValidationException">Thrown when <paramref name="options"/> are invalid.</exception> [UnconditionalSuppressMessage( "Trimming", "IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code", Justification = "All options members preserved.")] [DynamicDependency(DynamicallyAccessedMemberTypes.All, typeof(RetryStrategyOptions))] public static ResiliencePipelineBuilder AddRetry(this ResiliencePipelineBuilder builder, RetryStrategyOptions options) { Guard.NotNull(builder); Guard.NotNull(options); return builder.AddStrategy( context => new RetryResilienceStrategy<object>(options, context.TimeProvider, context.Telemetry), options); } /// <summary> /// Adds a retry to the builder. /// </summary> /// <typeparam name="TResult">The type of result the retry handles.</typeparam> /// <param name="builder">The builder instance.</param> /// <param name="options">The retry options.</param> /// <returns>The builder instance with the retry added.</returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="builder"/> or <paramref name="options"/> is <see langword="null"/>.</exception> /// <exception cref="ValidationException">Thrown when <paramref name="options"/> are invalid.</exception> [UnconditionalSuppressMessage( "Trimming", "IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code", Justification = "All options members preserved.")] public static ResiliencePipelineBuilder<TResult> AddRetry<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] TResult>( this ResiliencePipelineBuilder<TResult> builder, RetryStrategyOptions<TResult> options) { Guard.NotNull(builder); Guard.NotNull(options); return builder.AddStrategy( context => new RetryResilienceStrategy<TResult>(options, context.TimeProvider, context.Telemetry), options); } }
using System.ComponentModel.DataAnnotations; using NSubstitute; using Polly.Retry; using Polly.Testing; namespace Polly.Core.Tests.Retry; public class RetryResiliencePipelineBuilderExtensionsTests { #pragma warning disable IDE0028 public static readonly TheoryData<Action<ResiliencePipelineBuilder>> OverloadsData = new() { builder => { builder.AddRetry(new RetryStrategyOptions { BackoffType = DelayBackoffType.Exponential, MaxRetryAttempts = 3, Delay = TimeSpan.FromSeconds(2), ShouldHandle = _ => PredicateResult.True(), }); AssertStrategy(builder, DelayBackoffType.Exponential, 3, TimeSpan.FromSeconds(2)); }, }; public static readonly TheoryData<Action<ResiliencePipelineBuilder<int>>> OverloadsDataGeneric = new() { builder => { builder.AddRetry(new RetryStrategyOptions<int> { BackoffType = DelayBackoffType.Exponential, MaxRetryAttempts = 3, Delay = TimeSpan.FromSeconds(2), ShouldHandle = _ => PredicateResult.True() }); AssertStrategy(builder, DelayBackoffType.Exponential, 3, TimeSpan.FromSeconds(2)); }, }; #pragma warning restore IDE0028 [MemberData(nameof(OverloadsData))] [Theory] public void AddRetry_Overloads_Ok(Action<ResiliencePipelineBuilder> configure) { var builder = new ResiliencePipelineBuilder(); Should.NotThrow(() => configure(builder)); } [MemberData(nameof(OverloadsDataGeneric))] [Theory] public void AddRetry_GenericOverloads_Ok(Action<ResiliencePipelineBuilder<int>> configure) { var builder = new ResiliencePipelineBuilder<int>(); Should.NotThrow(() => configure(builder)); } [Fact] public void AddRetry_DefaultOptions_Ok() { var builder = new ResiliencePipelineBuilder(); var options = new RetryStrategyOptions { ShouldHandle = _ => PredicateResult.True() }; builder.AddRetry(options); AssertStrategy(builder, options.BackoffType, options.MaxRetryAttempts, options.Delay); } private static void AssertStrategy(ResiliencePipelineBuilder builder, DelayBackoffType type, int retries, TimeSpan delay, Action<RetryResilienceStrategy<object>>? assert = null) { var strategy = builder.Build().GetPipelineDescriptor().FirstStrategy.StrategyInstance.ShouldBeOfType<RetryResilienceStrategy<object>>(); strategy.BackoffType.ShouldBe(type); strategy.RetryCount.ShouldBe(retries); strategy.BaseDelay.ShouldBe(delay); assert?.Invoke(strategy); } private static void AssertStrategy<T>( ResiliencePipelineBuilder<T> builder, DelayBackoffType type, int retries, TimeSpan delay, Action<RetryResilienceStrategy<T>>? assert = null) { var strategy = builder.Build().GetPipelineDescriptor().FirstStrategy.StrategyInstance.ShouldBeOfType<RetryResilienceStrategy<T>>(); strategy.BackoffType.ShouldBe(type); strategy.RetryCount.ShouldBe(retries); strategy.BaseDelay.ShouldBe(delay); assert?.Invoke(strategy); } [Fact] public void AddRetry_InvalidOptions_Throws() { Should.Throw<ValidationException>(() => new ResiliencePipelineBuilder().AddRetry(new RetryStrategyOptions { ShouldHandle = null! })); Should.Throw<ValidationException>(() => new ResiliencePipelineBuilder<int>().AddRetry(new RetryStrategyOptions<int> { ShouldHandle = null! })); } [Fact] public void GetAggregatedDelay_ShouldReturnTheSameValue() { var options = new RetryStrategyOptions { BackoffType = DelayBackoffType.Exponential, UseJitter = true }; var delay = GetAggregatedDelay(options); GetAggregatedDelay(options).ShouldBe(delay); } [Fact] public void GetAggregatedDelay_EnsureCorrectValue() { var options = new RetryStrategyOptions { BackoffType = DelayBackoffType.Constant, Delay = TimeSpan.FromSeconds(1), MaxRetryAttempts = 5 }; GetAggregatedDelay(options).ShouldBe(TimeSpan.FromSeconds(5)); } private static TimeSpan GetAggregatedDelay<T>(RetryStrategyOptions<T> options) { var aggregatedDelay = TimeSpan.Zero; var strategy = new ResiliencePipelineBuilder { TimeProvider = new NoWaitingTimeProvider() }.AddRetry(new() { MaxRetryAttempts = options.MaxRetryAttempts, Delay = options.Delay, BackoffType = options.BackoffType, ShouldHandle = _ => PredicateResult.True(), // always retry until all retries are exhausted OnRetry = args => { // the delay hint is calculated for this attempt by the retry strategy aggregatedDelay += args.RetryDelay; return default; }, Randomizer = () => 1.0, }) .Build(); // this executes all retries and we aggregate the delays immediately strategy.Execute(() => { }); return aggregatedDelay; } private class NoWaitingTimeProvider : TimeProvider { public override ITimer CreateTimer(TimerCallback callback, object? state, TimeSpan dueTime, TimeSpan period) { callback(state); return Substitute.For<ITimer>(); } } }
Polly
You are an expert .NET (C#) developer. Task: Write a unit test for 'RetryResiliencePipelineBuilderExtensions' using XUnit and Moq. Context: - Class: RetryResiliencePipelineBuilderExtensions Requirements: Use Mock<T> interface mocking.
industrial
namespace Polly.Retry; internal static class RetryHelper { private const double JitterFactor = 0.5; private const double ExponentialFactor = 2.0; // Upper-bound to prevent overflow beyond TimeSpan.MaxValue. Potential truncation during conversion from double to long // (as described at https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/numeric-conversions) // is avoided by the arbitrary subtraction of 1,000. private static readonly double MaxTimeSpanTicks = (double)TimeSpan.MaxValue.Ticks - 1_000; public static bool IsValidDelay(TimeSpan delay) => delay >= TimeSpan.Zero; public static TimeSpan GetRetryDelay( DelayBackoffType type, bool jitter, int attempt, TimeSpan baseDelay, TimeSpan? maxDelay, ref double state, Func<double> randomizer) { try { var delay = GetRetryDelayCore(type, jitter, attempt, baseDelay, ref state, randomizer); // stryker disable once equality : no means to test this if (maxDelay is TimeSpan maxDelayValue && delay > maxDelayValue) { return maxDelay.Value; } return delay; } catch (OverflowException) { if (maxDelay is { } value) { return value; } return TimeSpan.MaxValue; } } #pragma warning disable IDE0047 // Remove unnecessary parentheses which offer less mental gymnastics internal static TimeSpan ApplyJitter(TimeSpan delay, Func<double> randomizer) { var offset = (delay.TotalMilliseconds * JitterFactor) / 2; var randomDelay = (delay.TotalMilliseconds * JitterFactor * randomizer()) - offset; var newDelay = delay.TotalMilliseconds + randomDelay; return TimeSpan.FromMilliseconds(newDelay); } #pragma warning restore IDE0047 // Remove unnecessary parentheses which offer less mental gymnastics /// <summary> /// Generates sleep durations in an exponentially backing-off, jittered manner, making sure to mitigate any correlations. /// For example: 850ms, 1455ms, 3060ms. /// Per discussion in Polly issue https://github.com/App-vNext/Polly/issues/530, the jitter of this implementation exhibits fewer spikes and a smoother distribution than the AWS jitter formula. /// </summary> /// <param name="attempt">The current attempt.</param> /// <param name="baseDelay">The median delay to target before the first retry, call it <c>f (= f * 2^0).</c> /// Choose this value both to approximate the first delay, and to scale the remainder of the series. /// Subsequent retries will (over a large sample size) have a median approximating retries at time <c>f * 2^1, f * 2^2 ... f * 2^t</c> etc for try t. /// The actual amount of delay-before-retry for try t may be distributed between 0 and <c>f * (2^(t+1) - 2^(t-1)) for t >= 2;</c> /// or between 0 and <c>f * 2^(t+1)</c>, for t is 0 or 1.</param> /// <param name="prev">The previous state value used for calculations.</param> /// <param name="randomizer">The generator to use.</param> /// <remarks> /// This code was adopted from https://github.com/Polly-Contrib/Polly.Contrib.WaitAndRetry/blob/master/src/Polly.Contrib.WaitAndRetry/Backoff.DecorrelatedJitterV2.cs. /// </remarks> internal static TimeSpan DecorrelatedJitterBackoffV2(int attempt, TimeSpan baseDelay, ref double prev, Func<double> randomizer) { // The original author/credit for this jitter formula is @george-polevoy . // Jitter formula used with permission as described at https://github.com/App-vNext/Polly/issues/530#issuecomment-526555979 // Minor adaptations (pFactor = 4.0 and rpScalingFactor = 1 / 1.4d) by @reisenberger, to scale the formula output for easier parameterization to users. // A factor used within the formula to help smooth the first calculated delay. const double PFactor = 4.0; // A factor used to scale the median values of the retry times generated by the formula to be _near_ whole seconds, to aid Polly user comprehension. // This factor allows the median values to fall approximately at 1, 2, 4 etc seconds, instead of 1.4, 2.8, 5.6, 11.2. const double RpScalingFactor = 1 / 1.4d; long targetTicksFirstDelay = baseDelay.Ticks; double t = attempt + randomizer(); double next = Math.Pow(ExponentialFactor, t) * Math.Tanh(Math.Sqrt(PFactor * t)); // At t >=1024, the above will tend to infinity which would otherwise cause the // ticks to go negative. See https://github.com/App-vNext/Polly/issues/2163. if (double.IsInfinity(next)) { prev = next; return TimeSpan.FromTicks((long)MaxTimeSpanTicks); } double formulaIntrinsicValue = next - prev; prev = next; long ticks = (long)Math.Min(formulaIntrinsicValue * RpScalingFactor * targetTicksFirstDelay, MaxTimeSpanTicks); #pragma warning disable S3236 // Remove this argument from the method call; it hides the caller information. Debug.Assert(ticks >= 0, "ticks cannot be negative"); #pragma warning restore S3236 // Remove this argument from the method call; it hides the caller information. return TimeSpan.FromTicks(ticks); } private static TimeSpan GetRetryDelayCore(DelayBackoffType type, bool jitter, int attempt, TimeSpan baseDelay, ref double state, Func<double> randomizer) { if (baseDelay == TimeSpan.Zero) { return baseDelay; } if (jitter) { return type switch { DelayBackoffType.Constant => ApplyJitter(baseDelay, randomizer), DelayBackoffType.Linear => ApplyJitter(TimeSpan.FromMilliseconds((attempt + 1) * baseDelay.TotalMilliseconds), randomizer), DelayBackoffType.Exponential => DecorrelatedJitterBackoffV2(attempt, baseDelay, ref state, randomizer), _ => throw new ArgumentOutOfRangeException(nameof(type), type, "The retry backoff type is not supported.") }; } return type switch { DelayBackoffType.Constant => baseDelay, #if !NETCOREAPP DelayBackoffType.Linear => TimeSpan.FromMilliseconds((attempt + 1) * baseDelay.TotalMilliseconds), DelayBackoffType.Exponential => TimeSpan.FromMilliseconds(Math.Pow(ExponentialFactor, attempt) * baseDelay.TotalMilliseconds), #else DelayBackoffType.Linear => (attempt + 1) * baseDelay, DelayBackoffType.Exponential => Math.Pow(ExponentialFactor, attempt) * baseDelay, #endif _ => throw new ArgumentOutOfRangeException(nameof(type), type, "The retry backoff type is not supported.") }; } }
using FsCheck; using FsCheck.Fluent; using Polly.Contrib.WaitAndRetry; using Polly.Retry; using Polly.Utils; namespace Polly.Core.Tests.Retry; public class RetryHelperTests { private Func<double> _randomizer = new Random(0).NextDouble; public static TheoryData<int> Attempts() #pragma warning disable IDE0028 => new() { 1, 2, 3, 4, 10, 100, 1_000, 1_024, 1_025, }; #pragma warning restore IDE0028 [Fact] public void IsValidDelay_Ok() { RetryHelper.IsValidDelay(TimeSpan.Zero).ShouldBeTrue(); RetryHelper.IsValidDelay(TimeSpan.FromSeconds(1)).ShouldBeTrue(); RetryHelper.IsValidDelay(TimeSpan.MaxValue).ShouldBeTrue(); RetryHelper.IsValidDelay(TimeSpan.MinValue).ShouldBeFalse(); RetryHelper.IsValidDelay(TimeSpan.FromMilliseconds(-1)).ShouldBeFalse(); } [InlineData(true)] [InlineData(false)] [Theory] public void UnsupportedRetryBackoffType_Throws(bool jitter) { DelayBackoffType type = (DelayBackoffType)99; Assert.Throws<ArgumentOutOfRangeException>(() => { double state = 0; return RetryHelper.GetRetryDelay(type, jitter, 0, TimeSpan.FromSeconds(1), null, ref state, _randomizer); }); } [Fact] public void Constant_Ok() { double state = 0; RetryHelper.GetRetryDelay(DelayBackoffType.Constant, false, 0, TimeSpan.Zero, null, ref state, _randomizer).ShouldBe(TimeSpan.Zero); RetryHelper.GetRetryDelay(DelayBackoffType.Constant, false, 1, TimeSpan.Zero, null, ref state, _randomizer).ShouldBe(TimeSpan.Zero); RetryHelper.GetRetryDelay(DelayBackoffType.Constant, false, 2, TimeSpan.Zero, null, ref state, _randomizer).ShouldBe(TimeSpan.Zero); RetryHelper.GetRetryDelay(DelayBackoffType.Constant, false, 0, TimeSpan.FromSeconds(1), null, ref state, _randomizer).ShouldBe(TimeSpan.FromSeconds(1)); RetryHelper.GetRetryDelay(DelayBackoffType.Constant, false, 1, TimeSpan.FromSeconds(1), null, ref state, _randomizer).ShouldBe(TimeSpan.FromSeconds(1)); RetryHelper.GetRetryDelay(DelayBackoffType.Constant, false, 2, TimeSpan.FromSeconds(1), null, ref state, _randomizer).ShouldBe(TimeSpan.FromSeconds(1)); } [Fact] public void Constant_Jitter_Ok() { double state = 0; RetryHelper.GetRetryDelay(DelayBackoffType.Constant, true, 0, TimeSpan.Zero, null, ref state, _randomizer).ShouldBe(TimeSpan.Zero); RetryHelper.GetRetryDelay(DelayBackoffType.Constant, true, 1, TimeSpan.Zero, null, ref state, _randomizer).ShouldBe(TimeSpan.Zero); RetryHelper.GetRetryDelay(DelayBackoffType.Constant, true, 2, TimeSpan.Zero, null, ref state, _randomizer).ShouldBe(TimeSpan.Zero); _randomizer = () => 0.0; RetryHelper .GetRetryDelay(DelayBackoffType.Constant, true, 0, TimeSpan.FromSeconds(1), null, ref state, _randomizer) .ShouldBe(TimeSpan.FromSeconds(0.75)); _randomizer = () => 0.4; RetryHelper .GetRetryDelay(DelayBackoffType.Constant, true, 0, TimeSpan.FromSeconds(1), null, ref state, _randomizer) .ShouldBe(TimeSpan.FromSeconds(0.95)); _randomizer = () => 0.6; RetryHelper.GetRetryDelay(DelayBackoffType.Constant, true, 1, TimeSpan.FromSeconds(1), null, ref state, _randomizer) .ShouldBe(TimeSpan.FromSeconds(1.05)); _randomizer = () => 1.0; RetryHelper .GetRetryDelay(DelayBackoffType.Constant, true, 0, TimeSpan.FromSeconds(1), null, ref state, _randomizer) .ShouldBe(TimeSpan.FromSeconds(1.25)); } [Fact] public void Linear_Ok() { double state = 0; RetryHelper.GetRetryDelay(DelayBackoffType.Linear, false, 0, TimeSpan.Zero, null, ref state, _randomizer).ShouldBe(TimeSpan.Zero); RetryHelper.GetRetryDelay(DelayBackoffType.Linear, false, 1, TimeSpan.Zero, null, ref state, _randomizer).ShouldBe(TimeSpan.Zero); RetryHelper.GetRetryDelay(DelayBackoffType.Linear, false, 2, TimeSpan.Zero, null, ref state, _randomizer).ShouldBe(TimeSpan.Zero); RetryHelper.GetRetryDelay(DelayBackoffType.Linear, false, 0, TimeSpan.FromSeconds(1), null, ref state, _randomizer).ShouldBe(TimeSpan.FromSeconds(1)); RetryHelper.GetRetryDelay(DelayBackoffType.Linear, false, 1, TimeSpan.FromSeconds(1), null, ref state, _randomizer).ShouldBe(TimeSpan.FromSeconds(2)); RetryHelper.GetRetryDelay(DelayBackoffType.Linear, false, 2, TimeSpan.FromSeconds(1), null, ref state, _randomizer).ShouldBe(TimeSpan.FromSeconds(3)); } [Fact] public void Linear_Jitter_Ok() { double state = 0; RetryHelper.GetRetryDelay(DelayBackoffType.Linear, true, 0, TimeSpan.Zero, null, ref state, _randomizer).ShouldBe(TimeSpan.Zero); RetryHelper.GetRetryDelay(DelayBackoffType.Linear, true, 1, TimeSpan.Zero, null, ref state, _randomizer).ShouldBe(TimeSpan.Zero); RetryHelper.GetRetryDelay(DelayBackoffType.Linear, true, 2, TimeSpan.Zero, null, ref state, _randomizer).ShouldBe(TimeSpan.Zero); _randomizer = () => 0.0; RetryHelper .GetRetryDelay(DelayBackoffType.Linear, true, 2, TimeSpan.FromSeconds(1), null, ref state, _randomizer) .ShouldBe(TimeSpan.FromSeconds(2.25)); _randomizer = () => 0.4; RetryHelper .GetRetryDelay(DelayBackoffType.Linear, true, 2, TimeSpan.FromSeconds(1), null, ref state, _randomizer) .ShouldBe(TimeSpan.FromSeconds(2.85)); _randomizer = () => 0.5; RetryHelper .GetRetryDelay(DelayBackoffType.Linear, true, 2, TimeSpan.FromSeconds(1), null, ref state, _randomizer) .ShouldBe(TimeSpan.FromSeconds(3)); _randomizer = () => 0.6; RetryHelper.GetRetryDelay(DelayBackoffType.Linear, true, 2, TimeSpan.FromSeconds(1), null, ref state, _randomizer) .ShouldBe(TimeSpan.FromSeconds(3.15)); _randomizer = () => 1.0; RetryHelper .GetRetryDelay(DelayBackoffType.Linear, true, 2, TimeSpan.FromSeconds(1), null, ref state, _randomizer) .ShouldBe(TimeSpan.FromSeconds(3.75)); } [Fact] public void Exponential_Ok() { double state = 0; RetryHelper.GetRetryDelay(DelayBackoffType.Exponential, false, 0, TimeSpan.Zero, null, ref state, _randomizer).ShouldBe(TimeSpan.Zero); RetryHelper.GetRetryDelay(DelayBackoffType.Exponential, false, 1, TimeSpan.Zero, null, ref state, _randomizer).ShouldBe(TimeSpan.Zero); RetryHelper.GetRetryDelay(DelayBackoffType.Exponential, false, 2, TimeSpan.Zero, null, ref state, _randomizer).ShouldBe(TimeSpan.Zero); RetryHelper.GetRetryDelay(DelayBackoffType.Exponential, false, 0, TimeSpan.FromSeconds(1), null, ref state, _randomizer).ShouldBe(TimeSpan.FromSeconds(1)); RetryHelper.GetRetryDelay(DelayBackoffType.Exponential, false, 1, TimeSpan.FromSeconds(1), null, ref state, _randomizer).ShouldBe(TimeSpan.FromSeconds(2)); RetryHelper.GetRetryDelay(DelayBackoffType.Exponential, false, 2, TimeSpan.FromSeconds(1), null, ref state, _randomizer).ShouldBe(TimeSpan.FromSeconds(4)); } [InlineData(DelayBackoffType.Linear, false)] [InlineData(DelayBackoffType.Exponential, false)] [InlineData(DelayBackoffType.Constant, false)] [InlineData(DelayBackoffType.Linear, true)] [InlineData(DelayBackoffType.Exponential, true)] [InlineData(DelayBackoffType.Constant, true)] [Theory] public void MaxDelay_Ok(DelayBackoffType type, bool jitter) { _randomizer = () => 0.5; var expected = TimeSpan.FromSeconds(1); double state = 0; RetryHelper.GetRetryDelay(type, jitter, 2, TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(1), ref state, _randomizer).ShouldBe(expected); } [Fact] public void MaxDelay_DelayLessThanMaxDelay_Respected() { double state = 0; var expected = TimeSpan.FromSeconds(1); RetryHelper.GetRetryDelay(DelayBackoffType.Constant, false, 2, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2), ref state, _randomizer).ShouldBe(expected); } [Fact] public void GetRetryDelay_Overflow_ReturnsMaxTimeSpan() { double state = 0; RetryHelper.GetRetryDelay(DelayBackoffType.Exponential, false, 1000, TimeSpan.FromDays(1), null, ref state, _randomizer).ShouldBe(TimeSpan.MaxValue); } [Fact] public void GetRetryDelay_OverflowWithMaxDelay_ReturnsMaxDelay() { double state = 0; RetryHelper.GetRetryDelay(DelayBackoffType.Exponential, false, 1000, TimeSpan.FromDays(1), TimeSpan.FromDays(2), ref state, _randomizer).ShouldBe(TimeSpan.FromDays(2)); } [Theory] [MemberData(nameof(Attempts))] public void GetRetryDelay_Exponential_Is_Positive_When_No_Maximum_Delay(int attempt) { var jitter = true; var type = DelayBackoffType.Exponential; var baseDelay = TimeSpan.FromSeconds(2); TimeSpan? maxDelay = null; var random = new Random(0).NextDouble; double state = 0; var first = RetryHelper.GetRetryDelay(type, jitter, attempt, baseDelay, maxDelay, ref state, random); var second = RetryHelper.GetRetryDelay(type, jitter, attempt, baseDelay, maxDelay, ref state, random); first.ShouldBeGreaterThan(TimeSpan.Zero); second.ShouldBeGreaterThan(TimeSpan.Zero); } [Theory] [MemberData(nameof(Attempts))] public void GetRetryDelay_Exponential_Does_Not_Exceed_MaxDelay(int attempt) { var jitter = true; var type = DelayBackoffType.Exponential; var baseDelay = TimeSpan.FromSeconds(2); var maxDelay = TimeSpan.FromSeconds(30); var random = new Random(0).NextDouble; double state = 0; var first = RetryHelper.GetRetryDelay(type, jitter, attempt, baseDelay, maxDelay, ref state, random); var second = RetryHelper.GetRetryDelay(type, jitter, attempt, baseDelay, maxDelay, ref state, random); first.ShouldBeGreaterThan(TimeSpan.Zero); first.ShouldBeLessThanOrEqualTo(maxDelay); second.ShouldBeGreaterThan(TimeSpan.Zero); second.ShouldBeLessThanOrEqualTo(maxDelay); } [Theory] [MemberData(nameof(Attempts))] public void ExponentialWithJitter_Ok(int count) { var delay = TimeSpan.FromSeconds(7.8); var oldDelays = GetExponentialWithJitterBackoff(true, delay, count); var newDelays = GetExponentialWithJitterBackoff(false, delay, count); newDelays.ShouldBeSubsetOf(oldDelays); newDelays.Count.ShouldBe(oldDelays.Count); newDelays.ShouldAllBe(delay => delay > TimeSpan.Zero); } [Fact] public void ExponentialWithJitter_EnsureRandomness() { var delay = TimeSpan.FromSeconds(7.8); var delays1 = GetExponentialWithJitterBackoff(false, delay, 100, RandomUtil.NextDouble); var delays2 = GetExponentialWithJitterBackoff(false, delay, 100, RandomUtil.NextDouble); delays1.SequenceEqual(delays2).ShouldBeFalse(); delays1.ShouldAllBe(delay => delay > TimeSpan.Zero); } #if !NETFRAMEWORK [FsCheck.Xunit.Property(Arbitrary = [typeof(Arbitraries)], MaxTest = 10_000)] public void ApplyJitter_Meets_Specification(TimeSpan value) { var delta = value / 4; var floor = value - delta; var ceiling = value + delta; var actual = RetryHelper.ApplyJitter(value, RandomUtil.NextDouble); actual.ShouldBeGreaterThanOrEqualTo(floor); actual.ShouldBeLessThanOrEqualTo(ceiling); } [FsCheck.Xunit.Property(Arbitrary = [typeof(Arbitraries)], MaxTest = 10_000)] public void DecorrelatedJitterBackoffV2_Meets_Specification(TimeSpan value, int attempt) { var rawCeiling = value.Ticks * Math.Pow(2, attempt) * 4; var clamped = (long)Math.Clamp(rawCeiling, value.Ticks, TimeSpan.MaxValue.Ticks); var floor = TimeSpan.Zero; var ceiling = TimeSpan.FromTicks(clamped - 1); var _ = default(double); var actual = RetryHelper.DecorrelatedJitterBackoffV2(attempt, value, ref _, RandomUtil.NextDouble); actual.ShouldBeGreaterThanOrEqualTo(floor); actual.ShouldBeLessThanOrEqualTo(ceiling); } #endif private static List<TimeSpan> GetExponentialWithJitterBackoff(bool contrib, TimeSpan baseDelay, int retryCount, Func<double>? randomizer = null) { if (contrib) { return [.. Backoff.DecorrelatedJitterBackoffV2(baseDelay, retryCount, 0, false).Take(retryCount)]; } var random = randomizer ?? new Random(0).NextDouble; double state = 0; var result = new List<TimeSpan>(); for (int i = 0; i < retryCount; i++) { result.Add(RetryHelper.GetRetryDelay(DelayBackoffType.Exponential, true, i, baseDelay, null, ref state, random)); } return result; } public static class Arbitraries { public static Arbitrary<int> PositiveInteger() { var minimum = 1; var maximum = 2048; var generator = Gen.Choose(minimum, maximum); return Arb.From(generator); } public static Arbitrary<TimeSpan> PositiveTimeSpan() { var minimum = (int)TimeSpan.FromMilliseconds(1).Ticks; var maximum = (int)TimeSpan.FromMinutes(60).Ticks; var generator = Gen.Choose(minimum, maximum) .Select((p) => TimeSpan.FromTicks(p)); return Arb.From(generator); } } }
Polly
You are an expert C++ developer. Task: Write a unit test for 'RetryHelper' using GoogleTest (gtest) and GoogleMock (gmock). Context: - Class: RetryHelper Requirements: Use EXPECT_CALL for virtual methods.
industrial
namespace Polly.Retry; #pragma warning disable CA1815 // Override equals and operator equals on value types /// <summary> /// Represents the arguments used by <see cref="RetryStrategyOptions{TResult}.OnRetry"/> for handling the retry event. /// </summary> /// <typeparam name="TResult">The type of result.</typeparam> /// <remarks> /// Always use the constructor when creating this struct, otherwise we do not guarantee binary compatibility. /// </remarks> public readonly struct OnRetryArguments<TResult> : IOutcomeArguments<TResult> { /// <summary> /// Initializes a new instance of the <see cref="OnRetryArguments{TResult}"/> struct. /// </summary> /// <param name="context">The context in which the resilience operation or event occurred.</param> /// <param name="outcome">The outcome of the resilience operation or event.</param> /// <param name="attemptNumber">The zero-based attempt number.</param> /// <param name="retryDelay">The delay before the next retry.</param> /// <param name="duration">The duration of this attempt.</param> public OnRetryArguments(ResilienceContext context, Outcome<TResult> outcome, int attemptNumber, TimeSpan retryDelay, TimeSpan duration) { Context = context; Outcome = outcome; AttemptNumber = attemptNumber; RetryDelay = retryDelay; Duration = duration; } /// <summary> /// Gets the outcome that will be retried. /// </summary> public Outcome<TResult> Outcome { get; } /// <summary> /// Gets the context of this event. /// </summary> public ResilienceContext Context { get; } /// <summary> /// Gets the zero-based attempt number. /// </summary> public int AttemptNumber { get; } /// <summary> /// Gets the delay before the next retry. /// </summary> public TimeSpan RetryDelay { get; } /// <summary> /// Gets the duration of this attempt. /// </summary> public TimeSpan Duration { get; } }
using Polly.Retry; namespace Polly.Core.Tests.Retry; public static class OnRetryArgumentsTests { [Fact] public static void Ctor_Ok() { // Arrange var context = ResilienceContextPool.Shared.Get(TestCancellation.Token); // Act var args = new OnRetryArguments<int>(context, Outcome.FromResult(1), 2, TimeSpan.FromSeconds(3), TimeSpan.MaxValue); // Assert args.Context.ShouldBe(context); args.Outcome.Result.ShouldBe(1); args.AttemptNumber.ShouldBe(2); args.RetryDelay.ShouldBe(TimeSpan.FromSeconds(3)); args.Duration.ShouldBe(TimeSpan.MaxValue); } }
Polly
You are an expert C++ developer. Task: Write a unit test for 'TargetModule' using GoogleTest (gtest) and GoogleMock (gmock). Context: - Class: TargetModule Requirements: Use EXPECT_CALL for virtual methods.
industrial
namespace Polly.Retry; internal static class RetryConstants { public const string DefaultName = "Retry"; public const string OnRetryEvent = "OnRetry"; public const DelayBackoffType DefaultBackoffType = DelayBackoffType.Constant; public const int DefaultRetryCount = 3; public const int MaxRetryCount = int.MaxValue; public static readonly TimeSpan DefaultBaseDelay = TimeSpan.FromSeconds(2); }
using Polly.Retry; namespace Polly.Core.Tests.Retry; public class RetryConstantsTests { [Fact] public void EnsureDefaults() { RetryConstants.DefaultBackoffType.ShouldBe(DelayBackoffType.Constant); RetryConstants.DefaultBaseDelay.ShouldBe(TimeSpan.FromSeconds(2)); RetryConstants.DefaultRetryCount.ShouldBe(3); RetryConstants.MaxRetryCount.ShouldBe(int.MaxValue); RetryConstants.OnRetryEvent.ShouldBe("OnRetry"); } }
Polly
You are an expert C++ developer. Task: Write a unit test for 'RetryConstants' using GoogleTest (gtest) and GoogleMock (gmock). Context: - Class: RetryConstants Requirements: Use EXPECT_CALL for virtual methods.
industrial
using Polly.Telemetry; namespace Polly.Retry; internal sealed class RetryResilienceStrategy<T> : ResilienceStrategy<T> { private readonly TimeProvider _timeProvider; private readonly ResilienceStrategyTelemetry _telemetry; private readonly Func<double> _randomizer; public RetryResilienceStrategy( RetryStrategyOptions<T> options, TimeProvider timeProvider, ResilienceStrategyTelemetry telemetry) { ShouldHandle = options.ShouldHandle; BaseDelay = options.Delay; MaxDelay = options.MaxDelay; BackoffType = options.BackoffType; RetryCount = options.MaxRetryAttempts; OnRetry = options.OnRetry; DelayGenerator = options.DelayGenerator; UseJitter = options.UseJitter; _timeProvider = timeProvider; _telemetry = telemetry; _randomizer = options.Randomizer; } public TimeSpan BaseDelay { get; } public TimeSpan? MaxDelay { get; } public DelayBackoffType BackoffType { get; } public int RetryCount { get; } public Func<RetryPredicateArguments<T>, ValueTask<bool>> ShouldHandle { get; } public Func<RetryDelayGeneratorArguments<T>, ValueTask<TimeSpan?>>? DelayGenerator { get; } public bool UseJitter { get; } public Func<OnRetryArguments<T>, ValueTask>? OnRetry { get; } protected internal override async ValueTask<Outcome<T>> ExecuteCore<TState>(Func<ResilienceContext, TState, ValueTask<Outcome<T>>> callback, ResilienceContext context, TState state) { double retryState = 0; int attempt = 0; while (true) { var startTimestamp = _timeProvider.GetTimestamp(); Outcome<T> outcome; try { outcome = await callback(context, state).ConfigureAwait(context.ContinueOnCapturedContext); } #pragma warning disable CA1031 catch (Exception ex) { outcome = new(ex); } #pragma warning restore CA1031 var shouldRetryArgs = new RetryPredicateArguments<T>(context, outcome, attempt); var handle = await ShouldHandle(shouldRetryArgs).ConfigureAwait(context.ContinueOnCapturedContext); var executionTime = _timeProvider.GetElapsedTime(startTimestamp); var isLastAttempt = IsLastAttempt(attempt, out bool incrementAttempts); if (isLastAttempt) { TelemetryUtil.ReportFinalExecutionAttempt(_telemetry, context, outcome, attempt, executionTime, handle); } else { TelemetryUtil.ReportExecutionAttempt(_telemetry, context, outcome, attempt, executionTime, handle); } if (isLastAttempt || !handle) { return outcome; } var delay = RetryHelper.GetRetryDelay(BackoffType, UseJitter, attempt, BaseDelay, MaxDelay, ref retryState, _randomizer); if (DelayGenerator is not null) { var delayArgs = new RetryDelayGeneratorArguments<T>(context, outcome, attempt); if (await DelayGenerator(delayArgs).ConfigureAwait(false) is TimeSpan newDelay && RetryHelper.IsValidDelay(newDelay)) { delay = newDelay; } } #pragma warning disable S3236 // Remove this argument from the method call; it hides the caller information. Debug.Assert(delay >= TimeSpan.Zero, "The delay cannot be negative."); #pragma warning restore S3236 // Remove this argument from the method call; it hides the caller information. var onRetryArgs = new OnRetryArguments<T>(context, outcome, attempt, delay, executionTime); _telemetry.Report<OnRetryArguments<T>, T>(new(ResilienceEventSeverity.Warning, RetryConstants.OnRetryEvent), onRetryArgs); if (OnRetry is not null) { await OnRetry(onRetryArgs).ConfigureAwait(context.ContinueOnCapturedContext); } if (outcome.TryGetResult(out var resultValue)) { await DisposeHelper.TryDisposeSafeAsync(resultValue, context.IsSynchronous).ConfigureAwait(context.ContinueOnCapturedContext); } try { context.CancellationToken.ThrowIfCancellationRequested(); // stryker disable once all : no means to test this if (delay > TimeSpan.Zero) { await _timeProvider.DelayAsync(delay, context).ConfigureAwait(context.ContinueOnCapturedContext); } } catch (OperationCanceledException e) { return Outcome.FromException<T>(e); } if (incrementAttempts) { attempt++; } } } internal bool IsLastAttempt(int attempt, out bool incrementAttempts) { if (attempt == int.MaxValue) { incrementAttempts = false; return false; } incrementAttempts = true; return attempt >= RetryCount; } }
using Microsoft.Extensions.Time.Testing; using Polly.Retry; using Polly.Telemetry; using Polly.Testing; namespace Polly.Core.Tests.Retry; public class RetryResilienceStrategyTests { private readonly RetryStrategyOptions _options = new(); private readonly FakeTimeProvider _timeProvider = new(); private readonly List<TelemetryEventArguments<object, object>> _args = []; private ResilienceStrategyTelemetry _telemetry; public RetryResilienceStrategyTests() { _telemetry = TestUtilities.CreateResilienceTelemetry(_args.Add); _options.ShouldHandle = _ => new ValueTask<bool>(false); _options.Randomizer = () => 1; } [Fact] public void ExecuteAsync_EnsureResultNotDisposed() { SetupNoDelay(); var sut = CreateSut(); var result = sut.Execute(() => new DisposableResult()); result.IsDisposed.ShouldBeFalse(); } [Fact] public async Task ExecuteAsync_CanceledBeforeExecution_EnsureNotExecuted() { var sut = CreateSut(); var executed = false; var result = await sut.ExecuteOutcomeAsync( (_, _) => { executed = true; return Outcome.FromResultAsValueTask(new object()); }, ResilienceContextPool.Shared.Get(new CancellationToken(canceled: true)), default(object)); result.Exception.ShouldBeAssignableTo<OperationCanceledException>(); executed.ShouldBeFalse(); } [Fact] public async Task ExecuteAsync_CanceledDuringExecution_EnsureResultReturned() { var sut = CreateSut(); using var cancellation = new CancellationTokenSource(); var executions = 0; var result = await sut.ExecuteOutcomeAsync( (_, _) => { executions++; cancellation.Cancel(); return Outcome.FromResultAsValueTask(new object()); }, ResilienceContextPool.Shared.Get(cancellation.Token), default(object)); result.Exception.ShouldBeNull(); executions.ShouldBe(1); } [Fact] public async Task ExecuteAsync_ExceptionInExecution_EnsureResultReturned() { var sut = CreateSut(); var result = await sut.ExecuteOutcomeAsync<object, object?>((_, _) => throw new ArgumentException(), ResilienceContextPool.Shared.Get(TestCancellation.Token), default); result.Exception.ShouldBeOfType<ArgumentException>(); } [Fact] public async Task ExecuteAsync_CanceledDuringExecution_EnsureNotExecutedAgain() { var reported = false; _options.ShouldHandle = _ => PredicateResult.True(); _options.OnRetry = args => { reported = true; return default; }; var sut = CreateSut(); using var cancellation = new CancellationTokenSource(); var executions = 0; var result = await sut.ExecuteOutcomeAsync( (_, _) => { executions++; cancellation.Cancel(); return Outcome.FromResultAsValueTask(new object()); }, ResilienceContextPool.Shared.Get(cancellation.Token), default(object)); result.Exception.ShouldBeAssignableTo<OperationCanceledException>(); executions.ShouldBe(1); reported.ShouldBeTrue(); } [Fact] public async Task ExecuteAsync_CanceledAfterExecution_EnsureNotExecutedAgain() { using var cancellation = new CancellationTokenSource(); _options.ShouldHandle = _ => PredicateResult.True(); _options.OnRetry = args => { cancellation.Cancel(); return default; }; var sut = CreateSut(); var executions = 0; var result = await sut.ExecuteOutcomeAsync( (_, _) => { executions++; return Outcome.FromResultAsValueTask(new object()); }, ResilienceContextPool.Shared.Get(cancellation.Token), default(object)); result.Exception.ShouldBeAssignableTo<OperationCanceledException>(); executions.ShouldBe(1); } [Fact] public async Task ExecuteAsync_CanceledDuringDelay_EnsureNotExecutedAgain() { _options.ShouldHandle = _ => PredicateResult.True(); using var cancellation = _timeProvider.CreateCancellationTokenSource(_options.Delay); var sut = CreateSut(); var executions = 0; var resultTask = sut.ExecuteOutcomeAsync( (_, _) => { executions++; return Outcome.FromResultAsValueTask(new object()); }, ResilienceContextPool.Shared.Get(cancellation.Token), default(object)); _timeProvider.Advance(_options.Delay); var result = await resultTask; result.Exception.ShouldBeAssignableTo<OperationCanceledException>(); executions.ShouldBe(1); } [Fact] public void ExecuteAsync_MultipleRetries_EnsureDiscardedResultsDisposed() { // arrange _options.MaxRetryAttempts = 5; SetupNoDelay(); _options.ShouldHandle = _ => PredicateResult.True(); var results = new List<DisposableResult>(); var sut = CreateSut(); // act var result = sut.Execute(_ => { var r = new DisposableResult(); results.Add(r); return r; }, TestCancellation.Token); // assert result.IsDisposed.ShouldBeFalse(); results.Count.ShouldBe(_options.MaxRetryAttempts + 1); results[results.Count - 1].IsDisposed.ShouldBeFalse(); results.Remove(results[results.Count - 1]); results.ShouldAllBe(r => r.IsDisposed); } [Fact] public void Retry_RetryCount_Respected() { int calls = 0; _options.OnRetry = _ => { calls++; return default; }; _options.ShouldHandle = args => args.Outcome.ResultPredicateAsync(0); _options.MaxRetryAttempts = 12; SetupNoDelay(); var sut = CreateSut(); sut.Execute(() => 0); calls.ShouldBe(12); } [Fact] public void RetryException_RetryCount_Respected() { int calls = 0; _options.OnRetry = args => { args.Outcome.Exception.ShouldBeOfType<InvalidOperationException>(); calls++; return default; }; _options.ShouldHandle = args => args.Outcome.ExceptionPredicateAsync<InvalidOperationException>(); _options.MaxRetryAttempts = 3; SetupNoDelay(); var sut = CreateSut(); Assert.Throws<InvalidOperationException>(() => sut.Execute<int>(() => throw new InvalidOperationException())); calls.ShouldBe(3); } [Fact] public void RetryDelayGenerator_Respected() { var retries = 0; var generatedValues = 0; var delay = TimeSpan.FromMilliseconds(120); _options.ShouldHandle = _ => PredicateResult.True(); _options.MaxRetryAttempts = 3; _options.BackoffType = DelayBackoffType.Constant; _options.OnRetry = args => { retries++; args.RetryDelay.ShouldBe(delay); return default; }; _options.DelayGenerator = _ => { generatedValues++; return new ValueTask<TimeSpan?>(delay); }; CreateSut(TimeProvider.System).Execute(_ => "dummy", TestCancellation.Token); retries.ShouldBe(3); generatedValues.ShouldBe(3); } [Fact] public async Task RetryDelayGenerator_ZeroDelay_NoTimeProviderCalls() { int retries = 0; int generatedValues = 0; var delay = TimeSpan.Zero; var provider = new FakeTimeProvider(); _options.ShouldHandle = _ => PredicateResult.True(); _options.MaxRetryAttempts = 3; _options.BackoffType = DelayBackoffType.Constant; _options.OnRetry = _ => { retries++; return default; }; _options.DelayGenerator = _ => { generatedValues++; return new ValueTask<TimeSpan?>(delay); }; var sut = CreateSut(provider); await sut.ExecuteAsync(_ => new ValueTask<string>("dummy"), TestCancellation.Token); retries.ShouldBe(3); generatedValues.ShouldBe(3); } [Fact] public void IsLastAttempt_Ok() { var sut = (RetryResilienceStrategy<object>)CreateSut().GetPipelineDescriptor().FirstStrategy.StrategyInstance; sut.IsLastAttempt(int.MaxValue, out var increment).ShouldBeFalse(); increment.ShouldBeFalse(); } [Fact] public async Task OnRetry_EnsureCorrectArguments() { var attempts = new List<int>(); var delays = new List<TimeSpan>(); _options.OnRetry = args => { attempts.Add(args.AttemptNumber); delays.Add(args.RetryDelay); args.Outcome.Exception.ShouldBeNull(); args.Outcome.Result.ShouldBe(0); return default; }; _options.ShouldHandle = args => PredicateResult.True(); _options.MaxRetryAttempts = 3; _options.BackoffType = DelayBackoffType.Linear; var sut = CreateSut(); var executing = ExecuteAndAdvance(sut); await executing; attempts.Count.ShouldBe(3); attempts[0].ShouldBe(0); attempts[1].ShouldBe(1); attempts[2].ShouldBe(2); delays[0].ShouldBe(TimeSpan.FromSeconds(2)); delays[1].ShouldBe(TimeSpan.FromSeconds(4)); delays[2].ShouldBe(TimeSpan.FromSeconds(6)); } [Fact] public async Task MaxDelay_EnsureRespected() { var delays = new List<TimeSpan>(); _options.OnRetry = args => { delays.Add(args.RetryDelay); return default; }; _options.ShouldHandle = args => PredicateResult.True(); _options.MaxRetryAttempts = 3; _options.BackoffType = DelayBackoffType.Linear; _options.MaxDelay = TimeSpan.FromMilliseconds(123); var sut = CreateSut(); await ExecuteAndAdvance(sut); delays[0].ShouldBe(TimeSpan.FromMilliseconds(123)); delays[1].ShouldBe(TimeSpan.FromMilliseconds(123)); delays[2].ShouldBe(TimeSpan.FromMilliseconds(123)); } [Fact] public async Task OnRetry_EnsureExecutionTime() { _options.OnRetry = args => { args.Duration.ShouldBe(TimeSpan.FromMinutes(1)); return default; }; _options.ShouldHandle = _ => PredicateResult.True(); _options.MaxRetryAttempts = 1; _options.BackoffType = DelayBackoffType.Constant; _options.Delay = TimeSpan.Zero; var sut = CreateSut(); await sut.ExecuteAsync(_ => { _timeProvider.Advance(TimeSpan.FromMinutes(1)); return new ValueTask<int>(0); }, TestCancellation.Token).AsTask(); } [Fact] public void Execute_NotHandledOriginalAttempt_EnsureAttemptReported() { var called = false; _telemetry = TestUtilities.CreateResilienceTelemetry(args => { var attempt = args.Arguments.ShouldBeOfType<ExecutionAttemptArguments>(); args.Event.Severity.ShouldBe(ResilienceEventSeverity.Information); attempt.Handled.ShouldBeFalse(); attempt.AttemptNumber.ShouldBe(0); attempt.Duration.ShouldBe(TimeSpan.FromSeconds(1)); called = true; }); var sut = CreateSut(); sut.Execute(() => { _timeProvider.Advance(TimeSpan.FromSeconds(1)); return 0; }); called.ShouldBeTrue(); } [Fact] public void Execute_NotHandledFinalAttempt_EnsureAttemptReported() { _options.MaxRetryAttempts = 1; _options.Delay = TimeSpan.Zero; // original attempt is handled, retried attempt is not handled _options.ShouldHandle = args => new ValueTask<bool>(args.AttemptNumber == 0); var called = false; _telemetry = TestUtilities.CreateResilienceTelemetry(args => { // ignore OnRetry event if (args.Arguments is OnRetryArguments<object>) { return; } var attempt = args.Arguments.ShouldBeOfType<ExecutionAttemptArguments>(); if (attempt.AttemptNumber == 0) { args.Event.Severity.ShouldBe(ResilienceEventSeverity.Warning); } else { args.Event.Severity.ShouldBe(ResilienceEventSeverity.Information); } called = true; }); var sut = CreateSut(); sut.Execute(() => { _timeProvider.Advance(TimeSpan.FromSeconds(1)); return 0; }); called.ShouldBeTrue(); } [Fact] public void Execute_HandledFinalAttempt_EnsureAttemptReported() { _options.MaxRetryAttempts = 1; _options.Delay = TimeSpan.Zero; _options.ShouldHandle = _ => new ValueTask<bool>(true); var called = false; _telemetry = TestUtilities.CreateResilienceTelemetry(args => { // ignore OnRetry event if (args.Arguments is OnRetryArguments<object>) { return; } var attempt = args.Arguments.ShouldBeOfType<ExecutionAttemptArguments>(); if (attempt.AttemptNumber == 0) { args.Event.Severity.ShouldBe(ResilienceEventSeverity.Warning); } else { args.Event.Severity.ShouldBe(ResilienceEventSeverity.Error); } called = true; }); var sut = CreateSut(); sut.Execute(() => { _timeProvider.Advance(TimeSpan.FromSeconds(1)); return 0; }); called.ShouldBeTrue(); } [Fact] public async Task OnRetry_EnsureTelemetry() { var attempts = new List<int>(); var delays = new List<TimeSpan>(); _options.ShouldHandle = args => args.Outcome.ResultPredicateAsync(0); _options.MaxRetryAttempts = 3; _options.BackoffType = DelayBackoffType.Linear; var sut = CreateSut(); await ExecuteAndAdvance(sut); _args.Select(a => a.Arguments).OfType<OnRetryArguments<object>>().Count().ShouldBe(3); } [Fact] public void RetryDelayGenerator_EnsureCorrectArguments() { var attempts = new List<int>(); var hints = new List<TimeSpan>(); _options.DelayGenerator = args => { attempts.Add(args.AttemptNumber); args.Outcome.Exception.ShouldBeNull(); args.Outcome.Result.ShouldBe(0); return new ValueTask<TimeSpan?>(TimeSpan.Zero); }; _options.ShouldHandle = args => args.Outcome.ResultPredicateAsync(0); _options.MaxRetryAttempts = 3; _options.BackoffType = DelayBackoffType.Linear; var sut = CreateSut(); sut.Execute(() => 0); attempts.Count.ShouldBe(3); attempts[0].ShouldBe(0); attempts[1].ShouldBe(1); attempts[2].ShouldBe(2); } [Fact] public void RetryDelayGenerator_ReturnsNull_EnsureDefaultRetry() { var delays = new List<TimeSpan>(); _options.DelayGenerator = args => new ValueTask<TimeSpan?>((TimeSpan?)null); _options.OnRetry = args => { delays.Add(args.RetryDelay); return default; }; _options.ShouldHandle = args => args.Outcome.ResultPredicateAsync(0); _options.MaxRetryAttempts = 2; _options.BackoffType = DelayBackoffType.Constant; _options.Delay = TimeSpan.FromMilliseconds(2); var sut = CreateSut(TimeProvider.System); sut.Execute(() => 0); delays.Count.ShouldBe(2); delays[0].ShouldBe(TimeSpan.FromMilliseconds(2)); delays[1].ShouldBe(TimeSpan.FromMilliseconds(2)); } private void SetupNoDelay() => _options.DelayGenerator = _ => new ValueTask<TimeSpan?>(TimeSpan.Zero); private async ValueTask<int> ExecuteAndAdvance(ResiliencePipeline<object> sut) { var executing = sut.ExecuteAsync(_ => new ValueTask<int>(0)).AsTask(); while (!executing.IsCompleted) { _timeProvider.Advance(TimeSpan.FromMinutes(1)); } return await executing; } private ResiliencePipeline<object> CreateSut(TimeProvider? timeProvider = null) => new RetryResilienceStrategy<object>(_options, timeProvider ?? _timeProvider, _telemetry).AsPipeline(); }
Polly
You are an expert C++ developer. Task: Write a unit test for 'RetryResilienceStrategy' using GoogleTest (gtest) and GoogleMock (gmock). Context: - Class: RetryResilienceStrategy Requirements: Use EXPECT_CALL for virtual methods.
industrial
using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Diagnostics.CodeAnalysis; namespace Polly.Retry; /// <summary> /// Represents the options used to configure a retry strategy. /// </summary> /// <typeparam name="TResult">The type of result the retry strategy handles.</typeparam> [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Addressed with DynamicDependency on ValidationHelper.Validate method")] public class RetryStrategyOptions<TResult> : ResilienceStrategyOptions { /// <summary> /// Initializes a new instance of the <see cref="RetryStrategyOptions{TResult}"/> class. /// </summary> public RetryStrategyOptions() => Name = RetryConstants.DefaultName; /// <summary> /// Gets or sets the maximum number of retries to use, in addition to the original call. /// </summary> /// <value> /// The default value is 3 retries. /// </value> /// <remarks> /// To retry indefinitely use <see cref="int.MaxValue"/>. Note that the reported attempt number is capped at <see cref="int.MaxValue"/>. /// </remarks> [Range(1, RetryConstants.MaxRetryCount)] public int MaxRetryAttempts { get; set; } = RetryConstants.DefaultRetryCount; /// <summary> /// Gets or sets the type of the back-off. /// </summary> /// <remarks> /// This property is ignored when <see cref="DelayGenerator"/> is set. /// </remarks> /// <value> /// The default value is <see cref="DelayBackoffType.Constant"/>. /// </value> public DelayBackoffType BackoffType { get; set; } = RetryConstants.DefaultBackoffType; /// <summary> /// Gets or sets a value indicating whether jitter should be used when calculating the backoff delay between retries. /// </summary> /// <remarks> /// See <see href="https://github.com/Polly-Contrib/Polly.Contrib.WaitAndRetry#new-jitter-recommendation"/> for more details /// on how jitter can improve the resilience when the retries are correlated. /// </remarks> /// <value> /// The default value is <see langword="false"/>. /// </value> public bool UseJitter { get; set; } /// <summary> /// Gets or sets the base delay between retries. /// </summary> /// <remarks> /// This value is used with the combination of <see cref="BackoffType"/> to generate the final delay for each individual retry attempt: /// <list type="bullet"> /// <item> /// <see cref="DelayBackoffType.Exponential"/>: Represents the median delay to target before the first retry. /// </item> /// <item> /// <see cref="DelayBackoffType.Linear"/>: Represents the initial delay, the following delays increasing linearly with this value. /// </item> /// <item> /// <see cref="DelayBackoffType.Constant"/> Represents the constant delay between retries. /// </item> /// </list> /// This property is ignored when <see cref="DelayGenerator"/> is set and returns a valid <see cref="TimeSpan"/> value. /// </remarks> /// <value> /// The default value is 2 seconds. /// </value> [Range(typeof(TimeSpan), "00:00:00", "1.00:00:00")] public TimeSpan Delay { get; set; } = RetryConstants.DefaultBaseDelay; /// <summary> /// Gets or sets the maximum delay between retries. /// </summary> /// <remarks> /// This property is used to cap the maximum delay between retries. It is useful when you want to limit the maximum delay after a certain /// number of retries when it could reach a unreasonably high values, especially if <see cref="DelayBackoffType.Exponential"/> backoff is used. /// If not specified, the delay is not capped. This property is ignored for delays generated by <see cref="DelayGenerator"/>. /// </remarks> /// <value> /// The default value is <see langword="null"/>. /// </value> [Range(typeof(TimeSpan), "00:00:00", "1.00:00:00")] public TimeSpan? MaxDelay { get; set; } /// <summary> /// Gets or sets a predicate that determines whether the retry should be executed for a given outcome. /// </summary> /// <value> /// The default is a delegate that retries on any exception except <see cref="OperationCanceledException"/>. This property is required. /// </value> [Required] public Func<RetryPredicateArguments<TResult>, ValueTask<bool>> ShouldHandle { get; set; } = DefaultPredicates<RetryPredicateArguments<TResult>, TResult>.HandleOutcome; /// <summary> /// Gets or sets a generator that calculates the delay between retries. /// </summary> /// <remarks> /// The generator can override the delay generated by the retry strategy. If the generator returns <see langword="null"/>, the delay generated /// by the retry strategy for that attempt will be used. /// </remarks> /// <value> /// The default value is <see langword="null"/>. /// </value> public Func<RetryDelayGeneratorArguments<TResult>, ValueTask<TimeSpan?>>? DelayGenerator { get; set; } /// <summary> /// Gets or sets an event delegate that is raised when the retry happens. /// </summary> /// <remarks> /// After this event, the result produced the by user-callback is discarded and disposed to prevent resource over-consumption. If /// you need to preserve the result for further processing, create the copy of the result or extract and store all necessary information /// from the result within the event. /// </remarks> /// <value> /// The default value is <see langword="null"/>. /// </value> public Func<OnRetryArguments<TResult>, ValueTask>? OnRetry { get; set; } /// <summary> /// Gets or sets the randomizer that is used by the retry strategy to generate random numbers. /// </summary> /// <value> /// The default value is thread-safe randomizer that returns values between 0.0 and 1.0. /// </value> [EditorBrowsable(EditorBrowsableState.Never)] [Required] public Func<double> Randomizer { get; set; } = RandomUtil.NextDouble; }
using System.ComponentModel.DataAnnotations; using Polly.Retry; using Polly.Utils; namespace Polly.Core.Tests.Retry; public class RetryStrategyOptionsTests { [Fact] public void Ctor_Ok() { var options = new RetryStrategyOptions<int>(); options.ShouldHandle.ShouldNotBeNull(); options.DelayGenerator.ShouldBeNull(); options.OnRetry.ShouldBeNull(); options.MaxRetryAttempts.ShouldBe(3); options.BackoffType.ShouldBe(DelayBackoffType.Constant); options.Delay.ShouldBe(TimeSpan.FromSeconds(2)); options.Name.ShouldBe("Retry"); options.Randomizer.ShouldNotBeNull(); } [Fact] public async Task ShouldHandle_EnsureDefaults() { var options = new RetryStrategyOptions<int>(); var context = ResilienceContextPool.Shared.Get(TestCancellation.Token); (await options.ShouldHandle(new RetryPredicateArguments<int>(context, Outcome.FromResult(0), 0))).ShouldBe(false); (await options.ShouldHandle(new RetryPredicateArguments<int>(context, Outcome.FromException<int>(new OperationCanceledException()), 0))).ShouldBe(false); (await options.ShouldHandle(new RetryPredicateArguments<int>(context, Outcome.FromException<int>(new InvalidOperationException()), 0))).ShouldBe(true); } [Fact] public void InvalidOptions() { var options = new RetryStrategyOptions<int> { ShouldHandle = null!, DelayGenerator = null!, OnRetry = null!, MaxRetryAttempts = -3, Delay = TimeSpan.MinValue, MaxDelay = TimeSpan.FromSeconds(-10) }; var exception = Should.Throw<ValidationException>(() => ValidationHelper.ValidateObject(new(options, "Invalid Options"))); exception.Message.Trim().ShouldBe(""" Invalid Options Validation Errors: The field MaxRetryAttempts must be between 1 and 2147483647. The field Delay must be between 00:00:00 and 1.00:00:00. The field MaxDelay must be between 00:00:00 and 1.00:00:00. The ShouldHandle field is required. """, StringCompareShould.IgnoreLineEndings); } }
Polly
You are an expert .NET (C#) developer. Task: Write a unit test for 'RetryStrategyOptions' using XUnit and Moq. Context: - Class: RetryStrategyOptions Requirements: Use Mock<T> interface mocking.
industrial
using Polly.Utilities.Wrappers; namespace Polly; /// <summary> /// Extensions for conversion of resilience strategies to policies. /// </summary> public static class ResiliencePipelineConversionExtensions { /// <summary> /// Converts a <see cref="ResiliencePipeline"/> to an <see cref="IAsyncPolicy"/>. /// </summary> /// <param name="strategy">The strategy instance.</param> /// <returns>An instance of <see cref="IAsyncPolicy"/>.</returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="strategy"/> is <see langword="null"/>.</exception> public static IAsyncPolicy AsAsyncPolicy(this ResiliencePipeline strategy) => new ResiliencePipelineAsyncPolicy(strategy ?? throw new ArgumentNullException(nameof(strategy))); /// <summary> /// Converts a <see cref="ResiliencePipeline{TResult}"/> to an <see cref="IAsyncPolicy{TResult}"/>. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="strategy">The strategy instance.</param> /// <returns>An instance of <see cref="IAsyncPolicy{TResult}"/>.</returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="strategy"/> is <see langword="null"/>.</exception> public static IAsyncPolicy<TResult> AsAsyncPolicy<TResult>(this ResiliencePipeline<TResult> strategy) => new ResiliencePipelineAsyncPolicy<TResult>(strategy ?? throw new ArgumentNullException(nameof(strategy))); /// <summary> /// Converts a <see cref="ResiliencePipeline"/> to an <see cref="ISyncPolicy"/>. /// </summary> /// <param name="strategy">The strategy instance.</param> /// <returns>An instance of <see cref="ISyncPolicy"/>.</returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="strategy"/> is <see langword="null"/>.</exception> public static ISyncPolicy AsSyncPolicy(this ResiliencePipeline strategy) => new ResiliencePipelineSyncPolicy(strategy ?? throw new ArgumentNullException(nameof(strategy))); /// <summary> /// Converts a <see cref="ResiliencePipeline{TResult}"/> to an <see cref="ISyncPolicy{TResult}"/>. /// </summary> /// <param name="strategy">The strategy instance.</param> /// <typeparam name="TResult">The type of the result.</typeparam> /// <returns>An instance of <see cref="ISyncPolicy{TResult}"/>.</returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="strategy"/> is <see langword="null"/>.</exception> public static ISyncPolicy<TResult> AsSyncPolicy<TResult>(this ResiliencePipeline<TResult> strategy) => new ResiliencePipelineSyncPolicy<TResult>(strategy ?? throw new ArgumentNullException(nameof(strategy))); }
using Polly; using Polly.TestUtils; namespace Polly.Specs; public class ResiliencePipelineConversionExtensionsTests { private static readonly ResiliencePropertyKey<string> Incoming = new("incoming-key"); private static readonly ResiliencePropertyKey<string> Executing = new("executing-key"); private static readonly ResiliencePropertyKey<string> Outgoing = new("outgoing-key"); private readonly TestResilienceStrategy _strategy; private readonly ResiliencePipeline<string> _genericStrategy; private bool _isSynchronous; private bool _isVoid; private bool _continueOnCapturedContext = true; public ResiliencePipelineConversionExtensionsTests() { _strategy = new TestResilienceStrategy { Before = (context, _) => { context.GetType().GetProperty("IsVoid", BindingFlags.Instance | BindingFlags.NonPublic)!.GetValue(context).ShouldBe(_isVoid); context.GetType().GetProperty("IsSynchronous", BindingFlags.Instance | BindingFlags.NonPublic)!.GetValue(context).ShouldBe(_isSynchronous); context.Properties.Set(Outgoing, "outgoing-value"); context.Properties.GetValue(Incoming, string.Empty).ShouldBe("incoming-value"); context.OperationKey.ShouldBe("op-key"); context.ContinueOnCapturedContext.ShouldBe(_continueOnCapturedContext); } }; _genericStrategy = new ResiliencePipelineBuilder<string>() .AddStrategy(_strategy) .Build(); } [Fact] public void AsAsyncPolicy_Throws_If_Null() { // Arrange ResiliencePipeline strategy = null!; ResiliencePipeline<string> strategyGeneric = null!; // Act and Assert Should.Throw<ArgumentNullException>(strategy.AsAsyncPolicy).ParamName.ShouldBe("strategy"); Should.Throw<ArgumentNullException>(strategyGeneric.AsAsyncPolicy).ParamName.ShouldBe("strategy"); } [Fact] public void AsSyncPolicy_Throws_If_Null() { // Arrange ResiliencePipeline strategy = null!; ResiliencePipeline<string> strategyGeneric = null!; // Act and Assert Should.Throw<ArgumentNullException>(strategy.AsSyncPolicy).ParamName.ShouldBe("strategy"); Should.Throw<ArgumentNullException>(strategyGeneric.AsSyncPolicy).ParamName.ShouldBe("strategy"); } [Fact] public void AsSyncPolicy_Ok() { _isVoid = true; _isSynchronous = true; var context = new Context("op-key") { [Incoming.Key] = "incoming-value" }; _strategy.AsPipeline().AsSyncPolicy().Execute(_ => { context[Executing.Key] = "executing-value"; }, context); AssertContext(context); } [Fact] public void AsSyncPolicy_Generic_Ok() { _isVoid = false; _isSynchronous = true; var context = new Context("op-key") { [Incoming.Key] = "incoming-value" }; var result = _genericStrategy.AsSyncPolicy().Execute(_ => { context[Executing.Key] = "executing-value"; return "dummy"; }, context); AssertContext(context); result.ShouldBe("dummy"); } [Fact] public void AsSyncPolicy_Result_Ok() { _isVoid = false; _isSynchronous = true; var context = new Context("op-key") { [Incoming.Key] = "incoming-value" }; var result = _strategy.AsPipeline().AsSyncPolicy().Execute(_ => { context[Executing.Key] = "executing-value"; return "dummy"; }, context); AssertContext(context); result.ShouldBe("dummy"); } [Fact] public async Task AsAsyncPolicy_Ok() { _isVoid = true; _isSynchronous = false; _continueOnCapturedContext = false; var context = new Context("op-key") { [Incoming.Key] = "incoming-value" }; await _strategy.AsPipeline().AsAsyncPolicy().ExecuteAsync(_ => { context[Executing.Key] = "executing-value"; return Task.CompletedTask; }, context); AssertContext(context); } [Fact] public async Task AsAsyncPolicy_Generic_Ok() { _isVoid = false; _isSynchronous = false; _continueOnCapturedContext = false; var context = new Context("op-key") { [Incoming.Key] = "incoming-value" }; var result = await _genericStrategy.AsAsyncPolicy().ExecuteAsync(_ => { context[Executing.Key] = "executing-value"; return Task.FromResult("dummy"); }, context); AssertContext(context); result.ShouldBe("dummy"); } [Fact] public async Task AsAsyncPolicy_Result_Ok() { _isVoid = false; _isSynchronous = false; _continueOnCapturedContext = false; var context = new Context("op-key") { [Incoming.Key] = "incoming-value" }; var result = await _strategy.AsPipeline().AsAsyncPolicy().ExecuteAsync(_ => { context[Executing.Key] = "executing-value"; return Task.FromResult("dummy"); }, context); AssertContext(context); result.ShouldBe("dummy"); } [Fact] public void RetryStrategy_AsSyncPolicy_Ok() { var policy = new ResiliencePipelineBuilder<string>() .AddRetry(new RetryStrategyOptions<string> { ShouldHandle = _ => PredicateResult.True(), BackoffType = DelayBackoffType.Constant, MaxRetryAttempts = 5, Delay = TimeSpan.FromMilliseconds(1) }) .Build() .AsSyncPolicy(); var context = new Context("op-key") { ["retry"] = 0 }; policy.Execute( c => { c["retry"] = (int)c["retry"] + 1; return "dummy"; }, context) .ShouldBe("dummy"); context["retry"].ShouldBe(6); } private static void AssertContext(Context context) { context[Outgoing.Key].ShouldBe("outgoing-value"); context[Executing.Key].ShouldBe("executing-value"); } }
Polly
You are an expert C++ developer. Task: Write a unit test for 'ResiliencePipelineConversionExtensions' using GoogleTest (gtest) and GoogleMock (gmock). Context: - Class: ResiliencePipelineConversionExtensions Requirements: Use EXPECT_CALL for virtual methods.
industrial
#nullable enable namespace Polly.CircuitBreaker; internal sealed class RollingHealthMetrics : IHealthMetrics { internal const short WindowCount = 10; private readonly long _samplingDuration; private readonly long _windowDuration; private readonly Queue<HealthCount> _windows; private HealthCount? _currentWindow; public RollingHealthMetrics(TimeSpan samplingDuration) { _samplingDuration = samplingDuration.Ticks; _windowDuration = _samplingDuration / WindowCount; // stryker disable once all : only affects capacity and not logic _windows = new(WindowCount + 1); } public void IncrementSuccess_NeedsLock() { var currentWindow = ActualiseCurrentMetric_NeedsLock(); currentWindow.Successes++; } public void IncrementFailure_NeedsLock() { var currentWindow = ActualiseCurrentMetric_NeedsLock(); currentWindow.Failures++; } public void Reset_NeedsLock() { _currentWindow = null; _windows.Clear(); } public HealthCount GetHealthCount_NeedsLock() { ActualiseCurrentMetric_NeedsLock(); int successes = 0; int failures = 0; foreach (var window in _windows) { successes += window.Successes; failures += window.Failures; } return new() { Successes = successes, Failures = failures, StartedAt = _windows.Peek().StartedAt }; } private HealthCount ActualiseCurrentMetric_NeedsLock() { var now = SystemClock.UtcNow().Ticks; var currentWindow = _currentWindow; // stryker disable once all : no means to test this if (currentWindow == null || now - currentWindow.StartedAt >= _windowDuration) { _currentWindow = currentWindow = new() { StartedAt = now }; _windows.Enqueue(currentWindow); } // stryker disable once all : no means to test this while (_windows.Count > 0 && now - _windows.Peek().StartedAt >= _samplingDuration) { _windows.Dequeue(); } return currentWindow; } }
namespace Polly.Specs.CircuitBreaker; [Collection(Constants.SystemClockDependentTestCollection)] public class RollingHealthMetricsTests : IDisposable { private readonly TimeSpan _samplingDuration = TimeSpan.FromSeconds(10); private DateTime _utcNow = new(2025, 02, 16, 12, 34, 56, DateTimeKind.Utc); public RollingHealthMetricsTests() => SystemClock.UtcNow = () => _utcNow; [Fact] public void Ctor_EnsureDefaults() { var metrics = Create(); var health = metrics.GetHealthCount_NeedsLock(); health.Successes.ShouldBe(0); health.Failures.ShouldBe(0); } [Fact] public void Increment_Ok() { var metrics = Create(); metrics.IncrementFailure_NeedsLock(); metrics.IncrementSuccess_NeedsLock(); metrics.IncrementSuccess_NeedsLock(); metrics.IncrementSuccess_NeedsLock(); metrics.IncrementSuccess_NeedsLock(); var health = metrics.GetHealthCount_NeedsLock(); health.Failures.ShouldBe(1); health.Successes.ShouldBe(4); } [Fact] public void GetHealthCount_NeedsLock_EnsureWindowRespected() { var metrics = Create(); var health = new List<HealthCount>(); var startedAt = _utcNow; for (int i = 0; i < 5; i++) { if (i < 2) { metrics.IncrementFailure_NeedsLock(); } else { metrics.IncrementSuccess_NeedsLock(); } metrics.IncrementSuccess_NeedsLock(); _utcNow += TimeSpan.FromSeconds(2); health.Add(metrics.GetHealthCount_NeedsLock()); } _utcNow += TimeSpan.FromSeconds(2); health.Add(metrics.GetHealthCount_NeedsLock()); health[0].ShouldBeEquivalentTo(new HealthCount { Successes = 1, Failures = 1, StartedAt = startedAt.AddSeconds(0).Ticks }); health[1].ShouldBeEquivalentTo(new HealthCount { Successes = 2, Failures = 2, StartedAt = startedAt.AddSeconds(0).Ticks }); health[2].ShouldBeEquivalentTo(new HealthCount { Successes = 4, Failures = 2, StartedAt = startedAt.AddSeconds(0).Ticks }); health[3].ShouldBeEquivalentTo(new HealthCount { Successes = 6, Failures = 2, StartedAt = startedAt.AddSeconds(0).Ticks }); health[4].ShouldBeEquivalentTo(new HealthCount { Successes = 7, Failures = 1, StartedAt = startedAt.AddSeconds(2).Ticks }); health[5].ShouldBeEquivalentTo(new HealthCount { Successes = 6, Failures = 0, StartedAt = startedAt.AddSeconds(4).Ticks }); } [Fact] public void GetHealthCount_NeedsLock_EnsureWindowCapacityRespected() { var delay = TimeSpan.FromSeconds(1); var metrics = Create(); for (int i = 0; i < 10; i++) { metrics.IncrementSuccess_NeedsLock(); _utcNow += delay; } metrics.GetHealthCount_NeedsLock().Successes.ShouldBe(9); _utcNow += delay; metrics.GetHealthCount_NeedsLock().Successes.ShouldBe(8); } [Fact] public void Reset_Ok() { var metrics = Create(); metrics.IncrementSuccess_NeedsLock(); metrics.Reset_NeedsLock(); _utcNow += _samplingDuration; _utcNow += _samplingDuration; metrics.GetHealthCount_NeedsLock().Successes.ShouldBe(0); _utcNow += _samplingDuration; _utcNow += _samplingDuration; metrics.GetHealthCount_NeedsLock().Successes.ShouldBe(0); } [InlineData(true)] [InlineData(false)] [Theory] public void GetHealthCount_NeedsLock_SamplingDurationRespected(bool variance) { var metrics = Create(); metrics.IncrementSuccess_NeedsLock(); metrics.IncrementSuccess_NeedsLock(); _utcNow += _samplingDuration + (variance ? TimeSpan.FromMilliseconds(1) : TimeSpan.Zero); metrics.GetHealthCount_NeedsLock().ShouldBeEquivalentTo(new HealthCount { StartedAt = _utcNow.Ticks }); } private RollingHealthMetrics Create() => new(_samplingDuration); public void Dispose() => SystemClock.Reset(); }
Polly
You are an expert C++ developer. Task: Write a unit test for 'RollingHealthMetrics' using GoogleTest (gtest) and GoogleMock (gmock). Context: - Class: RollingHealthMetrics Requirements: Use EXPECT_CALL for virtual methods.
industrial
#nullable enable #if NETSTANDARD2_0 using System.Runtime.Serialization; #endif namespace Polly.RateLimit; #pragma warning disable RS0016 // Add public types and members to the declared API /// <summary> /// Exception thrown when a delegate executed through a <see cref="IRateLimitPolicy"/> is rate-limited. /// </summary> #if NETSTANDARD2_0 [Serializable] #endif public class RateLimitRejectedException : ExecutionRejectedException { /// <summary> /// Gets the timespan after which the operation may be retried. /// </summary> public TimeSpan RetryAfter { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="RateLimitRejectedException"/> class. /// </summary> public RateLimitRejectedException() : base("The operation could not be executed because it was rejected by the rate limit.") { } /// <summary> /// Initializes a new instance of the <see cref="RateLimitRejectedException"/> class. /// </summary> /// <param name="message">The message that describes the error.</param> public RateLimitRejectedException(string message) : base(message) { } /// <summary> /// Initializes a new instance of the <see cref="RateLimitRejectedException"/> class. /// </summary> /// <param name="message">The message that describes the error.</param> /// <param name="inner">The inner exception.</param> public RateLimitRejectedException(string message, Exception inner) : base(message, inner) { } /// <summary> /// Initializes a new instance of the <see cref="RateLimitRejectedException"/> class. /// </summary> /// <param name="retryAfter">The timespan after which the operation may be retried.</param> public RateLimitRejectedException(TimeSpan retryAfter) : this(retryAfter, DefaultMessage(retryAfter)) { } /// <summary> /// Initializes a new instance of the <see cref="RateLimitRejectedException"/> class. /// </summary> /// <param name="retryAfter">The timespan after which the operation may be retried.</param> /// <param name="innerException">The inner exception.</param> public RateLimitRejectedException(TimeSpan retryAfter, Exception innerException) : base(DefaultMessage(retryAfter), innerException) => SetRetryAfter(retryAfter); /// <summary> /// Initializes a new instance of the <see cref="RateLimitRejectedException"/> class. /// </summary> /// <param name="retryAfter">The timespan after which the operation may be retried.</param> /// <param name="message">The message.</param> public RateLimitRejectedException(TimeSpan retryAfter, string message) : base(message) => SetRetryAfter(retryAfter); /// <summary> /// Initializes a new instance of the <see cref="RateLimitRejectedException"/> class. /// </summary> /// <param name="message">The message.</param> /// <param name="retryAfter">The timespan after which the operation may be retried.</param> /// <param name="innerException">The inner exception.</param> public RateLimitRejectedException(TimeSpan retryAfter, string message, Exception innerException) : base(message, innerException) => SetRetryAfter(retryAfter); private static string DefaultMessage(TimeSpan retryAfter) => $"The operation has been rate-limited and should be retried after {retryAfter}"; private void SetRetryAfter(TimeSpan retryAfter) { if (retryAfter < TimeSpan.Zero) { throw new ArgumentOutOfRangeException(nameof(retryAfter), retryAfter, $"The {nameof(retryAfter)} parameter must be a TimeSpan greater than or equal to TimeSpan.Zero."); } RetryAfter = retryAfter; } #if NETSTANDARD2_0 /// <summary> /// Initializes a new instance of the <see cref="RateLimitRejectedException"/> class. /// </summary> /// <param name="info">The information.</param> /// <param name="context">The context.</param> protected RateLimitRejectedException(SerializationInfo info, StreamingContext context) : base(info, context) { } #endif }
namespace Polly.Specs.RateLimit; public class RateLimitRejectedExceptionTests { [Fact] public void Ctor_Ok() { const string Dummy = "dummy"; var exception = new InvalidOperationException(); var retryAfter = TimeSpan.FromSeconds(4); new RateLimitRejectedException().Message.ShouldBe("The operation could not be executed because it was rejected by the rate limit."); new RateLimitRejectedException(Dummy).Message.ShouldBe(Dummy); var rate = new RateLimitRejectedException(Dummy, exception); rate.Message.ShouldBe(Dummy); rate.InnerException.ShouldBe(exception); new RateLimitRejectedException(retryAfter).RetryAfter.ShouldBe(retryAfter); new RateLimitRejectedException(retryAfter).Message.ShouldBe($"The operation has been rate-limited and should be retried after {retryAfter}"); rate = new RateLimitRejectedException(retryAfter, exception); rate.RetryAfter.ShouldBe(retryAfter); rate.InnerException.ShouldBe(exception); rate = new RateLimitRejectedException(retryAfter, Dummy); rate.RetryAfter.ShouldBe(retryAfter); rate.Message.ShouldBe(Dummy); rate = new RateLimitRejectedException(TimeSpan.Zero, Dummy); rate.RetryAfter.ShouldBe(TimeSpan.Zero); rate.Message.ShouldBe(Dummy); rate = new RateLimitRejectedException(retryAfter, Dummy, exception); rate.RetryAfter.ShouldBe(retryAfter); rate.Message.ShouldBe(Dummy); rate.InnerException.ShouldBe(exception); var ex = Should.Throw<ArgumentOutOfRangeException>(() => new RateLimitRejectedException(TimeSpan.FromSeconds(-1))); ex.ParamName.ShouldBe("retryAfter"); ex.ActualValue.ShouldBe(TimeSpan.FromSeconds(-1)); ex = Should.Throw<ArgumentOutOfRangeException>(() => new RateLimitRejectedException(TimeSpan.FromSeconds(-1), rate)); ex.ParamName.ShouldBe("retryAfter"); ex.ActualValue.ShouldBe(TimeSpan.FromSeconds(-1)); ex = Should.Throw<ArgumentOutOfRangeException>(() => new RateLimitRejectedException(TimeSpan.FromSeconds(-1), "Error", rate)); ex.ParamName.ShouldBe("retryAfter"); ex.ActualValue.ShouldBe(TimeSpan.FromSeconds(-1)); } }
Polly
You are an expert .NET (C#) developer. Task: Write a unit test for 'RateLimitRejectedException' using XUnit and Moq. Context: - Class: RateLimitRejectedException Requirements: Use Mock<T> interface mocking.
industrial
using Polly.Utils; using Polly.Utils.Pipeline; namespace Polly.Testing; /// <summary> /// The test-related extensions for <see cref="ResiliencePipeline"/> and <see cref="ResiliencePipeline{TResult}"/>. /// </summary> public static class ResiliencePipelineExtensions { /// <summary> /// Gets the pipeline descriptor. /// </summary> /// <typeparam name="TResult">The type of result.</typeparam> /// <param name="pipeline">The pipeline instance.</param> /// <returns>A pipeline descriptor.</returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="pipeline"/> is <see langword="null"/>.</exception> public static ResiliencePipelineDescriptor GetPipelineDescriptor<TResult>(this ResiliencePipeline<TResult> pipeline) { Guard.NotNull(pipeline); return GetPipelineDescriptorCore<TResult>(pipeline.Component); } /// <summary> /// Gets the pipeline descriptor. /// </summary> /// <param name="pipeline">The pipeline instance.</param> /// <returns>A pipeline descriptor.</returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="pipeline"/> is <see langword="null"/>.</exception> public static ResiliencePipelineDescriptor GetPipelineDescriptor(this ResiliencePipeline pipeline) { Guard.NotNull(pipeline); return GetPipelineDescriptorCore<object>(pipeline.Component); } private static ResiliencePipelineDescriptor GetPipelineDescriptorCore<T>(PipelineComponent component) { var components = new List<PipelineComponent>(); component.ExpandComponents(components); var descriptors = components .OfType<BridgeComponentBase>() .Select(s => new ResilienceStrategyDescriptor(s.Options, GetStrategyInstance<T>(s))) .ToList() .AsReadOnly(); return new ResiliencePipelineDescriptor( descriptors, isReloadable: components.Exists(static s => s is ReloadableComponent)); } private static object GetStrategyInstance<T>(PipelineComponent component) { if (component is BridgeComponent<T> reactiveBridge) { return reactiveBridge.Strategy; } return ((BridgeComponent)component).Strategy; } private static void ExpandComponents(this PipelineComponent component, List<PipelineComponent> components) { if (component is CompositeComponent pipeline) { foreach (var inner in pipeline.Components) { inner.ExpandComponents(components); } } else if (component is ReloadableComponent reloadable) { components.Add(reloadable); ExpandComponents(reloadable.Component, components); } else if (component is ExecutionTrackingComponent tracking) { ExpandComponents(tracking.Component, components); } else if (component is ComponentWithDisposeCallbacks callbacks) { ExpandComponents(callbacks.Component, components); } else if (component is ExternalComponent nonDisposable) { ExpandComponents(nonDisposable.Component, components); } else { components.Add(component); } } }
using Microsoft.Extensions.Logging.Abstractions; using Polly.CircuitBreaker; using Polly.Fallback; using Polly.Hedging; using Polly.RateLimiting; using Polly.Registry; using Polly.Retry; using Polly.Timeout; namespace Polly.Testing.Tests; public class ResiliencePipelineExtensionsTests { [Fact] public void GetPipelineDescriptor_Throws_If_Pipeline_Null() { // Arrange ResiliencePipeline pipeline = null!; ResiliencePipeline<string> pipelineGeneric = null!; // Act and Assert Should.Throw<ArgumentNullException>(() => pipeline.GetPipelineDescriptor()).ParamName.ShouldBe("pipeline"); Should.Throw<ArgumentNullException>(() => pipelineGeneric.GetPipelineDescriptor()).ParamName.ShouldBe("pipeline"); } [Fact] public void GetPipelineDescriptor_Generic_Ok() { // Arrange var strategy = new ResiliencePipelineBuilder<string>() .AddFallback(new() { FallbackAction = _ => Outcome.FromResultAsValueTask("dummy"), }) .AddRetry(new()) .AddCircuitBreaker(new()) .AddTimeout(TimeSpan.FromSeconds(1)) .AddHedging(new()) .AddConcurrencyLimiter(10) .AddStrategy(_ => new CustomStrategy(), new TestOptions()) .ConfigureTelemetry(NullLoggerFactory.Instance) .Build(); // Act var descriptor = strategy.GetPipelineDescriptor(); // Assert descriptor.ShouldNotBeNull(); descriptor.IsReloadable.ShouldBeFalse(); descriptor.Strategies.Count.ShouldBe(7); descriptor.FirstStrategy.Options.ShouldBeOfType<FallbackStrategyOptions<string>>(); descriptor.Strategies[0].Options.ShouldBeOfType<FallbackStrategyOptions<string>>(); descriptor.Strategies[0].StrategyInstance.GetType().FullName.ShouldNotBeNull().ShouldContain("Fallback"); descriptor.Strategies[1].Options.ShouldBeOfType<RetryStrategyOptions<string>>(); descriptor.Strategies[1].StrategyInstance.GetType().FullName.ShouldNotBeNull().ShouldContain("Retry"); descriptor.Strategies[2].Options.ShouldBeOfType<CircuitBreakerStrategyOptions<string>>(); descriptor.Strategies[2].StrategyInstance.GetType().FullName.ShouldNotBeNull().ShouldContain("CircuitBreaker"); descriptor.Strategies[3].Options.ShouldBeOfType<TimeoutStrategyOptions>(); descriptor.Strategies[3].StrategyInstance.GetType().FullName.ShouldNotBeNull().ShouldContain("Timeout"); descriptor.Strategies[3].Options .ShouldBeOfType<TimeoutStrategyOptions>().Timeout .ShouldBe(TimeSpan.FromSeconds(1)); descriptor.Strategies[4].Options.ShouldBeOfType<HedgingStrategyOptions<string>>(); descriptor.Strategies[4].StrategyInstance.GetType().FullName.ShouldNotBeNull().ShouldContain("Hedging"); descriptor.Strategies[5].Options.ShouldBeOfType<RateLimiterStrategyOptions>(); descriptor.Strategies[5].StrategyInstance.GetType().FullName.ShouldNotBeNull().ShouldContain("RateLimiter"); descriptor.Strategies[6].StrategyInstance.ShouldBeOfType<CustomStrategy>(); } [Fact] public void GetPipelineDescriptor_NonGeneric_Ok() { // Arrange var strategy = new ResiliencePipelineBuilder() .AddRetry(new()) .AddCircuitBreaker(new()) .AddTimeout(TimeSpan.FromSeconds(1)) .AddConcurrencyLimiter(10) .AddStrategy(_ => new CustomStrategy(), new TestOptions()) .ConfigureTelemetry(NullLoggerFactory.Instance) .Build(); // Act var descriptor = strategy.GetPipelineDescriptor(); // Assert descriptor.ShouldNotBeNull(); descriptor.IsReloadable.ShouldBeFalse(); descriptor.Strategies.Count.ShouldBe(5); descriptor.Strategies[0].Options.ShouldBeOfType<RetryStrategyOptions>(); descriptor.Strategies[0].StrategyInstance.GetType().FullName.ShouldNotBeNull().ShouldContain("Retry"); descriptor.Strategies[1].Options.ShouldBeOfType<CircuitBreakerStrategyOptions>(); descriptor.Strategies[1].StrategyInstance.GetType().FullName.ShouldNotBeNull().ShouldContain("CircuitBreaker"); descriptor.Strategies[2].Options.ShouldBeOfType<TimeoutStrategyOptions>(); descriptor.Strategies[2].StrategyInstance.GetType().FullName.ShouldNotBeNull().ShouldContain("Timeout"); descriptor.Strategies[2].Options .ShouldBeOfType<TimeoutStrategyOptions>().Timeout .ShouldBe(TimeSpan.FromSeconds(1)); descriptor.Strategies[3].Options.ShouldBeOfType<RateLimiterStrategyOptions>(); descriptor.Strategies[3].StrategyInstance.GetType().FullName.ShouldNotBeNull().ShouldContain("RateLimiter"); descriptor.Strategies[4].StrategyInstance.ShouldBeOfType<CustomStrategy>(); } [Fact] public void GetPipelineDescriptor_SingleStrategy_Ok() { // Arrange var strategy = new ResiliencePipelineBuilder<string>() .AddTimeout(TimeSpan.FromSeconds(1)) .Build(); // Act var descriptor = strategy.GetPipelineDescriptor(); // Assert descriptor.ShouldNotBeNull(); descriptor.IsReloadable.ShouldBeFalse(); descriptor.Strategies.Count.ShouldBe(1); descriptor.Strategies[0].Options.ShouldBeOfType<TimeoutStrategyOptions>(); } [Fact] public async Task GetPipelineDescriptor_Reloadable_Ok() { // Arrange using var source = new CancellationTokenSource(); await using var registry = new ResiliencePipelineRegistry<string>(); var pipeline = registry.GetOrAddPipeline("first", (builder, context) => { context.OnPipelineDisposed(() => { }); context.AddReloadToken(source.Token); builder .AddConcurrencyLimiter(10) .AddStrategy(_ => new CustomStrategy(), new TestOptions()); }); // Act var descriptor = pipeline.GetPipelineDescriptor(); // Assert descriptor.ShouldNotBeNull(); descriptor.IsReloadable.ShouldBeTrue(); descriptor.Strategies.Count.ShouldBe(2); descriptor.Strategies[0].Options.ShouldBeOfType<RateLimiterStrategyOptions>(); descriptor.Strategies[1].StrategyInstance.ShouldBeOfType<CustomStrategy>(); } [Fact] public void GetPipelineDescriptor_InnerPipeline_Ok() { // Arrange var pipeline = new ResiliencePipelineBuilder() .AddPipeline(new ResiliencePipelineBuilder().AddConcurrencyLimiter(1).Build()) .Build(); // Act var descriptor = pipeline.GetPipelineDescriptor(); // Assert descriptor.ShouldNotBeNull(); descriptor.Strategies.Count.ShouldBe(1); descriptor.Strategies[0].Options.ShouldBeOfType<RateLimiterStrategyOptions>(); } private sealed class CustomStrategy : ResilienceStrategy { protected override ValueTask<Outcome<TResult>> ExecuteCore<TResult, TState>(Func<ResilienceContext, TState, ValueTask<Outcome<TResult>>> callback, ResilienceContext context, TState state) => throw new NotSupportedException(); } private class TestOptions : ResilienceStrategyOptions; }
Polly
You are an expert C++ developer. Task: Write a unit test for 'ResiliencePipelineExtensions' using GoogleTest (gtest) and GoogleMock (gmock). Context: - Class: ResiliencePipelineExtensions Requirements: Use EXPECT_CALL for virtual methods.
industrial
#if !NETCOREAPP using System.Runtime.Serialization; #endif using System.Threading.RateLimiting; namespace Polly.RateLimiting; /// <summary> /// Exception thrown when a rate limiter rejects an execution. /// </summary> #if !NETCOREAPP [Serializable] #endif public sealed class RateLimiterRejectedException : ExecutionRejectedException { /// <summary> /// Initializes a new instance of the <see cref="RateLimiterRejectedException"/> class. /// </summary> public RateLimiterRejectedException() : base("The operation could not be executed because it was rejected by the rate limiter.") { } /// <summary> /// Initializes a new instance of the <see cref="RateLimiterRejectedException"/> class. /// </summary> /// <param name="retryAfter">The retry after value.</param> public RateLimiterRejectedException(TimeSpan retryAfter) : base($"The operation could not be executed because it was rejected by the rate limiter. It can be retried after '{retryAfter}'.") => RetryAfter = retryAfter; /// <summary> /// Initializes a new instance of the <see cref="RateLimiterRejectedException"/> class. /// </summary> /// <param name="message">The message that describes the error.</param> public RateLimiterRejectedException(string message) : base(message) { } /// <summary> /// Initializes a new instance of the <see cref="RateLimiterRejectedException"/> class. /// </summary> /// <param name="message">The message that describes the error.</param> /// <param name="retryAfter">The retry after value.</param> public RateLimiterRejectedException(string message, TimeSpan retryAfter) : base(message) => RetryAfter = retryAfter; /// <summary> /// Initializes a new instance of the <see cref="RateLimiterRejectedException"/> class. /// </summary> /// <param name="message">The message that describes the error.</param> /// <param name="inner">The inner exception.</param> public RateLimiterRejectedException(string message, Exception inner) : base(message, inner) { } /// <summary> /// Initializes a new instance of the <see cref="RateLimiterRejectedException"/> class. /// </summary> /// <param name="message">The message that describes the error.</param> /// <param name="retryAfter">The retry after value.</param> /// <param name="inner">The inner exception.</param> public RateLimiterRejectedException(string message, TimeSpan retryAfter, Exception inner) : base(message, inner) => RetryAfter = retryAfter; /// <summary> /// Gets the amount of time to wait before retrying again. /// </summary> /// <remarks> /// This value was retrieved from the <see cref="RateLimitLease"/> by reading the <see cref="MetadataName.RetryAfter"/>. /// Defaults to <c>null</c>. /// </remarks> public TimeSpan? RetryAfter { get; } #pragma warning disable RS0016 // Add public types and members to the declared API #if !NETCOREAPP /// <summary> /// Initializes a new instance of the <see cref="RateLimiterRejectedException"/> class. /// </summary> /// <param name="info">The information.</param> /// <param name="context">The context.</param> private RateLimiterRejectedException(SerializationInfo info, StreamingContext context) : base(info, context) { var retryAfter = info.GetDouble(nameof(RetryAfter)); if (retryAfter >= 0.0) { RetryAfter = TimeSpan.FromSeconds(retryAfter); } } /// <inheritdoc/> public override void GetObjectData(SerializationInfo info, StreamingContext context) { Guard.NotNull(info); info.AddValue(nameof(RetryAfter), RetryAfter.HasValue ? RetryAfter.Value.TotalSeconds : -1.0); base.GetObjectData(info, context); } #endif #pragma warning restore RS0016 // Add public types and members to the declared API }
using Polly.RateLimiting; namespace Polly.Core.Tests.Timeout; public class RateLimiterRejectedExceptionTests { private readonly string _message = "dummy"; private readonly TimeSpan _retryAfter = TimeSpan.FromSeconds(4); [Fact] public void Ctor_Ok() { var exception = new RateLimiterRejectedException(); exception.InnerException.ShouldBeNull(); exception.Message.ShouldBe("The operation could not be executed because it was rejected by the rate limiter."); exception.RetryAfter.ShouldBeNull(); exception.TelemetrySource.ShouldBeNull(); } [Fact] public void Ctor_RetryAfter_Ok() { var exception = new RateLimiterRejectedException(_retryAfter); exception.InnerException.ShouldBeNull(); exception.Message.ShouldBe($"The operation could not be executed because it was rejected by the rate limiter. It can be retried after '00:00:04'."); exception.RetryAfter.ShouldBe(_retryAfter); exception.TelemetrySource.ShouldBeNull(); } [Fact] public void Ctor_Message_Ok() { var exception = new RateLimiterRejectedException(_message); exception.InnerException.ShouldBeNull(); exception.Message.ShouldBe(_message); exception.RetryAfter.ShouldBeNull(); exception.TelemetrySource.ShouldBeNull(); } [Fact] public void Ctor_Message_RetryAfter_Ok() { var exception = new RateLimiterRejectedException(_message, _retryAfter); exception.InnerException.ShouldBeNull(); exception.Message.ShouldBe(_message); exception.RetryAfter.ShouldBe(_retryAfter); exception.TelemetrySource.ShouldBeNull(); } [Fact] public void Ctor_Message_InnerException_Ok() { var exception = new RateLimiterRejectedException(_message, new InvalidOperationException()); exception.InnerException.ShouldBeOfType<InvalidOperationException>(); exception.Message.ShouldBe(_message); exception.RetryAfter.ShouldBeNull(); exception.TelemetrySource.ShouldBeNull(); } [Fact] public void Ctor_Message_RetryAfter_InnerException_Ok() { var exception = new RateLimiterRejectedException(_message, _retryAfter, new InvalidOperationException()); exception.InnerException.ShouldBeOfType<InvalidOperationException>(); exception.Message.ShouldBe(_message); exception.RetryAfter.ShouldBe(_retryAfter); exception.TelemetrySource.ShouldBeNull(); } #if NETFRAMEWORK [Fact] public void BinaryDeserialization_Ok() { var timeout = TimeSpan.FromSeconds(4); var result = SerializeAndDeserializeException(new RateLimiterRejectedException(timeout)); result.RetryAfter.ShouldBe(timeout); result = SerializeAndDeserializeException(new RateLimiterRejectedException()); result.RetryAfter.ShouldBeNull(); } public static T SerializeAndDeserializeException<T>(T exception) where T : Exception { using var stream = new MemoryStream(); var formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); formatter.Serialize(stream, exception); stream.Position = 0; return (T)formatter.Deserialize(stream); } #endif }
Polly
You are an expert .NET (C#) developer. Task: Write a unit test for 'RateLimiterRejectedException' using XUnit and Moq. Context: - Class: RateLimiterRejectedException Requirements: Use Mock<T> interface mocking.
industrial
namespace Polly.RateLimiting; internal static class RateLimiterConstants { public const string DefaultName = "RateLimiter"; public const int DefaultPermitLimit = 1000; public const int DefaultQueueLimit = 0; public const string OnRateLimiterRejectedEvent = "OnRateLimiterRejected"; }
namespace Polly.RateLimiting.Tests; public class RateLimiterConstantsTests { [Fact] public void Ctor_EnsureDefaults() => RateLimiterConstants.OnRateLimiterRejectedEvent.ShouldBe("OnRateLimiterRejected"); }
Polly
You are an expert C++ developer. Task: Write a unit test for 'RateLimiterConstants' using GoogleTest (gtest) and GoogleMock (gmock). Context: - Class: RateLimiterConstants Requirements: Use EXPECT_CALL for virtual methods.
industrial
using System.Threading.RateLimiting; namespace Polly.RateLimiting; #pragma warning disable CA1815 // Override equals and operator equals on value types /// <summary> /// The arguments used by the <see cref="RateLimiterStrategyOptions.OnRejected"/>. /// </summary> /// <remarks> /// Always use the constructor when creating this struct, otherwise we do not guarantee binary compatibility. /// </remarks> public readonly struct OnRateLimiterRejectedArguments { /// <summary> /// Initializes a new instance of the <see cref="OnRateLimiterRejectedArguments"/> struct. /// </summary> /// <param name="context">The context associated with the execution of a user-provided callback.</param> /// <param name="lease">The lease that has no permits and was rejected by the rate limiter.</param> public OnRateLimiterRejectedArguments(ResilienceContext context, RateLimitLease lease) { Context = context; Lease = lease; } /// <summary> /// Gets the context associated with the execution of a user-provided callback. /// </summary> public ResilienceContext Context { get; } /// <summary> /// Gets the lease that has no permits and was rejected by the rate limiter. /// </summary> public RateLimitLease Lease { get; } }
using System.Threading.RateLimiting; using NSubstitute; namespace Polly.RateLimiting.Tests; public static class OnRateLimiterRejectedArgumentsTests { [Fact] public static void Ctor_Ok() { var args = new OnRateLimiterRejectedArguments( ResilienceContextPool.Shared.Get(TestCancellation.Token), Substitute.For<RateLimitLease>()); args.Context.ShouldNotBeNull(); args.Lease.ShouldNotBeNull(); } }
Polly
You are an expert .NET (C#) developer. Task: Write a unit test for 'TargetModule' using XUnit and Moq. Context: - Class: TargetModule Requirements: Use Mock<T> interface mocking.
industrial
using System.Threading.RateLimiting; using Polly.Telemetry; namespace Polly.RateLimiting; internal sealed class RateLimiterResilienceStrategy : ResilienceStrategy, IDisposable, IAsyncDisposable { private readonly ResilienceStrategyTelemetry _telemetry; public RateLimiterResilienceStrategy( Func<RateLimiterArguments, ValueTask<RateLimitLease>> limiter, Func<OnRateLimiterRejectedArguments, ValueTask>? onRejected, ResilienceStrategyTelemetry telemetry, RateLimiter? wrapper) { Limiter = limiter; OnLeaseRejected = onRejected; _telemetry = telemetry; Wrapper = wrapper; } public Func<RateLimiterArguments, ValueTask<RateLimitLease>> Limiter { get; } public Func<OnRateLimiterRejectedArguments, ValueTask>? OnLeaseRejected { get; } public RateLimiter? Wrapper { get; } public void Dispose() => Wrapper?.Dispose(); public ValueTask DisposeAsync() { if (Wrapper is not null) { return Wrapper.DisposeAsync(); } return default; } protected override async ValueTask<Outcome<TResult>> ExecuteCore<TResult, TState>( Func<ResilienceContext, TState, ValueTask<Outcome<TResult>>> callback, ResilienceContext context, TState state) { using var lease = await Limiter(new RateLimiterArguments(context)).ConfigureAwait(context.ContinueOnCapturedContext); if (lease.IsAcquired) { return await callback(context, state).ConfigureAwait(context.ContinueOnCapturedContext); } TimeSpan? retryAfter = null; if (lease.TryGetMetadata(MetadataName.RetryAfter, out TimeSpan retryAfterValue)) { retryAfter = retryAfterValue; } var args = new OnRateLimiterRejectedArguments(context, lease); _telemetry.Report(new(ResilienceEventSeverity.Error, RateLimiterConstants.OnRateLimiterRejectedEvent), context, args); if (OnLeaseRejected != null) { await OnLeaseRejected(new OnRateLimiterRejectedArguments(context, lease)).ConfigureAwait(context.ContinueOnCapturedContext); } var exception = retryAfter is not null ? new RateLimiterRejectedException(retryAfterValue) : new RateLimiterRejectedException(); _telemetry.SetTelemetrySource(exception); return Outcome.FromException<TResult>(exception.TrySetStackTrace()); } }
using System.Threading.RateLimiting; using NSubstitute; using Polly.TestUtils; namespace Polly.RateLimiting.Tests; public class RateLimiterResilienceStrategyTests { private readonly RateLimiter _limiter = Substitute.For<RateLimiter>(); private readonly RateLimitLease _lease = Substitute.For<RateLimitLease>(); private readonly FakeTelemetryListener _listener = new(); private Func<OnRateLimiterRejectedArguments, ValueTask>? _event; [Fact] public void Ctor_Ok() => Create().ShouldNotBeNull(); [Fact] public async Task Execute_HappyPath() { using var cts = new CancellationTokenSource(); SetupLimiter(cts.Token); _lease.IsAcquired.Returns(true); Create().ShouldNotBeNull(); var strategy = Create(); strategy.Execute(_ => { }, cts.Token); await _limiter.ReceivedWithAnyArgs().AcquireAsync(default, TestCancellation.Token); _lease.Received().Dispose(); } [InlineData(false, true)] [InlineData(false, false)] [InlineData(true, true)] [InlineData(true, false)] [Theory] public async Task Execute_LeaseRejected(bool hasEvents, bool hasRetryAfter) { object? metadata = hasRetryAfter ? TimeSpan.FromSeconds(123) : null; using var cts = new CancellationTokenSource(); var eventCalled = false; SetupLimiter(cts.Token); _lease.IsAcquired.Returns(false); _lease.TryGetMetadata("RETRY_AFTER", out Arg.Any<object?>()) .Returns(x => { x[1] = hasRetryAfter ? metadata : null; return hasRetryAfter; }); if (hasEvents) { _event = args => { args.Context.ShouldNotBeNull(); args.Lease.ShouldBe(_lease); eventCalled = true; return default; }; } var strategy = Create(); var context = ResilienceContextPool.Shared.Get(cts.Token); var outcome = await strategy.ExecuteOutcomeAsync((_, _) => Outcome.FromResultAsValueTask("dummy"), context, "state"); outcome.Exception.ShouldNotBeNull(); RateLimiterRejectedException exception = outcome.Exception .ShouldBeOfType<RateLimiterRejectedException>(); exception.RetryAfter.ShouldBe((TimeSpan?)metadata); exception.StackTrace.ShouldNotBeNull(); exception.StackTrace.ShouldContain("Execute_LeaseRejected"); exception.TelemetrySource.ShouldNotBeNull(); eventCalled.ShouldBe(hasEvents); await _limiter.ReceivedWithAnyArgs().AcquireAsync(default, TestCancellation.Token); _lease.Received().Dispose(); _listener.GetArgs<OnRateLimiterRejectedArguments>().Count().ShouldBe(1); } [InlineData(true)] [InlineData(false)] [Theory] public async Task Dispose_DisposableResourcesShouldBeDisposed(bool isAsync) { using var limiter = new ConcurrencyLimiter(new ConcurrencyLimiterOptions { PermitLimit = 1 }); var strategy = new RateLimiterResilienceStrategy(null!, null, null!, limiter); if (isAsync) { await strategy.DisposeAsync(); } else { #pragma warning disable S6966 strategy.Dispose(); #pragma warning restore S6966 } await Should.ThrowAsync<ObjectDisposedException>(() => limiter.AcquireAsync(1).AsTask()); } [InlineData(true)] [InlineData(false)] [Theory] public async Task Dispose_NoDisposableResources_ShouldNotThrow(bool isAsync) { using var strategy = new RateLimiterResilienceStrategy(null!, null, null!, null); if (isAsync) { await Should.NotThrowAsync(() => strategy.DisposeAsync().AsTask()); } else { Should.NotThrow(() => strategy.Dispose()); } } private void SetupLimiter(CancellationToken token) { var result = new ValueTask<RateLimitLease>(_lease); _limiter .GetType() .GetMethod("AcquireAsyncCore", BindingFlags.NonPublic | BindingFlags.Instance)! .Invoke(_limiter, [1, token]) .Returns(result); } private ResiliencePipeline Create() { var builder = new ResiliencePipelineBuilder { TelemetryListener = _listener }; return builder.AddRateLimiter(new RateLimiterStrategyOptions { RateLimiter = args => _limiter.AcquireAsync(1, args.Context.CancellationToken), OnRejected = _event }) .Build(); } }
Polly
You are an expert .NET (C#) developer. Task: Write a unit test for 'RateLimiterResilienceStrategy' using XUnit and Moq. Context: - Class: RateLimiterResilienceStrategy Requirements: Use Mock<T> interface mocking.
industrial
using System.ComponentModel.DataAnnotations; using System.Diagnostics.CodeAnalysis; using System.Threading.RateLimiting; using Polly.RateLimiting; namespace Polly; /// <summary> /// Extensions for adding rate limiting to <see cref="ResiliencePipelineBuilder"/>. /// </summary> public static class RateLimiterResiliencePipelineBuilderExtensions { /// <summary> /// Adds the concurrency limiter. /// </summary> /// <typeparam name="TBuilder">The builder type.</typeparam> /// <param name="builder">The builder instance.</param> /// <param name="permitLimit">Maximum number of permits that can be leased concurrently.</param> /// <param name="queueLimit">Maximum number of permits that can be queued concurrently.</param> /// <returns>The builder instance with the concurrency limiter added.</returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="builder"/> is <see langword="null"/>.</exception> /// <exception cref="ValidationException">Thrown when the options constructed from the arguments are invalid.</exception> /// <exception cref="ArgumentException">Thrown when <paramref name="permitLimit"/> or <paramref name="queueLimit"/> is invalid.</exception> public static TBuilder AddConcurrencyLimiter<TBuilder>( this TBuilder builder, int permitLimit, int queueLimit = 0) where TBuilder : ResiliencePipelineBuilderBase { return builder.AddConcurrencyLimiter(new ConcurrencyLimiterOptions { PermitLimit = permitLimit, QueueLimit = queueLimit }); } /// <summary> /// Adds the concurrency limiter. /// </summary> /// <typeparam name="TBuilder">The builder type.</typeparam> /// <param name="builder">The builder instance.</param> /// <param name="options">The concurrency limiter options.</param> /// <returns>The builder instance with the concurrency limiter added.</returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="builder"/> or <paramref name="options"/> is <see langword="null"/>.</exception> /// <exception cref="ValidationException">Thrown when the options constructed from the arguments are invalid.</exception> /// <exception cref="ArgumentException">Thrown when <paramref name="options"/> are invalid.</exception> public static TBuilder AddConcurrencyLimiter<TBuilder>( this TBuilder builder, ConcurrencyLimiterOptions options) where TBuilder : ResiliencePipelineBuilderBase { Guard.NotNull(builder); Guard.NotNull(options); return builder.AddRateLimiter(new RateLimiterStrategyOptions { DefaultRateLimiterOptions = options }); } /// <summary> /// Adds the rate limiter. /// </summary> /// <typeparam name="TBuilder">The builder type.</typeparam> /// <param name="builder">The builder instance.</param> /// <param name="limiter">The rate limiter to use.</param> /// <returns>The builder instance with the rate limiter added.</returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="builder"/> or <paramref name="limiter"/> is <see langword="null"/>.</exception> /// <exception cref="ValidationException">Thrown when the options constructed from the arguments are invalid.</exception> public static TBuilder AddRateLimiter<TBuilder>( this TBuilder builder, RateLimiter limiter) where TBuilder : ResiliencePipelineBuilderBase { Guard.NotNull(builder); Guard.NotNull(limiter); return builder.AddRateLimiter(new RateLimiterStrategyOptions { RateLimiter = args => limiter.AcquireAsync(cancellationToken: args.Context.CancellationToken), }); } /// <summary> /// Adds the rate limiter. /// </summary> /// <typeparam name="TBuilder">The builder type.</typeparam> /// <param name="builder">The builder instance.</param> /// <param name="options">The rate limiter options.</param> /// <returns>The builder instance with the rate limiter added.</returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="builder"/> or <paramref name="options"/> is <see langword="null"/>.</exception> /// <exception cref="ValidationException">Thrown when <paramref name="options"/> are invalid.</exception> /// <exception cref="ArgumentException">Thrown when <see cref="RateLimiterStrategyOptions.DefaultRateLimiterOptions"/> for <paramref name="options"/> are invalid.</exception> [DynamicDependency(DynamicallyAccessedMemberTypes.All, typeof(RateLimiterStrategyOptions))] [UnconditionalSuppressMessage( "Trimming", "IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code", Justification = "All options members are preserved.")] public static TBuilder AddRateLimiter<TBuilder>( this TBuilder builder, RateLimiterStrategyOptions options) where TBuilder : ResiliencePipelineBuilderBase { Guard.NotNull(builder); Guard.NotNull(options); return builder.AddStrategy( context => { RateLimiter? wrapper = default; var limiter = options.RateLimiter; if (limiter is null) { var defaultLimiter = new ConcurrencyLimiter(options.DefaultRateLimiterOptions); wrapper = defaultLimiter; limiter = args => defaultLimiter.AcquireAsync(cancellationToken: args.Context.CancellationToken); } return new RateLimiterResilienceStrategy( limiter, options.OnRejected, context.Telemetry, wrapper); }, options); } }
using System.ComponentModel.DataAnnotations; using System.Threading.RateLimiting; using NSubstitute; using Polly.Registry; using Polly.Testing; using Polly.TestUtils; namespace Polly.RateLimiting.Tests; public class RateLimiterResiliencePipelineBuilderExtensionsTests { #pragma warning disable IDE0028 public static readonly TheoryData<Action<ResiliencePipelineBuilder>> Data = new() { builder => { builder.AddConcurrencyLimiter(2, 2); AssertRateLimiterStrategy(builder, strategy => strategy.Wrapper.ShouldBeOfType<ConcurrencyLimiter>()); }, builder => { builder.AddConcurrencyLimiter( new ConcurrencyLimiterOptions { PermitLimit = 2, QueueLimit = 2 }); AssertRateLimiterStrategy(builder, strategy => strategy.Wrapper.ShouldBeOfType<ConcurrencyLimiter>()); }, builder => { var expected = Substitute.For<RateLimiter>(); builder.AddRateLimiter(expected); AssertRateLimiterStrategy(builder, strategy => strategy.Wrapper.ShouldBeNull()); }, builder => { var limiter = new ConcurrencyLimiter(new ConcurrencyLimiterOptions { PermitLimit = 1 }); builder.AddRateLimiter(limiter); builder.Build().Execute(() => { }); AssertRateLimiterStrategy(builder, strategy => strategy.Wrapper.ShouldBeNull()); } }; #pragma warning restore IDE0028 [Theory(Skip = "https://github.com/stryker-mutator/stryker-net/issues/2144")] #pragma warning disable xUnit1045 [MemberData(nameof(Data))] #pragma warning restore xUnit1045 public void AddRateLimiter_Extensions_Ok(Action<ResiliencePipelineBuilder> configure) { var builder = new ResiliencePipelineBuilder(); configure(builder); builder.Build().ShouldBeOfType<RateLimiterResilienceStrategy>(); } [Fact] public void AddConcurrencyLimiter_InvalidOptions_Throws() => Assert.Throws<ArgumentException>(() => { return new ResiliencePipelineBuilder().AddConcurrencyLimiter(new ConcurrencyLimiterOptions { PermitLimit = -10, QueueLimit = -10 }) .Build(); }); [Fact] public void AddRateLimiter_AllExtensions_Ok() { foreach (Action<ResiliencePipelineBuilder> configure in Data) { var builder = new ResiliencePipelineBuilder(); configure(builder); AssertRateLimiterStrategy(builder); } } [Fact] public void AddRateLimiter_Ok() { using var limiter = new ConcurrencyLimiter(new ConcurrencyLimiterOptions { QueueLimit = 10, PermitLimit = 10 }); new ResiliencePipelineBuilder() .AddRateLimiter(new RateLimiterStrategyOptions { RateLimiter = args => limiter.AcquireAsync(1, args.Context.CancellationToken) }) .Build() .GetPipelineDescriptor() .FirstStrategy .StrategyInstance .ShouldBeOfType<RateLimiterResilienceStrategy>(); } [Fact] public void AddRateLimiter_InvalidOptions_Throws() { var options = new RateLimiterStrategyOptions { DefaultRateLimiterOptions = null! }; var builder = new ResiliencePipelineBuilder(); var exception = Should.Throw<ValidationException>(() => builder.AddRateLimiter(options)); exception.Message.Trim().ShouldBe(""" The 'RateLimiterStrategyOptions' are invalid. Validation Errors: The DefaultRateLimiterOptions field is required. """, StringCompareShould.IgnoreLineEndings); } [Fact] public void AddGenericRateLimiter_InvalidOptions_Throws() { var options = new RateLimiterStrategyOptions { DefaultRateLimiterOptions = null! }; var builder = new ResiliencePipelineBuilder<int>(); var exception = Should.Throw<ValidationException>(() => builder.AddRateLimiter(options)); exception.Message.Trim().ShouldBe(""" The 'RateLimiterStrategyOptions' are invalid. Validation Errors: The DefaultRateLimiterOptions field is required. """, StringCompareShould.IgnoreLineEndings); } [Fact] public void AddRateLimiter_Options_Ok() { var strategy = new ResiliencePipelineBuilder() .AddRateLimiter(new RateLimiterStrategyOptions { RateLimiter = args => new ValueTask<RateLimitLease>(Substitute.For<RateLimitLease>()) }) .Build() .GetPipelineDescriptor() .FirstStrategy .StrategyInstance .ShouldBeOfType<RateLimiterResilienceStrategy>(); } [Fact] public async Task DisposeRegistry_EnsureRateLimiterDisposed() { var registry = new ResiliencePipelineRegistry<string>(); var pipeline = registry.GetOrAddPipeline("limiter", p => p.AddRateLimiter(new RateLimiterStrategyOptions())); var strategy = (RateLimiterResilienceStrategy)pipeline.GetPipelineDescriptor().FirstStrategy.StrategyInstance; await registry.DisposeAsync(); Should.Throw<ObjectDisposedException>(() => strategy.AsPipeline().Execute(() => { })); } [Fact] public void TypedBuilder_AddConcurrencyLimiter_BuildsRateLimiterStrategy() { var pipeline = new ResiliencePipelineBuilder<int>() .AddConcurrencyLimiter(permitLimit: 2, queueLimit: 1); pipeline.Build() .GetPipelineDescriptor() .FirstStrategy .StrategyInstance .ShouldBeOfType<RateLimiterResilienceStrategy>(); } [Fact] public void AddRateLimiter_WithNullLimiter_Throws() { var builder = new ResiliencePipelineBuilder(); Should.Throw<ArgumentNullException>(() => builder.AddRateLimiter(limiter: null!)); } [Fact] public void AddRateLimiter_WithNullOptions_Throws() { var builder = new ResiliencePipelineBuilder(); Should.Throw<ArgumentNullException>(() => builder.AddRateLimiter(options: null!)); } [Fact] public void AddConcurrencyLimiter_WithNullOptions_Throws() { var builder = new ResiliencePipelineBuilder(); Should.Throw<ArgumentNullException>(() => builder.AddConcurrencyLimiter(options: null!)); } [Fact] public async Task RegistryDispose_DoesNotDisposeExternalLimiter() { using var externalLimiter = new ConcurrencyLimiter(new ConcurrencyLimiterOptions { PermitLimit = 1, QueueLimit = 0 }); var registry = new ResiliencePipelineRegistry<string>(); _ = registry.GetOrAddPipeline("ext", p => p.AddRateLimiter(externalLimiter)); await registry.DisposeAsync(); await Should.NotThrowAsync(async () => { var lease = await externalLimiter.AcquireAsync(1, CancellationToken.None); try { lease.IsAcquired.ShouldBeTrue(); } finally { lease.Dispose(); } }); } private static void AssertRateLimiterStrategy(ResiliencePipelineBuilder builder, Action<RateLimiterResilienceStrategy>? assert = null, bool hasEvents = false) { ResiliencePipeline strategy = builder.Build(); var limiterStrategy = (RateLimiterResilienceStrategy)strategy.GetPipelineDescriptor().FirstStrategy.StrategyInstance; assert?.Invoke(limiterStrategy); if (hasEvents) { limiterStrategy.OnLeaseRejected.ShouldNotBeNull(); limiterStrategy .OnLeaseRejected!(new OnRateLimiterRejectedArguments(ResilienceContextPool.Shared.Get(TestCancellation.Token), Substitute.For<RateLimitLease>())) .Preserve().GetAwaiter().GetResult(); } else { limiterStrategy.OnLeaseRejected.ShouldBeNull(); } strategy .GetPipelineDescriptor() .FirstStrategy .StrategyInstance .ShouldBeOfType<RateLimiterResilienceStrategy>(); } }
Polly
You are an expert .NET (C#) developer. Task: Write a unit test for 'RateLimiterResiliencePipelineBuilderExtensions' using XUnit and Moq. Context: - Class: RateLimiterResiliencePipelineBuilderExtensions Requirements: Use Mock<T> interface mocking.
industrial
using System.ComponentModel.DataAnnotations; using System.Threading.RateLimiting; namespace Polly.RateLimiting; /// <summary> /// Options for the rate limiter strategy. /// </summary> public class RateLimiterStrategyOptions : ResilienceStrategyOptions { /// <summary> /// Initializes a new instance of the <see cref="RateLimiterStrategyOptions"/> class. /// </summary> public RateLimiterStrategyOptions() => Name = RateLimiterConstants.DefaultName; /// <summary> /// Gets or sets a rate limiter delegate that produces <see cref="RateLimitLease"/>. /// </summary> /// <value> /// The default value is <see langword="null"/>. If this property is <see langword="null"/>, then the strategy /// will use a <see cref="ConcurrencyLimiter"/> created using <see cref="DefaultRateLimiterOptions"/>. /// </value> public Func<RateLimiterArguments, ValueTask<RateLimitLease>>? RateLimiter { get; set; } /// <summary> /// Gets or sets the default rate limiter options. /// </summary> /// <remarks> /// The options for the default limiter that will be used when <see cref="RateLimiter"/> is <see langword="null"/>. /// <para> /// <see cref="ConcurrencyLimiterOptions.PermitLimit"/> defaults to 1000. /// <see cref="ConcurrencyLimiterOptions.QueueLimit"/> defaults to 0. /// </para> /// </remarks> [Required] public ConcurrencyLimiterOptions DefaultRateLimiterOptions { get; set; } = new() { QueueLimit = RateLimiterConstants.DefaultQueueLimit, PermitLimit = RateLimiterConstants.DefaultPermitLimit, }; /// <summary> /// Gets or sets an event that is raised when the execution of user-provided callback is rejected by the rate limiter. /// </summary> /// <value> /// The default value is <see langword="null"/>. /// </value> public Func<OnRateLimiterRejectedArguments, ValueTask>? OnRejected { get; set; } }
namespace Polly.RateLimiting.Tests; public class RateLimiterStrategyOptionsTests { [Fact] public void Ctor_EnsureDefaults() { var options = new RateLimiterStrategyOptions(); options.RateLimiter.ShouldBeNull(); options.OnRejected.ShouldBeNull(); options.DefaultRateLimiterOptions.PermitLimit.ShouldBe(1000); options.DefaultRateLimiterOptions.QueueLimit.ShouldBe(0); options.Name.ShouldBe("RateLimiter"); } }
Polly
You are an expert .NET (C#) developer. Task: Write a unit test for 'RateLimiterStrategyOptions' using XUnit and Moq. Context: - Class: RateLimiterStrategyOptions Requirements: Use Mock<T> interface mocking.
industrial
// Copyright (c) .NET Foundation and Contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.Text; namespace RestSharp.Serializers.Xml; /// <summary> /// Wrapper for System.Xml.Serialization.XmlSerializer. /// </summary> public class DotNetXmlDeserializer : IXmlDeserializer { /// <summary> /// Encoding for serialized content /// </summary> public Encoding Encoding { get; set; } = Encoding.UTF8; /// <summary> /// Name of the root element to use when serializing /// </summary> [Obsolete("DotnetXmlDeserializer does not support RootElement.")] public string? RootElement { get; set; } /// <summary> /// XML namespace to use when serializing /// </summary> public string? Namespace { get; set; } [Obsolete("DotnetXmlDeserializer does not support DateFormat.")] public string? DateFormat { get; set; } public T? Deserialize<T>(RestResponse response) { if (string.IsNullOrEmpty(response.Content)) return default; using var stream = new MemoryStream(Encoding.GetBytes(response.Content!)); var serializer = new System.Xml.Serialization.XmlSerializer(typeof(T), Namespace); return (T?)serializer.Deserialize(stream); } }
using System.Globalization; using System.Xml.Linq; using RestSharp.Serializers.Xml; using RestSharp.Tests.Serializers.Xml.SampleClasses; using RestSharp.Tests.Serializers.Xml.SampleClasses.DeserializeAsTest; namespace RestSharp.Tests.Serializers.Xml; public class XmlDeserializerTests { const string GuidString = "AC1FC4BC-087A-4242-B8EE-C53EBE9887A5"; #if NET readonly string _sampleDataPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SampleData"); #else readonly string _sampleDataPath = Path.Combine(Directory.GetCurrentDirectory(), "SampleData"); #endif string PathFor(string sampleFile) => Path.Combine(_sampleDataPath, sampleFile); static string CreateUnderscoresXml() { var doc = new XDocument(); var root = new XElement("Person"); root.Add(new XElement("Name", "John Sheehan")); root.Add(new XElement("Start_Date", new DateTime(2009, 9, 25, 0, 6, 1))); root.Add(new XAttribute("Age", 28)); root.Add(new XElement("Percent", 99.9999m)); root.Add(new XElement("Big_Number", long.MaxValue)); root.Add(new XAttribute("Is_Cool", false)); root.Add(new XElement("Ignore", "dummy")); root.Add(new XAttribute("Read_Only", "dummy")); root.Add(new XElement("Unique_Id", new Guid(GuidString))); root.Add(new XElement("Url", "https://example.com")); root.Add(new XElement("Url_Path", "/foo/bar")); root.Add( new XElement( "Best_Friend", new XElement("Name", "The Fonz"), new XAttribute("Since", 1952) ) ); var friends = new XElement("Friends"); for (var i = 0; i < 10; i++) { friends.Add( new XElement( "Friend", new XElement("Name", $"Friend{i}"), new XAttribute("Since", DateTime.Now.Year - i) ) ); } root.Add(friends); var foes = new XElement("Foes"); foes.Add(new XAttribute("Team", "Yankees")); for (var i = 0; i < 5; i++) foes.Add(new XElement("Foe", new XElement("Nickname", $"Foe{i}"))); root.Add(foes); doc.Add(root); return doc.ToString(); } static string CreateLowercaseUnderscoresXml() { var doc = new XDocument(); var root = new XElement("Person"); root.Add(new XElement("Name", "John Sheehan")); root.Add(new XElement("start_date", new DateTime(2009, 9, 25, 0, 6, 1))); root.Add(new XAttribute("Age", 28)); root.Add(new XElement("Percent", 99.9999m)); root.Add(new XElement("big_number", long.MaxValue)); root.Add(new XAttribute("is_cool", false)); root.Add(new XElement("Ignore", "dummy")); root.Add(new XAttribute("read_only", "dummy")); root.Add(new XElement("unique_id", new Guid(GuidString))); root.Add(new XElement("Url", "https://example.com")); root.Add(new XElement("url_path", "/foo/bar")); root.Add( new XElement( "best_friend", new XElement("name", "The Fonz"), new XAttribute("Since", 1952) ) ); var friends = new XElement("Friends"); for (var i = 0; i < 10; i++) { friends.Add( new XElement( "Friend", new XElement("Name", $"Friend{i}"), new XAttribute("Since", DateTime.Now.Year - i) ) ); } root.Add(friends); var foes = new XElement("Foes"); foes.Add(new XAttribute("Team", "Yankees")); for (var i = 0; i < 5; i++) foes.Add(new XElement("Foe", new XElement("Nickname", $"Foe{i}"))); root.Add(foes); doc.Add(root); return doc.ToString(); } static string CreateDashesXml() { var doc = new XDocument(); var root = new XElement("Person"); root.Add(new XElement("Name", "John Sheehan")); root.Add(new XElement("Start_Date", new DateTime(2009, 9, 25, 0, 6, 1))); root.Add(new XAttribute("Age", 28)); root.Add(new XElement("Percent", 99.9999m)); root.Add(new XElement("Big-Number", long.MaxValue)); root.Add(new XAttribute("Is-Cool", false)); root.Add(new XElement("Ignore", "dummy")); root.Add(new XAttribute("Read-Only", "dummy")); root.Add(new XElement("Unique-Id", new Guid(GuidString))); root.Add(new XElement("Url", "https://example.com")); root.Add(new XElement("Url-Path", "/foo/bar")); root.Add( new XElement( "Best-Friend", new XElement("Name", "The Fonz"), new XAttribute("Since", 1952) ) ); var friends = new XElement("Friends"); for (var i = 0; i < 10; i++) { friends.Add( new XElement( "Friend", new XElement("Name", $"Friend{i}"), new XAttribute("Since", DateTime.Now.Year - i) ) ); } root.Add(friends); var foes = new XElement("Foes"); foes.Add(new XAttribute("Team", "Yankees")); for (var i = 0; i < 5; i++) foes.Add(new XElement("Foe", new XElement("Nickname", $"Foe{i}"))); root.Add(foes); doc.Add(root); return doc.ToString(); } static string CreateLowerCasedRootElementWithDashesXml() { var doc = new XDocument(); var root = new XElement( "incoming-invoices", new XElement("incoming-invoice", new XElement("concept-id", 45)) ); doc.Add(root); return doc.ToString(); } static string CreateElementsXml() { var doc = new XDocument(); var root = new XElement("Person"); root.Add(new XElement("Name", "John Sheehan")); root.Add(new XElement("StartDate", new DateTime(2009, 9, 25, 0, 6, 1))); root.Add(new XElement("Age", 28)); root.Add(new XElement("Percent", 99.9999m)); root.Add(new XElement("BigNumber", long.MaxValue)); root.Add(new XElement("IsCool", false)); root.Add(new XElement("Ignore", "dummy")); root.Add(new XElement("ReadOnly", "dummy")); root.Add(new XElement("UniqueId", new Guid(GuidString))); root.Add(new XElement("EmptyGuid", "")); root.Add(new XElement("Url", "https://example.com")); root.Add(new XElement("UrlPath", "/foo/bar")); root.Add(new XElement("Order", "third")); root.Add(new XElement("Disposition", "so-so")); root.Add( new XElement( "BestFriend", new XElement("Name", "The Fonz"), new XElement("Since", 1952) ) ); var friends = new XElement("Friends"); for (var i = 0; i < 10; i++) { friends.Add( new XElement( "Friend", new XElement("Name", $"Friend{i}"), new XElement("Since", DateTime.Now.Year - i) ) ); } root.Add(friends); doc.Add(root); return doc.ToString(); } static string CreateAttributesXml() { var doc = new XDocument(); var root = new XElement("Person"); root.Add(new XAttribute("Name", "John Sheehan")); root.Add(new XAttribute("StartDate", new DateTime(2009, 9, 25, 0, 6, 1))); root.Add(new XAttribute("Age", 28)); root.Add(new XAttribute("Percent", 99.9999m)); root.Add(new XAttribute("BigNumber", long.MaxValue)); root.Add(new XAttribute("IsCool", false)); root.Add(new XAttribute("Ignore", "dummy")); root.Add(new XAttribute("ReadOnly", "dummy")); root.Add(new XAttribute("UniqueId", new Guid(GuidString))); root.Add(new XAttribute("Url", "https://example.com")); root.Add(new XAttribute("UrlPath", "/foo/bar")); root.Add( new XElement( "BestFriend", new XAttribute("Name", "The Fonz"), new XAttribute("Since", 1952) ) ); doc.Add(root); return doc.ToString(); } static string CreateNoteXml() { var doc = new XDocument(); var root = new XElement("Note"); root.SetAttributeValue("Id", 1); root.Value = Note.ConstMessage; root.Add(new XElement("Title", Note.ConstTitle)); doc.Add(root); return doc.ToString(); } static string CreateXmlWithNullValues() { var doc = new XDocument(); var root = new XElement("NullableValues"); root.Add( new XElement("Id", null!), new XElement("StartDate", null!), new XElement("UniqueId", null!) ); doc.Add(root); return doc.ToString(); } static string CreateXmlWithoutEmptyValues(CultureInfo culture) { var doc = new XDocument(); var root = new XElement("NullableValues"); root.Add( new XElement("Id", 123), new XElement("StartDate", new DateTime(2010, 2, 21, 9, 35, 00).ToString(culture)), new XElement("UniqueId", new Guid(GuidString)) ); doc.Add(root); return doc.ToString(); } static string CreateXmlWithEmptyNestedList() { var doc = new XDocument(); var root = new XElement("EmptyListSample"); root.Add(new XElement("Images")); doc.Add(root); return doc.ToString(); } static string CreateXmlWithEmptyInlineList() { var doc = new XDocument(); var root = new XElement("EmptyListSample"); doc.Add(root); return doc.ToString(); } static string CreateXmlWithAttributesAndNullValues() { var doc = new XDocument(); var root = new XElement("NullableValues"); var idElement = new XElement("Id", null!); idElement.SetAttributeValue("SomeAttribute", "SomeAttribute_Value"); root.Add( idElement, new XElement("StartDate", null!), new XElement("UniqueId", null!) ); doc.Add(root); return doc.ToString(); } static string CreateXmlWithAttributesAndNullValuesAndPopulatedValues() { var doc = new XDocument(); var root = new XElement("NullableValues"); var idElement = new XElement("Id", null!); idElement.SetAttributeValue("SomeAttribute", "SomeAttribute_Value"); root.Add( idElement, new XElement("StartDate", null!), new XElement("UniqueId", new Guid(GuidString)) ); doc.Add(root); return doc.ToString(); } [Fact] public void Able_to_use_alternative_name_for_arrays() { var xmlFilePath = PathFor("header_and_rows.xml"); var doc = XDocument.Load(xmlFilePath); var xml = new XmlDeserializer(); var output = xml.Deserialize<Header>(new() { Content = doc.ToString() })!; Assert.NotNull(output); Assert.Equal("text title", output.Title); Assert.Contains(output.Othername, x => x.Text1 == "first row text 1 sample"); } [Fact] public void Can_deal_with_value_attribute() { const string content = "<Color><Name>Green</Name><Value>255</Value></Color>"; var xml = new XmlDeserializer(); var output = xml.Deserialize<ColorWithValue>(new() { Content = content })!; Assert.NotNull(output); Assert.Equal("Green", output.Name); Assert.Equal(255, output.Value); } [Fact] public void Can_Deserialize_Attribute_Using_Exact_Name_Defined_In_DeserializeAs_Attribute() { const string content = """<response attribute-value="711"></response>"""; var expected = new NodeWithAttributeAndValue { AttributeValue = "711" }; var xml = new XmlDeserializer(); var output = xml.Deserialize<NodeWithAttributeAndValue>(new() { Content = content })!; Assert.Equal(expected.AttributeValue, output.AttributeValue); } [Fact] public void Can_Deserialize_AttributeNamedValue() { var doc = new XDocument(); var root = new XElement("ValueCollection"); var xmlCollection = new XElement("Values"); var first = new XElement("Value"); first.Add(new XAttribute("Timestamp", new DateTime(1969, 7, 20, 20, 18, 00, DateTimeKind.Utc))); first.Add(new XAttribute("Value", "Eagle landed")); xmlCollection.Add(first); var second = new XElement("Value"); second.Add(new XAttribute("Timestamp", new DateTime(1969, 7, 21, 2, 56, 15, DateTimeKind.Utc))); second.Add(new XAttribute("Value", "First step")); xmlCollection.Add(second); root.Add(xmlCollection); doc.Add(root); var response = new RestResponse { Content = doc.ToString() }; var d = new XmlDeserializer(); var valueCollection = d.Deserialize<ValueCollectionForXml>(response)!; Assert.Equal(2, valueCollection.Values.Count); Assert.Equal("Eagle landed", valueCollection.Values.First().Value); } [Fact] public void Can_Deserialize_Attributes_On_Default_Root() { var doc = CreateAttributesXml(); var response = new RestResponse { Content = doc }; var d = new XmlDeserializer(); var p = d.Deserialize<PersonForXml>(response)!; Assert.Equal("John Sheehan", p.Name); Assert.Equal(new DateTime(2009, 9, 25, 0, 6, 1), p.StartDate); Assert.Equal(28, p.Age); Assert.Equal(long.MaxValue, p.BigNumber); Assert.Equal(99.9999m, p.Percent); Assert.False(p.IsCool); Assert.Equal(new Guid(GuidString), p.UniqueId); Assert.Equal(new Uri("https://example.com", UriKind.RelativeOrAbsolute), p.Url); Assert.Equal(new Uri("/foo/bar", UriKind.RelativeOrAbsolute), p.UrlPath); Assert.NotNull(p.BestFriend); Assert.Equal("The Fonz", p.BestFriend.Name); Assert.Equal(1952, p.BestFriend.Since); } [Fact] public void Can_Deserialize_Boolean_From_Number() { var xmlFilePath = PathFor("boolean_from_number.xml"); var doc = XDocument.Load(xmlFilePath); var response = new RestResponse { Content = doc.ToString() }; var d = new XmlDeserializer(); var output = d.Deserialize<BooleanTest>(response)!; Assert.True(output.Value); } [Fact] public void Can_Deserialize_Boolean_From_String() { var xmlFilePath = PathFor("boolean_from_string.xml"); var doc = XDocument.Load(xmlFilePath); var response = new RestResponse { Content = doc.ToString() }; var d = new XmlDeserializer(); var output = d.Deserialize<BooleanTest>(response)!; Assert.True(output.Value); } [Fact] public void Can_Deserialize_Custom_Formatted_Date() { const string format = "dd yyyy MMM, hh:mm ss tt zzz"; var culture = CultureInfo.InvariantCulture; var date = new DateTime(2010, 2, 8, 11, 11, 11); var doc = new XDocument(); var root = new XElement("Person"); root.Add(new XElement("StartDate", date.ToString(format, culture))); doc.Add(root); var xml = new XmlDeserializer { DateFormat = format, Culture = culture }; var response = new RestResponse { Content = doc.ToString() }; var output = xml.Deserialize<PersonForXml>(response)!; Assert.Equal(date, output.StartDate); } [Fact] public void Can_Deserialize_DateTimeOffset() { var culture = CultureInfo.InvariantCulture; var doc = new XDocument(culture); var dateTimeOffset = new DateTimeOffset(2013, 02, 08, 9, 18, 22, TimeSpan.FromHours(10)); DateTimeOffset? nullableDateTimeOffsetWithValue = new DateTimeOffset(2013, 02, 08, 9, 18, 23, TimeSpan.FromHours(10)); var root = new XElement("Dates"); root.Add(new XElement("DateTimeOffset", dateTimeOffset)); root.Add(new XElement("NullableDateTimeOffsetWithNull", string.Empty)); root.Add(new XElement("NullableDateTimeOffsetWithValue", nullableDateTimeOffsetWithValue)); doc.Add(root); //var xml = new XmlDeserializer { Culture = culture, }; var response = new RestResponse { Content = doc.ToString() }; var d = new XmlDeserializer { Culture = culture }; var payload = d.Deserialize<DateTimeTestStructure>(response)!; Assert.Equal(dateTimeOffset, payload.DateTimeOffset); Assert.Null(payload.NullableDateTimeOffsetWithNull); Assert.True(payload.NullableDateTimeOffsetWithValue.HasValue); Assert.Equal(nullableDateTimeOffsetWithValue, payload.NullableDateTimeOffsetWithValue); } [Fact] public void Can_Deserialize_Directly_To_Lists_Off_Root_Element() { var xmlFilePath = PathFor("directlists.xml"); var doc = XDocument.Load(xmlFilePath); var xml = new XmlDeserializer(); var output = xml.Deserialize<List<Database>>(new() { Content = doc.ToString() })!; Assert.Equal(2, output.Count); } [Fact] public void Can_Deserialize_ElementNamedValue() { var doc = new XDocument(); var root = new XElement("ValueCollection"); const string valueName = "First moon landing events"; root.Add(new XElement("Value", valueName)); var xmlCollection = new XElement("Values"); var first = new XElement("Value"); first.Add(new XAttribute("Timestamp", new DateTime(1969, 7, 20, 20, 18, 00, DateTimeKind.Utc))); xmlCollection.Add(first); var second = new XElement("Value"); second.Add(new XAttribute("Timestamp", new DateTime(1969, 7, 21, 2, 56, 15, DateTimeKind.Utc))); xmlCollection.Add(second); root.Add(xmlCollection); doc.Add(root); var response = new RestResponse { Content = doc.ToString() }; var d = new XmlDeserializer(); var valueCollection = d.Deserialize<ValueCollectionForXml>(response)!; Assert.Equal(valueName, valueCollection.Value); Assert.Equal(2, valueCollection.Values.Count); Assert.Equal( new DateTime(1969, 7, 20, 20, 18, 00, DateTimeKind.Utc), valueCollection.Values.First().Timestamp.ToUniversalTime() ); } [Fact] public void Can_Deserialize_Elements_On_Default_Root() { var doc = CreateElementsXml(); var response = new RestResponse { Content = doc }; var d = new XmlDeserializer(); var p = d.Deserialize<PersonForXml>(response)!; Assert.Equal("John Sheehan", p.Name); Assert.Equal(new DateTime(2009, 9, 25, 0, 6, 1), p.StartDate); Assert.Equal(28, p.Age); Assert.Equal(long.MaxValue, p.BigNumber); Assert.Equal(99.9999m, p.Percent); Assert.False(p.IsCool); Assert.Equal(new Guid(GuidString), p.UniqueId); Assert.Equal(Guid.Empty, p.EmptyGuid); Assert.Equal(new Uri("https://example.com", UriKind.RelativeOrAbsolute), p.Url); Assert.Equal(new Uri("/foo/bar", UriKind.RelativeOrAbsolute), p.UrlPath); Assert.Equal(Order.Third, p.Order); Assert.Equal(Disposition.SoSo, p.Disposition); Assert.NotNull(p.Friends); Assert.Equal(10, p.Friends.Count); Assert.NotNull(p.BestFriend); Assert.Equal("The Fonz", p.BestFriend.Name); Assert.Equal(1952, p.BestFriend.Since); } [Fact] public void Can_Deserialize_Elements_to_Nullable_Values() { var culture = CultureInfo.InvariantCulture; var doc = CreateXmlWithoutEmptyValues(culture); var xml = new XmlDeserializer { Culture = culture }; var output = xml.Deserialize<NullableValues>(new() { Content = doc })!; Assert.NotNull(output.Id); Assert.NotNull(output.StartDate); Assert.NotNull(output.UniqueId); Assert.Equal(123, output.Id); Assert.Equal(new DateTime(2010, 2, 21, 9, 35, 00), output.StartDate); Assert.Equal(new Guid(GuidString), output.UniqueId); } [Fact] public void Can_Deserialize_Empty_Elements_to_Nullable_Values() { var doc = CreateXmlWithNullValues(); var xml = new XmlDeserializer(); var output = xml.Deserialize<NullableValues>(new() { Content = doc })!; Assert.Null(output.Id); Assert.Null(output.StartDate); Assert.Null(output.UniqueId); } [Fact] public void Can_Deserialize_Empty_Elements_With_Attributes_to_Nullable_Values() { var doc = CreateXmlWithAttributesAndNullValues(); var xml = new XmlDeserializer(); var output = xml.Deserialize<NullableValues>(new() { Content = doc })!; Assert.Null(output.Id); Assert.Null(output.StartDate); Assert.Null(output.UniqueId); } [Fact] public void Can_Deserialize_Eventful_Xml() { var xmlFilePath = PathFor("eventful.xml"); var doc = XDocument.Load(xmlFilePath); var response = new RestResponse { Content = doc.ToString() }; var d = new XmlDeserializer(); var output = d.Deserialize<VenueSearch>(response)!; Assert.Equal(3, output.venues.Count); Assert.Equal("Tivoli", output.venues[0].name); Assert.Equal("https://eventful.com/brisbane/venues/tivoli-/V0-001-002169294-8", output.venues[1].url); Assert.Equal("V0-001-000266914-3", output.venues[2].id); } [Fact] public void Can_Deserialize_Goodreads_Xml() { var xmlFilePath = PathFor("Goodreads.xml"); var doc = XDocument.Load(xmlFilePath); var response = new RestResponse { Content = doc.ToString() }; var d = new XmlDeserializer(); var output = d.Deserialize<GoodReadsReviewCollection>(response)!; Assert.Equal(2, output.Reviews.Count); Assert.Equal("1208943892", output.Reviews[0].Id); // This fails without fixing the XmlDeserializer Assert.Equal("1198344567", output.Reviews[1].Id); } [Fact] public void Can_throw_format_exception_xml() { var xmlPath = PathFor("GoodreadsFormatError.xml"); var doc = XDocument.Load(xmlPath); var response = new RestResponse { Content = doc.ToString() }; var d = new XmlDeserializer(); Assert.Throws<FormatException>(() => d.Deserialize<GoodReadsReviewCollection>(response) ); } [Fact] public void Can_Deserialize_Google_Weather_Xml() { var xmlPath = PathFor("GoogleWeather.xml"); var doc = XDocument.Load(xmlPath); var response = new RestResponse { Content = doc.ToString() }; var d = new XmlDeserializer(); var output = d.Deserialize<xml_api_reply>(response)!; Assert.Equal(4, output.weather.Count); Assert.Equal("Sunny", output.weather[0].condition.data); } [Fact] public void Can_Deserialize_Inline_List_Without_Elements_To_Empty_List() { var doc = CreateXmlWithEmptyInlineList(); var xml = new XmlDeserializer(); var output = xml.Deserialize<EmptyListSample>(new() { Content = doc })!; Assert.NotNull(output.Images); Assert.Empty(output.Images); } [Fact] public void Can_Deserialize_Into_Struct() { const string content = "<root><one>oneOneOne</one><two>twoTwoTwo</two><three>3</three></root>"; var xml = new XmlDeserializer(); var output = xml.Deserialize<SimpleStruct>(new() { Content = content }); Assert.Equal("oneOneOne", output.One); Assert.Equal("twoTwoTwo", output.Two); Assert.Equal(3, output.Three); } [Fact] public void Can_Deserialize_Lastfm_Xml() { var xmlPath = PathFor("Lastfm.xml"); var doc = XDocument.Load(xmlPath); var response = new RestResponse { Content = doc.ToString() }; var d = new XmlDeserializer(); var output = d.Deserialize<Event>(response)!; Assert.Equal( "https://www.last.fm/event/328799+Philip+Glass+at+Barbican+Centre+on+12+June+2008", output.url ); Assert.Equal("https://www.last.fm/venue/8777860+Barbican+Centre", output.venue.url); } [Fact] public void Can_Deserialize_Lists_of_Simple_Types() { var xmlPath = PathFor("xmllists.xml"); var doc = XDocument.Load(xmlPath); var xml = new XmlDeserializer(); var output = xml.Deserialize<SimpleTypesListSample>(new() { Content = doc.ToString() })!; Assert.NotEqual(0, output.Names[0].Length); Assert.NotEqual(0, output.Numbers.Sum()); } [Fact] public void Can_Deserialize_Lower_Cased_Root_Elements_With_Dashes() { var doc = CreateDashesXml(); var response = new RestResponse { Content = doc }; var d = new XmlDeserializer(); var p = d.Deserialize<PersonForXml>(response)!; Assert.Equal("John Sheehan", p.Name); Assert.Equal(new(2009, 9, 25, 0, 6, 1), p.StartDate); Assert.Equal(28, p.Age); Assert.Equal(long.MaxValue, p.BigNumber); Assert.Equal(99.9999m, p.Percent); Assert.False(p.IsCool); Assert.Equal(new(GuidString), p.UniqueId); Assert.Equal(new("https://example.com", UriKind.RelativeOrAbsolute), p.Url); Assert.Equal(new("/foo/bar", UriKind.RelativeOrAbsolute), p.UrlPath); Assert.NotNull(p.Friends); Assert.Equal(10, p.Friends.Count); Assert.NotNull(p.BestFriend); Assert.Equal("The Fonz", p.BestFriend.Name); Assert.Equal(1952, p.BestFriend.Since); Assert.NotNull(p.Foes); Assert.Equal(5, p.Foes.Count); Assert.Equal("Yankees", p.Foes.Team); } [Fact] public void Can_Deserialize_Mixture_Of_Empty_Elements_With_Attributes_And_Populated_Elements() { var doc = CreateXmlWithAttributesAndNullValuesAndPopulatedValues(); var xml = new XmlDeserializer(); var output = xml.Deserialize<NullableValues>(new() { Content = doc })!; Assert.Null(output.Id); Assert.Null(output.StartDate); Assert.Equal(new Guid(GuidString), output.UniqueId); } [Fact] public void Can_Deserialize_Names_With_Dashes_On_Default_Root() { var doc = CreateDashesXml(); var response = new RestResponse { Content = doc }; var d = new XmlDeserializer(); var p = d.Deserialize<PersonForXml>(response)!; Assert.Equal("John Sheehan", p.Name); Assert.Equal(new(2009, 9, 25, 0, 6, 1), p.StartDate); Assert.Equal(28, p.Age); Assert.Equal(long.MaxValue, p.BigNumber); Assert.Equal(99.9999m, p.Percent); Assert.False(p.IsCool); Assert.Equal(new(GuidString), p.UniqueId); Assert.Equal(new("https://example.com", UriKind.RelativeOrAbsolute), p.Url); Assert.Equal(new("/foo/bar", UriKind.RelativeOrAbsolute), p.UrlPath); Assert.NotNull(p.Friends); Assert.Equal(10, p.Friends.Count); Assert.NotNull(p.BestFriend); Assert.Equal("The Fonz", p.BestFriend.Name); Assert.Equal(1952, p.BestFriend.Since); Assert.NotNull(p.Foes); Assert.Equal(5, p.Foes.Count); Assert.Equal("Yankees", p.Foes.Team); } [Fact] public void Can_Deserialize_Names_With_Underscores_On_Default_Root() { var doc = CreateUnderscoresXml(); var response = new RestResponse { Content = doc }; var d = new XmlDeserializer(); var p = d.Deserialize<PersonForXml>(response)!; Assert.Equal("John Sheehan", p.Name); Assert.Equal(new(2009, 9, 25, 0, 6, 1), p.StartDate); Assert.Equal(28, p.Age); Assert.Equal(long.MaxValue, p.BigNumber); Assert.Equal(99.9999m, p.Percent); Assert.False(p.IsCool); Assert.Equal(new(GuidString), p.UniqueId); Assert.Equal(new("https://example.com", UriKind.RelativeOrAbsolute), p.Url); Assert.Equal(new("/foo/bar", UriKind.RelativeOrAbsolute), p.UrlPath); Assert.NotNull(p.Friends); Assert.Equal(10, p.Friends.Count); Assert.NotNull(p.BestFriend); Assert.Equal("The Fonz", p.BestFriend.Name); Assert.Equal(1952, p.BestFriend.Since); Assert.NotNull(p.Foes); Assert.Equal(5, p.Foes.Count); Assert.Equal("Yankees", p.Foes.Team); } [Fact] public void Can_Deserialize_Names_With_Underscores_Without_Matching_Case_On_Default_Root() { var doc = CreateLowercaseUnderscoresXml(); var response = new RestResponse { Content = doc }; var d = new XmlDeserializer(); var p = d.Deserialize<PersonForXml>(response)!; Assert.Equal("John Sheehan", p.Name); Assert.Equal(new(2009, 9, 25, 0, 6, 1), p.StartDate); Assert.Equal(28, p.Age); Assert.Equal(long.MaxValue, p.BigNumber); Assert.Equal(99.9999m, p.Percent); Assert.False(p.IsCool); Assert.Equal(new(GuidString), p.UniqueId); Assert.Equal(new("https://example.com", UriKind.RelativeOrAbsolute), p.Url); Assert.Equal(new("/foo/bar", UriKind.RelativeOrAbsolute), p.UrlPath); Assert.NotNull(p.Friends); Assert.Equal(10, p.Friends.Count); Assert.NotNull(p.BestFriend); Assert.Equal("The Fonz", p.BestFriend.Name); Assert.Equal(1952, p.BestFriend.Since); Assert.NotNull(p.Foes); Assert.Equal(5, p.Foes.Count); Assert.Equal("Yankees", p.Foes.Team); } [Fact] public void Can_Deserialize_Nested_List_Items_With_Matching_Class_Name() { var xmlFilePath = PathFor("NestedListSample.xml"); var doc = XDocument.Load(xmlFilePath); var xml = new XmlDeserializer(); var output = xml.Deserialize<InlineListSample>(new() { Content = doc.ToString() })!; Assert.Equal(4, output.images.Count); } [Fact] public void Can_Deserialize_Nested_List_Items_Without_Matching_Class_Name() { var xmlFilePath = PathFor("NestedListSample.xml"); var doc = XDocument.Load(xmlFilePath); var xml = new XmlDeserializer(); var output = xml.Deserialize<InlineListSample>(new() { Content = doc.ToString() })!; Assert.Equal(4, output.Images.Count); } [Fact] public void Can_Deserialize_Nested_List_Without_Elements_To_Empty_List() { var doc = CreateXmlWithEmptyNestedList(); var xml = new XmlDeserializer(); var output = xml.Deserialize<EmptyListSample>(new() { Content = doc })!; Assert.NotNull(output.Images); Assert.Empty(output.Images); } [Fact] public void Can_Deserialize_Node_That_Has_Attribute_And_Content() { var doc = CreateNoteXml(); var response = new RestResponse { Content = doc }; var d = new XmlDeserializer(); var note = d.Deserialize<Note>(response)!; Assert.Equal(1, note.Id); Assert.Equal(Note.ConstTitle, note.Title); Assert.Equal(Note.ConstMessage, note.Message); } [Fact] public void Can_Deserialize_Node_Using_Exact_Name_Defined_In_DeserializeAs_Attribute() { const string content = "<response><node-value>711</node-value></response>"; var expected = new SingleNode { Node = "711" }; var xml = new XmlDeserializer(); var output = xml.Deserialize<SingleNode>(new() { Content = content })!; Assert.NotNull(output); Assert.Equal(expected.Node, output.Node); } [Fact] public void Can_Deserialize_Parentless_aka_Inline_List_Items_With_Matching_Class_Name() { var xmlFilePath = PathFor("InlineListSample.xml"); var doc = XDocument.Load(xmlFilePath); var xml = new XmlDeserializer(); var output = xml.Deserialize<InlineListSample>(new() { Content = doc.ToString() })!; Assert.Equal(4, output.images.Count); } [Fact] public void Can_Deserialize_Parentless_aka_Inline_List_Items_With_Matching_Class_Name_With_Additional_Property() { var xmlFilePath = PathFor("InlineListSample.xml"); var doc = XDocument.Load(xmlFilePath); var xml = new XmlDeserializer(); var output = xml.Deserialize<InlineListSample>(new() { Content = doc.ToString() })!; Assert.Equal(4, output.Count); } [Fact] public void Can_Deserialize_Parentless_aka_Inline_List_Items_Without_Matching_Class_Name() { var xmlFilePath = PathFor("InlineListSample.xml"); var doc = XDocument.Load(xmlFilePath); var xml = new XmlDeserializer(); var output = xml.Deserialize<InlineListSample>(new() { Content = doc.ToString() })!; Assert.Equal(4, output.Images.Count); } [Fact] public void Can_Deserialize_Root_Elements_Without_Matching_Case_And_Dashes() { var doc = CreateLowerCasedRootElementWithDashesXml(); var response = new RestResponse { Content = doc }; var d = new XmlDeserializer(); var p = d.Deserialize<List<IncomingInvoice>>(response)!; Assert.NotNull(p); Assert.Single(p); Assert.Equal(45, p[0].ConceptId); } [Fact] public void Can_Deserialize_TimeSpan() { var culture = CultureInfo.InvariantCulture; var doc = new XDocument(culture); TimeSpan? nullable = new TimeSpan(21, 30, 7); var root = new XElement("Person"); root.Add(new XElement("Tick", new TimeSpan(468006))); root.Add(new XElement("Millisecond", new TimeSpan(0, 0, 0, 0, 125))); root.Add(new XElement("Second", new TimeSpan(0, 0, 8))); root.Add(new XElement("Minute", new TimeSpan(0, 55, 2))); root.Add(new XElement("Hour", new TimeSpan(21, 30, 7))); root.Add(new XElement("NullableWithoutValue", (TimeSpan?)null)); root.Add(new XElement("NullableWithValue", nullable)); doc.Add(root); var response = new RestResponse { Content = doc.ToString() }; var d = new XmlDeserializer { Culture = culture }; var payload = d.Deserialize<TimeSpanTestStructure>(response)!; Assert.Equal(new(468006), payload.Tick); Assert.Equal(new(0, 0, 0, 0, 125), payload.Millisecond); Assert.Equal(new(0, 0, 8), payload.Second); Assert.Equal(new(0, 55, 2), payload.Minute); Assert.Equal(new(21, 30, 7), payload.Hour); Assert.Null(payload.NullableWithoutValue); Assert.NotNull(payload.NullableWithValue); Assert.Equal(new(21, 30, 7), payload.NullableWithValue.Value); } [Fact] public void Can_Deserialize_To_List_Inheritor_From_Custom_Root_With_Attributes() { var xmlFilePath = PathFor("ListWithAttributes.xml"); var doc = XDocument.Load(xmlFilePath); var xml = new XmlDeserializer { RootElement = "Calls" }; var output = xml.Deserialize<TwilioCallList>(new() { Content = doc.ToString() })!; Assert.Equal(3, output.NumPages); Assert.Equal(2, output.Count); } [Fact] public void Can_Deserialize_To_Standalone_List_With_Matching_Class_Case() { var xmlFilePath = PathFor("InlineListSample.xml"); var doc = XDocument.Load(xmlFilePath); var xml = new XmlDeserializer(); var output = xml.Deserialize<List<image>>(new() { Content = doc.ToString() })!; Assert.Equal(4, output.Count); } [Fact] public void Can_Deserialize_To_Standalone_List_Without_Matching_Class_Case() { var xmlFilePath = PathFor("InlineListSample.xml"); var doc = XDocument.Load(xmlFilePath); var xml = new XmlDeserializer(); var output = xml.Deserialize<List<Image>>(new() { Content = doc.ToString() })!; Assert.Equal(4, output.Count); } [Fact] public void Can_Deserialize_When_RootElement_Deeper_Then_One() { const string content = "<root><subroot><subsubroot><one>oneOneOne</one><two>twoTwoTwo</two><three>3</three></subsubroot></subroot></root>"; var xml = new XmlDeserializer { RootElement = "subsubroot" }; var output = xml.Deserialize<SimpleStruct>(new() { Content = content }); Assert.Equal("oneOneOne", output.One); Assert.Equal("twoTwoTwo", output.Two); Assert.Equal(3, output.Three); } [Fact] public void Can_Use_DeserializeAs_Attribute() { const string content = "<oddball><sid>1</sid><friendlyName>Jackson</friendlyName><oddballPropertyName>oddball</oddballPropertyName></oddball>"; var xml = new XmlDeserializer(); var output = xml.Deserialize<Oddball>(new() { Content = content })!; Assert.NotNull(output); Assert.Equal("1", output.Sid); Assert.Equal("Jackson", output.FriendlyName); Assert.Equal("oddball", output.GoodPropertyName); } [Fact] public void Can_Use_DeserializeAs_Attribute_for_List() { var xmlFilePath = PathFor("deserialize_as_list.xml"); var doc = XDocument.Load(xmlFilePath); var xml = new XmlDeserializer(); var output = xml.Deserialize<List<Oddball>>(new() { Content = doc.ToString() })!; Assert.NotNull(output); Assert.Equal("1", output[0].Sid); } [Fact] public void Can_Use_DeserializeAs_Attribute_for_List_Property() { const string content = "<oddball><oddballListName><item>TestValue</item></oddballListName></oddball>"; var xml = new XmlDeserializer(); var output = xml.Deserialize<Oddball>(new() { Content = content })!; Assert.NotNull(output); Assert.NotNull(output.ListWithGoodName); Assert.NotEmpty(output.ListWithGoodName); } [Fact] public void Cannot_Deserialize_Node_To_An_Object_That_Has_Two_Properties_With_Text_Content_Attributes() { var doc = CreateNoteXml(); var response = new RestResponse { Content = doc }; var d = new XmlDeserializer(); Assert.Throws<ArgumentException>(() => d.Deserialize<WrongNote>(response)); } [Fact] public void Ignore_Protected_Property_That_Exists_In_Data() { var doc = CreateElementsXml(); var response = new RestResponse { Content = doc }; var d = new XmlDeserializer(); var p = d.Deserialize<PersonForXml>(response)!; Assert.Null(p.IgnoreProxy); } [Fact] public void Ignore_ReadOnly_Property_That_Exists_In_Data() { var doc = CreateElementsXml(); var response = new RestResponse { Content = doc }; var d = new XmlDeserializer(); var p = d.Deserialize<PersonForXml>(response)!; Assert.Null(p.ReadOnlyProxy); } }
RestSharp
You are an expert .NET (C#) developer. Task: Write a unit test for 'DotNetXmlDeserializer' using XUnit and Moq. Context: - Class: DotNetXmlDeserializer Requirements: Use Mock<T> interface mocking.
industrial
// Copyright (c) .NET Foundation and Contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.Reflection; using System.Xml.Linq; using RestSharp.Extensions; namespace RestSharp.Serializers.Xml; public class XmlAttributeDeserializer : XmlDeserializer { protected override object? GetValueFromXml(XElement? root, XName? name, PropertyInfo prop, bool useExactName) { var isAttribute = false; //Check for the DeserializeAs attribute on the property var options = prop.GetAttribute<DeserializeAsAttribute>(); if (options != null) { name = options.Name ?? name; isAttribute = options.Attribute; } if (!isAttribute) return base.GetValueFromXml(root, name, prop, useExactName); var attributeVal = GetAttributeByName(root!, name!, useExactName); return attributeVal?.Value ?? base.GetValueFromXml(root, name, prop, useExactName); } }
using System.Globalization; using System.Xml.Linq; using RestSharp.Serializers.Xml; using RestSharp.Tests.Serializers.Xml.SampleClasses; namespace RestSharp.Tests.Serializers.Xml; public class XmlAttributeDeserializerTests { const string GuidString = "AC1FC4BC-087A-4242-B8EE-C53EBE9887A5"; #if NET readonly string _sampleDataPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SampleData"); #else readonly string _sampleDataPath = Path.Combine(Directory.GetCurrentDirectory(), "SampleData"); #endif string PathFor(string sampleFile) => Path.Combine(_sampleDataPath, sampleFile); [Fact] public void Can_Deserialize_Lists_of_Simple_Types() { var xmlPath = PathFor("xmllists.xml"); var doc = XDocument.Load(xmlPath); var xml = new XmlAttributeDeserializer(); var output = xml.Deserialize<SimpleTypesListSample>(new() { Content = doc.ToString() })!; Assert.NotEmpty(output.Numbers); Assert.NotEqual(0, output.Names[0].Length); Assert.NotEqual(0, output.Numbers.Sum()); } [Fact] public void Can_Deserialize_To_List_Inheritor_From_Custom_Root_With_Attributes() { var xmlPath = PathFor("ListWithAttributes.xml"); var doc = XDocument.Load(xmlPath); var xml = new XmlAttributeDeserializer { RootElement = "Calls" }; var output = xml.Deserialize<TwilioCallList>(new() { Content = doc.ToString() })!; Assert.Equal(3, output.NumPages); Assert.Equal(2, output.Count); } [Fact] public void Can_Deserialize_To_Standalone_List_Without_Matching_Class_Case() { var xmlPath = PathFor("InlineListSample.xml"); var doc = XDocument.Load(xmlPath); var xml = new XmlAttributeDeserializer(); var output = xml.Deserialize<List<Image>>(new() { Content = doc.ToString() })!; Assert.Equal(4, output.Count); } [Fact] public void Can_Deserialize_To_Standalone_List_With_Matching_Class_Case() { var xmlPath = PathFor("InlineListSample.xml"); var doc = XDocument.Load(xmlPath); var xml = new XmlAttributeDeserializer(); var output = xml.Deserialize<List<image>>(new() { Content = doc.ToString() })!; Assert.Equal(4, output.Count); } [Fact] public void Can_Deserialize_Directly_To_Lists_Off_Root_Element() { var xmlPath = PathFor("directlists.xml"); var doc = XDocument.Load(xmlPath); var xml = new XmlAttributeDeserializer(); var output = xml.Deserialize<List<Database>>(new() { Content = doc.ToString() })!; Assert.Equal(2, output.Count); } [Fact] public void Can_Deserialize_Parentless_aka_Inline_List_Items_Without_Matching_Class_Name() { var xmlPath = PathFor("InlineListSample.xml"); var doc = XDocument.Load(xmlPath); var xml = new XmlAttributeDeserializer(); var output = xml.Deserialize<InlineListSample>(new() { Content = doc.ToString() })!; Assert.Equal(4, output.Images.Count); } [Fact] public void Can_Deserialize_Parentless_aka_Inline_List_Items_With_Matching_Class_Name() { var xmlpath = PathFor("InlineListSample.xml"); var doc = XDocument.Load(xmlpath); var xml = new XmlAttributeDeserializer(); var output = xml.Deserialize<InlineListSample>(new() { Content = doc.ToString() })!; Assert.Equal(4, output.images.Count); } [Fact] public void Can_Deserialize_Parentless_aka_Inline_List_Items_With_Matching_Class_Name_With_Additional_Property() { var xmlpath = PathFor("InlineListSample.xml"); var doc = XDocument.Load(xmlpath); var xml = new XmlAttributeDeserializer(); var output = xml.Deserialize<InlineListSample>(new() { Content = doc.ToString() })!; Assert.Equal(4, output.Count); } [Fact] public void Can_Deserialize_Nested_List_Items_Without_Matching_Class_Name() { var xmlpath = PathFor("NestedListSample.xml"); var doc = XDocument.Load(xmlpath); var xml = new XmlAttributeDeserializer(); var output = xml.Deserialize<InlineListSample>(new() { Content = doc.ToString() })!; Assert.Equal(4, output.Images.Count); } [Fact] public void Can_Deserialize_Nested_List_Items_With_Matching_Class_Name() { var xmlpath = PathFor("NestedListSample.xml"); var doc = XDocument.Load(xmlpath); var xml = new XmlAttributeDeserializer(); var output = xml.Deserialize<InlineListSample>(new() { Content = doc.ToString() })!; Assert.Equal(4, output.images.Count); } [Fact] public void Can_Deserialize_Nested_List_Without_Elements_To_Empty_List() { var doc = CreateXmlWithEmptyNestedList(); var xml = new XmlAttributeDeserializer(); var output = xml.Deserialize<EmptyListSample>(new() { Content = doc })!; Assert.NotNull(output.Images); Assert.Empty(output.Images); } [Fact] public void Can_Deserialize_Inline_List_Without_Elements_To_Empty_List() { var doc = CreateXmlWithEmptyInlineList(); var xml = new XmlAttributeDeserializer(); var output = xml.Deserialize<EmptyListSample>(new() { Content = doc })!; Assert.NotNull(output.Images); Assert.Empty(output.Images); } [Fact] public void Can_Deserialize_Empty_Elements_to_Nullable_Values() { var doc = CreateXmlWithNullValues(); var xml = new XmlAttributeDeserializer(); var output = xml.Deserialize<NullableValues>(new() { Content = doc })!; Assert.Null(output.Id); Assert.Null(output.StartDate); Assert.Null(output.UniqueId); } [Fact] public void Can_Deserialize_Elements_to_Nullable_Values() { var culture = CultureInfo.InvariantCulture; var doc = CreateXmlWithoutEmptyValues(culture); var xml = new XmlAttributeDeserializer { Culture = culture }; var output = xml.Deserialize<NullableValues>(new() { Content = doc })!; Assert.NotNull(output.Id); Assert.NotNull(output.StartDate); Assert.NotNull(output.UniqueId); Assert.Equal(123, output.Id); Assert.Equal(new DateTime(2010, 2, 21, 9, 35, 00), output.StartDate); Assert.Equal(new Guid(GuidString), output.UniqueId); } [Fact] public void Can_Deserialize_TimeSpan() { var culture = CultureInfo.InvariantCulture; var doc = new XDocument(culture); TimeSpan? nullTimespan = null; TimeSpan? nullValueTimeSpan = new TimeSpan(21, 30, 7); var root = new XElement("Person"); root.Add(new XElement("Tick", new TimeSpan(468006))); root.Add(new XElement("Millisecond", new TimeSpan(0, 0, 0, 0, 125))); root.Add(new XElement("Second", new TimeSpan(0, 0, 8))); root.Add(new XElement("Minute", new TimeSpan(0, 55, 2))); root.Add(new XElement("Hour", new TimeSpan(21, 30, 7))); root.Add(new XElement("NullableWithoutValue", nullTimespan)); root.Add(new XElement("NullableWithValue", nullValueTimeSpan)); doc.Add(root); var response = new RestResponse { Content = doc.ToString() }; var d = new XmlAttributeDeserializer { Culture = culture }; var payload = d.Deserialize<TimeSpanTestStructure>(response)!; Assert.Equal(new(468006), payload.Tick); Assert.Equal(new(0, 0, 0, 0, 125), payload.Millisecond); Assert.Equal(new(0, 0, 8), payload.Second); Assert.Equal(new(0, 55, 2), payload.Minute); Assert.Equal(new(21, 30, 7), payload.Hour); Assert.Null(payload.NullableWithoutValue); Assert.NotNull(payload.NullableWithValue); Assert.Equal(new(21, 30, 7), payload.NullableWithValue.Value); } [Fact] public void Can_Deserialize_Custom_Formatted_Date() { const string format = "dd yyyy MMM, hh:mm ss tt zzz"; var culture = CultureInfo.InvariantCulture; var date = new DateTime(2010, 2, 8, 11, 11, 11); var doc = new XDocument(); var root = new XElement("Person"); root.Add(new XElement("StartDate", date.ToString(format, culture))); doc.Add(root); var xml = new XmlAttributeDeserializer { DateFormat = format, Culture = culture }; var response = new RestResponse { Content = doc.ToString() }; var output = xml.Deserialize<PersonForXml>(response)!; Assert.Equal(date, output.StartDate); } [Fact] public void Can_Deserialize_Nested_Class() { var doc = CreateElementsXml(); var response = new RestResponse { Content = doc }; var d = new XmlAttributeDeserializer(); var p = d.Deserialize<PersonForXml>(response); Assert.NotNull(p.FavoriteBand); Assert.Equal("Goldfinger", p.FavoriteBand.Name); } [Fact] public void Can_Deserialize_Elements_On_Default_Root() { var doc = CreateElementsXml(); var response = new RestResponse { Content = doc }; var d = new XmlAttributeDeserializer(); var p = d.Deserialize<PersonForXml>(response); Assert.Equal("John Sheehan", p.Name); Assert.Equal(new(2009, 9, 25, 0, 6, 1), p.StartDate); Assert.Equal(28, p.Age); Assert.Equal(long.MaxValue, p.BigNumber); Assert.Equal(99.9999m, p.Percent); Assert.False(p.IsCool); Assert.Equal(new(GuidString), p.UniqueId); Assert.Equal(Guid.Empty, p.EmptyGuid); Assert.Equal(new("http://example.com", UriKind.RelativeOrAbsolute), p.Url); Assert.Equal(new("/foo/bar", UriKind.RelativeOrAbsolute), p.UrlPath); Assert.Equal(Order.Third, p.Order); Assert.Equal(Disposition.SoSo, p.Disposition); Assert.NotNull(p.Friends); Assert.Equal(10, p.Friends.Count); Assert.NotNull(p.BestFriend); Assert.Equal("The Fonz", p.BestFriend.Name); Assert.Equal(1952, p.BestFriend.Since); } [Fact] public void Can_Deserialize_Attributes_On_Default_Root() { var doc = CreateAttributesXml(); var response = new RestResponse { Content = doc }; var d = new XmlAttributeDeserializer(); var p = d.Deserialize<PersonForXml>(response); Assert.Equal("John Sheehan", p.Name); Assert.Equal(new (2009, 9, 25, 0, 6, 1), p.StartDate); Assert.Equal(28, p.Age); Assert.Equal(long.MaxValue, p.BigNumber); Assert.Equal(99.9999m, p.Percent); Assert.False(p.IsCool); Assert.Equal(new (GuidString), p.UniqueId); Assert.Equal(new ("http://example.com", UriKind.RelativeOrAbsolute), p.Url); Assert.Equal(new ("/foo/bar", UriKind.RelativeOrAbsolute), p.UrlPath); Assert.NotNull(p.BestFriend); Assert.Equal("The Fonz", p.BestFriend.Name); Assert.Equal(1952, p.BestFriend.Since); } [Fact] public void Ignore_Protected_Property_That_Exists_In_Data() { var doc = CreateElementsXml(); var response = new RestResponse { Content = doc }; var d = new XmlAttributeDeserializer(); var p = d.Deserialize<PersonForXml>(response); Assert.Null(p.IgnoreProxy); } [Fact] public void Ignore_ReadOnly_Property_That_Exists_In_Data() { var doc = CreateElementsXml(); var response = new RestResponse { Content = doc }; var d = new XmlAttributeDeserializer(); var p = d.Deserialize<PersonForXml>(response); Assert.Null(p.ReadOnlyProxy); } [Fact] public void Can_Deserialize_Names_With_Underscores_On_Default_Root() { var doc = CreateUnderscoresXml(); var response = new RestResponse { Content = doc }; var d = new XmlAttributeDeserializer(); var p = d.Deserialize<PersonForXml>(response); Assert.Equal("John Sheehan", p.Name); Assert.Equal(new (2009, 9, 25, 0, 6, 1), p.StartDate); Assert.Equal(28, p.Age); Assert.Equal(long.MaxValue, p.BigNumber); Assert.Equal(99.9999m, p.Percent); Assert.False(p.IsCool); Assert.Equal(new (GuidString), p.UniqueId); Assert.Equal(new ("http://example.com", UriKind.RelativeOrAbsolute), p.Url); Assert.Equal(new ("/foo/bar", UriKind.RelativeOrAbsolute), p.UrlPath); Assert.NotNull(p.Friends); Assert.Equal(10, p.Friends.Count); Assert.NotNull(p.BestFriend); Assert.Equal("The Fonz", p.BestFriend.Name); Assert.Equal(1952, p.BestFriend.Since); Assert.NotNull(p.Foes); Assert.Equal(5, p.Foes.Count); Assert.Equal("Yankees", p.Foes.Team); } [Fact] public void Can_Deserialize_Names_With_Dashes_On_Default_Root() { var doc = CreateDashesXml(); var response = new RestResponse { Content = doc }; var d = new XmlAttributeDeserializer(); var p = d.Deserialize<PersonForXml>(response); Assert.Equal("John Sheehan", p.Name); Assert.Equal(new (2009, 9, 25, 0, 6, 1), p.StartDate); Assert.Equal(28, p.Age); Assert.Equal(long.MaxValue, p.BigNumber); Assert.Equal(99.9999m, p.Percent); Assert.False(p.IsCool); Assert.Equal(new (GuidString), p.UniqueId); Assert.Equal(new ("http://example.com", UriKind.RelativeOrAbsolute), p.Url); Assert.Equal(new ("/foo/bar", UriKind.RelativeOrAbsolute), p.UrlPath); Assert.NotNull(p.Friends); Assert.Equal(10, p.Friends.Count); Assert.NotNull(p.BestFriend); Assert.Equal("The Fonz", p.BestFriend.Name); Assert.Equal(1952, p.BestFriend.Since); Assert.NotNull(p.Foes); Assert.Equal(5, p.Foes.Count); Assert.Equal("Yankees", p.Foes.Team); } [Fact] public void Can_Deserialize_Names_With_Underscores_Without_Matching_Case_On_Default_Root() { var doc = CreateLowercaseUnderscoresXml(); var response = new RestResponse { Content = doc }; var d = new XmlAttributeDeserializer(); var p = d.Deserialize<PersonForXml>(response); Assert.Equal("John Sheehan", p.Name); Assert.Equal(new (2009, 9, 25, 0, 6, 1), p.StartDate); Assert.Equal(28, p.Age); Assert.Equal(long.MaxValue, p.BigNumber); Assert.Equal(99.9999m, p.Percent); Assert.False(p.IsCool); Assert.Equal(new (GuidString), p.UniqueId); Assert.Equal(new ("http://example.com", UriKind.RelativeOrAbsolute), p.Url); Assert.Equal(new ("/foo/bar", UriKind.RelativeOrAbsolute), p.UrlPath); Assert.NotNull(p.Friends); Assert.Equal(10, p.Friends.Count); Assert.NotNull(p.BestFriend); Assert.Equal("The Fonz", p.BestFriend.Name); Assert.Equal(1952, p.BestFriend.Since); Assert.NotNull(p.Foes); Assert.Equal(5, p.Foes.Count); Assert.Equal("Yankees", p.Foes.Team); } [Fact] public void Can_Deserialize_Lower_Cased_Root_Elements_With_Dashes() { var doc = CreateDashesXml(); var response = new RestResponse { Content = doc }; var d = new XmlAttributeDeserializer(); var p = d.Deserialize<PersonForXml>(response); Assert.Equal("John Sheehan", p.Name); Assert.Equal(new (2009, 9, 25, 0, 6, 1), p.StartDate); Assert.Equal(28, p.Age); Assert.Equal(long.MaxValue, p.BigNumber); Assert.Equal(99.9999m, p.Percent); Assert.False(p.IsCool); Assert.Equal(new (GuidString), p.UniqueId); Assert.Equal(new ("http://example.com", UriKind.RelativeOrAbsolute), p.Url); Assert.Equal(new ("/foo/bar", UriKind.RelativeOrAbsolute), p.UrlPath); Assert.NotNull(p.Friends); Assert.Equal(10, p.Friends.Count); Assert.NotNull(p.BestFriend); Assert.Equal("The Fonz", p.BestFriend.Name); Assert.Equal(1952, p.BestFriend.Since); Assert.NotNull(p.Foes); Assert.Equal(5, p.Foes.Count); Assert.Equal("Yankees", p.Foes.Team); } [Fact] public void Can_Deserialize_Root_Elements_Without_Matching_Case_And_Dashes() { var doc = CreateLowerCasedRootElementWithDashesXml(); var response = new RestResponse { Content = doc }; var d = new XmlAttributeDeserializer(); var p = d.Deserialize<List<IncomingInvoice>>(response); Assert.NotNull(p); Assert.Single(p); Assert.Equal(45, p[0].ConceptId); } [Fact] public void Can_Deserialize_Eventful_Xml() { var xmlFilePath = PathFor("eventful.xml"); var doc = XDocument.Load(xmlFilePath); var response = new RestResponse { Content = doc.ToString() }; var d = new XmlAttributeDeserializer(); var output = d.Deserialize<VenueSearch>(response)!; Assert.Equal(3, output.venues.Count); Assert.Equal("Tivoli", output.venues[0].name); Assert.Equal("https://eventful.com/brisbane/venues/tivoli-/V0-001-002169294-8", output.venues[1].url); Assert.Equal("V0-001-000266914-3", output.venues[2].id); } [Fact] public void Can_Deserialize_Lastfm_Xml() { var xmlFilePath = PathFor("Lastfm.xml"); var doc = XDocument.Load(xmlFilePath); var response = new RestResponse { Content = doc.ToString() }; var d = new XmlAttributeDeserializer(); var output = d.Deserialize<Event>(response)!; Assert.Equal("https://www.last.fm/event/328799+Philip+Glass+at+Barbican+Centre+on+12+June+2008", output.url); Assert.Equal("https://www.last.fm/venue/8777860+Barbican+Centre", output.venue.url); } [Fact] public void Can_Deserialize_Google_Weather_Xml() { var xmlFilePath = PathFor("GoogleWeather.xml"); var doc = XDocument.Load(xmlFilePath); var response = new RestResponse { Content = doc.ToString() }; var d = new XmlAttributeDeserializer(); var output = d.Deserialize<xml_api_reply>(response)!; Assert.Equal(4, output.weather.Count); Assert.Equal("Sunny", output.weather[0].condition.data); } [Fact] public void Can_Deserialize_Google_Weather_Xml_WithDeserializeAs() { var xmlFilePath = PathFor("GoogleWeather.xml"); var doc = XDocument.Load(xmlFilePath); var response = new RestResponse { Content = doc.ToString() }; var d = new XmlAttributeDeserializer(); var output = d.Deserialize<GoogleWeatherApi>(response)!; Assert.Equal(4, output.Weather.Count); Assert.Equal("Sunny", output.Weather[0].Condition.Data); } [Fact] public void Can_Deserialize_Boolean_From_Number() { var xmlFilePath = PathFor("boolean_from_number.xml"); var doc = XDocument.Load(xmlFilePath); var response = new RestResponse { Content = doc.ToString() }; var d = new XmlAttributeDeserializer(); var output = d.Deserialize<BooleanTest>(response)!; Assert.True(output.Value); } [Fact] public void Can_Deserialize_Boolean_From_String() { var xmlFilePath = PathFor("boolean_from_string.xml"); var doc = XDocument.Load(xmlFilePath); var response = new RestResponse { Content = doc.ToString() }; var d = new XmlAttributeDeserializer(); var output = d.Deserialize<BooleanTest>(response)!; Assert.True(output.Value); } [Fact] public void Can_Deserialize_Empty_Elements_With_Attributes_to_Nullable_Values() { var doc = CreateXmlWithAttributesAndNullValues(); var xml = new XmlAttributeDeserializer(); var output = xml.Deserialize<NullableValues>(new() { Content = doc })!; Assert.Null(output.Id); Assert.Null(output.StartDate); Assert.Null(output.UniqueId); } [Fact] public void Can_Deserialize_Mixture_Of_Empty_Elements_With_Attributes_And_Populated_Elements() { var doc = CreateXmlWithAttributesAndNullValuesAndPopulatedValues(); var xml = new XmlAttributeDeserializer(); var output = xml.Deserialize<NullableValues>(new RestResponse { Content = doc })!; Assert.Null(output.Id); Assert.Null(output.StartDate); Assert.Equal(new Guid(GuidString), output.UniqueId); } [Fact] public void Can_Deserialize_DateTimeOffset() { var culture = CultureInfo.InvariantCulture; var doc = new XDocument(culture); var dateTimeOffset = new DateTimeOffset(2013, 02, 08, 9, 18, 22, TimeSpan.FromHours(10)); DateTimeOffset? nullableDateTimeOffsetWithValue = new DateTimeOffset(2013, 02, 08, 9, 18, 23, TimeSpan.FromHours(10)); var root = new XElement("Dates"); root.Add(new XElement("DateTimeOffset", dateTimeOffset)); root.Add(new XElement("NullableDateTimeOffsetWithNull", string.Empty)); root.Add(new XElement("NullableDateTimeOffsetWithValue", nullableDateTimeOffsetWithValue)); doc.Add(root); //var xml = new XmlAttributeDeserializer { Culture = culture }; var response = new RestResponse { Content = doc.ToString() }; var d = new XmlAttributeDeserializer { Culture = culture }; var payload = d.Deserialize<DateTimeTestStructure>(response)!; Assert.Equal(dateTimeOffset, payload.DateTimeOffset); Assert.Null(payload.NullableDateTimeOffsetWithNull); Assert.True(payload.NullableDateTimeOffsetWithValue.HasValue); Assert.Equal(nullableDateTimeOffsetWithValue, payload.NullableDateTimeOffsetWithValue); } static string CreateUnderscoresXml() { var doc = new XDocument(); var root = new XElement("Person"); root.Add(new XElement("Name", "John Sheehan")); root.Add(new XElement("Start_Date", new DateTime(2009, 9, 25, 0, 6, 1))); root.Add(new XAttribute("Age", 28)); root.Add(new XElement("Percent", 99.9999m)); root.Add(new XElement("Big_Number", long.MaxValue)); root.Add(new XAttribute("Is_Cool", false)); root.Add(new XElement("Ignore", "dummy")); root.Add(new XAttribute("Read_Only", "dummy")); root.Add(new XElement("Unique_Id", new Guid(GuidString))); root.Add(new XElement("Url", "http://example.com")); root.Add(new XElement("Url_Path", "/foo/bar")); root.Add( new XElement( "Best_Friend", new XElement("Name", "The Fonz"), new XAttribute("Since", 1952) ) ); var friends = new XElement("Friends"); for (var i = 0; i < 10; i++) { friends.Add( new XElement( "Friend", new XElement("Name", "Friend" + i), new XAttribute("Since", DateTime.Now.Year - i) ) ); } root.Add(friends); var foes = new XElement("Foes"); foes.Add(new XAttribute("Team", "Yankees")); for (var i = 0; i < 5; i++) foes.Add(new XElement("Foe", new XElement("Nickname", "Foe" + i))); root.Add(foes); doc.Add(root); return doc.ToString(); } static string CreateLowercaseUnderscoresXml() { var doc = new XDocument(); var root = new XElement("Person"); root.Add(new XElement("Name", "John Sheehan")); root.Add(new XElement("start_date", new DateTime(2009, 9, 25, 0, 6, 1))); root.Add(new XAttribute("Age", 28)); root.Add(new XElement("Percent", 99.9999m)); root.Add(new XElement("big_number", long.MaxValue)); root.Add(new XAttribute("is_cool", false)); root.Add(new XElement("Ignore", "dummy")); root.Add(new XAttribute("read_only", "dummy")); root.Add(new XElement("unique_id", new Guid(GuidString))); root.Add(new XElement("Url", "http://example.com")); root.Add(new XElement("url_path", "/foo/bar")); root.Add( new XElement( "best_friend", new XElement("name", "The Fonz"), new XAttribute("Since", 1952) ) ); var friends = new XElement("Friends"); for (var i = 0; i < 10; i++) { friends.Add( new XElement( "Friend", new XElement("Name", "Friend" + i), new XAttribute("Since", DateTime.Now.Year - i) ) ); } root.Add(friends); var foes = new XElement("Foes"); foes.Add(new XAttribute("Team", "Yankees")); for (var i = 0; i < 5; i++) foes.Add(new XElement("Foe", new XElement("Nickname", "Foe" + i))); root.Add(foes); doc.Add(root); return doc.ToString(); } static string CreateDashesXml() { var doc = new XDocument(); var root = new XElement("Person"); root.Add(new XElement("Name", "John Sheehan")); root.Add(new XElement("Start_Date", new DateTime(2009, 9, 25, 0, 6, 1))); root.Add(new XAttribute("Age", 28)); root.Add(new XElement("Percent", 99.9999m)); root.Add(new XElement("Big-Number", long.MaxValue)); root.Add(new XAttribute("Is-Cool", false)); root.Add(new XElement("Ignore", "dummy")); root.Add(new XAttribute("Read-Only", "dummy")); root.Add(new XElement("Unique-Id", new Guid(GuidString))); root.Add(new XElement("Url", "http://example.com")); root.Add(new XElement("Url-Path", "/foo/bar")); root.Add( new XElement( "Best-Friend", new XElement("Name", "The Fonz"), new XAttribute("Since", 1952) ) ); var friends = new XElement("Friends"); for (var i = 0; i < 10; i++) { friends.Add( new XElement( "Friend", new XElement("Name", "Friend" + i), new XAttribute("Since", DateTime.Now.Year - i) ) ); } root.Add(friends); var foes = new XElement("Foes"); foes.Add(new XAttribute("Team", "Yankees")); for (var i = 0; i < 5; i++) foes.Add(new XElement("Foe", new XElement("Nickname", "Foe" + i))); root.Add(foes); doc.Add(root); return doc.ToString(); } static string CreateLowerCasedRootElementWithDashesXml() { var doc = new XDocument(); var root = new XElement( "incoming-invoices", new XElement( "incoming-invoice", new XElement("concept-id", 45) ) ); doc.Add(root); return doc.ToString(); } static string CreateElementsXml() { var doc = new XDocument(); var root = new XElement("Person"); root.Add(new XElement("Name", "John Sheehan")); root.Add(new XElement("StartDate", new DateTime(2009, 9, 25, 0, 6, 1))); root.Add(new XElement("Age", 28)); root.Add(new XElement("Percent", 99.9999m)); root.Add(new XElement("BigNumber", long.MaxValue)); root.Add(new XElement("IsCool", false)); root.Add(new XElement("Ignore", "dummy")); root.Add(new XElement("ReadOnly", "dummy")); root.Add(new XElement("UniqueId", new Guid(GuidString))); root.Add(new XElement("EmptyGuid", "")); root.Add(new XElement("Url", "http://example.com")); root.Add(new XElement("UrlPath", "/foo/bar")); root.Add(new XElement("Order", "third")); root.Add(new XElement("Disposition", "so-so")); root.Add( new XElement( "BestFriend", new XElement("Name", "The Fonz"), new XElement("Since", 1952) ) ); var friends = new XElement("Friends"); for (var i = 0; i < 10; i++) { friends.Add( new XElement( "Friend", new XElement("Name", "Friend" + i), new XElement("Since", DateTime.Now.Year - i) ) ); } root.Add(friends); root.Add( new XElement( "FavoriteBand", new XElement("Name", "Goldfinger") ) ); doc.Add(root); return doc.ToString(); } static string CreateAttributesXml() { var doc = new XDocument(); var root = new XElement("Person"); root.Add(new XAttribute("Name", "John Sheehan")); root.Add(new XAttribute("StartDate", new DateTime(2009, 9, 25, 0, 6, 1))); root.Add(new XAttribute("Age", 28)); root.Add(new XAttribute("Percent", 99.9999m)); root.Add(new XAttribute("BigNumber", long.MaxValue)); root.Add(new XAttribute("IsCool", false)); root.Add(new XAttribute("Ignore", "dummy")); root.Add(new XAttribute("ReadOnly", "dummy")); root.Add(new XAttribute("UniqueId", new Guid(GuidString))); root.Add(new XAttribute("Url", "http://example.com")); root.Add(new XAttribute("UrlPath", "/foo/bar")); root.Add( new XElement( "BestFriend", new XAttribute("Name", "The Fonz"), new XAttribute("Since", 1952) ) ); doc.Add(root); return doc.ToString(); } static string CreateXmlWithNullValues() { var doc = new XDocument(); var root = new XElement("NullableValues"); root.Add( new XElement("Id", null), new XElement("StartDate", null), new XElement("UniqueId", null) ); doc.Add(root); return doc.ToString(); } static string CreateXmlWithoutEmptyValues(CultureInfo culture) { var doc = new XDocument(); var root = new XElement("NullableValues"); root.Add( new XElement("Id", 123), new XElement("StartDate", new DateTime(2010, 2, 21, 9, 35, 00).ToString(culture)), new XElement("UniqueId", new Guid(GuidString)) ); doc.Add(root); return doc.ToString(); } static string CreateXmlWithEmptyNestedList() { var doc = new XDocument(); var root = new XElement("EmptyListSample"); root.Add(new XElement("Images")); doc.Add(root); return doc.ToString(); } static string CreateXmlWithEmptyInlineList() { var doc = new XDocument(); var root = new XElement("EmptyListSample"); doc.Add(root); return doc.ToString(); } static string CreateXmlWithAttributesAndNullValues() { var doc = new XDocument(); var root = new XElement("NullableValues"); var idElement = new XElement("Id", null); idElement.SetAttributeValue("SomeAttribute", "SomeAttribute_Value"); root.Add( idElement, new XElement("StartDate", null), new XElement("UniqueId", null) ); doc.Add(root); return doc.ToString(); } static string CreateXmlWithAttributesAndNullValuesAndPopulatedValues() { var doc = new XDocument(); var root = new XElement("NullableValues"); var idElement = new XElement("Id", null); idElement.SetAttributeValue("SomeAttribute", "SomeAttribute_Value"); root.Add( idElement, new XElement("StartDate", null), new XElement("UniqueId", new Guid(GuidString)) ); doc.Add(root); return doc.ToString(); } }
RestSharp
You are an expert .NET (C#) developer. Task: Write a unit test for 'XmlAttributeDeserializer' using XUnit and Moq. Context: - Class: XmlAttributeDeserializer Requirements: Use Mock<T> interface mocking.
industrial
// Copyright (c) .NET Foundation and Contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace RestSharp.Serializers.Xml; public interface IXmlSerializer : ISerializer { string? Namespace { get; set; } }
using System.Globalization; using System.Xml.Linq; using RestSharp.Serializers; using RestSharp.Serializers.Xml; using RestSharp.Tests.Serializers.Xml.SampleClasses; namespace RestSharp.Tests.Serializers.Xml; public class XmlSerializerTests { public XmlSerializerTests() { Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; Thread.CurrentThread.CurrentUICulture = CultureInfo.InstalledUICulture; } [Fact] public void Can_serialize_a_list_of_items_with_interface_type() { var items = new NamedItems { Items = [ new Person { Name = "Foo", Age = 50, Price = 19.95m, StartDate = new(2009, 12, 18, 10, 2, 23), Items = [new() { Name = "One", Value = 1 }] }, new Item { Name = "Two", Value = 2 }, new Item { Name = "Three", Value = 3 } ] }; var xml = new XmlSerializer(); var doc = xml.Serialize(items); var expected = GetNamedItemsXDoc(CultureInfo.InvariantCulture); Assert.Equal(expected.ToString(), doc); } [Fact] public void Can_serialize_a_list_which_is_the_content_of_root_element() { var contacts = new Contacts { People = [ new() { Name = "Foo", Age = 50, Price = 19.95m, StartDate = new(2009, 12, 18, 10, 2, 23), Items = [ new() { Name = "One", Value = 1 }, new() { Name = "Two", Value = 2 }, new() { Name = "Three", Value = 3 } ] }, new() { Name = "Bar", Age = 23, Price = 23.23m, StartDate = new(2009, 12, 23, 10, 23, 23), Items = [ new() { Name = "One", Value = 1 }, new() { Name = "Two", Value = 2 }, new() { Name = "Three", Value = 3 } ] } ] }; var xml = new XmlSerializer(); var doc = xml.Serialize(contacts); var expected = GetPeopleXDoc(CultureInfo.InvariantCulture); Assert.Equal(expected.ToString(), doc); } [Fact] public void Can_serialize_a_list_which_is_the_root_element() { var pocoList = new PersonList { new() { Name = "Foo", Age = 50, Price = 19.95m, StartDate = new(2009, 12, 18, 10, 2, 23), Items = [ new() { Name = "One", Value = 1 }, new() { Name = "Two", Value = 2 }, new() { Name = "Three", Value = 3 } ] }, new() { Name = "Bar", Age = 23, Price = 23.23m, StartDate = new(2009, 12, 23, 10, 23, 23), Items = [ new() { Name = "One", Value = 1 }, new() { Name = "Two", Value = 2 }, new() { Name = "Three", Value = 3 } ] } }; var xml = new XmlSerializer(); var doc = xml.Serialize(pocoList); var expected = GetPeopleXDoc(CultureInfo.InvariantCulture); Assert.Equal(expected.ToString(), doc); } [Fact] public void Can_Serialize_An_Object_To_Node_With_Attribute_And_Text_Content() { var note = new Note { Id = 1, Title = Note.ConstTitle, Message = Note.ConstMessage }; var xml = new XmlSerializer(); var doc = xml.Serialize(note); var expected = GetNoteXDoc(); var expectedStr = expected.ToString(); Assert.Equal(expectedStr, doc); } [Fact] public void Can_serialize_Enum() { var enumClass = new ClassWithEnum { Color = Color.Red }; var xml = new XmlSerializer(); var doc = xml.Serialize(enumClass); var expected = new XDocument(); var root = new XElement("ClassWithEnum"); root.Add(new XElement("Color", "Red")); expected.Add(root); Assert.Equal(expected.ToString(), doc); } [Fact] public void Can_serialize_simple_POCO() { var poco = new Person { Name = "Foo", Age = 50, Price = 19.95m, StartDate = new(2009, 12, 18, 10, 2, 23), Items = [ new() { Name = "One", Value = 1 }, new() { Name = "Two", Value = 2 }, new() { Name = "Three", Value = 3 } ] }; var xml = new XmlSerializer(); var doc = xml.Serialize(poco); var expected = GetSimplePocoXDoc(); Assert.Equal(expected.ToString(), doc); } [Fact] public void Can_serialize_simple_POCO_With_Attribute_Options_Defined() { var poco = new WackyPerson { Name = "Foo", Age = 50, Price = 19.95m, StartDate = new(2009, 12, 18, 10, 2, 23) }; var xml = new XmlSerializer(); var doc = xml.Serialize(poco); var expected = GetSimplePocoXDocWackyNames(); Assert.Equal(expected.ToString(), doc); } [Fact] public void Can_serialize_simple_POCO_With_Attribute_Options_Defined_And_Property_Containing_IList_Elements() { var poco = new WackyPerson { Name = "Foo", Age = 50, Price = 19.95m, StartDate = new(2009, 12, 18, 10, 2, 23), ContactData = new() { EmailAddresses = [ new() { Address = "[email protected]", Location = "Work" } ] } }; var xml = new XmlSerializer(); var doc = xml.Serialize(poco); var expected = GetSimplePocoXDocWackyNamesWithIListProperty(); Assert.Equal(expected.ToString(), doc); } [Fact] public void Can_serialize_simple_POCO_With_DateFormat_Specified() { var poco = new Person { Name = "Foo", Age = 50, Price = 19.95m, StartDate = new(2009, 12, 18, 10, 2, 23) }; var xml = new XmlSerializer { DateFormat = DateFormat.ISO_8601 }; var doc = xml.Serialize(poco); var expected = GetSimplePocoXDocWithIsoDate(); Assert.Equal(expected.ToString(), doc); } [Fact] public void Can_serialize_simple_POCO_With_Different_Root_Element() { var poco = new Person { Name = "Foo", Age = 50, Price = 19.95m, StartDate = new(2009, 12, 18, 10, 2, 23) }; var xml = new XmlSerializer { RootElement = "Result" }; var doc = xml.Serialize(poco); var expected = GetSimplePocoXDocWithRoot(); Assert.Equal(expected.ToString(), doc); } [Fact] public void Can_serialize_simple_POCO_With_XmlFormat_Specified() { var poco = new Person { Name = "Foo", Age = 50, Price = 19.95m, StartDate = new(2009, 12, 18, 10, 2, 23), IsCool = false }; var xml = new XmlSerializer { DateFormat = DateFormat.ISO_8601 }; var doc = xml.Serialize(poco); var expected = GetSimplePocoXDocWithXmlProperty(); Assert.Equal(expected.ToString(), doc); } [Fact] public void Cannot_Serialize_An_Object_With_Two_Properties_With_Text_Content_Attributes() { var note = new WrongNote { Id = 1, Text = "What a note." }; var xml = new XmlSerializer(); Assert.Throws<ArgumentException>(() => xml.Serialize(note)); } [Fact] public void Serializes_Properties_In_Specified_Order() { var ordered = new OrderedProperties { Name = "Name", Age = 99, StartDate = new(2010, 1, 1) }; var xml = new XmlSerializer(); var doc = xml.Serialize(ordered); var expected = GetSortedPropsXDoc(); Assert.Equal(expected.ToString(), doc); } interface INamed { string Name { get; set; } } class Person : INamed { public string Name { get; set; } public int Age { get; set; } public decimal Price { get; set; } public DateTime StartDate { get; set; } public List<Item> Items { get; set; } public bool? IsCool { get; set; } } class Item : INamed { public string Name { get; set; } public int Value { get; set; } } enum Color { Red, Blue, Green } class ClassWithEnum { public Color Color { get; set; } } [SerializeAs(Name = "Person")] class WackyPerson { [SerializeAs(Name = "WackyName", Attribute = true)] public string Name { get; set; } public int Age { get; set; } [SerializeAs(Attribute = true)] public decimal Price { get; set; } [SerializeAs(Name = "start_date", Attribute = true)] public DateTime StartDate { get; set; } [SerializeAs(Name = "contact-data")] public ContactData ContactData { get; set; } } class NamedItems { [SerializeAs(Content = true)] public List<INamed> Items { get; set; } } [SerializeAs(Name = "People")] class Contacts { [SerializeAs(Content = true)] public List<Person> People { get; set; } } [SerializeAs(Name = "People")] class PersonList : List<Person>; class ContactData { [SerializeAs(Name = "email-addresses")] public List<EmailAddress> EmailAddresses { get; set; } = []; } [SerializeAs(Name = "email-address")] class EmailAddress { [SerializeAs(Name = "address")] public string Address { get; set; } [SerializeAs(Name = "location")] public string Location { get; set; } } static XDocument GetNoteXDoc() { var doc = new XDocument(); var root = new XElement("Note"); root.SetAttributeValue("Id", 1); root.Value = Note.ConstMessage; root.Add(new XElement("Title", Note.ConstTitle)); doc.Add(root); return doc; } static XDocument GetSimplePocoXDoc() { var doc = new XDocument(); var root = new XElement("Person"); root.Add( new XElement("Name", "Foo"), new XElement("Age", 50), new XElement("Price", 19.95m), new XElement( "StartDate", new DateTime(2009, 12, 18, 10, 2, 23).ToString(CultureInfo.InvariantCulture) ) ); var items = new XElement("Items"); items.Add(new XElement("Item", new XElement("Name", "One"), new XElement("Value", 1))); items.Add(new XElement("Item", new XElement("Name", "Two"), new XElement("Value", 2))); items.Add(new XElement("Item", new XElement("Name", "Three"), new XElement("Value", 3))); root.Add(items); doc.Add(root); return doc; } static XDocument GetSimplePocoXDocWithIsoDate() { var doc = new XDocument(); var root = new XElement("Person"); root.Add( new XElement("Name", "Foo"), new XElement("Age", 50), new XElement("Price", 19.95m), new XElement("StartDate", new DateTime(2009, 12, 18, 10, 2, 23).ToString("s")) ); doc.Add(root); return doc; } static XDocument GetSimplePocoXDocWithXmlProperty() { var doc = new XDocument(); var root = new XElement("Person"); root.Add( new XElement("Name", "Foo"), new XElement("Age", 50), new XElement("Price", 19.95m), new XElement("StartDate", new DateTime(2009, 12, 18, 10, 2, 23).ToString("s")), new XElement("IsCool", false) ); doc.Add(root); return doc; } static XDocument GetSimplePocoXDocWithRoot() { var doc = new XDocument(); var root = new XElement("Result"); var start = new XElement("Person"); start.Add( new XElement("Name", "Foo"), new XElement("Age", 50), new XElement("Price", 19.95m), new XElement( "StartDate", new DateTime(2009, 12, 18, 10, 2, 23).ToString(CultureInfo.InvariantCulture) ) ); root.Add(start); doc.Add(root); return doc; } static XDocument GetSimplePocoXDocWackyNames() { var doc = new XDocument(); var root = new XElement("Person"); root.Add( new XAttribute("WackyName", "Foo"), new XElement("Age", 50), new XAttribute("Price", 19.95m), new XAttribute( "start_date", new DateTime(2009, 12, 18, 10, 2, 23).ToString(CultureInfo.InvariantCulture) ) ); doc.Add(root); return doc; } static XDocument GetSimplePocoXDocWackyNamesWithIListProperty() { var doc = new XDocument(); var root = new XElement("Person"); root.Add( new XAttribute("WackyName", "Foo"), new XElement("Age", 50), new XAttribute("Price", 19.95m), new XAttribute( "start_date", new DateTime(2009, 12, 18, 10, 2, 23).ToString(CultureInfo.InvariantCulture) ), new XElement( "contact-data", new XElement( "email-addresses", new XElement( "email-address", new XElement("address", "[email protected]"), new XElement("location", "Work") ) ) ) ); doc.Add(root); return doc; } static XDocument GetSortedPropsXDoc() { var doc = new XDocument(); var root = new XElement("OrderedProperties"); root.Add(new XElement("StartDate", new DateTime(2010, 1, 1).ToString(CultureInfo.InvariantCulture))); root.Add(new XElement("Name", "Name")); root.Add(new XElement("Age", 99)); doc.Add(root); return doc; } static XDocument GetNamedItemsXDoc(IFormatProvider culture) { var doc = new XDocument(); var root = new XElement("NamedItems"); var element = new XElement("Person"); var items = new XElement("Items"); items.Add(new XElement("Item", new XElement("Name", "One"), new XElement("Value", 1))); element.Add( new XElement("Name", "Foo"), new XElement("Age", 50), new XElement("Price", 19.95m.ToString(culture)), new XElement("StartDate", new DateTime(2009, 12, 18, 10, 2, 23).ToString(culture)) ); element.Add(items); root.Add(element); root.Add(new XElement("Item", new XElement("Name", "Two"), new XElement("Value", 2))); root.Add(new XElement("Item", new XElement("Name", "Three"), new XElement("Value", 3))); doc.Add(root); return doc; } static XDocument GetPeopleXDoc(IFormatProvider culture) { var doc = new XDocument(); var root = new XElement("People"); var element = new XElement("Person"); var items = new XElement("Items"); items.Add(new XElement("Item", new XElement("Name", "One"), new XElement("Value", 1))); items.Add(new XElement("Item", new XElement("Name", "Two"), new XElement("Value", 2))); items.Add(new XElement("Item", new XElement("Name", "Three"), new XElement("Value", 3))); element.Add( new XElement("Name", "Foo"), new XElement("Age", 50), new XElement("Price", 19.95m.ToString(culture)), new XElement("StartDate", new DateTime(2009, 12, 18, 10, 2, 23).ToString(culture)) ); element.Add(items); root.Add(element); element = new("Person"); element.Add( new XElement("Name", "Bar"), new XElement("Age", 23), new XElement("Price", 23.23m.ToString(culture)), new XElement("StartDate", new DateTime(2009, 12, 23, 10, 23, 23).ToString(culture)) ); element.Add(items); root.Add(element); doc.Add(root); return doc; } }
RestSharp
You are an expert C++ developer. Task: Write a unit test for 'TargetModule' using GoogleTest (gtest) and GoogleMock (gmock). Context: - Class: TargetModule Requirements: Use EXPECT_CALL for virtual methods.
industrial
// Copyright (c) .NET Foundation and Contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // namespace RestSharp; public static partial class RestClientExtensions { /// <param name="client"></param> extension(IRestClient client) { /// <summary> /// Executes a POST-style request asynchronously, authenticating if needed. /// The response content then gets deserialized to T. /// </summary> /// <typeparam name="T">Target deserialization type</typeparam> /// <param name="request">Request to be executed</param> /// <param name="cancellationToken">The cancellation token</param> /// <returns>Deserialized response content</returns> public Task<RestResponse<T>> ExecutePostAsync<T>( RestRequest request, CancellationToken cancellationToken = default ) => client.ExecuteAsync<T>(request, Method.Post, cancellationToken); /// <summary> /// Executes a POST-style request synchronously, authenticating if needed. /// The response content then gets deserialized to T. /// </summary> /// <typeparam name="T">Target deserialization type</typeparam> /// <param name="request">Request to be executed</param> /// <returns>Deserialized response content</returns> public RestResponse<T> ExecutePost<T>(RestRequest request) => AsyncHelpers.RunSync(() => client.ExecuteAsync<T>(request, Method.Post)); /// <summary> /// Executes a POST-style asynchronously, authenticating if needed /// </summary> /// <param name="request">Request to be executed</param> /// <param name="cancellationToken">Cancellation token</param> public Task<RestResponse> ExecutePostAsync(RestRequest request, CancellationToken cancellationToken = default) => client.ExecuteAsync(request, Method.Post, cancellationToken); /// <summary> /// Executes a POST-style synchronously, authenticating if needed /// </summary> /// <param name="request">Request to be executed</param> public RestResponse ExecutePost(RestRequest request) => AsyncHelpers.RunSync(() => client.ExecuteAsync(request, Method.Post)); /// <summary> /// Execute the request using POST HTTP method. Exception will be thrown if the request does not succeed. /// The response data is deserialized to the Data property of the returned response object. /// </summary> /// <param name="request">The request</param> /// <param name="cancellationToken">Cancellation token</param> /// <typeparam name="T">Expected result type</typeparam> /// <returns></returns> public async Task<T?> PostAsync<T>(RestRequest request, CancellationToken cancellationToken = default) { var response = await client.ExecutePostAsync<T>(request, cancellationToken).ConfigureAwait(false); return response.ThrowIfError().Data; } /// <summary> /// Execute the request using POST HTTP method. Exception will be thrown if the request does not succeed. /// The response data is deserialized to the Data property of the returned response object. /// </summary> /// <param name="request">The request</param> /// <typeparam name="T">Expected result type</typeparam> /// <returns></returns> public T? Post<T>(RestRequest request) => AsyncHelpers.RunSync(() => client.PostAsync<T>(request)); /// <summary> /// Execute the request using POST HTTP method. Exception will be thrown if the request does not succeed. /// </summary> /// <param name="request">The request</param> /// <param name="cancellationToken">Cancellation token</param> /// <returns></returns> public async Task<RestResponse> PostAsync(RestRequest request, CancellationToken cancellationToken = default) { var response = await client.ExecutePostAsync(request, cancellationToken).ConfigureAwait(false); return response.ThrowIfError(); } /// <summary> /// Execute the request using POST HTTP method. Exception will be thrown if the request does not succeed. /// </summary> /// <param name="request">The request</param> /// <returns></returns> public RestResponse Post(RestRequest request) => AsyncHelpers.RunSync(() => client.PostAsync(request)); /// <summary> /// Serializes the <code>request</code> object to JSON and makes a POST call to the resource specified in the <code>resource</code> parameter. /// Expects a JSON response back, deserializes it to <code>TResponse</code> type and returns it. /// </summary> /// <param name="resource">Resource URL</param> /// <param name="request">Request object, must be serializable to JSON</param> /// <param name="cancellationToken">Cancellation token</param> /// <typeparam name="TRequest">Request object type</typeparam> /// <typeparam name="TResponse">Response object type</typeparam> /// <returns>Deserialized response object</returns> public Task<TResponse?> PostJsonAsync<TRequest, TResponse>( string resource, TRequest request, CancellationToken cancellationToken = default ) where TRequest : class { var restRequest = new RestRequest(resource).AddJsonBody(request); return client.PostAsync<TResponse>(restRequest, cancellationToken); } /// <summary> /// Serializes the <code>request</code> object to JSON and makes a POST call to the resource specified in the <code>resource</code> parameter. /// Expects a JSON response back, deserializes it to <code>TResponse</code> type and returns it. /// </summary> /// <param name="resource">Resource URL</param> /// <param name="request">Request object, must be serializable to JSON</param> /// <typeparam name="TRequest">Request object type</typeparam> /// <typeparam name="TResponse">Response object type</typeparam> /// <returns>Deserialized response object</returns> public TResponse? PostJson<TRequest, TResponse>(string resource, TRequest request) where TRequest : class => AsyncHelpers.RunSync(() => client.PostJsonAsync<TRequest, TResponse>(resource, request)); /// <summary> /// Serializes the <code>request</code> object to JSON and makes a POST call to the resource specified in the <code>resource</code> parameter. /// Expects no response back, just the status code. /// </summary> /// <param name="resource">Resource URL</param> /// <param name="request">Request object, must be serializable to JSON</param> /// <param name="cancellationToken">Cancellation token</param> /// <typeparam name="TRequest">Request object type</typeparam> /// <returns>Response status code</returns> public async Task<HttpStatusCode> PostJsonAsync<TRequest>( string resource, TRequest request, CancellationToken cancellationToken = default ) where TRequest : class { var restRequest = new RestRequest(resource).AddJsonBody(request); var response = await client.PostAsync(restRequest, cancellationToken).ConfigureAwait(false); return response.StatusCode; } /// <summary> /// Serializes the <code>request</code> object to JSON and makes a POST call to the resource specified in the <code>resource</code> parameter. /// Expects no response back, just the status code. /// </summary> /// <param name="resource">Resource URL</param> /// <param name="request">Request object, must be serializable to JSON</param> /// <typeparam name="TRequest">Request object type</typeparam> /// <returns>Response status code</returns> public HttpStatusCode PostJson<TRequest>(string resource, TRequest request) where TRequest : class => AsyncHelpers.RunSync(() => client.PostJsonAsync(resource, request)); } }
namespace RestSharp.Tests.Integrated; public sealed class PostTests(WireMockTestServer server) : IClassFixture<WireMockTestServer>, IDisposable { readonly RestClient _client = new(server.Url!); [Fact] public async Task Should_post_json() { var body = new TestRequest("foo", 100); var request = new RestRequest("post/json").AddJsonBody(body); var response = await _client.ExecutePostAsync<TestResponse>(request); response.Data!.Message.Should().Be(body.Data); } [Fact] public async Task Should_post_json_with_PostAsync() { var body = new TestRequest("foo", 100); var request = new RestRequest("post/json").AddJsonBody(body); var response = await _client.PostAsync<TestResponse>(request); response!.Message.Should().Be(body.Data); } [Fact] public async Task Should_post_json_with_PostJsonAsync() { var body = new TestRequest("foo", 100); var response = await _client.PostJsonAsync<TestRequest, TestResponse>("post/json", body); response!.Message.Should().Be(body.Data); } [Fact] public async Task Should_post_large_form_data() { const int length = 1024 * 1024; var superLongString = new string('?', length); var request = new RestRequest("post/form", Method.Post).AddParameter("big_string", superLongString); var response = await _client.ExecuteAsync<Response>(request); response.StatusCode.Should().Be(HttpStatusCode.OK); response.Data!.Message.Should().Be($"Works! Length: {length}"); } [Fact] public async Task Should_post_both_default_and_request_parameters() { var defParam = new PostParameter("default", "default"); var reqParam = new PostParameter("request", "request"); _client.AddDefaultParameter(defParam.Name, defParam.Value); var request = new RestRequest("post/data") .AddParameter(reqParam.Name, reqParam.Value); var response = await _client.ExecutePostAsync<TestServerResponse[]>(request); response.StatusCode.Should().Be(HttpStatusCode.OK); CheckResponse(defParam); CheckResponse(reqParam); return; void CheckResponse(PostParameter parameter) { var p = response.Data!.FirstOrDefault(x => x.Name == parameter.Name); p.Should().NotBeNull(); p!.Value.Should().Be(parameter.Value); } } class Response { public string Message { get; set; } = null!; } record PostParameter(string Name, string Value); public void Dispose() => _client.Dispose(); }
RestSharp
You are an expert C++ developer. Task: Write a unit test for 'RestClientExtensions' using GoogleTest (gtest) and GoogleMock (gmock). Context: - Class: RestClientExtensions Requirements: Use EXPECT_CALL for virtual methods.
industrial
// Copyright (c) .NET Foundation and Contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // namespace RestSharp.Extensions; static class CookieContainerExtensions { public static void AddCookies(this CookieContainer cookieContainer, Uri uri, IEnumerable<string> cookiesHeader) { foreach (var header in cookiesHeader) { try { cookieContainer.SetCookies(uri, header); } catch (CookieException) { // Do not fail request if we cannot parse a cookie } } } }
using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Primitives; using Microsoft.Net.Http.Headers; using RestSharp.Tests.Integrated.Fixtures; using WireMock.Types; using WireMock.Util; namespace RestSharp.Tests.Integrated; public sealed class CookieTests : IDisposable { readonly RestClient _client; readonly string _host; readonly WireMockServer _server = WireMockServer.Start(); public CookieTests() { var options = new RestClientOptions(_server.Url!) { CookieContainer = new CookieContainer() }; _client = new RestClient(options); _host = _client.Options.BaseUrl!.Host; _server .Given(Request.Create().WithPath("/get-cookies")) .RespondWith(Response.Create().WithCallback(HandleGetCookies)); _server .Given(Request.Create().WithPath("/set-cookies")) .RespondWith(Response.Create().WithCallback(HandleSetCookies)); _server .Given(Request.Create().WithPath("/invalid-cookies")) .RespondWith(Response.Create().WithCallback(HandleInvalidCookies)); } [Fact] public async Task Can_Perform_GET_Async_With_Request_Cookies() { var request = new RestRequest("get-cookies") { CookieContainer = new CookieContainer() }; request.CookieContainer.Add(new Cookie("cookie", "value", null, _host)); request.CookieContainer.Add(new Cookie("cookie2", "value2", null, _host)); var response = await _client.ExecuteAsync(request); response.Content.Should().Be("[\"cookie=value\",\"cookie2=value2\"]"); } [Fact] public async Task Can_Perform_GET_Async_With_Request_And_Client_Cookies() { _client.Options.CookieContainer!.Add(new Cookie("clientCookie", "clientCookieValue", null, _host)); var request = new RestRequest("get-cookies") { CookieContainer = new CookieContainer() }; request.CookieContainer.Add(new Cookie("cookie", "value", null, _host)); request.CookieContainer.Add(new Cookie("cookie2", "value2", null, _host)); var response = await _client.ExecuteAsync<string[]>(request); var expected = new[] { "cookie=value", "cookie2=value2", "clientCookie=clientCookieValue" }; response.Data.Should().BeEquivalentTo(expected); } [Fact] public async Task Can_Perform_GET_Async_With_Response_Cookies() { var request = new RestRequest("set-cookies"); var response = await _client.ExecuteAsync(request); response.Content.Should().Be("success"); AssertCookie("cookie1", "value1", x => x == DateTime.MinValue); response.Cookies.Find("cookie2").Should().BeNull("Cookie 2 should vanish as the path will not match"); AssertCookie("cookie3", "value3", x => x > DateTime.UtcNow); AssertCookie("cookie4", "value4", x => x > DateTime.UtcNow); response.Cookies.Find("cookie5").Should().BeNull("Cookie 5 should vanish as the request is not SSL"); AssertCookie("cookie6", "value6", x => x == DateTime.MinValue, true); return; void AssertCookie(string name, string value, Func<DateTime, bool> checkExpiration, bool httpOnly = false) { var c = response.Cookies.Find(name)!; c.Value.Should().Be(value); c.Path.Should().Be("/"); c.Domain.Should().Be(_host); checkExpiration(c.Expires).Should().BeTrue($"Expires at {c.Expires}"); c.HttpOnly.Should().Be(httpOnly); } } [Fact] public async Task GET_Async_With_Response_Cookies_Should_Not_Fail_With_Cookie_With_Empty_Domain() { var request = new RestRequest("set-cookies"); var response = await _client.ExecuteAsync(request); response.Content.Should().Be("success"); var notFoundCookie = response.Cookies.Find("cookie_empty_domain"); notFoundCookie.Should().BeNull(); var emptyDomainCookieHeader = response .GetHeaderValues(KnownHeaders.SetCookie) .SingleOrDefault(h => h.StartsWith("cookie_empty_domain")); emptyDomainCookieHeader.Should().NotBeNull(); emptyDomainCookieHeader.Should().Contain("domain=;"); } [Fact] public async Task GET_Async_With_Invalid_Cookies_Should_Still_Return_Response_When_IgnoreInvalidCookies_Is_False() { var request = new RestRequest("invalid-cookies") { CookieContainer = new() }; var response = await _client.ExecuteAsync(request); // Even with IgnoreInvalidCookies = false, the response should be successful // because AddCookies swallows CookieException by default response.IsSuccessful.Should().BeTrue(); response.Content.Should().Be("success"); } [Fact] public async Task GET_Async_With_Invalid_Cookies_Should_Return_Response_When_IgnoreInvalidCookies_Is_True() { var options = new RestClientOptions(_server.Url!) { CookieContainer = new() }; using var client = new RestClient(options); var request = new RestRequest("invalid-cookies"); var response = await client.ExecuteAsync(request); response.IsSuccessful.Should().BeTrue(); response.Content.Should().Be("success"); } static ResponseMessage HandleGetCookies(IRequestMessage request) { var response = request.Cookies!.Select(x => $"{x.Key}={x.Value}").ToArray(); return WireMockTestServer.CreateJson(response); } static ResponseMessage HandleSetCookies(IRequestMessage request) { var cookies = new List<CookieInternal> { new("cookie1", "value1", new()), new("cookie2", "value2", new() { Path = "/path_extra" }), new("cookie3", "value3", new() { Expires = DateTimeOffset.Now.AddDays(2) }), new("cookie4", "value4", new() { MaxAge = TimeSpan.FromSeconds(100) }), new("cookie5", "value5", new() { Secure = true }), new("cookie6", "value6", new() { HttpOnly = true }), new("cookie_empty_domain", "value_empty_domain", new() { HttpOnly = true, Domain = string.Empty }) }; var response = new ResponseMessage { Headers = new Dictionary<string, WireMockList<string>>(), BodyData = new BodyData { DetectedBodyType = BodyType.String, BodyAsString = "success" } }; var valuesList = new WireMockList<string>(); valuesList.AddRange(cookies.Select(cookie => cookie.Options.GetHeader(cookie.Name, cookie.Value))); response.Headers.Add(KnownHeaders.SetCookie, valuesList); return response; } static ResponseMessage HandleInvalidCookies(IRequestMessage request) { var response = new ResponseMessage { Headers = new Dictionary<string, WireMockList<string>>(), BodyData = new BodyData { DetectedBodyType = BodyType.String, BodyAsString = "success" } }; // Create an invalid cookie with a domain mismatch that will cause CookieException // The cookie domain doesn't match the request URL domain var valuesList = new WireMockList<string> { "invalid_cookie=value; Domain=.invalid-domain.com" }; response.Headers.Add(KnownHeaders.SetCookie, valuesList); return response; } record CookieInternal(string Name, string Value, CookieOptions Options); public void Dispose() { _client.Dispose(); _server.Dispose(); } } static class CookieExtensions { public static string GetHeader(this CookieOptions self, string name, string value) { var cookieHeader = new SetCookieHeaderValue((StringSegment)name, (StringSegment)value) { Domain = (StringSegment)self.Domain, Path = (StringSegment)self.Path, Expires = self.Expires, Secure = self.Secure, HttpOnly = self.HttpOnly, MaxAge = self.MaxAge, SameSite = (Microsoft.Net.Http.Headers.SameSiteMode)self.SameSite }; return cookieHeader.ToString(); } }
RestSharp
You are an expert C++ developer. Task: Write a unit test for 'CookieContainerExtensions' using GoogleTest (gtest) and GoogleMock (gmock). Context: - Class: CookieContainerExtensions Requirements: Use EXPECT_CALL for virtual methods.
industrial
using RichardSzalay.MockHttp; namespace RestSharp.Tests.Fixtures; public static class MockHttpClient { const string Url = "https://dummy.org"; public static RestClient Create(Method method, Func<MockedRequest, MockedRequest> configureHandler, ConfigureRestClient configure = null) { var mockHttp = new MockHttpMessageHandler(); configureHandler(mockHttp.When(RestClient.AsHttpMethod(method), Url)); var options = new RestClientOptions(Url) { ConfigureMessageHandler = _ => mockHttp }; configure?.Invoke(options); return new RestClient(options); } }
namespace RestSharp.Tests.Integrated; public sealed class HttpClientTests(WireMockTestServer server) : IClassFixture<WireMockTestServer> { [Fact] public async Task ShouldUseBaseAddress() { using var httpClient = new HttpClient(); httpClient.BaseAddress = new Uri(server.Url!); using var client = new RestClient(httpClient); var request = new RestRequest("success"); var response = await client.ExecuteAsync<SuccessResponse>(request); response.StatusCode.Should().Be(HttpStatusCode.OK); response.Data!.Message.Should().Be("Works!"); } }
RestSharp
You are an expert C++ developer. Task: Write a unit test for 'MockHttpClient' using GoogleTest (gtest) and GoogleMock (gmock). Context: - Class: MockHttpClient Requirements: Use EXPECT_CALL for virtual methods.
industrial
// Copyright (c) .NET Foundation and Contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // namespace RestSharp; public static partial class RestClientExtensions { /// <param name="client"></param> extension(IRestClient client) { /// <summary> /// Executes a PUT-style request asynchronously, authenticating if needed. /// The response content then gets deserialized to T. /// </summary> /// <typeparam name="T">Target deserialization type</typeparam> /// <param name="request">Request to be executed</param> /// <param name="cancellationToken">The cancellation token</param> /// <returns>Deserialized response content</returns> public Task<RestResponse<T>> ExecutePutAsync<T>( RestRequest request, CancellationToken cancellationToken = default ) => client.ExecuteAsync<T>(request, Method.Put, cancellationToken); /// <summary> /// Executes a PUT-style request synchronously, authenticating if needed. /// The response content then gets deserialized to T. /// </summary> /// <typeparam name="T">Target deserialization type</typeparam> /// <param name="request">Request to be executed</param> /// <returns>Deserialized response content</returns> public RestResponse<T> ExecutePut<T>(RestRequest request) => AsyncHelpers.RunSync(() => client.ExecuteAsync<T>(request, Method.Put)); /// <summary> /// Executes a PUP-style request asynchronously, authenticating if needed /// </summary> /// <param name="request">Request to be executed</param> /// <param name="cancellationToken">Cancellation token</param> public Task<RestResponse> ExecutePutAsync(RestRequest request, CancellationToken cancellationToken = default) => client.ExecuteAsync(request, Method.Put, cancellationToken); /// <summary> /// Executes a PUT-style synchronously, authenticating if needed /// </summary> /// <param name="request">Request to be executed</param> public RestResponse ExecutePut(RestRequest request) => AsyncHelpers.RunSync(() => client.ExecuteAsync(request, Method.Put)); /// <summary> /// Execute the request using PUT HTTP method. Exception will be thrown if the request does not succeed. /// The response data is deserialized to the Data property of the returned response object. /// </summary> /// <param name="request">The request</param> /// <param name="cancellationToken">Cancellation token</param> /// <typeparam name="T">Expected result type</typeparam> /// <returns>Deserialaized response</returns> public async Task<T?> PutAsync<T>(RestRequest request, CancellationToken cancellationToken = default) { var response = await client.ExecuteAsync<T>(request, Method.Put, cancellationToken).ConfigureAwait(false); return response.ThrowIfError().Data; } /// <summary> /// Execute the request using PUT HTTP method. Exception will be thrown if the request does not succeed. /// The response data is deserialized to the Data property of the returned response object. /// </summary> /// <param name="request">The request</param> /// <typeparam name="T">Expected result type</typeparam> /// <returns></returns> public T? Put<T>(RestRequest request) => AsyncHelpers.RunSync(() => client.PutAsync<T>(request)); /// <summary> /// Execute the request using PUT HTTP method. Exception will be thrown if the request does not succeed. /// </summary> /// <param name="request">The request</param> /// <param name="cancellationToken">Cancellation token</param> /// <returns></returns> public async Task<RestResponse> PutAsync(RestRequest request, CancellationToken cancellationToken = default) { var response = await client.ExecuteAsync(request, Method.Put, cancellationToken).ConfigureAwait(false); return response.ThrowIfError(); } /// <summary> /// Execute the request using PUT HTTP method. Exception will be thrown if the request does not succeed. /// </summary> /// <param name="request">The request</param> /// <returns></returns> public RestResponse Put(RestRequest request) => AsyncHelpers.RunSync(() => client.PutAsync(request)); /// <summary> /// Serializes the <code>request</code> object to JSON and makes a PUT call to the resource specified in the <code>resource</code> parameter. /// Expects a JSON response back, deserializes it to <code>TResponse</code> type and returns it. /// </summary> /// <param name="resource">Resource URL</param> /// <param name="request">Request object, must be serializable to JSON</param> /// <param name="cancellationToken">Cancellation token</param> /// <typeparam name="TRequest">Request object type</typeparam> /// <typeparam name="TResponse">Response object type</typeparam> /// <returns>Deserialized response object</returns> public Task<TResponse?> PutJsonAsync<TRequest, TResponse>( string resource, TRequest request, CancellationToken cancellationToken = default ) where TRequest : class { var restRequest = new RestRequest(resource).AddJsonBody(request); return client.PutAsync<TResponse>(restRequest, cancellationToken); } /// <summary> /// Serializes the <code>request</code> object to JSON and makes a PUT call to the resource specified in the <code>resource</code> parameter. /// Expects a JSON response back, deserializes it to <code>TResponse</code> type and returns it. /// </summary> /// <param name="resource">Resource URL</param> /// <param name="request">Request object, must be serializable to JSON</param> /// <typeparam name="TRequest">Request object type</typeparam> /// <typeparam name="TResponse">Response object type</typeparam> /// <returns>Deserialized response object</returns> public TResponse? PutJson<TRequest, TResponse>(string resource, TRequest request) where TRequest : class => AsyncHelpers.RunSync(() => client.PutJsonAsync<TRequest, TResponse>(resource, request)); /// <summary> /// Serializes the <code>request</code> object to JSON and makes a PUT call to the resource specified in the <code>resource</code> parameter. /// Expects no response back, just the status code. /// </summary> /// <param name="resource">Resource URL</param> /// <param name="request">Request object, must be serializable to JSON</param> /// <param name="cancellationToken">Cancellation token</param> /// <typeparam name="TRequest">Request object type</typeparam> /// <returns>Response status code</returns> public async Task<HttpStatusCode> PutJsonAsync<TRequest>( string resource, TRequest request, CancellationToken cancellationToken = default ) where TRequest : class { var restRequest = new RestRequest(resource).AddJsonBody(request); var response = await client.PutAsync(restRequest, cancellationToken).ConfigureAwait(false); return response.StatusCode; } /// <summary> /// Serializes the <code>request</code> object to JSON and makes a PUT call to the resource specified in the <code>resource</code> parameter. /// Expects no response back, just the status code. /// </summary> /// <param name="resource">Resource URL</param> /// <param name="request">Request object, must be serializable to JSON</param> /// <typeparam name="TRequest">Request object type</typeparam> /// <returns>Response status code</returns> public HttpStatusCode PutJson<TRequest>(string resource, TRequest request) where TRequest : class => AsyncHelpers.RunSync(() => client.PutJsonAsync(resource, request)); } }
using System.Text.Json; namespace RestSharp.Tests.Integrated; public sealed class PutTests(WireMockTestServer server) : IClassFixture<WireMockTestServer>, IDisposable { readonly RestClient _client = new(server.Url!); static readonly JsonSerializerOptions Options = new(JsonSerializerDefaults.Web); [Fact] public async Task Should_put_json_body() { var body = new TestRequest("foo", 100); var request = new RestRequest("/content").AddJsonBody(body); var response = await _client.PutAsync(request); var expected = JsonSerializer.Serialize(body, Options); response.Content.Should().Be(expected); } [Fact] public async Task Should_put_json_body_using_extension() { var body = new TestRequest("foo", 100); var response = await _client.PutJsonAsync<TestRequest, TestRequest>("/content", body); response.Should().BeEquivalentTo(body); } [Fact] public async Task Can_Timeout_PUT_Async() { var request = new RestRequest("/timeout", Method.Put).AddBody("Body_Content"); // Half the value of ResponseHandler.Timeout request.Timeout = TimeSpan.FromMilliseconds(200); var response = await _client.ExecuteAsync(request); Assert.Equal(ResponseStatus.TimedOut, response.ResponseStatus); } public void Dispose() => _client.Dispose(); }
RestSharp
You are an expert C++ developer. Task: Write a unit test for 'RestClientExtensions' using GoogleTest (gtest) and GoogleMock (gmock). Context: - Class: RestClientExtensions Requirements: Use EXPECT_CALL for virtual methods.
industrial
// Copyright (c) .NET Foundation and Contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System.Net.Http.Headers; namespace RestSharp.Extensions; static class HttpHeadersExtensions { public static IReadOnlyCollection<HeaderParameter> GetHeaderParameters(this HttpHeaders httpHeaders) => httpHeaders .SelectMany(x => x.Value.Select(y => (x.Key, y))) .Select(x => new HeaderParameter(x.Key, x.y)) .ToList(); }
namespace RestSharp.Tests.Integrated; public sealed class HttpHeadersTests(WireMockTestServer server) : IClassFixture<WireMockTestServer>, IDisposable { const string UserAgent = "RestSharp/test"; readonly RestClient _client = new(new RestClientOptions(server.Url!) { ThrowOnAnyError = true, UserAgent = UserAgent }); [Fact] public async Task Ensure_headers_correctly_set_in_the_interceptor() { const string headerName = "HeaderName"; const string headerValue = "HeaderValue"; var request = new RestRequest("/headers") { Interceptors = [new HeaderInterceptor(headerName, headerValue)] }; var response = await _client.ExecuteAsync<TestServerResponse[]>(request); response.StatusCode.Should().Be(HttpStatusCode.OK); var header = FindHeader(response, headerName); header.Should().NotBeNull(); header.Value.Should().Be(headerValue); } [Fact, Obsolete("Obsolete")] public async Task Ensure_headers_correctly_set_in_the_hook() { const string headerName = "HeaderName"; const string headerValue = "HeaderValue"; var request = new RestRequest("/headers") { OnBeforeRequest = http => { http.Headers.Add(headerName, headerValue); return default; } }; var response = await _client.ExecuteAsync<TestServerResponse[]>(request); response.StatusCode.Should().Be(HttpStatusCode.OK); response.Data.Should().NotBeNull(); var header = FindHeader(response, headerName); header.Should().NotBeNull(); header.Value.Should().Be(headerValue); } [Fact] public async Task Should_use_both_default_and_request_headers() { var defaultHeader = new Header("defName", "defValue"); var requestHeader = new Header("reqName", "reqValue"); _client.AddDefaultHeader(defaultHeader.Name, defaultHeader.Value); var request = new RestRequest("/headers").AddHeader(requestHeader.Name, requestHeader.Value); var response = await _client.ExecuteAsync<TestServerResponse[]>(request); CheckHeader(response, defaultHeader); CheckHeader(response, requestHeader); } [Fact] public async Task Should_sent_custom_UserAgent() { var request = new RestRequest("/headers"); var response = await _client.ExecuteAsync<TestServerResponse[]>(request); var h = FindHeader(response, "User-Agent"); h.Should().NotBeNull(); h.Value.Should().Be(UserAgent); response.GetHeaderValue("Server").Should().Be("Kestrel"); } static void CheckHeader(RestResponse<TestServerResponse[]> response, Header header) { var h = FindHeader(response, header.Name); h.Should().NotBeNull(); h.Value.Should().Be(header.Value); } static TestServerResponse FindHeader(RestResponse<TestServerResponse[]> response, string headerName) => response.Data!.First(x => x.Name == headerName); record Header(string Name, string Value); class HeaderInterceptor(string headerName, string headerValue) : Interceptors.Interceptor { public override ValueTask BeforeHttpRequest(HttpRequestMessage requestMessage, CancellationToken cancellationToken) { requestMessage.Headers.Add(headerName, headerValue); return default; } } public void Dispose() => _client.Dispose(); }
RestSharp
You are an expert .NET (C#) developer. Task: Write a unit test for 'HttpHeadersExtensions' using XUnit and Moq. Context: - Class: HttpHeadersExtensions Requirements: Use Mock<T> interface mocking.
industrial
namespace RestSharp.Tests.Shared.Fixtures; public class RequestBodyCapturer { public const string Resource = "/capture"; public string ContentType { get; private set; } public bool HasBody { get; private set; } public string Body { get; private set; } public Uri Url { get; private set; } public bool CaptureBody(string content) { Body = content; HasBody = !string.IsNullOrWhiteSpace(content); return true; } public bool CaptureHeaders(IDictionary<string, string[]> headers) { if (headers.TryGetValue("Content-Type", out var contentType)) { ContentType = contentType[0]; } return true; } public bool CaptureUrl(string url) { Url = new(url); return true; } }
using RestSharp.Tests.Shared.Extensions; using RestSharp.Tests.Shared.Fixtures; namespace RestSharp.Tests.Integrated; public sealed class RequestBodyTests : IDisposable { // const string NewLine = "\r\n"; static readonly string ExpectedTextContentType = $"{ContentType.Plain}; charset=utf-8"; static readonly string ExpectedTextContentTypeNoCharset = ContentType.Plain; readonly WireMockServer _server = WireMockServer.Start(s => s.AllowBodyForAllHttpMethods = true); async Task AssertBody(Method method, bool disableCharset = false) { #if NET var options = new RestClientOptions(_server.Url!) { DisableCharset = disableCharset }; using var client = new RestClient(options); var request = new RestRequest(RequestBodyCapturer.Resource, method); var capturer = _server.ConfigureBodyCapturer(method); const string bodyData = "abc123 foo bar baz BING!"; request.AddBody(bodyData, ContentType.Plain); await client.ExecuteAsync(request); var expected = disableCharset ? ExpectedTextContentTypeNoCharset : ExpectedTextContentType; AssertHasRequestBody(capturer, expected, bodyData); #endif } [Fact] public Task Can_Be_Added_To_COPY_Request() => AssertBody(Method.Copy); [Fact] public Task Can_Be_Added_To_DELETE_Request() => AssertBody(Method.Delete); [Fact] public Task Can_Be_Added_To_OPTIONS_Request() => AssertBody(Method.Options); [Fact] public Task Can_Be_Added_To_PATCH_Request() => AssertBody(Method.Patch); [Fact] public Task Can_Be_Added_To_POST_Request_NoCharset() => AssertBody(Method.Post, true); [Fact] public Task Can_Be_Added_To_POST_Request() => AssertBody(Method.Post); [Fact] public Task Can_Be_Added_To_PUT_Request_NoCharset() => AssertBody(Method.Put, true); [Fact] public Task Can_Be_Added_To_PUT_Request() => AssertBody(Method.Put); [Fact] public async Task Can_Have_No_Body_Added_To_POST_Request() { const Method httpMethod = Method.Post; using var client = new RestClient(_server.Url!); var request = new RestRequest(RequestBodyCapturer.Resource, httpMethod); var capturer = _server.ConfigureBodyCapturer(httpMethod); await client.ExecuteAsync(request); AssertHasNoRequestBody(capturer); } [Fact] public Task Can_Be_Added_To_GET_Request() => AssertBody(Method.Get); [Fact] public Task Can_Be_Added_To_HEAD_Request() => AssertBody(Method.Head); static void AssertHasNoRequestBody(RequestBodyCapturer capturer) { capturer.ContentType.Should().BeNull(); capturer.HasBody.Should().BeFalse(); capturer.Body.Should().BeNullOrEmpty(); } static void AssertHasRequestBody(RequestBodyCapturer capturer, string contentType, string bodyData) { capturer.ContentType.Should().Be(contentType); capturer.HasBody.Should().BeTrue(); capturer.Body.Should().Be(bodyData); } public void Dispose() => _server.Dispose(); }
RestSharp
You are an expert C++ developer. Task: Write a unit test for 'RequestBodyCapturer' using GoogleTest (gtest) and GoogleMock (gmock). Context: - Class: RequestBodyCapturer Requirements: Use EXPECT_CALL for virtual methods.
industrial
// Copyright (c) .NET Foundation and Contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System.Runtime.CompilerServices; namespace RestSharp; public sealed class DefaultParameters(ReadOnlyRestClientOptions options) : ParametersCollection { /// <summary> /// Safely add a default parameter to the collection. /// </summary> /// <param name="parameter">Parameter to add</param> /// <returns></returns> /// <exception cref="NotSupportedException"></exception> /// <exception cref="ArgumentException"></exception> [MethodImpl(MethodImplOptions.Synchronized)] public DefaultParameters AddParameter(Parameter parameter) { if (parameter.Type == ParameterType.RequestBody) throw new NotSupportedException("Cannot set request body using default parameters. Use Request.AddBody() instead."); if (!options.AllowMultipleDefaultParametersWithSameName && parameter.Type != ParameterType.HttpHeader && !MultiParameterTypes.Contains(parameter.Type) && this.Any(x => x.Name == parameter.Name)) { throw new ArgumentException("A default parameters with the same name has already been added", nameof(parameter)); } Parameters.Add(parameter); return this; } /// <summary> /// Safely removes all the default parameters with the given name and type. /// </summary> /// <param name="name">Parameter name</param> /// <param name="type">Parameter type</param> /// <returns></returns> [PublicAPI] [MethodImpl(MethodImplOptions.Synchronized)] public DefaultParameters RemoveParameter(string name, ParameterType type) { Parameters.RemoveAll(x => x.Name == name && x.Type == type); return this; } /// <summary> /// Replace a default parameter with the same name and type. /// </summary> /// <param name="parameter">Parameter instance</param> /// <returns></returns> [PublicAPI] public DefaultParameters ReplaceParameter(Parameter parameter) => // ReSharper disable once NotResolvedInText RemoveParameter(Ensure.NotEmptyString(parameter.Name, "Parameter name"), parameter.Type) .AddParameter(parameter); static readonly ParameterType[] MultiParameterTypes = [ParameterType.QueryString, ParameterType.GetOrPost]; }
using RestSharp.Tests.Shared.Extensions; using RestSharp.Tests.Shared.Fixtures; namespace RestSharp.Tests.Integrated; public sealed class DefaultParameterTests(WireMockTestServer server) : IClassFixture<WireMockTestServer> { readonly RequestBodyCapturer _capturer = server.ConfigureBodyCapturer(Method.Get, false); [Fact] public async Task Should_add_default_and_request_query_get_parameters() { using var client = new RestClient(server.Url!).AddDefaultParameter("foo", "bar", ParameterType.QueryString); var request = new RestRequest().AddParameter("foo1", "bar1", ParameterType.QueryString); await client.GetAsync(request); var query = _capturer.Url!.Query; query.Should().Contain("foo=bar"); query.Should().Contain("foo1=bar1"); } [Fact] public async Task Should_add_default_and_request_url_get_parameters() { using var client = new RestClient($"{server.Url}/{{foo}}/").AddDefaultParameter("foo", "bar", ParameterType.UrlSegment); var request = new RestRequest("{foo1}").AddParameter("foo1", "bar1", ParameterType.UrlSegment); await client.GetAsync(request); _capturer.Url!.Segments.Should().BeEquivalentTo("/", "bar/", "bar1"); } [Fact] public async Task Should_not_throw_exception_when_name_is_null() { using var client = new RestClient($"{server.Url}/request-echo").AddDefaultParameter("foo", "bar", ParameterType.UrlSegment); var request = new RestRequest("{foo1}").AddParameter(null, "value", ParameterType.RequestBody); await client.ExecuteAsync(request); } }
RestSharp
You are an expert .NET (C#) developer. Task: Write a unit test for 'DefaultParameters' using XUnit and Moq. Context: - Class: DefaultParameters Requirements: Use Mock<T> interface mocking.
industrial
// Copyright (c) .NET Foundation and Contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace RestSharp.Serializers; public interface IWithRootElement { string? RootElement { get; set; } }
using RestSharp.Serializers.Xml; namespace RestSharp.Tests.Integrated; public class RootElementTests { [Fact] public async Task Copy_RootElement_From_Request_To_IWithRootElement_Deserializer() { using var server = WireMockServer.Start(); const string xmlBody = """ <?xml version="1.0" encoding="utf-8" ?> <Response> <Success> <Message>Works!</Message> </Success> </Response> """; server .Given(Request.Create().WithPath("/success")) .RespondWith(Response.Create().WithBody(xmlBody).WithHeader(KnownHeaders.ContentType, ContentType.Xml)); using var client = new RestClient(server.Url!, configureSerialization: cfg => cfg.UseXmlSerializer()); var request = new RestRequest("success") { RootElement = "Success" }; var response = await client.ExecuteAsync<TestResponse>(request); response.Data.Should().NotBeNull(); response.Data!.Message.Should().Be("Works!"); } }
RestSharp
You are an expert C++ developer. Task: Write a unit test for 'TargetModule' using GoogleTest (gtest) and GoogleMock (gmock). Context: - Class: TargetModule Requirements: Use EXPECT_CALL for virtual methods.
industrial
// Copyright (c) .NET Foundation and Contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // namespace RestSharp.Interceptors; /// <summary> /// Base Interceptor /// </summary> public abstract class Interceptor { static readonly ValueTask Completed = #if NET ValueTask.CompletedTask; #else new (); #endif /// <summary> /// Intercepts the request before composing the request message /// </summary> /// <param name="request">RestRequest before composing the request message</param> /// <param name="cancellationToken">Cancellation token</param> public virtual ValueTask BeforeRequest(RestRequest request, CancellationToken cancellationToken) => Completed; /// <summary> /// Intercepts the request before being sent /// </summary> /// <param name="requestMessage">HttpRequestMessage before being sent</param> /// <param name="cancellationToken">Cancellation token</param> public virtual ValueTask BeforeHttpRequest(HttpRequestMessage requestMessage, CancellationToken cancellationToken) => Completed; /// <summary> /// Intercepts the request before being sent /// </summary> /// <param name="responseMessage">HttpResponseMessage as received from the remote server</param> /// <param name="cancellationToken">Cancellation token</param> public virtual ValueTask AfterHttpRequest(HttpResponseMessage responseMessage, CancellationToken cancellationToken) => Completed; /// <summary> /// Intercepts the request after it's created from HttpResponseMessage /// </summary> /// <param name="response">HttpResponseMessage as received from the remote server</param> /// <param name="cancellationToken">Cancellation token</param> public virtual ValueTask AfterRequest(RestResponse response, CancellationToken cancellationToken) => Completed; /// <summary> /// Intercepts the request before deserialization, won't be called if using non-generic ExecuteAsync /// </summary> /// <param name="response">HttpResponseMessage as received from the remote server</param> /// <param name="cancellationToken">Cancellation token</param> public virtual ValueTask BeforeDeserialization(RestResponse response, CancellationToken cancellationToken) => Completed; }
// ReSharper disable AccessToDisposedClosure namespace RestSharp.Tests.Integrated.Interceptor; public class InterceptorTests(WireMockTestServer server) : IClassFixture<WireMockTestServer> { [Fact] public async Task Should_call_client_interceptor() { // Arrange var request = CreateRequest(); var (client, interceptor) = SetupClient( test => test.BeforeRequestAction = req => req.AddHeader("foo", "bar") ); //Act var response = await client.ExecutePostAsync<TestResponse>(request); //Assert response.Request.Parameters.Should().Contain(x => x.Name == "foo" && (string)x.Value! == "bar"); interceptor.BeforeRequestCalled.Should().BeTrue(); interceptor.BeforeHttpRequestCalled.Should().BeTrue(); interceptor.AfterHttpRequestCalled.Should().BeTrue(); interceptor.AfterRequestCalled.Should().BeTrue(); interceptor.BeforeDeserializationCalled.Should().BeTrue(); client.Dispose(); } [Fact] public async Task Should_call_request_interceptor() { // Arrange var request = CreateRequest(); var interceptor = new TestInterceptor(); request.Interceptors = new List<Interceptors.Interceptor> { interceptor }; //Act using var client = new RestClient(server.Url!); await client.ExecutePostAsync<TestResponse>(request); //Assert interceptor.ShouldHaveCalledAll(); } [Fact] public async Task Should_call_both_client_and_request_interceptors() { // Arrange var request = CreateRequest(); var (client, interceptor) = SetupClient(); var requestInterceptor = new TestInterceptor(); request.Interceptors = new List<Interceptors.Interceptor> { requestInterceptor }; //Act await client.ExecutePostAsync<TestResponse>(request); //Assert interceptor.ShouldHaveCalledAll(); requestInterceptor.ShouldHaveCalledAll(); client.Dispose(); } [Fact] public async Task ThrowExceptionIn_InterceptBeforeRequest() { //Arrange var request = CreateRequest(); var (client, interceptor) = SetupClient(test => test.BeforeRequestAction = req => throw new Exception("DummyException")); //Act var action = () => client.ExecutePostAsync<TestResponse>(request); //Assert await action.Should().ThrowAsync<Exception>().WithMessage("DummyException"); interceptor.BeforeRequestCalled.Should().BeTrue(); interceptor.BeforeHttpRequestCalled.Should().BeFalse(); interceptor.AfterHttpRequestCalled.Should().BeFalse(); interceptor.AfterRequestCalled.Should().BeFalse(); interceptor.BeforeDeserializationCalled.Should().BeFalse(); client.Dispose(); } [Fact] public async Task ThrowExceptionIn_InterceptBeforeHttpRequest() { // Arrange var request = CreateRequest(); var (client, interceptor) = SetupClient(test => test.BeforeHttpRequestAction = req => throw new Exception("DummyException")); //Act var action = () => client.ExecutePostAsync<TestResponse>(request); //Assert await action.Should().ThrowAsync<Exception>().WithMessage("DummyException"); interceptor.BeforeRequestCalled.Should().BeTrue(); interceptor.BeforeHttpRequestCalled.Should().BeTrue(); interceptor.AfterHttpRequestCalled.Should().BeFalse(); interceptor.AfterRequestCalled.Should().BeFalse(); interceptor.BeforeDeserializationCalled.Should().BeFalse(); client.Dispose(); } [Fact] public async Task ThrowException_InInterceptAfterHttpRequest() { // Arrange var request = CreateRequest(); var (client, interceptor) = SetupClient(test => test.AfterHttpRequestAction = req => throw new Exception("DummyException")); //Act var action = () => client.ExecutePostAsync<TestResponse>(request); //Assert await action.Should().ThrowAsync<Exception>().WithMessage("DummyException"); interceptor.BeforeRequestCalled.Should().BeTrue(); interceptor.BeforeHttpRequestCalled.Should().BeTrue(); interceptor.AfterHttpRequestCalled.Should().BeTrue(); interceptor.AfterRequestCalled.Should().BeFalse(); interceptor.BeforeDeserializationCalled.Should().BeFalse(); client.Dispose(); } [Fact] public async Task ThrowExceptionIn_InterceptAfterRequest() { // Arrange var request = CreateRequest(); var (client, interceptor) = SetupClient(test => test.AfterRequestAction = req => throw new Exception("DummyException")); //Act var action = () => client.ExecutePostAsync<TestResponse>(request); //Assert await action.Should().ThrowAsync<Exception>().WithMessage("DummyException"); interceptor.BeforeRequestCalled.Should().BeTrue(); interceptor.BeforeHttpRequestCalled.Should().BeTrue(); interceptor.AfterHttpRequestCalled.Should().BeTrue(); interceptor.AfterRequestCalled.Should().BeTrue(); interceptor.BeforeDeserializationCalled.Should().BeFalse(); client.Dispose(); } (RestClient client, TestInterceptor interceptor) SetupClient(Action<TestInterceptor>? configureInterceptor = null) { var interceptor = new TestInterceptor(); configureInterceptor?.Invoke(interceptor); var options = new RestClientOptions(server.Url!) { Interceptors = [interceptor] }; return (new RestClient(options), interceptor); } static RestRequest CreateRequest() { var body = new TestRequest("foo", 100); return new RestRequest("post/json").AddJsonBody(body); } } static class InterceptorChecks { public static void ShouldHaveCalledAll(this TestInterceptor interceptor) { interceptor.BeforeRequestCalled.Should().BeTrue(); interceptor.BeforeHttpRequestCalled.Should().BeTrue(); interceptor.AfterHttpRequestCalled.Should().BeTrue(); interceptor.AfterRequestCalled.Should().BeTrue(); interceptor.BeforeDeserializationCalled.Should().BeTrue(); } }
RestSharp
You are an expert C++ developer. Task: Write a unit test for 'Interceptor' using GoogleTest (gtest) and GoogleMock (gmock). Context: - Class: Interceptor Requirements: Use EXPECT_CALL for virtual methods.
industrial
// Copyright (c) .NET Foundation and Contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace RestSharp.Authenticators.OAuth2; /// <summary> /// The OAuth 2 authenticator using URI query parameter. /// </summary> /// <remarks> /// Based on http://tools.ietf.org/html/draft-ietf-oauth-v2-10#section-5.1.2 /// </remarks> [PublicAPI] public class OAuth2UriQueryParameterAuthenticator : AuthenticatorBase { /// <summary> /// Initializes a new instance of the <see cref="OAuth2UriQueryParameterAuthenticator" /> class. /// </summary> /// <param name="accessToken">The access token.</param> public OAuth2UriQueryParameterAuthenticator(string accessToken) : base(accessToken) { } protected override ValueTask<Parameter> GetAuthenticationParameter(string accessToken) => new(new GetOrPostParameter("oauth_token", accessToken)); }
using RestSharp.Authenticators.OAuth2; namespace RestSharp.Tests.Integrated.Authentication; public class OAuth2Tests(WireMockTestServer server) : IClassFixture<WireMockTestServer> { [Fact] public async Task ShouldHaveProperHeader() { var auth = new OAuth2AuthorizationRequestHeaderAuthenticator("token", "Bearer"); using var client = new RestClient(server.Url!, o => o.Authenticator = auth); var response = await client.GetAsync<TestServerResponse[]>("headers"); var authHeader = response!.FirstOrDefault(x => x.Name == KnownHeaders.Authorization); authHeader.Should().NotBeNull(); authHeader!.Value.Should().Be("Bearer token"); } }
RestSharp
You are an expert C++ developer. Task: Write a unit test for 'OAuth2UriQueryParameterAuthenticator' using GoogleTest (gtest) and GoogleMock (gmock). Context: - Class: OAuth2UriQueryParameterAuthenticator Requirements: Use EXPECT_CALL for virtual methods.
industrial
// Copyright (c) .NET Foundation and Contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System.Reflection; namespace RestSharp; static class ObjectParser { public static IEnumerable<ParsedParameter> GetProperties(this object obj, params string[] includedProperties) { // automatically create parameters from object props var type = obj.GetType(); var props = type.GetProperties(); var properties = new List<ParsedParameter>(); foreach (var prop in props.Where(x => IsAllowedProperty(x.Name))) { var val = prop.GetValue(obj, null); if (val == null) continue; if (prop.PropertyType.IsArray) properties.AddRange(GetArray(prop, val)); else properties.Add(GetValue(prop, val)); } return properties; ParsedParameter GetValue(PropertyInfo propertyInfo, object? value) { var attribute = propertyInfo.GetCustomAttribute<RequestPropertyAttribute>(); var name = attribute?.Name ?? propertyInfo.Name; var val = ParseValue(attribute?.Format, value); return new(name, val, attribute?.Encode ?? true); } IEnumerable<ParsedParameter> GetArray(PropertyInfo propertyInfo, object? value) { var elementType = propertyInfo.PropertyType.GetElementType(); var array = (Array)value!; var attribute = propertyInfo.GetCustomAttribute<RequestPropertyAttribute>(); var name = attribute?.Name ?? propertyInfo.Name; var queryType = attribute?.ArrayQueryType ?? RequestArrayQueryType.CommaSeparated; var encode = attribute?.Encode ?? true; if (array.Length <= 0 || elementType == null) return [new(name, null, encode)]; // convert the array to an array of strings var values = array .Cast<object>() .Select(item => ParseValue(attribute?.Format, item)); return queryType switch { RequestArrayQueryType.CommaSeparated => [new(name, string.Join(",", values), encode)], RequestArrayQueryType.ArrayParameters => values.Select(x => new ParsedParameter($"{name}[]", x, encode)), _ => throw new ArgumentOutOfRangeException() }; } bool IsAllowedProperty(string propertyName) => includedProperties.Length == 0 || includedProperties.Length > 0 && includedProperties.Contains(propertyName); string? ParseValue(string? format, object? value) => format == null ? value?.ToString() : string.Format($"{{0:{format}}}", value); } } record ParsedParameter(string Name, string? Value, bool Encode); [AttributeUsage(AttributeTargets.Property)] public class RequestPropertyAttribute : Attribute { public string? Name { get; set; } public string? Format { get; set; } public RequestArrayQueryType ArrayQueryType { get; set; } = RequestArrayQueryType.CommaSeparated; public bool Encode { get; set; } = true; } public enum RequestArrayQueryType { CommaSeparated, ArrayParameters }
// ReSharper disable PropertyCanBeMadeInitOnly.Local namespace RestSharp.Tests; public class ObjectParserTests { [Fact] public void ShouldUseRequestProperty() { var now = DateTime.Now; var dates = new[] { now, now.AddDays(1), now.AddDays(2) }; var request = new TestObject { SomeData = "test", SomeDate = now, Plain = 123, PlainArray = dates, DatesArray = dates }; var parsed = request.GetProperties().ToDictionary(x => x.Name, x => x.Value); parsed["some_data"].Should().Be(request.SomeData); parsed["SomeDate"].Should().Be(request.SomeDate.ToString("d")); parsed["Plain"].Should().Be(request.Plain.ToString()); // ReSharper disable once SpecifyACultureInStringConversionExplicitly parsed["PlainArray"].Should().Be(string.Join(",", dates.Select(x => x.ToString()))); parsed["dates"].Should().Be(string.Join(",", dates.Select(x => x.ToString("d")))); } [Fact] public void ShouldProduceMultipleParametersForArray() { var request = new AnotherTestObject { SomeIds = [1, 2, 3] }; var expected = request.SomeIds.Select(x => ("ids[]", x.ToString())); var parsed = request.GetProperties().Select(x => (x.Name, x.Value)); parsed.Should().BeEquivalentTo(expected); } class AnotherTestObject { [RequestProperty(Name = "ids", ArrayQueryType = RequestArrayQueryType.ArrayParameters)] public int[] SomeIds { get; set; } } class TestObject { [RequestProperty(Name = "some_data")] public string SomeData { get; set; } [RequestProperty(Format = "d")] public DateTime SomeDate { get; set; } [RequestProperty(Name = "dates", Format = "d")] public DateTime[] DatesArray { get; set; } public int Plain { get; set; } public DateTime[] PlainArray { get; set; } } }
RestSharp
You are an expert .NET (C#) developer. Task: Write a unit test for 'RequestPropertyAttribute' using XUnit and Moq. Context: - Class: RequestPropertyAttribute Requirements: Use Mock<T> interface mocking.
industrial
// Copyright (c) .NET Foundation and Contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.Text; namespace RestSharp.Authenticators.OAuth.Extensions; static class StringExtensions { extension(string left) { public bool EqualsIgnoreCase(string right) => string.Equals(left, right, StringComparison.InvariantCultureIgnoreCase); public string Then(string value) => string.Concat(left, value); public Uri AsUri() => new(left); public byte[] GetBytes() => Encoding.UTF8.GetBytes(left); public string PercentEncode() => string.Join("", left.GetBytes().Select(x => $"%{x:X2}")); } }
using System.Globalization; using System.Text; using RestSharp.Extensions; namespace RestSharp.Tests; public class StringExtensionsTests { [Fact] public void UrlEncode_Throws_ArgumentNullException_For_Null_Input() { string nullString = null; // ReSharper disable once ExpressionIsAlwaysNull Assert.Throws<ArgumentNullException>(() => nullString!.UrlEncode()); } [Fact] public void UrlEncode_Returns_Correct_Length_When_Less_Than_Limit() { const int numLessThanLimit = 32766; var stringWithLimitLength = new string('*', numLessThanLimit); var encodedAndDecoded = stringWithLimitLength.UrlEncode().UrlDecode(); Assert.Equal(numLessThanLimit, encodedAndDecoded.Length); } [Fact] public void UrlEncode_Returns_Correct_Length_When_More_Than_Limit() { const int numGreaterThanLimit = 65000; var stringWithLimitLength = new string('*', numGreaterThanLimit); var encodedAndDecoded = stringWithLimitLength.UrlEncode().UrlDecode(); Assert.Equal(numGreaterThanLimit, encodedAndDecoded.Length); } [Fact] public void UrlEncode_Does_Not_Fail_When_4_Byte_Unicode_Character_Lies_Between_Chunks() { var stringWithLimitLength = new string('*', 32765); stringWithLimitLength += "😉*****"; // 2 + 5 chars var encodedAndDecoded = stringWithLimitLength.UrlEncode().UrlDecode(); Assert.Equal(stringWithLimitLength, encodedAndDecoded); // now between another 2 chunks stringWithLimitLength = new string('*', 32766 * 2 - 1); stringWithLimitLength += "😉*****"; // 2 + 5 chars encodedAndDecoded = stringWithLimitLength.UrlEncode().UrlDecode(); Assert.Equal(stringWithLimitLength, encodedAndDecoded); } [Fact] public void UrlEncodeTest() { const string parameter = "ø"; Assert.Equal("%F8", parameter.UrlEncode(Encoding.GetEncoding("ISO-8859-1")), true); Assert.Equal("%C3%B8", parameter.UrlEncode(), true); } [Theory] [InlineData("this_is_a_test", true, "ThisIsATest")] [InlineData("this_is_a_test", false, "This_Is_A_Test")] public void ToPascalCase(string start, bool removeUnderscores, string finish) { var result = start.ToPascalCase(removeUnderscores, CultureInfo.InvariantCulture); Assert.Equal(finish, result); } [Theory] [InlineData("DueDate", "dueDate")] [InlineData("ID", "id")] [InlineData("IDENTIFIER", "identifier")] [InlineData("primaryId", "primaryId")] [InlineData("A", "a")] [InlineData("ThisIsATest", "thisIsATest")] public void ToCamelCase(string start, string finish) { var result = start.ToCamelCase(CultureInfo.InvariantCulture); Assert.Equal(finish, result); } }
RestSharp
You are an expert .NET (C#) developer. Task: Write a unit test for 'StringExtensions' using XUnit and Moq. Context: - Class: StringExtensions Requirements: Use Mock<T> interface mocking.
industrial
// Copyright (c) .NET Foundation and Contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace RestSharp.Serializers.NewtonsoftJson; [PublicAPI] public static class RestClientExtensions { /// <param name="config"></param> extension(SerializerConfig config) { /// <summary> /// Use Newtonsoft.Json serializer with default settings /// </summary> /// <returns></returns> public SerializerConfig UseNewtonsoftJson() => config.UseSerializer(() => new JsonNetSerializer()); /// <summary> /// Use Newtonsoft.Json serializer with custom settings /// </summary> /// <param name="settings">Newtonsoft.Json serializer settings</param> /// <returns></returns> public SerializerConfig UseNewtonsoftJson(JsonSerializerSettings settings) => config.UseSerializer(() => new JsonNetSerializer(settings)); } }
using RestSharp.Serializers; using RestSharp.Serializers.Json; namespace RestSharp.Tests; public class RestClientTests { const string BaseUrl = "http://localhost:8888/"; [Theory] [InlineData(Method.Get, Method.Post)] [InlineData(Method.Post, Method.Get)] [InlineData(Method.Delete, Method.Get)] [InlineData(Method.Head, Method.Post)] [InlineData(Method.Put, Method.Patch)] [InlineData(Method.Patch, Method.Put)] [InlineData(Method.Post, Method.Put)] [InlineData(Method.Get, Method.Delete)] public async Task Execute_with_RestRequest_and_Method_overrides_previous_request_method(Method reqMethod, Method overrideMethod) { var req = new RestRequest("", reqMethod); using var client = new RestClient(BaseUrl); await client.ExecuteAsync(req, overrideMethod); req.Method.Should().Be(overrideMethod); } [Fact] public async Task ConfigureHttp_will_set_proxy_to_null_with_no_exceptions_When_no_proxy_can_be_found() { var req = new RestRequest(); using var client = new RestClient(new RestClientOptions(BaseUrl) { Proxy = null }); await client.ExecuteAsync(req); } [Fact] public void UseJson_leaves_only_json_serializer() { // arrange var baseUrl = new Uri(BaseUrl); // act using var client = new RestClient(baseUrl, configureSerialization: cfg => cfg.UseJson()); // assert client.Serializers.Serializers.Should().HaveCount(1); client.Serializers.GetSerializer(DataFormat.Json).Should().NotBeNull(); } [Fact] public void UseXml_leaves_only_json_serializer() { // arrange var baseUrl = new Uri(BaseUrl); // act using var client = new RestClient(baseUrl, configureSerialization: cfg => cfg.UseXml()); // assert client.Serializers.Serializers.Should().HaveCount(1); client.Serializers.GetSerializer(DataFormat.Xml).Should().NotBeNull(); } [Fact] public void UseOnlySerializer_leaves_only_custom_serializer() { // arrange var baseUrl = new Uri(BaseUrl); // act using var client = new RestClient(baseUrl, configureSerialization: cfg => cfg.UseOnlySerializer(() => new SystemTextJsonSerializer())); // assert client.Serializers.Serializers.Should().HaveCount(1); client.Serializers.GetSerializer(DataFormat.Json).Should().NotBeNull(); } [Fact] public void Should_reuse_httpClient_instance() { using var client1 = new RestClient(new Uri("https://fake.api"), useClientFactory: true); using var client2 = new RestClient(new Uri("https://fake.api"), useClientFactory: true); client1.HttpClient.Should().BeSameAs(client2.HttpClient); } [Fact] public void Should_use_new_httpClient_instance() { using var client1 = new RestClient(new Uri("https://fake.api")); using var client2 = new RestClient(new Uri("https://fake.api")); client1.HttpClient.Should().NotBeSameAs(client2.HttpClient); } [Fact] public void ConfigureDefaultParameters_sets_user_agent_new_httpClient_instance() { // arrange var clientOptions = new RestClientOptions(); // act using var restClient = new RestClient(clientOptions); //assert Assert.Single( restClient.DefaultParameters, parameter => parameter is { Type: ParameterType.HttpHeader, Name: KnownHeaders.UserAgent, Value: string valueAsString } && valueAsString == clientOptions.UserAgent ); Assert.Empty(restClient.HttpClient.DefaultRequestHeaders.UserAgent); } [Fact] public void ConfigureDefaultParameters_sets_user_agent_given_httpClient_instance() { // arrange var httpClient = new HttpClient(); var clientOptions = new RestClientOptions(); // act using var restClient = new RestClient(httpClient, clientOptions); //assert Assert.Single( restClient.DefaultParameters, parameter => parameter is { Type: ParameterType.HttpHeader, Name: KnownHeaders.UserAgent, Value: string valueAsString } && valueAsString == clientOptions.UserAgent ); Assert.Empty(httpClient.DefaultRequestHeaders.UserAgent); } }
RestSharp
You are an expert C++ developer. Task: Write a unit test for 'RestClientExtensions' using GoogleTest (gtest) and GoogleMock (gmock). Context: - Class: RestClientExtensions Requirements: Use EXPECT_CALL for virtual methods.
industrial
// Copyright (c) .NET Foundation and Contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace RestSharp.Extensions.DependencyInjection; class RestClientConfigOptions { public ConfigureRestClient? ConfigureRestClient { get; set; } public ConfigureSerialization? ConfigureSerialization { get; set; } }
namespace RestSharp.Tests; public class OptionsTests { [Fact] public void Ensure_follow_redirect() { var value = false; var options = new RestClientOptions { FollowRedirects = true, ConfigureMessageHandler = Configure }; using var _ = new RestClient(options); value.Should().BeTrue(); return; HttpMessageHandler Configure(HttpMessageHandler handler) { value = (handler as HttpClientHandler)!.AllowAutoRedirect; return handler; } } }
RestSharp
You are an expert C++ developer. Task: Write a unit test for 'RestClientConfigOptions' using GoogleTest (gtest) and GoogleMock (gmock). Context: - Class: RestClientConfigOptions Requirements: Use EXPECT_CALL for virtual methods.
industrial
// Copyright (c) .NET Foundation and Contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace RestSharp; public static partial class RestRequestExtensions { /// <param name="request">Request instance</param> extension(RestRequest request) { /// <summary> /// Adds a body parameter to the request /// </summary> /// <param name="obj">Object to be used as the request body, or string for plain content</param> /// <param name="contentType">Optional: content type</param> /// <returns></returns> /// <exception cref="ArgumentException">Thrown if request body type cannot be resolved</exception> /// <remarks>This method will try to figure out the right content type based on the request data format and the provided content type</remarks> public RestRequest AddBody(object obj, ContentType? contentType = null) { if (contentType == null) { return request.RequestFormat switch { DataFormat.Json => request.AddJsonBody(obj, contentType), DataFormat.Xml => request.AddXmlBody(obj, contentType), DataFormat.Binary => request.AddParameter(new BodyParameter("", obj, ContentType.Binary)), _ => request.AddParameter(new BodyParameter("", obj.ToString()!, ContentType.Plain)) }; } return obj is string str ? request.AddStringBody(str, contentType) : obj is byte[] bytes ? request.AddParameter(new BodyParameter("", bytes, contentType, DataFormat.Binary)) : contentType.Value.Contains("xml") ? request.AddXmlBody(obj, contentType) : contentType.Value.Contains("json") ? request.AddJsonBody(obj, contentType) : throw new ArgumentException("Non-string body found with unsupported content type", nameof(obj)); } /// <summary> /// Adds a string body and figures out the content type from the data format specified. You can, for example, add a JSON string /// using this method as request body, using DataFormat.Json/> /// </summary> /// <param name="body">String body</param> /// <param name="dataFormat"><see cref="DataFormat"/> for the content</param> /// <returns></returns> public RestRequest AddStringBody(string body, DataFormat dataFormat) { var contentType = ContentType.FromDataFormat(dataFormat); request.RequestFormat = dataFormat; return request.AddParameter(new BodyParameter("", body, contentType)); } /// <summary> /// Adds a string body to the request using the specified content type. /// </summary> /// <param name="body">String body</param> /// <param name="contentType">Content type of the body</param> /// <returns></returns> public RestRequest AddStringBody(string body, ContentType contentType) => request.AddParameter(new BodyParameter(body, Ensure.NotNull(contentType, nameof(contentType)))); /// <summary> /// Adds a JSON body parameter to the request from a string /// </summary> /// <param name="forceSerialize">Force serialize the top-level string</param> /// <param name="contentType">Optional: content type. Default is ContentType.Json</param> /// <param name="jsonString">JSON string to be used as a body</param> /// <returns></returns> public RestRequest AddJsonBody(string jsonString, bool forceSerialize, ContentType? contentType = null) { request.RequestFormat = DataFormat.Json; return !forceSerialize ? request.AddStringBody(jsonString, DataFormat.Json) : request.AddParameter(new JsonParameter(jsonString, contentType)); } /// <summary> /// Adds a JSON body parameter to the request /// </summary> /// <param name="obj">Object that will be serialized to JSON</param> /// <param name="contentType">Optional: content type. Default is ContentType.Json</param> /// <returns></returns> public RestRequest AddJsonBody<T>(T obj, ContentType? contentType = null) where T : class { request.RequestFormat = DataFormat.Json; return obj is string str ? request.AddStringBody(str, DataFormat.Json) : request.AddParameter(new JsonParameter(obj, contentType)); } /// <summary> /// Adds an XML body parameter to the request /// </summary> /// <param name="obj">Object that will be serialized to XML</param> /// <param name="contentType">Optional: content type. Default is ContentType.Xml</param> /// <param name="xmlNamespace">Optional: XML namespace</param> /// <returns></returns> public RestRequest AddXmlBody<T>(T obj, ContentType? contentType = null, string xmlNamespace = "") where T : class { request.RequestFormat = DataFormat.Xml; return obj is string str ? request.AddStringBody(str, DataFormat.Xml) : request.AddParameter(new XmlParameter(obj, xmlNamespace, contentType)); } RestRequest AddBodyParameter(string? name, object value) => name != null && name.Contains('/') ? request.AddBody(value, name) : request.AddParameter(new BodyParameter(name, value, ContentType.Plain)); } }
namespace RestSharp.Tests; public class RestRequestTests { [Fact] public void RestRequest_Request_Property() { var request = new RestRequest("resource"); request.Resource.Should().Be("resource"); } [Fact] public void RestRequest_Test_Already_Encoded() { const string resource = "/api/get?query=Id%3d198&another=notencoded&novalue="; const string baseUrl = "https://example.com"; var request = new RestRequest(resource); var parameters = request.Parameters.ToArray(); request.Resource.Should().Be("/api/get"); parameters.Length.Should().Be(3); var expected = new[] { new { Name = "query", Value = "Id%3d198", Type = ParameterType.QueryString, Encode = false }, new { Name = "another", Value = "notencoded", Type = ParameterType.QueryString, Encode = false }, new { Name = "novalue", Value = "", Type = ParameterType.QueryString, Encode = false } }; parameters.Should().BeEquivalentTo(expected, options => options.ExcludingMissingMembers()); using var client = new RestClient(baseUrl); var actual = client.BuildUri(request); actual.AbsoluteUri.Should().Be($"{baseUrl}{resource}"); } [Fact] public async Task RestRequest_Fail_On_Exception() { var req = new RestRequest("nonexisting"); using var client = new RestClient(new RestClientOptions("http://localhost:12345") { ThrowOnAnyError = true }); await Assert.ThrowsAsync<HttpRequestException>(() => client.ExecuteAsync(req)); } }
RestSharp
You are an expert C++ developer. Task: Write a unit test for 'RestRequestExtensions' using GoogleTest (gtest) and GoogleMock (gmock). Context: - Class: RestRequestExtensions Requirements: Use EXPECT_CALL for virtual methods.
industrial
// Copyright (c) .NET Foundation and Contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace RestSharp.Authenticators; /// <summary> /// JSON WEB TOKEN (JWT) Authenticator class. /// <remarks>https://tools.ietf.org/html/draft-ietf-oauth-json-web-token</remarks> /// </summary> public class JwtAuthenticator(string accessToken) : AuthenticatorBase(GetToken(accessToken)) { /// <summary> /// Set the new bearer token so the request gets the new header value /// </summary> /// <param name="accessToken"></param> [PublicAPI] public void SetBearerToken(string accessToken) => Token = GetToken(accessToken); static string GetToken(string accessToken) => Ensure.NotEmptyString(accessToken, nameof(accessToken)).StartsWith("Bearer ") ? accessToken : $"Bearer {accessToken}"; protected override ValueTask<Parameter> GetAuthenticationParameter(string accessToken) => new(new HeaderParameter(KnownHeaders.Authorization, accessToken)); }
using System.Globalization; using RestSharp.Authenticators; namespace RestSharp.Tests.Auth; public class JwtAuthTests { readonly string _testJwt; readonly string _expectedAuthHeaderContent; public JwtAuthTests() { Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; Thread.CurrentThread.CurrentUICulture = CultureInfo.InstalledUICulture; _testJwt = "eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9" + "." + "eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQo" + "gImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ" + "." + "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"; _expectedAuthHeaderContent = $"Bearer {_testJwt}"; } [Fact] public async Task Can_Set_ValidFormat_Auth_Header() { using var client = new RestClient(new RestClientOptions { Authenticator = new JwtAuthenticator(_testJwt) }); var request = new RestRequest(); //In real case client.Execute(request) will invoke Authenticate method await client.Options.Authenticator!.Authenticate(client, request); var authParam = request.Parameters.Single(p => p.Name!.Equals(KnownHeaders.Authorization, StringComparison.OrdinalIgnoreCase)); Assert.Equal(ParameterType.HttpHeader, authParam.Type); Assert.Equal(_expectedAuthHeaderContent, authParam.Value); } [Fact] public async Task Can_Set_ValidFormat_Auth_Header_With_Bearer_Prefix() { using var client = new RestClient(new RestClientOptions { Authenticator = new JwtAuthenticator($"Bearer {_testJwt}") }); var request = new RestRequest(); //In real case client.Execute(request) will invoke Authenticate method await client.Options.Authenticator!.Authenticate(client, request); var authParam = request.Parameters.Single(p => p.Name!.Equals(KnownHeaders.Authorization, StringComparison.OrdinalIgnoreCase)); Assert.Equal(ParameterType.HttpHeader, authParam.Type); Assert.Equal(_expectedAuthHeaderContent, authParam.Value); } [Fact] public async Task Check_Only_Header_Authorization() { using var client = new RestClient(new RestClientOptions { Authenticator = new JwtAuthenticator(_testJwt) }); var request = new RestRequest(); // Paranoid server needs "two-factor authentication": JWT header and query param key for example request.AddParameter(KnownHeaders.Authorization, "manualAuth", ParameterType.QueryString); // In real case client.Execute(request) will invoke Authenticate method await client.Options.Authenticator!.Authenticate(client, request); var paramList = request.Parameters.Where(p => p.Name!.Equals(KnownHeaders.Authorization)).ToList(); Assert.Equal(2, paramList.Count); var queryAuthParam = paramList.Single(p => p.Type.Equals(ParameterType.QueryString)); var headerAuthParam = paramList.Single(p => p.Type.Equals(ParameterType.HttpHeader)); Assert.Equal("manualAuth", queryAuthParam.Value); Assert.Equal(_expectedAuthHeaderContent, headerAuthParam.Value); } [Fact] public async Task Set_Auth_Header_Only_Once() { using var client = new RestClient(new RestClientOptions { Authenticator = new JwtAuthenticator(_testJwt) }); var request = new RestRequest(); request.AddHeader(KnownHeaders.Authorization, "second_header_auth_token"); //In real case client.Execute(...) will invoke Authenticate method await client.Options.Authenticator!.Authenticate(client, request); var paramList = request.Parameters.Where(p => p.Name.Equals(KnownHeaders.Authorization)).ToList(); paramList.Should().HaveCount(1); var authParam = paramList[0]; Assert.Equal(ParameterType.HttpHeader, authParam.Type); Assert.Equal(_expectedAuthHeaderContent, authParam.Value); Assert.NotEqual("Bearer second_header_auth_token", authParam.Value); } [Fact] public async Task Updates_Auth_Header() { var request = new RestRequest(); var authenticator = new JwtAuthenticator(_expectedAuthHeaderContent); using var client = new RestClient(new RestClientOptions { Authenticator = authenticator }); await client.Options.Authenticator!.Authenticate(client, request); authenticator.SetBearerToken("second_header_auth_token"); await client.Options.Authenticator.Authenticate(client, request); var paramList = request.Parameters.Where(p => p.Name.Equals(KnownHeaders.Authorization)).ToList(); Assert.Single(paramList); var authParam = paramList[0]; Assert.Equal(ParameterType.HttpHeader, authParam.Type); Assert.NotEqual(_expectedAuthHeaderContent, authParam.Value); Assert.Equal("Bearer second_header_auth_token", authParam.Value); } [Fact] public void Throw_Argument_Null_Exception() { var exception = Assert.Throws<ArgumentNullException>(() => new JwtAuthenticator(null!)); Assert.Equal("accessToken", exception.ParamName); } }
RestSharp
You are an expert C++ developer. Task: Write a unit test for 'JwtAuthenticator' using GoogleTest (gtest) and GoogleMock (gmock). Context: - Class: JwtAuthenticator Requirements: Use EXPECT_CALL for virtual methods.
industrial
// Copyright (c) .NET Foundation and Contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using RestSharp.Authenticators.OAuth; using RestSharp.Extensions; using System.Web; // ReSharper disable PropertyCanBeMadeInitOnly.Global // ReSharper disable NotResolvedInText // ReSharper disable CheckNamespace namespace RestSharp.Authenticators; /// <seealso href="http://tools.ietf.org/html/rfc5849">RFC: The OAuth 1.0 Protocol</seealso> // ReSharper disable once ClassWithVirtualMembersNeverInherited.Global public class OAuth1Authenticator : IAuthenticator { public virtual string? Realm { get; set; } public virtual OAuthParameterHandling ParameterHandling { get; set; } public virtual OAuthSignatureMethod SignatureMethod { get; set; } public virtual OAuthSignatureTreatment SignatureTreatment { get; set; } public virtual OAuthType Type { get; set; } public virtual string? ConsumerKey { get; set; } public virtual string? ConsumerSecret { get; set; } public virtual string? Token { get; set; } public virtual string? TokenSecret { get; set; } public virtual string? Verifier { get; set; } public virtual string? Version { get; set; } public virtual string? CallbackUrl { get; set; } public virtual string? SessionHandle { get; set; } public virtual string? ClientUsername { get; set; } public virtual string? ClientPassword { get; set; } public ValueTask Authenticate(IRestClient client, RestRequest request) { var workflow = new OAuthWorkflow { ConsumerKey = ConsumerKey, ConsumerSecret = ConsumerSecret, ParameterHandling = ParameterHandling, SignatureMethod = SignatureMethod, SignatureTreatment = SignatureTreatment, Verifier = Verifier, Version = Version, CallbackUrl = CallbackUrl, SessionHandle = SessionHandle, Token = Token, TokenSecret = TokenSecret, ClientUsername = ClientUsername, ClientPassword = ClientPassword }; AddOAuthData(client, request, workflow, Type, Realm); return default; } /// <summary> /// Creates an authenticator to retrieve a request token. /// </summary> /// <param name="consumerKey">Consumer or API key</param> /// <param name="consumerSecret">Consumer or API secret</param> /// <param name="signatureMethod">Signature method, default is HMAC SHA1</param> /// <returns>Authenticator instance</returns> [PublicAPI] public static OAuth1Authenticator ForRequestToken( string consumerKey, string? consumerSecret, OAuthSignatureMethod signatureMethod = OAuthSignatureMethod.HmacSha1 ) => new() { ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader, SignatureMethod = signatureMethod, SignatureTreatment = OAuthSignatureTreatment.Escaped, ConsumerKey = consumerKey, ConsumerSecret = consumerSecret, Type = OAuthType.RequestToken }; /// <summary> /// Creates an authenticator to retrieve a request token with custom callback. /// </summary> /// <param name="consumerKey">Consumer or API key</param> /// <param name="consumerSecret">Consumer or API secret</param> /// <param name="callbackUrl">URL to where the user will be redirected to after authhentication</param> /// <returns>Authenticator instance</returns> [PublicAPI] public static OAuth1Authenticator ForRequestToken(string consumerKey, string? consumerSecret, string callbackUrl) { var authenticator = ForRequestToken(consumerKey, consumerSecret); authenticator.CallbackUrl = callbackUrl; return authenticator; } /// <summary> /// Creates an authenticator to retrieve an access token using the request token. /// </summary> /// <param name="consumerKey">Consumer or API key</param> /// <param name="consumerSecret">Consumer or API secret</param> /// <param name="token">Request token</param> /// <param name="tokenSecret">Request token secret</param> /// <param name="signatureMethod">Signature method, default is HMAC SHA1</param> /// <returns>Authenticator instance</returns> [PublicAPI] public static OAuth1Authenticator ForAccessToken( string consumerKey, string? consumerSecret, string token, string tokenSecret, OAuthSignatureMethod signatureMethod = OAuthSignatureMethod.HmacSha1 ) => new() { ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader, SignatureMethod = signatureMethod, SignatureTreatment = OAuthSignatureTreatment.Escaped, ConsumerKey = consumerKey, ConsumerSecret = consumerSecret, Token = token, TokenSecret = tokenSecret, Type = OAuthType.AccessToken }; /// <summary> /// Creates an authenticator to retrieve an access token using the request token and a verifier. /// </summary> /// <param name="consumerKey">Consumer or API key</param> /// <param name="consumerSecret">Consumer or API secret</param> /// <param name="token">Request token</param> /// <param name="tokenSecret">Request token secret</param> /// <param name="verifier">Verifier received from the API server</param> /// <returns>Authenticator instance</returns> [PublicAPI] public static OAuth1Authenticator ForAccessToken( string consumerKey, string? consumerSecret, string token, string tokenSecret, string verifier ) { var authenticator = ForAccessToken(consumerKey, consumerSecret, token, tokenSecret); authenticator.Verifier = verifier; return authenticator; } [PublicAPI] public static OAuth1Authenticator ForAccessTokenRefresh( string consumerKey, string? consumerSecret, string token, string tokenSecret, string sessionHandle ) { var authenticator = ForAccessToken(consumerKey, consumerSecret, token, tokenSecret); authenticator.SessionHandle = sessionHandle; return authenticator; } [PublicAPI] public static OAuth1Authenticator ForAccessTokenRefresh( string consumerKey, string? consumerSecret, string token, string tokenSecret, string verifier, string sessionHandle ) { var authenticator = ForAccessToken(consumerKey, consumerSecret, token, tokenSecret); authenticator.SessionHandle = sessionHandle; authenticator.Verifier = verifier; return authenticator; } [PublicAPI] public static OAuth1Authenticator ForClientAuthentication( string consumerKey, string? consumerSecret, string username, string password, OAuthSignatureMethod signatureMethod = OAuthSignatureMethod.HmacSha1 ) => new() { ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader, SignatureMethod = signatureMethod, SignatureTreatment = OAuthSignatureTreatment.Escaped, ConsumerKey = consumerKey, ConsumerSecret = consumerSecret, ClientUsername = username, ClientPassword = password, Type = OAuthType.ClientAuthentication }; /// <summary> /// Creates an authenticator to make calls to protected resources using the access token. /// </summary> /// <param name="consumerKey">Consumer or API key</param> /// <param name="consumerSecret">Consumer or API secret</param> /// <param name="accessToken">Access token</param> /// <param name="accessTokenSecret">Access token secret</param> /// <param name="signatureMethod">Signature method, default is HMAC SHA1</param> /// <returns>Authenticator instance</returns> [PublicAPI] public static OAuth1Authenticator ForProtectedResource( string consumerKey, string? consumerSecret, string accessToken, string accessTokenSecret, OAuthSignatureMethod signatureMethod = OAuthSignatureMethod.HmacSha1 ) => new() { Type = OAuthType.ProtectedResource, ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader, SignatureMethod = signatureMethod, SignatureTreatment = OAuthSignatureTreatment.Escaped, ConsumerKey = consumerKey, ConsumerSecret = consumerSecret, Token = accessToken, TokenSecret = accessTokenSecret }; internal static void AddOAuthData( IRestClient client, RestRequest request, OAuthWorkflow workflow, OAuthType type, string? realm ) { var requestUrl = client.BuildUriWithoutQueryParameters(request).AbsoluteUri; if (requestUrl.Contains('?')) throw new ApplicationException( "Using query parameters in the base URL is not supported for OAuth calls. Consider using AddDefaultQueryParameter instead." ); var url = client.BuildUri(request).ToString(); var queryStringStart = url.IndexOf('?'); if (queryStringStart != -1) url = url[..queryStringStart]; var method = request.Method.ToString().ToUpperInvariant(); var parameters = new WebPairCollection(); var query = request.AlwaysMultipartFormData || request.Files.Count > 0 ? x => BaseQuery(x) && x.Name != null && x.Name.StartsWith("oauth_") : (Func<Parameter, bool>)BaseQuery; parameters.AddRange(client.DefaultParameters.Where(query).ToWebParameters()); parameters.AddRange(request.Parameters.Where(query).ToWebParameters()); workflow.RequestUrl = url; var oauth = type switch { OAuthType.RequestToken => workflow.BuildRequestTokenSignature(method, parameters), OAuthType.AccessToken => workflow.BuildAccessTokenSignature(method, parameters), OAuthType.ClientAuthentication => workflow.BuildClientAuthAccessTokenSignature(method, parameters), OAuthType.ProtectedResource => workflow.BuildProtectedResourceSignature(method, parameters), _ => throw new ArgumentOutOfRangeException(nameof(Type)) }; oauth.Parameters.Add("oauth_signature", oauth.Signature); var oauthParameters = workflow.ParameterHandling switch { OAuthParameterHandling.HttpAuthorizationHeader => CreateHeaderParameters(), OAuthParameterHandling.UrlOrPostParameters => CreateUrlParameters(), _ => throw new ArgumentOutOfRangeException(nameof(ParameterHandling)) }; request.AddOrUpdateParameters(oauthParameters); return; // include all GET and POST parameters before generating the signature // according to the RFC 5849 - The OAuth 1.0 Protocol // http://tools.ietf.org/html/rfc5849#section-3.4.1 // if this change causes trouble we need to introduce a flag indicating the specific OAuth implementation level, // or implement a separate class for each OAuth version static bool BaseQuery(Parameter x) => x.Type is ParameterType.GetOrPost or ParameterType.QueryString; IEnumerable<Parameter> CreateHeaderParameters() => [new HeaderParameter(KnownHeaders.Authorization, GetAuthorizationHeader())]; IEnumerable<Parameter> CreateUrlParameters() => oauth.Parameters.Select(p => new GetOrPostParameter(p.Name, HttpUtility.UrlDecode(p.Value))); string GetAuthorizationHeader() { var oathParameters = oauth.Parameters .OrderBy(x => x, WebPair.Comparer) .Select(x => x.GetQueryParameter(true)) .ToList(); if (!realm.IsEmpty()) oathParameters.Insert(0, $"realm=\"{OAuthTools.UrlEncodeRelaxed(realm)}\""); return $"OAuth {string.Join(",", oathParameters)}"; } } } static class ParametersExtensions { internal static IEnumerable<WebPair> ToWebParameters(this IEnumerable<Parameter> p) => p.Select(x => new WebPair(Ensure.NotNull(x.Name, "Parameter name"), x.Value?.ToString())); }
using System.Globalization; using System.Security.Cryptography; using RestSharp.Authenticators.OAuth; using RestSharp.Authenticators.OAuth.Extensions; namespace RestSharp.Tests.Auth; public class OAuthTests { public OAuthTests() { Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; Thread.CurrentThread.CurrentUICulture = CultureInfo.InstalledUICulture; } [Fact] public void HmacSha256_Does_Not_Accept_Nulls() { const string consumerSecret = "12345678"; Assert.Throws<ArgumentNullException>( () => OAuthTools.GetSignature(OAuthSignatureMethod.HmacSha256, null, consumerSecret) ); } [Theory] [InlineData( "The quick brown fox jumps over the lazy dog", "rVL90tHhGt0eQ0TCITY74nVL22P%2FltlWS7WvJXpECPs%3D", "12345678" )] [InlineData( "The quick\tbrown\nfox\rjumps\r\nover\t\tthe\n\nlazy\r\n\r\ndog", "C%2B2RY0Hna6VrfK1crCkU%2FV1e0ECoxoDh41iOOdmEMx8%3D", "12345678" )] [InlineData("", "%2BnkCwZfv%2FQVmBbNZsPKbBT3kAg3JtVn3f3YMBtV83L8%3D", "12345678")] [InlineData(" !\"#$%&'()*+,", "xcTgWGBVZaw%2Bilg6kjWAGt%2FhCcsVBMMe1CcDEnxnh8Y%3D", "12345678")] [InlineData("AB", "JJgraAxzpO2Q6wiC3blM4eiQeA9WmkALaZI8yGRH4qM%3D", "CD!")] public void HmacSha256_Hashes_Correctly(string value, string expected, string consumerSecret) { var actual = OAuthTools.GetSignature(OAuthSignatureMethod.HmacSha256, value, consumerSecret); Assert.Equal(expected, actual); } [Theory] [InlineData("1234", "%31%32%33%34")] [InlineData("\x00\x01\x02\x03", "%00%01%02%03")] [InlineData("\r\n\t", "%0D%0A%09")] public void PercentEncode_Encodes_Correctly(string value, string expected) { var actual = value.PercentEncode(); Assert.Equal(expected, actual); } [Theory] [InlineData("The quick brown fox jumps over the lazy dog", 1024)] [InlineData("The quick brown fox jumps over the lazy dog", 2048)] [InlineData("The quick brown fox jumps over the lazy dog", 4096)] [InlineData("", 2048)] [InlineData(" !\"#$%&'()*+,", 2048)] public void RsaSha1_Signs_Correctly(string value, int keySize) { var hasher = SHA1.Create(); var hash = hasher.ComputeHash(value.GetBytes()); using var crypto = new RSACryptoServiceProvider(keySize); crypto.PersistKeyInCsp = false; var privateKey = crypto.ToXmlString(true); var signature = OAuthTools.GetSignature( OAuthSignatureMethod.RsaSha1, OAuthSignatureTreatment.Unescaped, value, privateKey ); var signatureBytes = Convert.FromBase64String(signature); Assert.True(crypto.VerifyHash(hash, CryptoConfig.MapNameToOID("SHA1"), signatureBytes)); } [Theory] [InlineData("abcdefghijklmnopqrstuvwxyz", "abcdefghijklmnopqrstuvwxyz")] [InlineData("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "ABCDEFGHIJKLMNOPQRSTUVWXYZ")] [InlineData("0123456789", "0123456789")] [InlineData("-._~", "-._~")] [InlineData(" !\"#$%&'()*+,", "%20%21%22%23%24%25%26%27%28%29%2A%2B%2C")] [InlineData("%$%", "%25%24%25")] [InlineData("%", "%25")] [InlineData("/:;<=>?@", "%2F%3A%3B%3C%3D%3E%3F%40")] [InlineData("\x00\x01\a\b\f\n\r\t\v", "%00%01%07%08%0C%0A%0D%09%0B")] public void UrlStrictEncode_Encodes_Correctly(string value, string expected) { var actual = OAuthTools.UrlEncodeStrict(value); Assert.Equal(expected, actual); } }
RestSharp
You are an expert .NET (C#) developer. Task: Write a unit test for 'ParametersExtensions' using XUnit and Moq. Context: - Class: ParametersExtensions Requirements: Use Mock<T> interface mocking.
industrial
// Copyright (c) .NET Foundation and Contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace RestSharp.Authenticators; public abstract class AuthenticatorBase(string token) : IAuthenticator { protected string Token { get; set; } = token; protected abstract ValueTask<Parameter> GetAuthenticationParameter(string accessToken); public async ValueTask Authenticate(IRestClient client, RestRequest request) => request.AddOrUpdateParameter(await GetAuthenticationParameter(Token).ConfigureAwait(false)); }
using System.Net; using RestSharp.Authenticators; using RestSharp.Tests.Fixtures; using RichardSzalay.MockHttp; namespace RestSharp.Tests.Auth; public class AuthenticatorTests { [Fact] public async Task Should_add_authorization_header() { const string auth = "LetMeIn"; using var client = MockHttpClient.Create( Method.Get, request => request.WithHeaders(KnownHeaders.Authorization, auth).Respond(HttpStatusCode.OK), opt => opt.Authenticator = new TestAuthenticator(ParameterType.HttpHeader, KnownHeaders.Authorization, auth) ); var response = await client.ExecuteGetAsync(new RestRequest()); response.StatusCode.Should().Be(HttpStatusCode.OK); } [Fact] public async Task Should_add_authorization_form_parameter() { const string auth = "LetMeIn"; const string formField = "token"; using var client = MockHttpClient.Create( Method.Post, request => request.WithFormData(formField, auth).Respond(HttpStatusCode.OK), opt => opt.Authenticator = new TestAuthenticator(ParameterType.GetOrPost, formField, auth) ); var response = await client.ExecutePostAsync(new RestRequest()); response.StatusCode.Should().Be(HttpStatusCode.OK); } class TestAuthenticator(ParameterType type, string name, string value) : IAuthenticator { public ValueTask Authenticate(IRestClient client, RestRequest request) { request.AddParameter(name, value, type); return default; } } }
RestSharp
You are an expert C++ developer. Task: Write a unit test for 'AuthenticatorBase' using GoogleTest (gtest) and GoogleMock (gmock). Context: - Class: AuthenticatorBase Requirements: Use EXPECT_CALL for virtual methods.
industrial
// Copyright (c) .NET Foundation and Contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.Text; namespace RestSharp.Authenticators; /// <summary> /// Allows "basic access authentication" for HTTP requests. /// </summary> /// <remarks> /// Encoding can be specified depending on what your server expect (see https://stackoverflow.com/a/7243567). /// UTF-8 is used by default but some servers might expect ISO-8859-1 encoding. /// </remarks> [PublicAPI] public class HttpBasicAuthenticator(string username, string password, Encoding encoding) : AuthenticatorBase(GetHeader(username, password, encoding)) { public HttpBasicAuthenticator(string username, string password) : this(username, password, Encoding.UTF8) { } static string GetHeader(string username, string password, Encoding encoding) => Convert.ToBase64String(encoding.GetBytes($"{username}:{password}")); // return ; protected override ValueTask<Parameter> GetAuthenticationParameter(string accessToken) => new(new HeaderParameter(KnownHeaders.Authorization, $"Basic {accessToken}")); }
using System.Text; using RestSharp.Authenticators; namespace RestSharp.Tests.Auth; public class HttpBasicAuthTests { const string Username = "username"; const string Password = "password"; readonly HttpBasicAuthenticator _auth = new(Username, Password); [Fact] public async Task Authenticate_ShouldAddAuthorizationParameter_IfPreviouslyUnassigned() { // Arrange using var client = new RestClient(); var request = new RestRequest(); request.AddQueryParameter("NotMatching", "", default); var expectedToken = $"Basic {Convert.ToBase64String(Encoding.UTF8.GetBytes($"{Username}:{Password}"))}"; // Act await _auth.Authenticate(client, request); // Assert request.Parameters.Single(x => x.Name == KnownHeaders.Authorization).Value.Should().Be(expectedToken); } }
RestSharp
You are an expert .NET (C#) developer. Task: Write a unit test for 'HttpBasicAuthenticator' using XUnit and Moq. Context: - Class: HttpBasicAuthenticator Requirements: Use Mock<T> interface mocking.
industrial
// Copyright (c) .NET Foundation and Contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using RestSharp.Authenticators.OAuth; using RestSharp.Extensions; using System.Web; // ReSharper disable PropertyCanBeMadeInitOnly.Global // ReSharper disable NotResolvedInText // ReSharper disable CheckNamespace namespace RestSharp.Authenticators; /// <seealso href="http://tools.ietf.org/html/rfc5849">RFC: The OAuth 1.0 Protocol</seealso> // ReSharper disable once ClassWithVirtualMembersNeverInherited.Global public class OAuth1Authenticator : IAuthenticator { public virtual string? Realm { get; set; } public virtual OAuthParameterHandling ParameterHandling { get; set; } public virtual OAuthSignatureMethod SignatureMethod { get; set; } public virtual OAuthSignatureTreatment SignatureTreatment { get; set; } public virtual OAuthType Type { get; set; } public virtual string? ConsumerKey { get; set; } public virtual string? ConsumerSecret { get; set; } public virtual string? Token { get; set; } public virtual string? TokenSecret { get; set; } public virtual string? Verifier { get; set; } public virtual string? Version { get; set; } public virtual string? CallbackUrl { get; set; } public virtual string? SessionHandle { get; set; } public virtual string? ClientUsername { get; set; } public virtual string? ClientPassword { get; set; } public ValueTask Authenticate(IRestClient client, RestRequest request) { var workflow = new OAuthWorkflow { ConsumerKey = ConsumerKey, ConsumerSecret = ConsumerSecret, ParameterHandling = ParameterHandling, SignatureMethod = SignatureMethod, SignatureTreatment = SignatureTreatment, Verifier = Verifier, Version = Version, CallbackUrl = CallbackUrl, SessionHandle = SessionHandle, Token = Token, TokenSecret = TokenSecret, ClientUsername = ClientUsername, ClientPassword = ClientPassword }; AddOAuthData(client, request, workflow, Type, Realm); return default; } /// <summary> /// Creates an authenticator to retrieve a request token. /// </summary> /// <param name="consumerKey">Consumer or API key</param> /// <param name="consumerSecret">Consumer or API secret</param> /// <param name="signatureMethod">Signature method, default is HMAC SHA1</param> /// <returns>Authenticator instance</returns> [PublicAPI] public static OAuth1Authenticator ForRequestToken( string consumerKey, string? consumerSecret, OAuthSignatureMethod signatureMethod = OAuthSignatureMethod.HmacSha1 ) => new() { ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader, SignatureMethod = signatureMethod, SignatureTreatment = OAuthSignatureTreatment.Escaped, ConsumerKey = consumerKey, ConsumerSecret = consumerSecret, Type = OAuthType.RequestToken }; /// <summary> /// Creates an authenticator to retrieve a request token with custom callback. /// </summary> /// <param name="consumerKey">Consumer or API key</param> /// <param name="consumerSecret">Consumer or API secret</param> /// <param name="callbackUrl">URL to where the user will be redirected to after authhentication</param> /// <returns>Authenticator instance</returns> [PublicAPI] public static OAuth1Authenticator ForRequestToken(string consumerKey, string? consumerSecret, string callbackUrl) { var authenticator = ForRequestToken(consumerKey, consumerSecret); authenticator.CallbackUrl = callbackUrl; return authenticator; } /// <summary> /// Creates an authenticator to retrieve an access token using the request token. /// </summary> /// <param name="consumerKey">Consumer or API key</param> /// <param name="consumerSecret">Consumer or API secret</param> /// <param name="token">Request token</param> /// <param name="tokenSecret">Request token secret</param> /// <param name="signatureMethod">Signature method, default is HMAC SHA1</param> /// <returns>Authenticator instance</returns> [PublicAPI] public static OAuth1Authenticator ForAccessToken( string consumerKey, string? consumerSecret, string token, string tokenSecret, OAuthSignatureMethod signatureMethod = OAuthSignatureMethod.HmacSha1 ) => new() { ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader, SignatureMethod = signatureMethod, SignatureTreatment = OAuthSignatureTreatment.Escaped, ConsumerKey = consumerKey, ConsumerSecret = consumerSecret, Token = token, TokenSecret = tokenSecret, Type = OAuthType.AccessToken }; /// <summary> /// Creates an authenticator to retrieve an access token using the request token and a verifier. /// </summary> /// <param name="consumerKey">Consumer or API key</param> /// <param name="consumerSecret">Consumer or API secret</param> /// <param name="token">Request token</param> /// <param name="tokenSecret">Request token secret</param> /// <param name="verifier">Verifier received from the API server</param> /// <returns>Authenticator instance</returns> [PublicAPI] public static OAuth1Authenticator ForAccessToken( string consumerKey, string? consumerSecret, string token, string tokenSecret, string verifier ) { var authenticator = ForAccessToken(consumerKey, consumerSecret, token, tokenSecret); authenticator.Verifier = verifier; return authenticator; } [PublicAPI] public static OAuth1Authenticator ForAccessTokenRefresh( string consumerKey, string? consumerSecret, string token, string tokenSecret, string sessionHandle ) { var authenticator = ForAccessToken(consumerKey, consumerSecret, token, tokenSecret); authenticator.SessionHandle = sessionHandle; return authenticator; } [PublicAPI] public static OAuth1Authenticator ForAccessTokenRefresh( string consumerKey, string? consumerSecret, string token, string tokenSecret, string verifier, string sessionHandle ) { var authenticator = ForAccessToken(consumerKey, consumerSecret, token, tokenSecret); authenticator.SessionHandle = sessionHandle; authenticator.Verifier = verifier; return authenticator; } [PublicAPI] public static OAuth1Authenticator ForClientAuthentication( string consumerKey, string? consumerSecret, string username, string password, OAuthSignatureMethod signatureMethod = OAuthSignatureMethod.HmacSha1 ) => new() { ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader, SignatureMethod = signatureMethod, SignatureTreatment = OAuthSignatureTreatment.Escaped, ConsumerKey = consumerKey, ConsumerSecret = consumerSecret, ClientUsername = username, ClientPassword = password, Type = OAuthType.ClientAuthentication }; /// <summary> /// Creates an authenticator to make calls to protected resources using the access token. /// </summary> /// <param name="consumerKey">Consumer or API key</param> /// <param name="consumerSecret">Consumer or API secret</param> /// <param name="accessToken">Access token</param> /// <param name="accessTokenSecret">Access token secret</param> /// <param name="signatureMethod">Signature method, default is HMAC SHA1</param> /// <returns>Authenticator instance</returns> [PublicAPI] public static OAuth1Authenticator ForProtectedResource( string consumerKey, string? consumerSecret, string accessToken, string accessTokenSecret, OAuthSignatureMethod signatureMethod = OAuthSignatureMethod.HmacSha1 ) => new() { Type = OAuthType.ProtectedResource, ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader, SignatureMethod = signatureMethod, SignatureTreatment = OAuthSignatureTreatment.Escaped, ConsumerKey = consumerKey, ConsumerSecret = consumerSecret, Token = accessToken, TokenSecret = accessTokenSecret }; internal static void AddOAuthData( IRestClient client, RestRequest request, OAuthWorkflow workflow, OAuthType type, string? realm ) { var requestUrl = client.BuildUriWithoutQueryParameters(request).AbsoluteUri; if (requestUrl.Contains('?')) throw new ApplicationException( "Using query parameters in the base URL is not supported for OAuth calls. Consider using AddDefaultQueryParameter instead." ); var url = client.BuildUri(request).ToString(); var queryStringStart = url.IndexOf('?'); if (queryStringStart != -1) url = url[..queryStringStart]; var method = request.Method.ToString().ToUpperInvariant(); var parameters = new WebPairCollection(); var query = request.AlwaysMultipartFormData || request.Files.Count > 0 ? x => BaseQuery(x) && x.Name != null && x.Name.StartsWith("oauth_") : (Func<Parameter, bool>)BaseQuery; parameters.AddRange(client.DefaultParameters.Where(query).ToWebParameters()); parameters.AddRange(request.Parameters.Where(query).ToWebParameters()); workflow.RequestUrl = url; var oauth = type switch { OAuthType.RequestToken => workflow.BuildRequestTokenSignature(method, parameters), OAuthType.AccessToken => workflow.BuildAccessTokenSignature(method, parameters), OAuthType.ClientAuthentication => workflow.BuildClientAuthAccessTokenSignature(method, parameters), OAuthType.ProtectedResource => workflow.BuildProtectedResourceSignature(method, parameters), _ => throw new ArgumentOutOfRangeException(nameof(Type)) }; oauth.Parameters.Add("oauth_signature", oauth.Signature); var oauthParameters = workflow.ParameterHandling switch { OAuthParameterHandling.HttpAuthorizationHeader => CreateHeaderParameters(), OAuthParameterHandling.UrlOrPostParameters => CreateUrlParameters(), _ => throw new ArgumentOutOfRangeException(nameof(ParameterHandling)) }; request.AddOrUpdateParameters(oauthParameters); return; // include all GET and POST parameters before generating the signature // according to the RFC 5849 - The OAuth 1.0 Protocol // http://tools.ietf.org/html/rfc5849#section-3.4.1 // if this change causes trouble we need to introduce a flag indicating the specific OAuth implementation level, // or implement a separate class for each OAuth version static bool BaseQuery(Parameter x) => x.Type is ParameterType.GetOrPost or ParameterType.QueryString; IEnumerable<Parameter> CreateHeaderParameters() => [new HeaderParameter(KnownHeaders.Authorization, GetAuthorizationHeader())]; IEnumerable<Parameter> CreateUrlParameters() => oauth.Parameters.Select(p => new GetOrPostParameter(p.Name, HttpUtility.UrlDecode(p.Value))); string GetAuthorizationHeader() { var oathParameters = oauth.Parameters .OrderBy(x => x, WebPair.Comparer) .Select(x => x.GetQueryParameter(true)) .ToList(); if (!realm.IsEmpty()) oathParameters.Insert(0, $"realm=\"{OAuthTools.UrlEncodeRelaxed(realm)}\""); return $"OAuth {string.Join(",", oathParameters)}"; } } } static class ParametersExtensions { internal static IEnumerable<WebPair> ToWebParameters(this IEnumerable<Parameter> p) => p.Select(x => new WebPair(Ensure.NotNull(x.Name, "Parameter name"), x.Value?.ToString())); }
using System.Xml.Serialization; using RestSharp.Authenticators; using RestSharp.Authenticators.OAuth; using RestSharp.Tests.Shared.Extensions; #pragma warning disable CS8618 namespace RestSharp.Tests.Auth; public class OAuth1Tests { [XmlRoot("queue")] class Queue { [XmlElement("etag")] public string Etag { get; set; } public List<QueueItem> Items { get; set; } } [XmlRoot("queue_item")] class QueueItem { [XmlElement("id")] public string Id { get; set; } [XmlElement("position")] public int Position { get; set; } } [Fact] public async Task Can_Authenticate_OAuth1_With_Querystring_Parameters() { const string consumerKey = "enterConsumerKeyHere"; const string consumerSecret = "enterConsumerSecretHere"; const string baseUrl = "http://restsharp.org"; var expected = new List<string> { "oauth_consumer_key", "oauth_nonce", "oauth_signature_method", "oauth_timestamp", "oauth_version", "oauth_signature" }; using var client = new RestClient(baseUrl); var request = new RestRequest(); var authenticator = OAuth1Authenticator.ForRequestToken(consumerKey, consumerSecret); authenticator.ParameterHandling = OAuthParameterHandling.UrlOrPostParameters; await authenticator.Authenticate(client, request); var requestUri = client.BuildUri(request); var actual = requestUri.ParseQuery().Select(x => x.Key).ToList(); actual.Should().BeEquivalentTo(expected); } [Theory] [MemberData(nameof(EncodeParametersTestData))] public void Properly_Encodes_Parameter_Names(IList<(string, string)> parameters, string expected) { var postData = new WebPairCollection(); postData.AddRange(parameters.Select(x => new WebPair(x.Item1, x.Item2))); var sortedParams = OAuthTools.SortParametersExcludingSignature(postData); sortedParams.First().Should().Be(expected); } public static IEnumerable<object[]> EncodeParametersTestData => new List<object[]> { new object[] { new List<(string, string)> { ("name[first]", "Chuck"), ("name[last]", "Testa") }, "name%5Bfirst%5D=Chuck" }, new object[] { new List<(string, string)> { ("country", "España") }, "country=Espa%C3%B1a" } }; [Fact] public void Encodes_parameter() { var parameter = new WebPair("status", "Hello Ladies + Gentlemen, a signed OAuth request!"); var parameters = new WebPairCollection { parameter }; const string expected = "status%3DHello%2520Ladies%2520%252B%2520Gentlemen%252C%2520a%2520signed%2520OAuth%2520request%2521"; var norm = OAuthTools.NormalizeRequestParameters(parameters); var escaped = OAuthTools.UrlEncodeRelaxed(norm); escaped.Should().Be(expected); } }
RestSharp
You are an expert .NET (C#) developer. Task: Write a unit test for 'ParametersExtensions' using XUnit and Moq. Context: - Class: ParametersExtensions Requirements: Use Mock<T> interface mocking.
industrial
// Copyright (c) .NET Foundation and Contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using RestSharp.Authenticators.OAuth; using RestSharp.Extensions; using System.Web; // ReSharper disable PropertyCanBeMadeInitOnly.Global // ReSharper disable NotResolvedInText // ReSharper disable CheckNamespace namespace RestSharp.Authenticators; /// <seealso href="http://tools.ietf.org/html/rfc5849">RFC: The OAuth 1.0 Protocol</seealso> // ReSharper disable once ClassWithVirtualMembersNeverInherited.Global public class OAuth1Authenticator : IAuthenticator { public virtual string? Realm { get; set; } public virtual OAuthParameterHandling ParameterHandling { get; set; } public virtual OAuthSignatureMethod SignatureMethod { get; set; } public virtual OAuthSignatureTreatment SignatureTreatment { get; set; } public virtual OAuthType Type { get; set; } public virtual string? ConsumerKey { get; set; } public virtual string? ConsumerSecret { get; set; } public virtual string? Token { get; set; } public virtual string? TokenSecret { get; set; } public virtual string? Verifier { get; set; } public virtual string? Version { get; set; } public virtual string? CallbackUrl { get; set; } public virtual string? SessionHandle { get; set; } public virtual string? ClientUsername { get; set; } public virtual string? ClientPassword { get; set; } public ValueTask Authenticate(IRestClient client, RestRequest request) { var workflow = new OAuthWorkflow { ConsumerKey = ConsumerKey, ConsumerSecret = ConsumerSecret, ParameterHandling = ParameterHandling, SignatureMethod = SignatureMethod, SignatureTreatment = SignatureTreatment, Verifier = Verifier, Version = Version, CallbackUrl = CallbackUrl, SessionHandle = SessionHandle, Token = Token, TokenSecret = TokenSecret, ClientUsername = ClientUsername, ClientPassword = ClientPassword }; AddOAuthData(client, request, workflow, Type, Realm); return default; } /// <summary> /// Creates an authenticator to retrieve a request token. /// </summary> /// <param name="consumerKey">Consumer or API key</param> /// <param name="consumerSecret">Consumer or API secret</param> /// <param name="signatureMethod">Signature method, default is HMAC SHA1</param> /// <returns>Authenticator instance</returns> [PublicAPI] public static OAuth1Authenticator ForRequestToken( string consumerKey, string? consumerSecret, OAuthSignatureMethod signatureMethod = OAuthSignatureMethod.HmacSha1 ) => new() { ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader, SignatureMethod = signatureMethod, SignatureTreatment = OAuthSignatureTreatment.Escaped, ConsumerKey = consumerKey, ConsumerSecret = consumerSecret, Type = OAuthType.RequestToken }; /// <summary> /// Creates an authenticator to retrieve a request token with custom callback. /// </summary> /// <param name="consumerKey">Consumer or API key</param> /// <param name="consumerSecret">Consumer or API secret</param> /// <param name="callbackUrl">URL to where the user will be redirected to after authhentication</param> /// <returns>Authenticator instance</returns> [PublicAPI] public static OAuth1Authenticator ForRequestToken(string consumerKey, string? consumerSecret, string callbackUrl) { var authenticator = ForRequestToken(consumerKey, consumerSecret); authenticator.CallbackUrl = callbackUrl; return authenticator; } /// <summary> /// Creates an authenticator to retrieve an access token using the request token. /// </summary> /// <param name="consumerKey">Consumer or API key</param> /// <param name="consumerSecret">Consumer or API secret</param> /// <param name="token">Request token</param> /// <param name="tokenSecret">Request token secret</param> /// <param name="signatureMethod">Signature method, default is HMAC SHA1</param> /// <returns>Authenticator instance</returns> [PublicAPI] public static OAuth1Authenticator ForAccessToken( string consumerKey, string? consumerSecret, string token, string tokenSecret, OAuthSignatureMethod signatureMethod = OAuthSignatureMethod.HmacSha1 ) => new() { ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader, SignatureMethod = signatureMethod, SignatureTreatment = OAuthSignatureTreatment.Escaped, ConsumerKey = consumerKey, ConsumerSecret = consumerSecret, Token = token, TokenSecret = tokenSecret, Type = OAuthType.AccessToken }; /// <summary> /// Creates an authenticator to retrieve an access token using the request token and a verifier. /// </summary> /// <param name="consumerKey">Consumer or API key</param> /// <param name="consumerSecret">Consumer or API secret</param> /// <param name="token">Request token</param> /// <param name="tokenSecret">Request token secret</param> /// <param name="verifier">Verifier received from the API server</param> /// <returns>Authenticator instance</returns> [PublicAPI] public static OAuth1Authenticator ForAccessToken( string consumerKey, string? consumerSecret, string token, string tokenSecret, string verifier ) { var authenticator = ForAccessToken(consumerKey, consumerSecret, token, tokenSecret); authenticator.Verifier = verifier; return authenticator; } [PublicAPI] public static OAuth1Authenticator ForAccessTokenRefresh( string consumerKey, string? consumerSecret, string token, string tokenSecret, string sessionHandle ) { var authenticator = ForAccessToken(consumerKey, consumerSecret, token, tokenSecret); authenticator.SessionHandle = sessionHandle; return authenticator; } [PublicAPI] public static OAuth1Authenticator ForAccessTokenRefresh( string consumerKey, string? consumerSecret, string token, string tokenSecret, string verifier, string sessionHandle ) { var authenticator = ForAccessToken(consumerKey, consumerSecret, token, tokenSecret); authenticator.SessionHandle = sessionHandle; authenticator.Verifier = verifier; return authenticator; } [PublicAPI] public static OAuth1Authenticator ForClientAuthentication( string consumerKey, string? consumerSecret, string username, string password, OAuthSignatureMethod signatureMethod = OAuthSignatureMethod.HmacSha1 ) => new() { ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader, SignatureMethod = signatureMethod, SignatureTreatment = OAuthSignatureTreatment.Escaped, ConsumerKey = consumerKey, ConsumerSecret = consumerSecret, ClientUsername = username, ClientPassword = password, Type = OAuthType.ClientAuthentication }; /// <summary> /// Creates an authenticator to make calls to protected resources using the access token. /// </summary> /// <param name="consumerKey">Consumer or API key</param> /// <param name="consumerSecret">Consumer or API secret</param> /// <param name="accessToken">Access token</param> /// <param name="accessTokenSecret">Access token secret</param> /// <param name="signatureMethod">Signature method, default is HMAC SHA1</param> /// <returns>Authenticator instance</returns> [PublicAPI] public static OAuth1Authenticator ForProtectedResource( string consumerKey, string? consumerSecret, string accessToken, string accessTokenSecret, OAuthSignatureMethod signatureMethod = OAuthSignatureMethod.HmacSha1 ) => new() { Type = OAuthType.ProtectedResource, ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader, SignatureMethod = signatureMethod, SignatureTreatment = OAuthSignatureTreatment.Escaped, ConsumerKey = consumerKey, ConsumerSecret = consumerSecret, Token = accessToken, TokenSecret = accessTokenSecret }; internal static void AddOAuthData( IRestClient client, RestRequest request, OAuthWorkflow workflow, OAuthType type, string? realm ) { var requestUrl = client.BuildUriWithoutQueryParameters(request).AbsoluteUri; if (requestUrl.Contains('?')) throw new ApplicationException( "Using query parameters in the base URL is not supported for OAuth calls. Consider using AddDefaultQueryParameter instead." ); var url = client.BuildUri(request).ToString(); var queryStringStart = url.IndexOf('?'); if (queryStringStart != -1) url = url[..queryStringStart]; var method = request.Method.ToString().ToUpperInvariant(); var parameters = new WebPairCollection(); var query = request.AlwaysMultipartFormData || request.Files.Count > 0 ? x => BaseQuery(x) && x.Name != null && x.Name.StartsWith("oauth_") : (Func<Parameter, bool>)BaseQuery; parameters.AddRange(client.DefaultParameters.Where(query).ToWebParameters()); parameters.AddRange(request.Parameters.Where(query).ToWebParameters()); workflow.RequestUrl = url; var oauth = type switch { OAuthType.RequestToken => workflow.BuildRequestTokenSignature(method, parameters), OAuthType.AccessToken => workflow.BuildAccessTokenSignature(method, parameters), OAuthType.ClientAuthentication => workflow.BuildClientAuthAccessTokenSignature(method, parameters), OAuthType.ProtectedResource => workflow.BuildProtectedResourceSignature(method, parameters), _ => throw new ArgumentOutOfRangeException(nameof(Type)) }; oauth.Parameters.Add("oauth_signature", oauth.Signature); var oauthParameters = workflow.ParameterHandling switch { OAuthParameterHandling.HttpAuthorizationHeader => CreateHeaderParameters(), OAuthParameterHandling.UrlOrPostParameters => CreateUrlParameters(), _ => throw new ArgumentOutOfRangeException(nameof(ParameterHandling)) }; request.AddOrUpdateParameters(oauthParameters); return; // include all GET and POST parameters before generating the signature // according to the RFC 5849 - The OAuth 1.0 Protocol // http://tools.ietf.org/html/rfc5849#section-3.4.1 // if this change causes trouble we need to introduce a flag indicating the specific OAuth implementation level, // or implement a separate class for each OAuth version static bool BaseQuery(Parameter x) => x.Type is ParameterType.GetOrPost or ParameterType.QueryString; IEnumerable<Parameter> CreateHeaderParameters() => [new HeaderParameter(KnownHeaders.Authorization, GetAuthorizationHeader())]; IEnumerable<Parameter> CreateUrlParameters() => oauth.Parameters.Select(p => new GetOrPostParameter(p.Name, HttpUtility.UrlDecode(p.Value))); string GetAuthorizationHeader() { var oathParameters = oauth.Parameters .OrderBy(x => x, WebPair.Comparer) .Select(x => x.GetQueryParameter(true)) .ToList(); if (!realm.IsEmpty()) oathParameters.Insert(0, $"realm=\"{OAuthTools.UrlEncodeRelaxed(realm)}\""); return $"OAuth {string.Join(",", oathParameters)}"; } } } static class ParametersExtensions { internal static IEnumerable<WebPair> ToWebParameters(this IEnumerable<Parameter> p) => p.Select(x => new WebPair(Ensure.NotNull(x.Name, "Parameter name"), x.Value?.ToString())); }
using RestSharp.Authenticators; using RestSharp.Authenticators.OAuth; namespace RestSharp.Tests.Auth; public class OAuth1AuthTests { readonly OAuth1Authenticator _auth = new() { CallbackUrl = "CallbackUrl", ClientPassword = "ClientPassword", Type = OAuthType.ClientAuthentication, ClientUsername = "ClientUsername", ConsumerKey = "ConsumerKey", ConsumerSecret = "ConsumerSecret", Realm = "Realm", SessionHandle = "SessionHandle", SignatureMethod = OAuthSignatureMethod.PlainText, SignatureTreatment = OAuthSignatureTreatment.Escaped, Token = "Token", TokenSecret = "TokenSecret", Verifier = "Verifier", Version = "Version" }; [Fact] public void Authenticate_ShouldAddAuthorizationAsTextValueToRequest_OnHttpAuthorizationHeaderHandling() { // Arrange const string url = "https://no-query.string"; using var client = new RestClient(url); var request = new RestRequest(); _auth.ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader; // Act _auth.Authenticate(client, request); // Assert var authParameter = request.Parameters.Single(x => x.Name == KnownHeaders.Authorization); var value = (string)authParameter.Value; Assert.Contains("OAuth", value); Assert.Contains("realm=\"Realm\"", value); Assert.Contains("oauth_timestamp=", value); Assert.Contains("oauth_signature=\"ConsumerSecret", value); Assert.Contains("oauth_nonce=", value); Assert.Contains("oauth_consumer_key=\"ConsumerKey\"", value); Assert.Contains("oauth_signature_method=\"PLAINTEXT\"", value); Assert.Contains("oauth_version=\"Version\"", value); Assert.Contains("x_auth_mode=\"client_auth\"", value); Assert.Contains("x_auth_username=\"ClientUsername\"", value); Assert.Contains("x_auth_password=\"ClientPassword\"", value); } [Fact] public void Authenticate_ShouldAddSignatureToRequestAsSeparateParameters_OnUrlOrPostParametersHandling() { // Arrange const string url = "https://no-query.string"; using var client = new RestClient(url); var request = new RestRequest(); request.AddQueryParameter("queryparameter", "foobartemp"); _auth.ParameterHandling = OAuthParameterHandling.UrlOrPostParameters; // Act _auth.Authenticate(client, request); // Assert var parameters = request.Parameters; ParameterShouldBe("x_auth_username", "ClientUsername"); ParameterShouldBe("x_auth_password", "ClientPassword"); ParameterShouldBe("x_auth_mode", "client_auth"); ParameterShouldBe("oauth_consumer_key", "ConsumerKey"); ParameterShouldHaveValue("oauth_signature"); ParameterShouldBe("oauth_signature_method", "PLAINTEXT"); ParameterShouldBe("oauth_version", "Version"); ParameterShouldHaveValue("oauth_nonce"); ParameterShouldHaveValue("oauth_timestamp"); return; void ParameterShould(string name, Func<Parameter, bool> check) { var parameter = parameters.FirstOrDefault(x => x.Type == ParameterType.GetOrPost && x.Name == name); parameter.Should().NotBeNull(); check(parameter).Should().BeTrue(); } void ParameterShouldBe(string name, string value) => ParameterShould(name, x => (string)x.Value == value); void ParameterShouldHaveValue(string name) => ParameterShould(name, x => !string.IsNullOrWhiteSpace((string)x.Value)); } [Theory] [InlineData(OAuthType.AccessToken, "Token", "Token")] [InlineData(OAuthType.ProtectedResource, "Token", "Token")] [InlineData(OAuthType.AccessToken, "SVyDD+RsFzSoZChk=", "SVyDD%2BRsFzSoZChk%3D")] [InlineData(OAuthType.ProtectedResource, "SVyDD+RsFzSoZChk=", "SVyDD%2BRsFzSoZChk%3D")] public void Authenticate_ShouldEncodeOAuthTokenParameter(OAuthType type, string value, string expected) { // Arrange const string url = "https://no-query.string"; using var client = new RestClient(url); var request = new RestRequest(); _auth.Type = type; _auth.Token = value; // Act _auth.Authenticate(client, request); // Assert var authParameter = request.Parameters.Single(x => x.Name == KnownHeaders.Authorization); var authHeader = (string)authParameter.Value; Assert.NotNull(authHeader); Assert.Contains($"oauth_token=\"{expected}\"", authHeader); } /// <summary> /// According to the specifications of OAuth 1.0a, the customer secret is not required. /// For more information, check the section 4 on https://oauth.net/core/1.0a/. /// </summary> [Theory] [InlineData(OAuthType.AccessToken)] [InlineData(OAuthType.ProtectedResource)] public void Authenticate_ShouldAllowEmptyConsumerSecret_OnHttpAuthorizationHeaderHandling(OAuthType type) { // Arrange const string url = "https://no-query.string"; using var client = new RestClient(url); var request = new RestRequest(); _auth.Type = type; _auth.ConsumerSecret = null; // Act _auth.Authenticate(client, request); // Assert var authParameter = request.Parameters.Single(x => x.Name == KnownHeaders.Authorization); var value = (string)authParameter.Value; Assert.NotNull(value); Assert.NotEmpty(value); Assert.Contains("OAuth", value!); Assert.Contains($"oauth_signature=\"{OAuthTools.UrlEncodeStrict("&")}", value); } [Fact] public async Task Authenticate_ShouldUriEncodeConsumerKey_OnHttpAuthorizationHeaderHandling() { // Arrange const string url = "https://no-query.string"; var client = new RestClient(url); var request = new RestRequest(); _auth.Type = OAuthType.ProtectedResource; _auth.ConsumerKey = "my@consumer!key"; _auth.ConsumerSecret = null; // Act await _auth.Authenticate(client, request); // Assert var authParameter = request.Parameters.Single(x => x.Name == KnownHeaders.Authorization); var value = (string)authParameter.Value; value.Should().Contain("OAuth"); value.Should().Contain("oauth_consumer_key=\"my%40consumer%21key"); } }
RestSharp
You are an expert .NET (C#) developer. Task: Write a unit test for 'ParametersExtensions' using XUnit and Moq. Context: - Class: ParametersExtensions Requirements: Use Mock<T> interface mocking.
industrial
// Copyright (c) .NET Foundation and Contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.Text.RegularExpressions; using RestSharp.Extensions; namespace RestSharp; public partial record UrlSegmentParameter : NamedParameter { static readonly Regex RegexPattern = Pattern(); /// <summary> /// Instantiates a new query parameter instance that will be added to the request URL by replacing part of the absolute path. /// The request resource should have a placeholder {name} that will be replaced with the parameter value when the request is made. /// </summary> /// <param name="name">Parameter name</param> /// <param name="value">Parameter value</param> /// <param name="encode">Optional: encode the value, default is true</param> /// <param name="replaceEncodedSlash">Optional: whether to replace all %2f and %2F in the parameter value with '/', default is true</param> public UrlSegmentParameter(string name, string? value, bool encode = true, bool replaceEncodedSlash = true) : base( name, value.IsEmpty() ? string.Empty : replaceEncodedSlash ? RegexPattern.Replace(value, "/") : value, ParameterType.UrlSegment, encode ) { } #if NET7_0_OR_GREATER [GeneratedRegex("%2f", RegexOptions.IgnoreCase | RegexOptions.Compiled, "en-NO")] private static partial Regex Pattern(); #else static Regex Pattern() => new("%2f", RegexOptions.IgnoreCase | RegexOptions.Compiled); #endif }
namespace RestSharp.Tests.Parameters; public class UrlSegmentTests { const string BaseUrl = "http://localhost:8888/"; [Fact] public void AddUrlSegmentWithInt() { const string name = "foo"; var request = new RestRequest().AddUrlSegment(name, 1); var actual = request.Parameters.FirstOrDefault(x => x.Name == name); var expected = new UrlSegmentParameter(name, "1"); expected.Should().BeEquivalentTo(actual); } [Fact] public void AddUrlSegmentModifiesUrlSegmentWithInt() { const string name = "foo"; const string pathTemplate = "/{0}/resource"; const int urlSegmentValue = 1; var path = string.Format(pathTemplate, $"{{{name}}}"); var request = new RestRequest(path).AddUrlSegment(name, urlSegmentValue); var expected = string.Format(pathTemplate, urlSegmentValue); using var client = new RestClient(BaseUrl); var actual = client.BuildUri(request).AbsolutePath; expected.Should().BeEquivalentTo(actual); } [Fact] public void AddUrlSegmentModifiesUrlSegmentWithString() { const string name = "foo"; const string pathTemplate = "/{0}/resource"; const string urlSegmentValue = "bar"; var path = string.Format(pathTemplate, $"{{{name}}}"); var request = new RestRequest(path).AddUrlSegment(name, urlSegmentValue); var expected = string.Format(pathTemplate, urlSegmentValue); using var client = new RestClient(BaseUrl); var actual = client.BuildUri(request).AbsolutePath; expected.Should().BeEquivalentTo(actual); } [Theory] [InlineData("bar%2fBAR")] [InlineData("bar%2FBAR")] public void UrlSegmentParameter_WithValueWithEncodedSlash_WillReplaceEncodedSlashByDefault(string inputValue) { var urlSegmentParameter = new UrlSegmentParameter("foo", inputValue); urlSegmentParameter.Value.Should().BeEquivalentTo("bar/BAR"); } [Theory] [InlineData("bar%2fBAR")] [InlineData("bar%2FBAR")] public void UrlSegmentParameter_WithValueWithEncodedSlash_CanReplaceEncodedSlash(string inputValue) { var urlSegmentParameter = new UrlSegmentParameter("foo", inputValue, replaceEncodedSlash: true); urlSegmentParameter.Value.Should().BeEquivalentTo("bar/BAR"); } [Theory] [InlineData("bar%2fBAR")] [InlineData("bar%2FBAR")] public void UrlSegmentParameter_WithValueWithEncodedSlash_CanLeaveEncodedSlash(string inputValue) { var urlSegmentParameter = new UrlSegmentParameter("foo", inputValue, replaceEncodedSlash: false); urlSegmentParameter.Value.Should().BeEquivalentTo(inputValue); } [Fact] public void AddSameUrlSegmentTwice_ShouldReplaceFirst() { var client = new RestClient(); var request = new RestRequest("https://api.example.com/orgs/{segment}/something"); request.AddUrlSegment("segment", 1); var url1 = client.BuildUri(request); request.AddUrlSegment("segment", 2); var url2 = client.BuildUri(request); url1.AbsolutePath.Should().Be("/orgs/1/something"); url2.AbsolutePath.Should().Be("/orgs/2/something"); } }
RestSharp
You are an expert .NET (C#) developer. Task: Write a unit test for 'TargetModule' using XUnit and Moq. Context: - Class: TargetModule Requirements: Use Mock<T> interface mocking.
industrial
// Copyright (c) .NET Foundation and Contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // ReSharper disable InvertIf using RestSharp.Extensions; namespace RestSharp; class RequestHeaders : ParametersCollection<HeaderParameter> { public RequestHeaders AddHeaders(ParametersCollection parameters) { Parameters.AddRange(parameters.GetParameters<HeaderParameter>()); return this; } // Add Accept header based on registered deserializers if the caller has set none. public RequestHeaders AddAcceptHeader(string[] acceptedContentTypes) { if (TryFind(KnownHeaders.Accept) == null) { var accepts = acceptedContentTypes.JoinToString(", "); Parameters.Add(new(KnownHeaders.Accept, accepts)); } return this; } // Add Cookie header from the cookie container public RequestHeaders AddCookieHeaders(Uri uri, CookieContainer? cookieContainer) { if (cookieContainer == null) return this; var cookies = cookieContainer.GetCookieHeader(uri); if (string.IsNullOrWhiteSpace(cookies)) return this; var newCookies = SplitHeader(cookies); var existing = GetParameters<HeaderParameter>().FirstOrDefault(x => x.Name == KnownHeaders.Cookie); if (existing?.Value != null) { newCookies = newCookies.Union(SplitHeader(existing.Value!)); } Parameters.Add(new(KnownHeaders.Cookie, string.Join("; ", newCookies))); return this; IEnumerable<string> SplitHeader(string header) => header.Split(';').Select(x => x.Trim()); } }
namespace RestSharp.Tests; public class RequestHeaderTests { static readonly KeyValuePair<string, string> AcceptHeader = new(KnownHeaders.Accept, ContentType.Json); static readonly KeyValuePair<string, string> AcceptLanguageHeader = new(KnownHeaders.AcceptLanguage, "en-us,en;q=0.5"); static readonly KeyValuePair<string, string> KeepAliveHeader = new(KnownHeaders.KeepAlive, "300"); readonly List<KeyValuePair<string, string>> _headers = [AcceptHeader, AcceptLanguageHeader, KeepAliveHeader]; [Fact] public void AddHeaders_SameCaseDuplicatesExist_ThrowsException() { var headers = _headers; _headers.Add(AcceptHeader); var request = new RestRequest(); var exception = Assert.Throws<ArgumentException>(() => request.AddHeaders(headers)); Assert.Equal("Duplicate header names exist: ACCEPT", exception.Message); } [Fact] public void AddHeaders_DifferentCaseDuplicatesExist_ThrowsException() { var headers = _headers; headers.Add(new(KnownHeaders.Accept, ContentType.Json)); var request = new RestRequest(); var exception = Assert.Throws<ArgumentException>(() => request.AddHeaders(headers)); Assert.Equal("Duplicate header names exist: ACCEPT", exception.Message); } [Fact] public void AddHeaders_NoDuplicatesExist_Has3Headers() { var request = new RestRequest(); request.AddHeaders(_headers); var httpParameters = GetHeaders(request); Assert.Equal(3, httpParameters.Length); } [Fact] public void AddHeaders_NoDuplicatesExistUsingDictionary_Has3Headers() { var headers = new Dictionary<string, string> { { KnownHeaders.Accept, ContentType.Json }, { KnownHeaders.AcceptLanguage, "en-us,en;q=0.5" }, { KnownHeaders.KeepAlive, "300" } }; var request = new RestRequest(); request.AddHeaders(headers); var httpParameters = GetHeaders(request); Assert.Equal(3, httpParameters.Count()); } [Fact] public void AddOrUpdateHeader_ShouldUpdateExistingHeader_WhenHeaderExist() { // Arrange var request = new RestRequest(); request.AddHeader(KnownHeaders.Accept, ContentType.Xml); // Act request.AddOrUpdateHeader(KnownHeaders.Accept, ContentType.Json); // Assert GetHeader(request, KnownHeaders.Accept).Should().Be(ContentType.Json); } [Fact] public void AddOrUpdateHeader_ShouldUpdateExistingHeader_WhenHeaderDoesNotExist() { // Arrange var request = new RestRequest(); // Act request.AddOrUpdateHeader(KnownHeaders.Accept, ContentType.Json); // Assert GetHeader(request, KnownHeaders.Accept).Should().Be(ContentType.Json); } [Fact] public void AddOrUpdateHeaders_ShouldAddHeaders_WhenNoneExists() { // Arrange var headers = new Dictionary<string, string> { { KnownHeaders.Accept, ContentType.Json }, { KnownHeaders.AcceptLanguage, "en-us,en;q=0.5" }, { KnownHeaders.KeepAlive, "300" } }; var request = new RestRequest(); // Act request.AddOrUpdateHeaders(headers); // Assert var requestHeaders = GetHeaders(request); var expected = headers.Select(x => new HeaderParameter(x.Key, x.Value)); expected.Should().BeEquivalentTo(requestHeaders); } [Fact] public void AddOrUpdateHeaders_ShouldUpdateHeaders_WhenAllExists() { // Arrange var headers = new Dictionary<string, string> { { KnownHeaders.Accept, ContentType.Json }, { KnownHeaders.KeepAlive, "300" } }; var updatedHeaders = new Dictionary<string, string> { { KnownHeaders.Accept, ContentType.Xml }, { KnownHeaders.KeepAlive, "400" } }; var request = new RestRequest(); request.AddHeaders(headers); // Act request.AddOrUpdateHeaders(updatedHeaders); // Assert var requestHeaders = GetHeaders(request); HeaderParameter[] expected = [new(KnownHeaders.Accept, ContentType.Xml), new(KnownHeaders.KeepAlive, "400")]; requestHeaders.Should().BeEquivalentTo(expected); } [Fact] public void AddOrUpdateHeaders_ShouldAddAndUpdateHeaders_WhenSomeExists() { // Arrange var headers = new Dictionary<string, string> { { KnownHeaders.Accept, ContentType.Json }, { KnownHeaders.KeepAlive, "300" } }; var updatedHeaders = new Dictionary<string, string> { { KnownHeaders.Accept, ContentType.Xml }, { KnownHeaders.AcceptLanguage, "en-us,en;q=0.5" } }; var request = new RestRequest(); request.AddHeaders(headers); // Act request.AddOrUpdateHeaders(updatedHeaders); // Assert var requestHeaders = GetHeaders(request); HeaderParameter[] expected = [ new(KnownHeaders.Accept, ContentType.Xml), new(KnownHeaders.AcceptLanguage, "en-us,en;q=0.5"), new(KnownHeaders.KeepAlive, "300") ]; requestHeaders.Should().BeEquivalentTo(expected); } [Fact] public void Should_not_allow_null_header_value() { string value = null; var request = new RestRequest(); // ReSharper disable once AssignNullToNotNullAttribute Assert.Throws<ArgumentNullException>("value", () => request.AddHeader("name", value)); } [Fact] public void Should_not_allow_null_header_name() { var request = new RestRequest(); Assert.Throws<ArgumentNullException>("name", () => request.AddHeader(null!, "value")); } [Fact] public void Should_not_allow_empty_header_name() { var request = new RestRequest(); Assert.Throws<ArgumentException>("name", () => request.AddHeader("", "value")); } [Fact] public void Should_not_allow_CRLF_in_header_value() { var request = new RestRequest(); Assert.Throws<ArgumentException>(() => request.AddHeader("name", "test\r\nUser-Agent: injected header!\r\n\r\nGET /smuggled HTTP/1.1\r\nHost: insert.some.site.here")); } static Parameter[] GetHeaders(RestRequest request) => request.Parameters.Where(x => x.Type == ParameterType.HttpHeader).ToArray(); static string GetHeader(RestRequest request, string name) => request.Parameters.FirstOrDefault(x => x.Name == name)?.Value?.ToString(); }
RestSharp
You are an expert C++ developer. Task: Write a unit test for 'RequestHeaders' using GoogleTest (gtest) and GoogleMock (gmock). Context: - Class: RequestHeaders Requirements: Use EXPECT_CALL for virtual methods.
industrial
using CsvHelper; using CsvHelper.Configuration; using System.Collections; using System.Globalization; namespace RestSharp.Serializers.CsvHelper; public class CsvHelperSerializer(CsvConfiguration configuration) : IDeserializer, IRestSerializer, ISerializer { public ISerializer Serializer => this; public IDeserializer Deserializer => this; public string[] AcceptedContentTypes => [ContentType.Csv, "application/x-download"]; public SupportsContentType SupportsContentType => x => Array.IndexOf(AcceptedContentTypes, x) != -1 || x.Value.Contains("csv"); public DataFormat DataFormat => DataFormat.None; public ContentType ContentType { get; set; } = ContentType.Csv; public CsvHelperSerializer() : this(new(CultureInfo.InvariantCulture)) { } public T? Deserialize<T>(RestResponse response) { try { if (response.Content == null) throw new InvalidOperationException(message: "Response content is null"); using var stringReader = new StringReader(response.Content); using var csvReader = new CsvReader(stringReader, configuration); var @interface = typeof(T).GetInterface("IEnumerable`1"); if (@interface == null) { csvReader.Read(); return csvReader.GetRecord<T>(); } var itemType = @interface.GenericTypeArguments[0]; T result; try { result = Activator.CreateInstance<T>(); } catch (MissingMethodException) { throw new InvalidOperationException(message: "The type must contain a public, parameterless constructor."); } var method = typeof(T).GetMethod(name: "Add"); if (method == null) { throw new InvalidOperationException( message: "If the type implements IEnumerable<T>, then it must contain a public \"Add(T)\" method." ); } foreach (var record in csvReader.GetRecords(itemType)) { method.Invoke(result, [record]); } return result; } catch (Exception exception) { throw new DeserializationException(response, exception); } } public string? Serialize(Parameter parameter) => Serialize(parameter.Value); public string? Serialize(object? obj) { if (obj == null) { return null; } using var stringWriter = new StringWriter(); using var csvWriter = new CsvWriter(stringWriter, configuration); if (obj is IEnumerable records) { csvWriter.WriteRecords(records); } else { csvWriter.WriteHeader(obj.GetType()); csvWriter.NextRecord(); csvWriter.WriteRecord(obj); csvWriter.NextRecord(); } return stringWriter.ToString(); } }
using RestSharp.Serializers.CsvHelper; using RestSharp.Serializers.Json; using System.Globalization; namespace RestSharp.Tests.Serializers.Csv; public sealed class CsvHelperTests : IDisposable { static readonly Fixture Fixture = new(); static CsvHelperTests() => Fixture.Customize(new TestObjectCustomization()); readonly WireMockServer _server = WireMockServer.Start(); void ConfigureResponse(object expected) { var serializer = new CsvHelperSerializer(); _server .Given(Request.Create().WithPath("/").UsingGet()) .RespondWith(Response.Create().WithBody(serializer.Serialize(expected)!).WithHeader(KnownHeaders.ContentType, ContentType.Csv)); } [Fact] public async Task Use_CsvHelper_For_Response() { var expected = Fixture.Create<TestObject>(); ConfigureResponse(expected); using var client = new RestClient(_server.Url!, configureSerialization: cfg => cfg.UseCsvHelper()); var actual = await client.GetAsync<TestObject>(new RestRequest()); actual.Should().BeEquivalentTo(expected); } [Fact] public async Task Use_CsvHelper_For_Collection_Response() { var expected = Fixture.CreateMany<TestObject>(); ConfigureResponse(expected); using var client = new RestClient(_server.Url!, configureSerialization: cfg => cfg.UseCsvHelper()); var actual = await client.GetAsync<List<TestObject>>(new RestRequest()); actual.Should().BeEquivalentTo(expected); } [Fact] public async Task Invalid_csv_request_body_should_fail() { _server .Given(Request.Create().WithPath("/").UsingGet()) .RespondWith(Response.Create().WithBody("invalid csv").WithHeader(KnownHeaders.ContentType, ContentType.Csv)); using var client = new RestClient(_server.Url!, configureSerialization: cfg => cfg.UseCsvHelper()); var response = await client.ExecuteAsync<TestObject>(new()); response.IsSuccessStatusCode.Should().BeTrue(); response.IsSuccessful.Should().BeFalse(); } [Fact] public async Task Valid_csv_response_should_succeed() { var item = Fixture.Create<TestObject>(); ConfigureResponse(item); using var client = new RestClient(_server.Url!, configureSerialization: cfg => cfg.UseSystemTextJson()); var response = await client.ExecuteAsync<TestObject>(new()); response.IsSuccessStatusCode.Should().BeTrue(); response.IsSuccessful.Should().BeTrue(); } [Fact] public void SerializedObject_Should_Be() { var serializer = new CsvHelperSerializer(new(CultureInfo.InvariantCulture) { NewLine = ";" }); var item = Fixture.Create<TestObject>(); var actual = serializer.Serialize(item); var expected = $"{TestObject.Titles};{item.ToString(CultureInfo.InvariantCulture)};"; actual.Should().Be(expected); } [Fact] public void SerializedCollection_Should_Be() { var serializer = new CsvHelperSerializer(new(CultureInfo.InvariantCulture) { NewLine = ";" }); var items = new TestObject[] { new() { Int32Value = 32, SingleValue = 16.5f, StringValue = "hello", TimeSpanValue = TimeSpan.FromMinutes(10), DateTimeValue = new(2024, 1, 20) }, new() { Int32Value = 65, DecimalValue = 89.555m, TimeSpanValue = TimeSpan.FromSeconds(61), DateTimeValue = new(2022, 8, 19, 5, 15, 21) }, new() { SingleValue = 80000, DoubleValue = 20.00001, StringValue = "String, with comma" } }; string[] strings = [TestObject.Titles, .. items.Select(i => i.ToString(CultureInfo.InvariantCulture))]; var expected = $"{string.Join(";", strings)};"; var actual = serializer.Serialize(items); actual.Should().Be(expected); } public void Dispose() => _server?.Dispose(); } class TestObjectCustomization : ICustomization { public void Customize(IFixture fixture) => fixture.Customize<TestObject>(o => o .WithAutoProperties() .With( p => p.DateTimeValue, () => { var dt = fixture.Create<DateTime>(); return new(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second); } ) ); }
RestSharp
You are an expert .NET (C#) developer. Task: Write a unit test for 'CsvHelperSerializer' using XUnit and Moq. Context: - Class: CsvHelperSerializer Requirements: Use Mock<T> interface mocking.
industrial
// Copyright (c) .NET Foundation and Contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.Text.Json; namespace RestSharp.Serializers.Json; public class SystemTextJsonSerializer : IRestSerializer, ISerializer, IDeserializer { readonly JsonSerializerOptions _options; /// <summary> /// Create the new serializer that uses System.Text.Json.JsonSerializer with default settings /// </summary> public SystemTextJsonSerializer() => _options = new(JsonSerializerDefaults.Web); /// <summary> /// Create the new serializer that uses System.Text.Json.JsonSerializer with custom settings /// </summary> /// <param name="options">Json serializer settings</param> public SystemTextJsonSerializer(JsonSerializerOptions options) => _options = options; public string? Serialize(object? obj) => obj == null ? null : JsonSerializer.Serialize(obj, _options); public string? Serialize(Parameter bodyParameter) => Serialize(bodyParameter.Value); public T? Deserialize<T>(RestResponse response) => JsonSerializer.Deserialize<T>(response.Content!, _options); public ContentType ContentType { get; set; } = ContentType.Json; public ISerializer Serializer => this; public IDeserializer Deserializer => this; public DataFormat DataFormat => DataFormat.Json; public string[] AcceptedContentTypes => ContentType.JsonAccept; public SupportsContentType SupportsContentType => contentType => contentType.Value.EndsWith("json", StringComparison.InvariantCultureIgnoreCase); }
using RestSharp.Serializers.Json; using RestSharp.Tests.Shared.Extensions; namespace RestSharp.Tests.Serializers.Json.SystemTextJson; public sealed class SystemTextJsonTests : IDisposable { static readonly Fixture Fixture = new(); readonly WireMockServer _server = WireMockServer.Start(); readonly RestClient _client; public SystemTextJsonTests() => _client = new(_server.Url!); [Fact] public async Task Should_serialize_request() { var serializer = new SystemTextJsonSerializer(); var capturer = _server.ConfigureBodyCapturer(Method.Post, false); var testData = Fixture.Create<TestClass>(); var request = new RestRequest().AddJsonBody(testData); await _client.PostAsync(request); var actual = serializer.Deserialize<TestClass>(new(request) { Content = capturer.Body }); actual.Should().BeEquivalentTo(testData); } [Fact] public async Task Should_deserialize_response_with_GenericGet() { var expected = Fixture.Create<TestClass>(); _server .Given(Request.Create().WithPath("/").UsingGet()) .RespondWith(Response.Create().WithBodyAsJson(expected)); var actual = await _client.GetAsync<TestClass>(new RestRequest()); actual.Should().BeEquivalentTo(expected); } [Fact] public async Task Posting_invalid_json_should_fail() { _server .Given(Request.Create().WithPath("/").UsingGet()) .RespondWith(Response.Create().WithBody("invalid json").WithHeader(KnownHeaders.ContentType, ContentType.Json)); var response = await _client.ExecuteAsync<TestClass>(new()); response.IsSuccessStatusCode.Should().BeTrue(); response.IsSuccessful.Should().BeFalse(); } [Fact] public async Task Receiving_valid_json_should_succeed() { var item = Fixture.Create<TestClass>(); _server .Given(Request.Create().WithPath("/").UsingGet()) .RespondWith(Response.Create().WithBodyAsJson(item)); var response = await _client.ExecuteAsync<TestClass>(new()); response.IsSuccessStatusCode.Should().BeTrue(); response.IsSuccessful.Should().BeTrue(); } public void Dispose() { _server?.Dispose(); _client.Dispose(); } }
RestSharp
You are an expert .NET (C#) developer. Task: Write a unit test for 'SystemTextJsonSerializer' using XUnit and Moq. Context: - Class: SystemTextJsonSerializer Requirements: Use Mock<T> interface mocking.
industrial
namespace AutoMapper.Configuration.Annotations; /// <summary> /// Substitute a custom value when the source member resolves as null /// </summary> /// <remarks> /// Must be used in combination with <see cref="AutoMapAttribute" /> /// </remarks> [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public sealed class NullSubstituteAttribute(object value) : Attribute, IMemberConfigurationProvider { /// <summary> /// Value to use if source value is null /// </summary> public object Value { get; } = value; public void ApplyConfiguration(IMemberConfigurationExpression memberConfigurationExpression) { memberConfigurationExpression.NullSubstitute(Value); } }
using System; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Shouldly; using Xunit; namespace AutoMapper.Extensions.Microsoft.DependencyInjection.Tests { public class AttributeTests { [Fact] public void Should_not_register_static_instance_when_configured() { IServiceCollection services = new ServiceCollection(); services.AddSingleton<ILoggerFactory>(NullLoggerFactory.Instance); services.AddAutoMapper(_ => { }, typeof(Source3)); var serviceProvider = services.BuildServiceProvider(); var mapper = serviceProvider.GetService<IMapper>(); var source = new Source3 {Value = 3}; var dest = mapper.Map<Dest3>(source); dest.Value.ShouldBe(source.Value); } } }
AutoMapper
You are an expert C++ developer. Task: Write a unit test for 'NullSubstituteAttribute' using GoogleTest (gtest) and GoogleMock (gmock). Context: - Class: NullSubstituteAttribute Requirements: Use EXPECT_CALL for virtual methods.
industrial
namespace AutoMapper.UnitTests { namespace ValueTransformers { public class BasicTransforming : AutoMapperSpecBase { public class Source { public string Value { get; set; } } public class Dest { public string Value { get; set; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.CreateMap<Source, Dest>(); cfg.ValueTransformers.Add<string>(dest => dest + " is straight up dope"); }); [Fact] public void Should_transform_value() { var source = new Source { Value = "Jimmy" }; var dest = Mapper.Map<Source, Dest>(source); dest.Value.ShouldBe("Jimmy is straight up dope"); } } public class StackingTransformers : AutoMapperSpecBase { public class Source { public string Value { get; set; } } public class Dest { public string Value { get; set; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.CreateMap<Source, Dest>(); cfg.ValueTransformers.Add<string>(dest => dest + " is straight up dope"); cfg.ValueTransformers.Add<string>(dest => dest + "! No joke!"); }); [Fact] public void Should_stack_transformers_in_order() { var source = new Source { Value = "Jimmy" }; var dest = Mapper.Map<Source, Dest>(source); dest.Value.ShouldBe("Jimmy is straight up dope! No joke!"); } } public class DifferentProfiles : AutoMapperSpecBase { public class Source { public string Value { get; set; } } public class Dest { public string Value { get; set; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.CreateMap<Source, Dest>(); cfg.ValueTransformers.Add<string>(dest => dest + " is straight up dope"); cfg.CreateProfile("Other", p => p.ValueTransformers.Add<string>(dest => dest + "! No joke!")); }); [Fact] public void Should_not_apply_other_transform() { var source = new Source { Value = "Jimmy" }; var dest = Mapper.Map<Source, Dest>(source); dest.Value.ShouldBe("Jimmy is straight up dope"); } } public class StackingRootConfigAndProfileTransform : AutoMapperSpecBase { public class Source { public string Value { get; set; } } public class Dest { public string Value { get; set; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.ValueTransformers.Add<string>(dest => dest + "! No joke!"); cfg.CreateProfile("Other", p => { p.CreateMap<Source, Dest>(); p.ValueTransformers.Add<string>(dest => dest + " is straight up dope"); }); }); [Fact] public void ShouldApplyProfileFirstThenRoot() { var source = new Source { Value = "Jimmy" }; var dest = Mapper.Map<Source, Dest>(source); dest.Value.ShouldBe("Jimmy is straight up dope! No joke!"); } } public class TransformingValueTypes : AutoMapperSpecBase { public class Source { public int Value { get; set; } } public class Dest { public int Value { get; set; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.ValueTransformers.Add<int>(dest => dest * 2); cfg.CreateProfile("Other", p => { p.CreateMap<Source, Dest>(); p.ValueTransformers.Add<int>(dest => dest + 3); }); }); [Fact] public void ShouldApplyProfileFirstThenRoot() { var source = new Source { Value = 5 }; var dest = Mapper.Map<Source, Dest>(source); dest.Value.ShouldBe((5 + 3) * 2); } } public class StackingRootAndProfileAndMemberConfig : AutoMapperSpecBase { public class Source { public string Value { get; set; } } public class Dest { public string Value { get; set; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.ValueTransformers.Add<string>(dest => dest + "! No joke!"); cfg.CreateProfile("Other", p => { p.CreateMap<Source, Dest>() .ValueTransformers.Add<string>(dest => dest + ", for real,"); p.ValueTransformers.Add<string>(dest => dest + " is straight up dope"); }); }); [Fact] public void ShouldApplyTypeMapThenProfileThenRoot() { var source = new Source { Value = "Jimmy" }; var dest = Mapper.Map<Source, Dest>(source); dest.Value.ShouldBe("Jimmy, for real, is straight up dope! No joke!"); } } public class StackingTypeMapAndRootAndProfileAndMemberConfig : AutoMapperSpecBase { public class Source { public string Value { get; set; } } public class Dest { public string Value { get; set; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.ValueTransformers.Add<string>(dest => dest + "! No joke!"); cfg.CreateProfile("Other", p => { p.CreateMap<Source, Dest>() .AddTransform<string>(dest => dest + ", for real,") .ForMember(d => d.Value, opt => opt.AddTransform(d => d + ", seriously")); p.ValueTransformers.Add<string>(dest => dest + " is straight up dope"); }); }); [Fact] public void ShouldApplyTypeMapThenProfileThenRoot() { var source = new Source { Value = "Jimmy" }; var dest = Mapper.Map<Source, Dest>(source); dest.Value.ShouldBe("Jimmy, seriously, for real, is straight up dope! No joke!"); } } } public class TransformingInheritance : AutoMapperSpecBase { public class SourceBase { public string Value { get; set; } } public class DestBase { public string Value { get; set; } } public class Source : SourceBase { } public class Dest : DestBase { } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.CreateMap<SourceBase, DestBase>().Include<Source, Dest>().AddTransform<string>(dest => dest + " was cool"); cfg.CreateMap<Source, Dest>().AddTransform<string>(dest => dest + " and now is straight up dope"); }); [Fact] public void Should_transform_value() { var source = new Source { Value = "Jimmy" }; var dest = Mapper.Map<Source, Dest>(source); dest.Value.ShouldBe("Jimmy was cool and now is straight up dope"); } } public class TransformingInheritanceForMember : AutoMapperSpecBase { public class SourceBase { public string Value { get; set; } } public class DestBase { public string Value { get; set; } } public class Source : SourceBase { } public class Dest : DestBase { } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.CreateMap<SourceBase, DestBase>().Include<Source, Dest>().ForMember(d => d.Value, o => o.AddTransform(dest => dest + " was cool")); cfg.CreateMap<Source, Dest>().ForMember(d=>d.Value, o=>o.AddTransform(dest => dest + " and now is straight up dope")); }); [Fact] public void Should_transform_value() { var source = new Source { Value = "Jimmy" }; var dest = Mapper.Map<Source, Dest>(source); dest.Value.ShouldBe("Jimmy was cool and now is straight up dope"); } } public class TransformingNullable : AutoMapperSpecBase { public class Source { public int Value { get; set; } public int? NotNull { get; set; } public int? Null { get; set; } } public class Dest { public int Value { get; set; } public int? NotNull { get; set; } public int? Null { get; set; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => cfg.CreateMap<Source, Dest>().AddTransform<int>(source=>source+1).AddTransform<int?>(source => source == null ? null : source + 2)); [Fact] public void Should_transform_value() { var dest = Mapper.Map<Source, Dest>(new Source { NotNull = 0 }); dest.Value.ShouldBe(1); dest.Null.ShouldBeNull(); dest.NotNull.ShouldBe(2); } } public class NonGenericMemberTransformer : AutoMapperSpecBase { public class Source { public string Value { get; set; } } public class Dest<T> { public T Value { get; set; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => cfg.CreateMap(typeof(Source), typeof(Dest<>)).ForMember("Value", opt => opt.AddTransform(d => d + " and more"))); [Fact] public void ShouldMatchMemberType() { var source = new Source { Value = "value" }; var dest = Mapper.Map<Dest<string>>(source); dest.Value.ShouldBe("value and more"); } public class ConstructorTransforming : AutoMapperSpecBase { public class Source { public string Value { get; set; } } public class Dest { public string Value { get; } public Dest(string value) { Value = value; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.CreateMap<Source, Dest>(); cfg.ValueTransformers.Add<string>(dest => dest + " is straight up dope"); }); [Fact] public void Should_transform_value() { var source = new Source { Value = "Jimmy" }; var dest = Mapper.Map<Source, Dest>(source); dest.Value.ShouldBe("Jimmy is straight up dope"); } } } }
namespace AutoMapper.IntegrationTests { namespace ValueTransformerTests { public class BasicTransforming(DatabaseFixture databaseFixture) : IntegrationTest<BasicTransforming.DatabaseInitializer>(databaseFixture) { public class Source { [Key] public int Id { get; set; } public string Value { get; set; } } public class Dest { public string Value { get; set; } } public class Context : LocalDbContext { public DbSet<Source> Sources { get; set; } } public class DatabaseInitializer : DropCreateDatabaseAlways<Context> { protected override void Seed(Context context) { context.Sources.Add(new Source { Value = "Jimmy" }); base.Seed(context); } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.CreateProjection<Source, Dest>(); cfg.ValueTransformers.Add<string>(dest => dest + " is straight up dope"); }); [Fact] public async Task Should_transform_value() { using (var context = Fixture.CreateContext()) { var dest = await ProjectTo<Dest>(context.Sources).SingleAsync(); dest.Value.ShouldBe("Jimmy is straight up dope"); } } } public class StackingTransformers(DatabaseFixture databaseFixture) : IntegrationTest<StackingTransformers.DatabaseInitializer>(databaseFixture) { public class Source { [Key] public int Id { get; set; } public string Value { get; set; } } public class Dest { public string Value { get; set; } } public class Context : LocalDbContext { public DbSet<Source> Sources { get; set; } } public class DatabaseInitializer : DropCreateDatabaseAlways<Context> { protected override void Seed(Context context) { context.Sources.Add(new Source { Value = "Jimmy" }); base.Seed(context); } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.CreateProjection<Source, Dest>(); cfg.ValueTransformers.Add<string>(dest => dest + " is straight up dope"); cfg.ValueTransformers.Add<string>(dest => dest + "! No joke!"); }); [Fact] public async Task Should_stack_transformers_in_order() { using (var context = Fixture.CreateContext()) { var dest = await ProjectTo<Dest>(context.Sources).SingleAsync(); dest.Value.ShouldBe("Jimmy is straight up dope! No joke!"); } } } public class DifferentProfiles(DatabaseFixture databaseFixture) : IntegrationTest<DifferentProfiles.DatabaseInitializer>(databaseFixture) { public class Source { [Key] public int Id { get; set; } public string Value { get; set; } } public class Dest { public string Value { get; set; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.CreateProjection<Source, Dest>(); cfg.ValueTransformers.Add<string>(dest => dest + " is straight up dope"); cfg.CreateProfile("Other", p => p.ValueTransformers.Add<string>(dest => dest + "! No joke!")); }); public class Context : LocalDbContext { public DbSet<Source> Sources { get; set; } } public class DatabaseInitializer : DropCreateDatabaseAlways<Context> { protected override void Seed(Context context) { context.Sources.Add(new Source { Value = "Jimmy" }); base.Seed(context); } } [Fact] public async Task Should_not_apply_other_transform() { using (var context = Fixture.CreateContext()) { var dest = await ProjectTo<Dest>(context.Sources).SingleAsync(); dest.Value.ShouldBe("Jimmy is straight up dope"); } } } public class StackingRootConfigAndProfileTransform(DatabaseFixture databaseFixture) : IntegrationTest<StackingRootConfigAndProfileTransform.DatabaseInitializer>(databaseFixture) { public class Source { [Key] public int Id { get; set; } public string Value { get; set; } } public class Dest { public string Value { get; set; } } public class Context : LocalDbContext { public DbSet<Source> Sources { get; set; } } public class DatabaseInitializer : DropCreateDatabaseAlways<Context> { protected override void Seed(Context context) { context.Sources.Add(new Source { Value = "Jimmy" }); base.Seed(context); } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.ValueTransformers.Add<string>(dest => dest + "! No joke!"); cfg.CreateProfile("Other", p => { p.CreateProjection<Source, Dest>(); p.ValueTransformers.Add<string>(dest => dest + " is straight up dope"); }); }); [Fact] public async Task ShouldApplyProfileFirstThenRoot() { using (var context = Fixture.CreateContext()) { var dest = await ProjectTo<Dest>(context.Sources).SingleAsync(); dest.Value.ShouldBe("Jimmy is straight up dope! No joke!"); } } } public class TransformingValueTypes(DatabaseFixture databaseFixture) : IntegrationTest<TransformingValueTypes.DatabaseInitializer>(databaseFixture) { public class Source { [Key] public int Id { get; set; } public int Value { get; set; } } public class Dest { public int Value { get; set; } } public class Context : LocalDbContext { public DbSet<Source> Sources { get; set; } } public class DatabaseInitializer : DropCreateDatabaseAlways<Context> { protected override void Seed(Context context) { context.Sources.Add(new Source { Value = 5 }); base.Seed(context); } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.ValueTransformers.Add<int>(dest => dest * 2); cfg.CreateProfile("Other", p => { p.CreateProjection<Source, Dest>(); p.ValueTransformers.Add<int>(dest => dest + 3); }); }); [Fact] public async Task ShouldApplyProfileFirstThenRoot() { using (var context = Fixture.CreateContext()) { var dest = await ProjectTo<Dest>(context.Sources).SingleAsync(); dest.Value.ShouldBe((5 + 3) * 2); } } } public class StackingRootAndProfileAndMemberConfig(DatabaseFixture databaseFixture) : IntegrationTest<StackingRootAndProfileAndMemberConfig.DatabaseInitializer>(databaseFixture) { public class Source { [Key] public int Id { get; set; } public string Value { get; set; } } public class Dest { public string Value { get; set; } } public class Context : LocalDbContext { public DbSet<Source> Sources { get; set; } } public class DatabaseInitializer : DropCreateDatabaseAlways<Context> { protected override void Seed(Context context) { context.Sources.Add(new Source { Value = "Jimmy" }); base.Seed(context); } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.ValueTransformers.Add<string>(dest => dest + "! No joke!"); cfg.CreateProfile("Other", p => { p.CreateProjection<Source, Dest>() .ValueTransformers.Add<string>(dest => dest + ", for real,"); p.ValueTransformers.Add<string>(dest => dest + " is straight up dope"); }); }); [Fact] public async Task ShouldApplyTypeMapThenProfileThenRoot() { using (var context = Fixture.CreateContext()) { var dest = await ProjectTo<Dest>(context.Sources).SingleAsync(); dest.Value.ShouldBe("Jimmy, for real, is straight up dope! No joke!"); } } } public class StackingTypeMapAndRootAndProfileAndMemberConfig(DatabaseFixture databaseFixture) : IntegrationTest<StackingTypeMapAndRootAndProfileAndMemberConfig.DatabaseInitializer>(databaseFixture) { public class Source { [Key] public int Id { get; set; } public string Value { get; set; } } public class Dest { public string Value { get; set; } } public class Context : LocalDbContext { public DbSet<Source> Sources { get; set; } } public class DatabaseInitializer : DropCreateDatabaseAlways<Context> { protected override void Seed(Context context) { context.Sources.Add(new Source { Value = "Jimmy" }); base.Seed(context); } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.ValueTransformers.Add<string>(dest => dest + "! No joke!"); cfg.CreateProfile("Other", p => { p.CreateProjection<Source, Dest>() .AddTransform<string>(dest => dest + ", for real,") .ForMember(d => d.Value, opt => opt.AddTransform(d => d + ", seriously")); p.ValueTransformers.Add<string>(dest => dest + " is straight up dope"); }); }); [Fact] public async Task ShouldApplyTypeMapThenProfileThenRoot() { using (var context = Fixture.CreateContext()) { var dest = await ProjectTo<Dest>(context.Sources).SingleAsync(); dest.Value.ShouldBe("Jimmy, seriously, for real, is straight up dope! No joke!"); } } } } }
AutoMapper
You are an expert C++ developer. Task: Write a unit test for 'TargetModule' using GoogleTest (gtest) and GoogleMock (gmock). Context: - Class: TargetModule Requirements: Use EXPECT_CALL for virtual methods.
industrial
using System.Reflection.Emit; namespace AutoMapper.Execution; public static class ProxyGenerator { private static readonly MethodInfo DelegateCombine = typeof(Delegate).GetMethod(nameof(Delegate.Combine), [typeof(Delegate), typeof(Delegate)]); private static readonly MethodInfo DelegateRemove = typeof(Delegate).GetMethod(nameof(Delegate.Remove)); private static readonly EventInfo PropertyChanged = typeof(INotifyPropertyChanged).GetEvent(nameof(INotifyPropertyChanged.PropertyChanged)); private static readonly ConstructorInfo ProxyBaseCtor = typeof(ProxyBase).GetConstructor([]); private static readonly ModuleBuilder ProxyModule = CreateProxyModule(); private static readonly LockingConcurrentDictionary<TypeDescription, Type> ProxyTypes = new(EmitProxy); private static ModuleBuilder CreateProxyModule() { var assemblyName = typeof(Mapper).Assembly.GetName(); assemblyName.Name = "AutoMapper.Proxies.emit"; var builder = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); return builder.DefineDynamicModule(assemblyName.Name); } private static Type EmitProxy(TypeDescription typeDescription) { var interfaceType = typeDescription.Type; var typeBuilder = GenerateType(); GenerateConstructor(); FieldBuilder propertyChangedField = null; if (typeof(INotifyPropertyChanged).IsAssignableFrom(interfaceType)) { GeneratePropertyChanged(); } GenerateFields(); return typeBuilder.CreateTypeInfo().AsType(); TypeBuilder GenerateType() { var propertyNames = string.Join("_", typeDescription.AdditionalProperties.Select(p => p.Name)); var typeName = $"Proxy_{interfaceType.FullName}_{typeDescription.GetHashCode()}_{propertyNames}"; const int MaxTypeNameLength = 1023; typeName = typeName[..Math.Min(MaxTypeNameLength, typeName.Length)]; Debug.WriteLine(typeName, "Emitting proxy type"); return ProxyModule.DefineType(typeName, TypeAttributes.Class | TypeAttributes.Sealed | TypeAttributes.Public, typeof(ProxyBase), interfaceType.IsInterface ? [interfaceType] : []); } void GeneratePropertyChanged() { propertyChangedField = typeBuilder.DefineField(PropertyChanged.Name, typeof(PropertyChangedEventHandler), FieldAttributes.Private); EventAccessor(PropertyChanged.AddMethod, DelegateCombine); EventAccessor(PropertyChanged.RemoveMethod, DelegateRemove); } void EventAccessor(MethodInfo method, MethodInfo delegateMethod) { var eventAccessor = typeBuilder.DefineMethod(method.Name, MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.NewSlot | MethodAttributes.Virtual, typeof(void), new[] { typeof(PropertyChangedEventHandler) }); var addIl = eventAccessor.GetILGenerator(); addIl.Emit(OpCodes.Ldarg_0); addIl.Emit(OpCodes.Dup); addIl.Emit(OpCodes.Ldfld, propertyChangedField); addIl.Emit(OpCodes.Ldarg_1); addIl.Emit(OpCodes.Call, delegateMethod); addIl.Emit(OpCodes.Castclass, typeof(PropertyChangedEventHandler)); addIl.Emit(OpCodes.Stfld, propertyChangedField); addIl.Emit(OpCodes.Ret); typeBuilder.DefineMethodOverride(eventAccessor, method); } void GenerateFields() { Dictionary<string, PropertyEmitter> fieldBuilders = []; foreach (var property in PropertiesToImplement()) { if (fieldBuilders.TryGetValue(property.Name, out var propertyEmitter)) { if (propertyEmitter.PropertyType != property.Type && (property.CanWrite || !property.Type.IsAssignableFrom(propertyEmitter.PropertyType))) { throw new ArgumentException($"The interface has a conflicting property {property.Name}", nameof(interfaceType)); } } else { fieldBuilders.Add(property.Name, new PropertyEmitter(typeBuilder, property, propertyChangedField)); } } } List<PropertyDescription> PropertiesToImplement() { List<PropertyDescription> propertiesToImplement = []; List<Type> allInterfaces = [..interfaceType.GetInterfaces(), interfaceType]; // first we collect all properties, those with setters before getters in order to enable less specific redundant getters foreach (var property in allInterfaces.Where(intf => intf != typeof(INotifyPropertyChanged)) .SelectMany(intf => intf.GetProperties()) .Select(p => new PropertyDescription(p)) .Concat(typeDescription.AdditionalProperties)) { if (property.CanWrite) { propertiesToImplement.Insert(0, property); } else { propertiesToImplement.Add(property); } } return propertiesToImplement; } void GenerateConstructor() { var constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, []); var ctorIl = constructorBuilder.GetILGenerator(); ctorIl.Emit(OpCodes.Ldarg_0); ctorIl.Emit(OpCodes.Call, ProxyBaseCtor); ctorIl.Emit(OpCodes.Ret); } } public static Type GetProxyType(Type interfaceType) => ProxyTypes.GetOrAdd(new(interfaceType, [])); public static Type GetSimilarType(Type sourceType, IEnumerable<PropertyDescription> additionalProperties) => ProxyTypes.GetOrAdd(new(sourceType, [..additionalProperties.OrderBy(p => p.Name)])); class PropertyEmitter { private static readonly MethodInfo ProxyBaseNotifyPropertyChanged = typeof(ProxyBase).GetInstanceMethod("NotifyPropertyChanged"); private readonly FieldBuilder _fieldBuilder; private readonly MethodBuilder _getterBuilder; private readonly PropertyBuilder _propertyBuilder; private readonly MethodBuilder _setterBuilder; public PropertyEmitter(TypeBuilder owner, PropertyDescription property, FieldBuilder propertyChangedField) { var name = property.Name; var propertyType = property.Type; _fieldBuilder = owner.DefineField($"<{name}>", propertyType, FieldAttributes.Private); _propertyBuilder = owner.DefineProperty(name, PropertyAttributes.None, propertyType, null); _getterBuilder = owner.DefineMethod($"get_{name}", MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.SpecialName, propertyType, Type.EmptyTypes); ILGenerator getterIl = _getterBuilder.GetILGenerator(); getterIl.Emit(OpCodes.Ldarg_0); getterIl.Emit(OpCodes.Ldfld, _fieldBuilder); getterIl.Emit(OpCodes.Ret); _propertyBuilder.SetGetMethod(_getterBuilder); if (!property.CanWrite) { return; } _setterBuilder = owner.DefineMethod($"set_{name}", MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.SpecialName, typeof(void), [propertyType]); ILGenerator setterIl = _setterBuilder.GetILGenerator(); setterIl.Emit(OpCodes.Ldarg_0); setterIl.Emit(OpCodes.Ldarg_1); setterIl.Emit(OpCodes.Stfld, _fieldBuilder); if (propertyChangedField != null) { setterIl.Emit(OpCodes.Ldarg_0); setterIl.Emit(OpCodes.Dup); setterIl.Emit(OpCodes.Ldfld, propertyChangedField); setterIl.Emit(OpCodes.Ldstr, name); setterIl.Emit(OpCodes.Call, ProxyBaseNotifyPropertyChanged); } setterIl.Emit(OpCodes.Ret); _propertyBuilder.SetSetMethod(_setterBuilder); } public Type PropertyType => _propertyBuilder.PropertyType; } } public abstract class ProxyBase { public ProxyBase() { } protected void NotifyPropertyChanged(PropertyChangedEventHandler handler, string method) => handler?.Invoke(this, new(method)); } public readonly record struct TypeDescription(Type Type, PropertyDescription[] AdditionalProperties) { public override int GetHashCode() { var hashCode = new HashCode(); hashCode.Add(Type); foreach (var property in AdditionalProperties) { hashCode.Add(property); } return hashCode.ToHashCode(); } public bool Equals(TypeDescription other) => Type == other.Type && AdditionalProperties.SequenceEqual(other.AdditionalProperties); } [DebuggerDisplay("{Name}-{Type.Name}")] public readonly record struct PropertyDescription(string Name, Type Type, bool CanWrite = true) { public PropertyDescription(PropertyInfo property) : this(property.Name, property.PropertyType, property.CanWrite) { } }
namespace AutoMapper.IntegrationTests.Inheritance; public class ProxyTests(DatabaseFixture databaseFixture) : IntegrationTest<ProxyTests.DatabaseInitializer>(databaseFixture) { [Fact] public void Test() { var config = new MapperConfiguration(cfg => { cfg.CreateMap<TrainingCourse, TrainingCourseDto>().Include<TrainingCourse, ParentTrainingCourseDto>(); cfg.CreateMap<TrainingCourse, ParentTrainingCourseDto>(); cfg.CreateMap<TrainingContent, TrainingContentDto>(); }); config.AssertConfigurationIsValid(); var context = Fixture.CreateContext(); var course = context.TrainingCourses.FirstOrDefault(n => n.CourseName == "Course 1"); var mapper = config.CreateMapper(); var dto = mapper.Map<TrainingCourseDto>(course); } public class DatabaseInitializer : DropCreateDatabaseAlways<ClientContext> { protected override void Seed(ClientContext context) { var course = new TrainingCourse { CourseName = "Course 1" }; context.TrainingCourses.Add(course); var content = new TrainingContent { ContentName = "Content 1", Course = course }; context.TrainingContents.Add(content); course.Content.Add(content); } } public class ClientContext : LocalDbContext { public ClientContext() { } public DbSet<TrainingCourse> TrainingCourses { get; set; } public DbSet<TrainingContent> TrainingContents { get; set; } } public class TrainingCourse { public TrainingCourse() { Content = new List<TrainingContent>(); } public TrainingCourse(TrainingCourse entity, IMapper mapper) { mapper.Map(entity, this); } [Key] public int CourseId { get; set; } public string CourseName { get; set; } public virtual ICollection<TrainingContent> Content { get; set; } } public class TrainingContent { public TrainingContent() { } [Key] public int ContentId { get; set; } public string ContentName { get; set; } public virtual TrainingCourse Course { get; set; } // public int CourseId { get; set; } } public class TrainingCourseDto { public int CourseId { get; set; } public string CourseName { get; set; } public virtual ICollection<TrainingContentDto> Content { get; set; } } public class ParentTrainingCourseDto : TrainingCourseDto { [IgnoreMap] public override ICollection<TrainingContentDto> Content { get; set; } } public class TrainingContentDto { public int ContentId { get; set; } public string ContentName { get; set; } public ParentTrainingCourseDto Course { get; set; } // public int CourseId { get; set; } } }
AutoMapper
You are an expert .NET (C#) developer. Task: Write a unit test for 'ProxyBase' using XUnit and Moq. Context: - Class: ProxyBase Requirements: Use Mock<T> interface mocking.
industrial
namespace AutoMapper.IntegrationTests.MaxDepth; public class MaxDepthWithCollections(DatabaseFixture databaseFixture) : IntegrationTest<MaxDepthWithCollections.DatabaseInitializer>(databaseFixture) { TrainingCourseDto _course; protected override MapperConfiguration CreateConfiguration() => new(cfg => { //cfg.AllowNullDestinationValues = false; cfg.CreateProjection<TrainingCourse, TrainingCourseDto>().MaxDepth(1); cfg.CreateProjection<TrainingContent, TrainingContentDto>(); }); [Fact] public void Should_project_with_MaxDepth() { using (var context = Fixture.CreateContext()) { _course = ProjectTo<TrainingCourseDto>(context.TrainingCourses).FirstOrDefault(n => n.CourseName == "Course 1"); } _course.CourseName.ShouldBe("Course 1"); var content = _course.Content[0]; content.ContentName.ShouldBe("Content 1"); content.Course.ShouldBeNull(); } public class DatabaseInitializer : DropCreateDatabaseAlways<ClientContext> { protected override void Seed(ClientContext context) { var course = new TrainingCourse { CourseName = "Course 1" }; context.TrainingCourses.Add(course); var content = new TrainingContent { ContentName = "Content 1", Course = course }; context.TrainingContents.Add(content); course.Content.Add(content); } } public class ClientContext : LocalDbContext { public DbSet<TrainingCourse> TrainingCourses { get; set; } public DbSet<TrainingContent> TrainingContents { get; set; } } public class TrainingCourse { [Key] public int CourseId { get; set; } public string CourseName { get; set; } public virtual IList<TrainingContent> Content { get; set; } = new List<TrainingContent>(); } public class TrainingContent { [Key] public int ContentId { get; set; } public string ContentName { get; set; } public virtual TrainingCourse Course { get; set; } } public class TrainingCourseDto { public int CourseId { get; set; } public string CourseName { get; set; } public virtual IList<TrainingContentDto> Content { get; set; } } public class TrainingContentDto { public int ContentId { get; set; } public string ContentName { get; set; } public TrainingCourseDto Course { get; set; } } }
namespace AutoMapper.UnitTests; public class MaxDepthTests { public class Source { public int Level { get; set; } public IList<Source> Children { get; set; } public Source Parent { get; set; } public Source(int level) { Children = new List<Source>(); Level = level; } public void AddChild(Source child) { Children.Add(child); child.Parent = this; } } public class Destination { public int Level { get; set; } public IList<Destination> Children { get; set; } public Destination Parent { get; set; } } private readonly Source _source; public MaxDepthTests() { var nest = new Source(1); nest.AddChild(new Source(2)); nest.Children[0].AddChild(new Source(3)); nest.Children[0].AddChild(new Source(3)); nest.Children[0].Children[1].AddChild(new Source(4)); nest.Children[0].Children[1].AddChild(new Source(4)); nest.Children[0].Children[1].AddChild(new Source(4)); nest.AddChild(new Source(2)); nest.Children[1].AddChild(new Source(3)); nest.AddChild(new Source(2)); nest.Children[2].AddChild(new Source(3)); _source = nest; } [Fact] public void Second_level_children_is_empty_with_max_depth_1() { var config = new MapperConfiguration(cfg => cfg.CreateMap<Source, Destination>().MaxDepth(1)); var destination = config.CreateMapper().Map<Source, Destination>(_source); destination.Children.ShouldBeEmpty(); } [Fact] public void Second_level_children_are_not_null_with_max_depth_2() { var config = new MapperConfiguration(cfg => cfg.CreateMap<Source, Destination>().MaxDepth(2)); var destination = config.CreateMapper().Map<Source, Destination>(_source); foreach (var child in destination.Children) { 2.ShouldBe(child.Level); child.ShouldNotBeNull(); destination.ShouldBe(child.Parent); } } [Fact] public void Third_level_children_is_empty_with_max_depth_2() { var config = new MapperConfiguration(cfg => cfg.CreateMap<Source, Destination>().MaxDepth(2)); var destination = config.CreateMapper().Map<Source, Destination>(_source); foreach (var child in destination.Children) { child.Children.ShouldBeEmpty(); } } [Fact] public void Third_level_children_are_not_null_max_depth_3() { var config = new MapperConfiguration(cfg => cfg.CreateMap<Source, Destination>().MaxDepth(3)); var destination = config.CreateMapper().Map<Source, Destination>(_source); foreach (var child in destination.Children) { child.Children.ShouldNotBeNull(); foreach (var subChild in child.Children) { 3.ShouldBe(subChild.Level); subChild.Children.ShouldNotBeNull(); child.ShouldBe(subChild.Parent); } } } }
AutoMapper
You are an expert C++ developer. Task: Write a unit test for 'MaxDepthWithCollections' using GoogleTest (gtest) and GoogleMock (gmock). Context: - Class: MaxDepthWithCollections Requirements: Use EXPECT_CALL for virtual methods.
industrial
using System.Collections; using System.Dynamic; namespace AutoMapper.Internal; public static class TypeExtensions { public const BindingFlags InstanceFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; public const BindingFlags StaticFlags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; public static MethodInfo StaticGenericMethod(this Type type, string methodName, int parametersCount) { foreach (MethodInfo foundMethod in type.GetMember(methodName, MemberTypes.Method, StaticFlags & ~BindingFlags.NonPublic)) { if (foundMethod.IsGenericMethodDefinition && foundMethod.GetParameters().Length == parametersCount) { return foundMethod; } } throw new ArgumentOutOfRangeException(nameof(methodName), $"Cannot find suitable method {type}.{methodName}({parametersCount} parameters)."); } public static void CheckIsDerivedFrom(this Type derivedType, Type baseType) { if (!baseType.IsAssignableFrom(derivedType) && !derivedType.IsGenericTypeDefinition && !baseType.IsGenericTypeDefinition) { throw new ArgumentOutOfRangeException(nameof(derivedType), $"{derivedType} is not derived from {baseType}."); } } public static bool IsDynamic(this Type type) => typeof(IDynamicMetaObjectProvider).IsAssignableFrom(type); public static IEnumerable<Type> BaseClassesAndInterfaces(this Type type) { var currentType = type; while ((currentType = currentType.BaseType) != null) { yield return currentType; } foreach (var interfaceType in type.GetInterfaces()) { yield return interfaceType; } } public static PropertyInfo GetInheritedProperty(this Type type, string name) => type.GetProperty(name, InstanceFlags) ?? type.GetBaseProperty(name); static PropertyInfo GetBaseProperty(this Type type, string name) => type.BaseClassesAndInterfaces().Select(t => t.GetProperty(name, InstanceFlags)).FirstOrDefault(p => p != null); public static FieldInfo GetInheritedField(this Type type, string name) => type.GetField(name, InstanceFlags) ?? type.GetBaseField(name); static FieldInfo GetBaseField(this Type type, string name) => type.BaseClassesAndInterfaces().Select(t => t.GetField(name, InstanceFlags)).FirstOrDefault(f => f != null); public static MethodInfo GetInheritedMethod(this Type type, string name) => type.GetInstanceMethod(name) ?? type.GetBaseMethod(name) ?? throw new ArgumentOutOfRangeException(nameof(name), $"Cannot find member {name} of type {type}."); static MethodInfo GetBaseMethod(this Type type, string name) => type.BaseClassesAndInterfaces().Select(t => t.GetInstanceMethod(name)).FirstOrDefault(m => m != null); public static MemberInfo GetFieldOrProperty(this Type type, string name) => type.GetInheritedProperty(name) ?? (MemberInfo)type.GetInheritedField(name) ?? throw new ArgumentOutOfRangeException(nameof(name), $"Cannot find member {name} of type {type}."); public static bool IsNullableType(this Type type) => type.IsGenericType(typeof(Nullable<>)); public static Type GetICollectionType(this Type type) => type.GetGenericInterface(typeof(ICollection<>)); public static bool IsCollection(this Type type) => type != typeof(string) && typeof(IEnumerable).IsAssignableFrom(type); public static bool IsListType(this Type type) => typeof(IList).IsAssignableFrom(type); public static bool IsGenericType(this Type type, Type genericType) => type.IsGenericType && type.GetGenericTypeDefinition() == genericType; public static Type GetIEnumerableType(this Type type) => type.GetGenericInterface(typeof(IEnumerable<>)); public static Type GetGenericInterface(this Type type, Type genericInterface) { if (type.IsGenericType(genericInterface)) { return type; } var interfaces = type.GetInterfaces(); for (int index = interfaces.Length - 1; index >= 0; index--) { var interfaceType = interfaces[index]; if (interfaceType.IsGenericType(genericInterface)) { return interfaceType; } } return null; } public static ConstructorInfo[] GetDeclaredConstructors(this Type type) => type.GetConstructors(InstanceFlags); public static int GenericParametersCount(this Type type) => type.GetTypeInfo().GenericTypeParameters.Length; public static IEnumerable<Type> GetTypeInheritance(this Type type) { while (type != null) { yield return type; type = type.BaseType; } } public static MethodInfo GetStaticMethod(this Type type, string name) => type.GetMethod(name, StaticFlags); public static MethodInfo GetInstanceMethod(this Type type, string name) => (MethodInfo)type.GetMember(name, MemberTypes.Method, InstanceFlags).FirstOrDefault(); }
namespace AutoMapper.UnitTests; public class TypeExtensionsTests { public class Foo { public Foo() { Value2 = "adsf"; Value4 = "Fasdfadsf"; } public string Value1 { get; set; } public string Value2 { get; private set; } protected string Value3 { get; set; } private string Value4 { get; set; } public string Value5 => "ASDf"; public string Value6 { set { Value4 = value; } } [Fact] public void Should_recognize_public_members() { // typeof(Foo).GetProperties().Length.ShouldBe(4); } } }
AutoMapper
You are an expert .NET (C#) developer. Task: Write a unit test for 'TypeExtensions' using XUnit and Moq. Context: - Class: TypeExtensions Requirements: Use Mock<T> interface mocking.
industrial
namespace AutoMapper.UnitTests.Bug; public class When_configuring_all_members_and_some_do_not_match { public class ModelObjectNotMatching { public string Foo_notfound { get; set; } public string Bar_notfound; } public class ModelDto { public string Foo { get; set; } public string Bar; } [Fact] public void Should_still_apply_configuration_to_missing_members() { var config = new MapperConfiguration(cfg => cfg.CreateMap<ModelObjectNotMatching, ModelDto>() .ForAllMembers(opt => opt.Ignore())); config.AssertConfigurationIsValid(); } } public class When_configuring_all_non_source_value_null_members : NonValidatingSpecBase { private Dest _destination; public class Source { public string Value1 { get; set; } public int? Value2 { get; set; } } public class Dest { public string Value1 { get; set; } public int? Value2 { get; set; } public string Unmapped { get; set; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.CreateMap<Source, Dest>() .ForAllMembers(opt => opt.Condition((src, dest, srcVal, destVal, c) => srcVal != null)); }); protected override void Because_of() { var source = new Source(); _destination = new Dest { Value1 = "Foo", Value2 = 10, Unmapped = "Asdf" }; Mapper.Map(source, _destination); } [Fact] public void Should_only_apply_source_value_when_not_null() { _destination.Value1.ShouldNotBeNull(); _destination.Value2.ShouldNotBe(null); _destination.Unmapped.ShouldNotBeNull(); } }
namespace AutoMapper.UnitTests; public class When_overriding_global_ignore : AutoMapperSpecBase { Destination _destination; public class Source { public int ShouldBeMapped { get; set; } } public class Destination { public int ShouldBeMapped { get; set; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.AddGlobalIgnore("ShouldBeMapped"); cfg.CreateMap<Source, Destination>().ForMember(d => d.ShouldBeMapped, o => o.MapFrom(src => 12)); }); protected override void Because_of() { _destination = Mapper.Map<Destination>(new Source()); } [Fact] public void Should_not_ignore() { _destination.ShouldBeMapped.ShouldBe(12); } } public class IgnoreAllTests { public class Source { public string ShouldBeMapped { get; set; } } public class Destination { public string ShouldBeMapped { get; set; } public string StartingWith_ShouldNotBeMapped { get; set; } public List<string> StartingWith_ShouldBeNullAfterwards { get; set; } public string AnotherString_ShouldBeNullAfterwards { get; set; } } public class DestinationWrongType { public Destination ShouldBeMapped { get; set; } } public class FooProfile : Profile { public FooProfile() { CreateMap<Source, Destination>() .ForMember(dest => dest.AnotherString_ShouldBeNullAfterwards, opt => opt.Ignore()); } } [Fact] public void GlobalIgnore_ignores_all_properties_beginning_with_string() { var config = new MapperConfiguration(cfg => { cfg.AddGlobalIgnore("StartingWith"); cfg.CreateMap<Source, Destination>() .ForMember(dest => dest.AnotherString_ShouldBeNullAfterwards, opt => opt.Ignore()); }); config.CreateMapper().Map<Source, Destination>(new Source{ShouldBeMapped = "true"}); config.AssertConfigurationIsValid(); } [Fact] public void GlobalIgnore_ignores_all_properties_beginning_with_string_in_profiles() { var config = new MapperConfiguration(cfg => { cfg.AddGlobalIgnore("StartingWith"); cfg.AddProfile<FooProfile>(); }); config.CreateMapper().Map<Source, Destination>(new Source{ShouldBeMapped = "true"}); config.AssertConfigurationIsValid(); } [Fact] public void GlobalIgnore_ignores_properties_with_names_matching_but_different_types() { var config = new MapperConfiguration(cfg => { cfg.AddGlobalIgnore("ShouldBeMapped"); cfg.CreateMap<Source, DestinationWrongType>(); }); config.CreateMapper().Map<Source, DestinationWrongType>(new Source { ShouldBeMapped = "true" }); config.AssertConfigurationIsValid(); } [Fact] public void Ignored_properties_should_be_default_value() { var config = new MapperConfiguration(cfg => { cfg.AddGlobalIgnore("StartingWith"); cfg.CreateMap<Source, Destination>() .ForMember(dest => dest.AnotherString_ShouldBeNullAfterwards, opt => opt.Ignore()); }); Destination destination = config.CreateMapper().Map<Source, Destination>(new Source { ShouldBeMapped = "true" }); destination.StartingWith_ShouldBeNullAfterwards.ShouldBe(null); destination.StartingWith_ShouldNotBeMapped.ShouldBe(null); } [Fact] public void Ignore_supports_two_different_values() { var config = new MapperConfiguration(cfg => { cfg.AddGlobalIgnore("StartingWith"); cfg.AddGlobalIgnore("AnotherString"); cfg.CreateMap<Source, Destination>(); }); Destination destination = config.CreateMapper().Map<Source, Destination>(new Source { ShouldBeMapped = "true" }); destination.AnotherString_ShouldBeNullAfterwards.ShouldBe(null); destination.StartingWith_ShouldNotBeMapped.ShouldBe(null); } } public class IgnoreAttributeTests { public class Source { public string ShouldBeMapped { get; set; } public string ShouldNotBeMapped { get; set; } } public class Destination { public string ShouldBeMapped { get; set; } [IgnoreMap] public string ShouldNotBeMapped { get; set; } } [Fact] public void Ignore_On_Source_Field() { var config = new MapperConfiguration(cfg => { cfg.AddIgnoreMapAttribute(); cfg.CreateMap<Source, Destination>(); }); config.AssertConfigurationIsValid(); Source source = new Source { ShouldBeMapped = "Value1", ShouldNotBeMapped = "Value2" }; Destination destination = config.CreateMapper().Map<Source, Destination>(source); destination.ShouldNotBeMapped.ShouldBe(null); } } public class ReverseMapIgnoreAttributeTests { public class Source { public string ShouldBeMapped { get; set; } public string ShouldNotBeMapped { get; set; } } public class Destination { public string ShouldBeMapped { get; set; } [IgnoreMap] public string ShouldNotBeMapped { get; set; } } [Fact] public void Ignore_On_Source_Field() { var config = new MapperConfiguration(cfg => { cfg.AddIgnoreMapAttribute(); cfg.CreateMap<Source, Destination>().ReverseMap(); }); config.AssertConfigurationIsValid(); Destination source = new Destination { ShouldBeMapped = "Value1", ShouldNotBeMapped = "Value2" }; Source destination = config.CreateMapper().Map<Destination, Source>(source); destination.ShouldNotBeMapped.ShouldBe(null); } public class Source2 { } public class Destination2 { [IgnoreMap] public string ShouldNotThrowExceptionOnReverseMapping { get; set; } } [Fact] public void Sould_not_throw_exception_when_reverse_property_does_not_exist() { typeof(ArgumentOutOfRangeException).ShouldNotBeThrownBy(() => new MapperConfiguration(cfg => cfg.CreateMap<Source2, Destination2>() .ReverseMap())); } }
AutoMapper
You are an expert C++ developer. Task: Write a unit test for 'When_configuring_all_non_source_value_null_members' using GoogleTest (gtest) and GoogleMock (gmock). Context: - Class: When_configuring_all_non_source_value_null_members Requirements: Use EXPECT_CALL for virtual methods.
industrial
using AutoMapper.QueryableExtensions.Impl; namespace AutoMapper.UnitTests.Projection; public class ProjectionMappers : AutoMapperSpecBase { class Source { public ConsoleColor Color { get; set; } } class Destination { public int Color { get; set; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.Internal().ProjectionMappers.Add(new EnumToUnderlyingTypeProjectionMapper()); cfg.CreateProjection<Source, Destination>(); }); [Fact] public void Should_work_with_projections() { var destination = new[] { new Source { Color = ConsoleColor.Cyan } }.AsQueryable().ProjectTo<Destination>(Configuration).First(); destination.Color.ShouldBe(11); } private class EnumToUnderlyingTypeProjectionMapper : IProjectionMapper { public Expression Project(IGlobalConfiguration configuration, in ProjectionRequest request, Expression resolvedSource, LetPropertyMaps letPropertyMaps) => Expression.Convert(resolvedSource, request.DestinationType); public bool IsMatch(TypePair context) => context.SourceType.IsEnum && Enum.GetUnderlyingType(context.SourceType) == context.DestinationType; } }
namespace AutoMapper.UnitTests.Tests; public class MapperTests : NonValidatingSpecBase { public class Source { } public class Destination { } [Fact] public void Should_find_configured_type_map_when_two_types_are_configured() { var config = new MapperConfiguration(cfg => cfg.CreateMap<Source, Destination>()); config.FindTypeMapFor<Source, Destination>().ShouldNotBeNull(); } }
AutoMapper
You are an expert C++ developer. Task: Write a unit test for 'ProjectionMappers' using GoogleTest (gtest) and GoogleMock (gmock). Context: - Class: ProjectionMappers Requirements: Use EXPECT_CALL for virtual methods.
industrial
using System.Collections.ObjectModel; namespace AutoMapper.Execution; [EditorBrowsable(EditorBrowsableState.Never)] public static class ObjectFactory { static readonly Expression EmptyString = Constant(string.Empty); static readonly LockingConcurrentDictionary<Type, Func<object>> CtorCache = new(GenerateConstructor); public static object CreateInstance(Type type) => CtorCache.GetOrAdd(type)(); private static Func<object> GenerateConstructor(Type type) => Lambda<Func<object>>(GenerateConstructorExpression(type, null).ToObject()).Compile(); public static object CreateInterfaceProxy(Type interfaceType) => CreateInstance(ProxyGenerator.GetProxyType(interfaceType)); public static Expression GenerateConstructorExpression(Type type, IGlobalConfiguration configuration) => type switch { { IsValueType: true } => configuration.Default(type), Type stringType when stringType == typeof(string) => EmptyString, { IsInterface: true } => CreateInterfaceExpression(type), { IsAbstract: true } => InvalidType(type, $"Cannot create an instance of abstract type {type}."), _ => CallConstructor(type, configuration) }; private static Expression CallConstructor(Type type, IGlobalConfiguration configuration) { var defaultCtor = type.GetConstructor(Internal.TypeExtensions.InstanceFlags, null, [], null); if (defaultCtor != null) { return New(defaultCtor); } var ctorWithOptionalArgs = (from ctor in type.GetDeclaredConstructors() let args = ctor.GetParameters() where args.All(p => p.IsOptional) select (ctor, args)).FirstOrDefault(); if (ctorWithOptionalArgs.args == null) { return InvalidType(type, $"{type} needs to have a constructor with 0 args or only optional args. Validate your configuration for details."); } var arguments = ctorWithOptionalArgs.args.Select(p => p.GetDefaultValue(configuration)); return New(ctorWithOptionalArgs.ctor, arguments); } private static Expression CreateInterfaceExpression(Type type) => type.IsGenericType(typeof(IDictionary<,>)) ? CreateCollection(type, typeof(Dictionary<,>)) : type.IsGenericType(typeof(IReadOnlyDictionary<,>)) ? CreateReadOnlyDictionary(type.GenericTypeArguments) : type.IsGenericType(typeof(ISet<>)) ? CreateCollection(type, typeof(HashSet<>)) : type.IsCollection() ? CreateCollection(type, typeof(List<>), GetIEnumerableArguments(type)) : InvalidType(type, $"Cannot create an instance of interface type {type}."); private static Type[] GetIEnumerableArguments(Type type) => type.GetIEnumerableType()?.GenericTypeArguments ?? [typeof(object)]; private static Expression CreateCollection(Type type, Type collectionType, Type[] genericArguments = null) => ToType(New(collectionType.MakeGenericType(genericArguments ?? type.GenericTypeArguments)), type); private static Expression CreateReadOnlyDictionary(Type[] typeArguments) { var ctor = typeof(ReadOnlyDictionary<,>).MakeGenericType(typeArguments).GetConstructors()[0]; return New(ctor, New(typeof(Dictionary<,>).MakeGenericType(typeArguments))); } private static Expression InvalidType(Type type, string message) => Throw(Constant(new ArgumentException(message, "type")), type); }
namespace AutoMapper.UnitTests; using Execution; public class ObjectFactoryTests { [Fact] public void Test_with_create_ctor() => ObjectFactory.CreateInstance(typeof(ObjectFactoryTests)).ShouldBeOfType<ObjectFactoryTests>(); [Fact] public void Test_with_value_object_create_ctor() => ObjectFactory.CreateInstance(typeof(DateTimeOffset)).ShouldBeOfType<DateTimeOffset>(); [Fact] public void Create_ctor_should_throw_when_default_constructor_is_missing() => new Action(() => ObjectFactory.CreateInstance(typeof(AssemblyLoadEventArgs))) .ShouldThrow<ArgumentException>().Message.ShouldStartWith(typeof(AssemblyLoadEventArgs).FullName); }
AutoMapper
You are an expert .NET (C#) developer. Task: Write a unit test for 'ObjectFactory' using XUnit and Moq. Context: - Class: ObjectFactory Requirements: Use Mock<T> interface mocking.
industrial
using Microsoft.Extensions.Logging; namespace AutoMapper.Licensing; internal class LicenseValidator { private readonly ILogger _logger; public LicenseValidator(ILoggerFactory loggerFactory) { _logger = loggerFactory.CreateLogger("LuckyPennySoftware.AutoMapper.License"); } public void Validate(License license) { var errors = new List<string>(); if (license is not { IsConfigured: true }) { var message = "You do not have a valid license key for the Lucky Penny software AutoMapper. " + "This is allowed for development and testing scenarios. " + "If you are running in production you are required to have a licensed version. " + "Please visit https://luckypennysoftware.com to obtain a valid license."; _logger.LogWarning(message); return; } _logger.LogDebug("The Lucky Penny license key details: {license}", license); var diff = DateTime.UtcNow.Date.Subtract(license.ExpirationDate.Value.Date).TotalDays; if (diff > 0) { errors.Add($"Your license for the Lucky Penny software AutoMapper expired {diff} days ago."); } if (license.ProductType.Value != ProductType.AutoMapper && license.ProductType.Value != ProductType.Bundle) { errors.Add("Your Lucky Penny software license does not include AutoMapper."); } if (errors.Count > 0) { foreach (var err in errors) { _logger.LogError(err); } _logger.LogError( "Please visit https://luckypennysoftware.com to obtain a valid license for the Lucky Penny software AutoMapper."); } else { _logger.LogInformation("You have a valid license key for the Lucky Penny software {type} {edition} edition. The license expires on {licenseExpiration}.", license.ProductType, license.Edition, license.ExpirationDate); } } }
using System.Security.Claims; using AutoMapper.Licensing; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Testing; using License = AutoMapper.Licensing.License; namespace AutoMapper.UnitTests.Licensing; public class LicenseValidatorTests { [Fact] public void Should_return_invalid_when_no_claims() { var factory = new LoggerFactory(); var provider = new FakeLoggerProvider(); factory.AddProvider(provider); var licenseValidator = new LicenseValidator(factory); var license = new License(); license.IsConfigured.ShouldBeFalse(); licenseValidator.Validate(license); var logMessages = provider.Collector.GetSnapshot(); logMessages .ShouldContain(log => log.Level == LogLevel.Warning); } [Fact] public void Should_return_valid_when_community() { var factory = new LoggerFactory(); var provider = new FakeLoggerProvider(); factory.AddProvider(provider); var licenseValidator = new LicenseValidator(factory); var license = new License( new Claim("account_id", Guid.NewGuid().ToString()), new Claim("customer_id", Guid.NewGuid().ToString()), new Claim("sub_id", Guid.NewGuid().ToString()), new Claim("iat", DateTimeOffset.UtcNow.AddDays(-1).ToUnixTimeSeconds().ToString()), new Claim("exp", DateTimeOffset.UtcNow.AddDays(1).ToUnixTimeSeconds().ToString()), new Claim("edition", nameof(Edition.Community)), new Claim("type", nameof(AutoMapper.Licensing.ProductType.Bundle))); license.IsConfigured.ShouldBeTrue(); licenseValidator.Validate(license); var logMessages = provider.Collector.GetSnapshot(); logMessages.ShouldNotContain(log => log.Level == LogLevel.Error || log.Level == LogLevel.Warning || log.Level == LogLevel.Critical); } [Fact] public void Should_return_invalid_when_not_correct_type() { var factory = new LoggerFactory(); var provider = new FakeLoggerProvider(); factory.AddProvider(provider); var licenseValidator = new LicenseValidator(factory); var license = new License( new Claim("account_id", Guid.NewGuid().ToString()), new Claim("customer_id", Guid.NewGuid().ToString()), new Claim("sub_id", Guid.NewGuid().ToString()), new Claim("iat", DateTimeOffset.UtcNow.AddDays(-1).ToUnixTimeSeconds().ToString()), new Claim("exp", DateTimeOffset.UtcNow.AddYears(1).ToUnixTimeSeconds().ToString()), new Claim("edition", nameof(Edition.Professional)), new Claim("type", nameof(AutoMapper.Licensing.ProductType.MediatR))); license.IsConfigured.ShouldBeTrue(); licenseValidator.Validate(license); var logMessages = provider.Collector.GetSnapshot(); logMessages .ShouldContain(log => log.Level == LogLevel.Error); } [Fact] public void Should_return_invalid_when_expired() { var factory = new LoggerFactory(); var provider = new FakeLoggerProvider(); factory.AddProvider(provider); var licenseValidator = new LicenseValidator(factory); var license = new License( new Claim("account_id", Guid.NewGuid().ToString()), new Claim("customer_id", Guid.NewGuid().ToString()), new Claim("sub_id", Guid.NewGuid().ToString()), new Claim("iat", DateTimeOffset.UtcNow.AddYears(-1).ToUnixTimeSeconds().ToString()), new Claim("exp", DateTimeOffset.UtcNow.AddDays(-1).ToUnixTimeSeconds().ToString()), new Claim("edition", nameof(Edition.Professional)), new Claim("type", nameof(AutoMapper.Licensing.ProductType.AutoMapper))); license.IsConfigured.ShouldBeTrue(); licenseValidator.Validate(license); var logMessages = provider.Collector.GetSnapshot(); logMessages .ShouldContain(log => log.Level == LogLevel.Error); } }
AutoMapper
You are an expert C++ developer. Task: Write a unit test for 'LicenseValidator' using GoogleTest (gtest) and GoogleMock (gmock). Context: - Class: LicenseValidator Requirements: Use EXPECT_CALL for virtual methods.
industrial
using StringDictionary = System.Collections.Generic.IDictionary<string, object>; namespace AutoMapper.Internal.Mappers; public sealed class FromStringDictionaryMapper : IObjectMapper { private static readonly MethodInfo MapDynamicMethod = typeof(FromStringDictionaryMapper).GetStaticMethod(nameof(MapDynamic)); public bool IsMatch(TypePair context) => typeof(StringDictionary).IsAssignableFrom(context.SourceType); public Expression MapExpression(IGlobalConfiguration configuration, ProfileMap profileMap, MemberMap memberMap, Expression sourceExpression, Expression destExpression) => Call(MapDynamicMethod, sourceExpression, destExpression.ToObject(), Constant(destExpression.Type), ContextParameter, Constant(profileMap)); private static object MapDynamic(StringDictionary source, object boxedDestination, Type destinationType, ResolutionContext context, ProfileMap profileMap) { boxedDestination ??= ObjectFactory.CreateInstance(destinationType); int matchedCount = 0; foreach (var member in profileMap.CreateTypeDetails(destinationType).WriteAccessors) { var (value, count) = MatchSource(member.Name); if (count == 0) { continue; } if (count > 1) { throw new AutoMapperMappingException($"Multiple matching keys were found in the source dictionary for destination member {member}.", null, new TypePair(typeof(StringDictionary), destinationType)); } var mappedValue = context.MapMember(member, value, boxedDestination); member.SetMemberValue(boxedDestination, mappedValue); matchedCount++; } if (matchedCount < source.Count) { MapInnerProperties(); } return boxedDestination; (object Value, int Count) MatchSource(string name) { if (source.TryGetValue(name, out var value)) { return (value, 1); } var matches = source.Where(s => s.Key.Trim() == name).Select(s=>s.Value).ToArray(); if (matches.Length == 1) { return (matches[0], 1); } return (null, matches.Length); } void MapInnerProperties() { MemberInfo[] innerMembers; foreach (var memberPath in source.Keys.Where(k => k.Contains('.'))) { innerMembers = ReflectionHelper.GetMemberPath(destinationType, memberPath); var innerDestination = GetInnerDestination(); if (innerDestination == null) { continue; } var lastMember = innerMembers[innerMembers.Length - 1]; var value = context.MapMember(lastMember, source[memberPath], innerDestination); lastMember.SetMemberValue(innerDestination, value); } return; object GetInnerDestination() { var currentDestination = boxedDestination; foreach (var member in innerMembers.Take(innerMembers.Length - 1)) { var newDestination = member.GetMemberValue(currentDestination); if (newDestination == null) { if (!member.CanBeSet()) { return null; } newDestination = ObjectFactory.CreateInstance(member.GetMemberType()); member.SetMemberValue(currentDestination, newDestination); } currentDestination = newDestination; } return currentDestination; } } } #if FULL_OR_STANDARD public TypePair? GetAssociatedTypes(TypePair initialTypes) => null; #endif }
using StringDictionary = System.Collections.Generic.Dictionary<string, object>; namespace AutoMapper.UnitTests.Mappers; class Destination { public string Foo { get; set; } public string Bar { get; set; } public int Baz { get; set; } public InnerDestination Inner { get; } = new InnerDestination(); public InnerDestination NullInner { get; } public InnerDestination SettableInner { get; set; } } class InnerDestination { public int Value { get; set; } public InnerDestination Child { get; set; } } public class When_mapping_to_StringDictionary : NonValidatingSpecBase { StringDictionary _destination; protected override MapperConfiguration CreateConfiguration() => new(cfg => { }); protected override void Because_of() { _destination = Mapper.Map<StringDictionary>(new Destination { Foo = "Foo", Bar = "Bar" }); } [Fact] public void Should_map_source_properties() { _destination["Foo"].ShouldBe("Foo"); _destination["Bar"].ShouldBe("Bar"); } [Fact] public void Should_map_struct() => Map<StringDictionary>(new KeyValuePair<int, string>(1, "one")).ShouldBe(new StringDictionary { { "Key", 1 }, {"Value", "one"} }); } public class When_mapping_from_StringDictionary : NonValidatingSpecBase { Destination _destination; protected override MapperConfiguration CreateConfiguration() => new(cfg => { }); protected override void Because_of() { var source = new StringDictionary() { { "Foo", "Foo" }, { "Bar", "Bar" } }; _destination = Mapper.Map<Destination>(source); } [Fact] public void Should_map_destination_properties() { _destination.Foo.ShouldBe("Foo"); _destination.Bar.ShouldBe("Bar"); _destination.Baz.ShouldBe(0); } [Fact] public void When_mapping_inner_properties() { var source = new StringDictionary() { { "Inner.Value", "5" }, { "NullInner.Value", "5" }, { "SettableInner.Value", "6" }, { "SettableInner.Child.Value", "7" }, { "Inner.Child.Value", "8" }}; var destination = Mapper.Map<Destination>(source); destination.Inner.Value.ShouldBe(5); destination.NullInner.ShouldBeNull(); destination.SettableInner.Value.ShouldBe(6); destination.SettableInner.Child.Value.ShouldBe(7); destination.Inner.Child.Value.ShouldBe(8); } } public class When_mapping_struct_from_StringDictionary : NonValidatingSpecBase { Destination _destination; struct Destination { public string Foo { get; set; } public string Bar { get; set; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { }); protected override void Because_of() { var source = new StringDictionary() { { "Foo", "Foo" }, { "Bar", "Bar" } }; _destination = Mapper.Map<Destination>(source); } [Fact] public void Should_map_destination_properties() { _destination.Foo.ShouldBe("Foo"); _destination.Bar.ShouldBe("Bar"); } [Fact] public void Should_map_non_generic() { var source = new StringDictionary() { { "Foo", "Foo" }, { "Bar", "Bar" } }; var destination = (Destination) Mapper.Map(source, null, typeof(Destination)); destination.Foo.ShouldBe("Foo"); destination.Bar.ShouldBe("Bar"); } } public class When_mapping_from_StringDictionary_with_missing_property : NonValidatingSpecBase { Destination _destination; protected override MapperConfiguration CreateConfiguration() => new(cfg => { }); protected override void Because_of() { var source = new StringDictionary() { { "Foo", "Foo" } }; _destination = Mapper.Map<Destination>(source); } [Fact] public void Should_map_existing_properties() { _destination.Foo.ShouldBe("Foo"); _destination.Bar.ShouldBeNull(); _destination.Baz.ShouldBe(0); } } public class When_mapping_from_StringDictionary_null_to_int : NonValidatingSpecBase { Destination _destination; protected override MapperConfiguration CreateConfiguration() => new(cfg => { }); protected override void Because_of() { var source = new StringDictionary() { { "Foo", "Foo" }, { "Baz", null } }; _destination = Mapper.Map<Destination>(source); } [Fact] public void Should_map_to_zero() { _destination.Foo.ShouldBe("Foo"); _destination.Bar.ShouldBeNull(); _destination.Baz.ShouldBe(0); } } public class When_mapping_from_StringDictionary_with_whitespace : NonValidatingSpecBase { Destination _destination; protected override MapperConfiguration CreateConfiguration() => new(cfg => { }); protected override void Because_of() { var source = new StringDictionary() { { " Foo", "Foo" }, { " Bar", "Bar" }, { " Baz ", 2 } }; _destination = Mapper.Map<Destination>(source); } [Fact] public void Should_map() { _destination.Foo.ShouldBe("Foo"); _destination.Bar.ShouldBe("Bar"); _destination.Baz.ShouldBe(2); } } public class When_mapping_from_StringDictionary_multiple_matching_keys : NonValidatingSpecBase { StringDictionary _source; protected override MapperConfiguration CreateConfiguration() => new(cfg => { }); protected override void Because_of() { _source = new StringDictionary() { { " Foo", "Foo1" }, { " Foo", "Foo2" }, { "Bar", "Bar" }, { "Baz", 2 } }; } [Fact] public void Should_throw_when_mapping() { Should.Throw<AutoMapperMappingException>(() => { Mapper.Map<Destination>(_source); }).InnerException.ShouldBeOfType<AutoMapperMappingException>().Types.ShouldBe(new TypePair(typeof(IDictionary<string, object>), typeof(Destination))); } } public class When_mapping_from_StringDictionary_to_StringDictionary : NonValidatingSpecBase { StringDictionary _destination; protected override MapperConfiguration CreateConfiguration() => new(cfg => { }); protected override void Because_of() { var source = new StringDictionary() { { "Foo", "Foo" }, { "Bar", "Bar" }, { "Bar ", "Bar_" } }; _destination = Mapper.Map<StringDictionary>(source); } [Fact] public void Should_map() { _destination["Foo"].ShouldBe("Foo"); _destination["Bar"].ShouldBe("Bar"); _destination["Bar "].ShouldBe("Bar_"); } } public class When_mapping_from_StringDictionary_to_existing_destination : AutoMapperSpecBase { public abstract class SomeBase { protected int _x = 100; public abstract int X { get; } protected int _y = 200; public abstract int Y { get; } } public class SomeBody : SomeBase { public override int X { get { return _x + 10; } } public override int Y { get { return _y + 20; } } private int _z = 300; public int Z { get { return _z + 30; } } public int Value { get; set; } public Collection<int> Integers { get; } = new(); } public class SomeOne : SomeBase { public override int X { get { return _x - 10; } } public override int Y { get { return _y - 20; } } private int _a = 300; public int A { get { return _a - 30; } } } protected override MapperConfiguration CreateConfiguration() => new(c => c.CreateMap<SomeBase, SomeBase>()); [Fact] public void Should_map_ok() { var someBase = new SomeBody(); var someOne = new StringDictionary { ["Integers"] = Enumerable.Range(1, 10).ToArray() }; Mapper.Map(someOne, someBase); someBase.Integers.ShouldBe(someOne["Integers"]); } public class Destination { public DateTime? NullableDate { get; set; } public int? NullableInt { get; set; } public int Int { get; set; } public SomeBody SomeBody { get; set; } = new SomeBody { Value = 15 }; public SomeOne SomeOne { get; set; } = new SomeOne(); public string String { get; set; } = "value"; } [Fact] public void Should_override_existing_values() { var source = new StringDictionary(); source["Int"] = 10; source["NullableDate"] = null; source["NullableInt"] = null; source["String"] = null; source["SomeBody"] = new SomeOne(); source["SomeOne"] = null; var destination = new Destination { NullableInt = 1, NullableDate = DateTime.Now }; var someBody = destination.SomeBody; Mapper.Map(source, destination); destination.Int.ShouldBe(10); destination.NullableInt.ShouldBeNull(); destination.NullableDate.ShouldBeNull(); destination.SomeBody.ShouldBe(someBody); destination.SomeBody.Value.ShouldBe(15); destination.String.ShouldBeNull(); destination.SomeOne.ShouldBeNull(); } } public class When_mapping_from_StringDictionary_to_abstract_type : AutoMapperSpecBase { public abstract class SomeBase { protected int _x = 100; public abstract int X { get; } protected int _y = 200; public abstract int Y { get; } } public class SomeBody : SomeBase { public override int X { get { return _x + 10; } } public override int Y { get { return _y + 20; } } private int _z = 300; public int Z { get { return _z + 30; } } } public class SomeOne : SomeBase { public override int X { get { return _x - 10; } } public override int Y { get { return _y - 20; } } private int _a = 300; public int A { get { return _a - 30; } } } protected override MapperConfiguration CreateConfiguration() => new(c => c.CreateMap<SomeBase, SomeBase>()); [Fact] public void Should_throw() { new Action(() => Mapper.Map<SomeBase>(new StringDictionary())) .ShouldThrowException<AutoMapperMappingException>(ex => ex.InnerException.Message.ShouldStartWith($"Cannot create an instance of abstract type {typeof(SomeBase)}.")); } }
AutoMapper
You are an expert C++ developer. Task: Write a unit test for 'FromStringDictionaryMapper' using GoogleTest (gtest) and GoogleMock (gmock). Context: - Class: FromStringDictionaryMapper Requirements: Use EXPECT_CALL for virtual methods.
industrial
namespace AutoMapper.Internal.Mappers; public sealed class ConvertMapper : IObjectMapper { public static bool IsPrimitive(Type type) => type.IsPrimitive || type == typeof(string) || type == typeof(decimal); public bool IsMatch(TypePair types) => (types.SourceType == typeof(string) && types.DestinationType == typeof(DateTime)) || (IsPrimitive(types.SourceType) && IsPrimitive(types.DestinationType)); public Expression MapExpression(IGlobalConfiguration configuration, ProfileMap profileMap, MemberMap memberMap, Expression sourceExpression, Expression destExpression) { var convertMethod = typeof(Convert).GetMethod("To" + destExpression.Type.Name, [sourceExpression.Type]); return Call(convertMethod, sourceExpression); } #if FULL_OR_STANDARD public TypePair? GetAssociatedTypes(TypePair initialTypes) => null; #endif }
using AutoMapper.Internal.Mappers; namespace AutoMapper.UnitTests.Mappers; public class ConvertMapperTests : AutoMapperSpecBase { protected override MapperConfiguration CreateConfiguration() => new(c => { }); [Fact] public void A_few_cases() { Mapper.Map<ushort, bool>(1).ShouldBeTrue(); Mapper.Map<decimal, bool>(0).ShouldBeFalse(); Mapper.Map<ushort, bool?>(1).Value.ShouldBeTrue(); Mapper.Map<decimal, bool?>(0).Value.ShouldBeFalse(); Mapper.Map<uint, ulong>(12).ShouldBe((ulong)12); Mapper.Map<uint, ulong?>(12).ShouldBe((ulong)12); Mapper.Map<bool, byte>(true).ShouldBe((byte)1); Mapper.Map<bool, ushort>(false).ShouldBe((byte)0); Mapper.Map<bool, byte?>(true).ShouldBe((byte)1); Mapper.Map<bool, ushort?>(false).ShouldBe((byte)0); Mapper.Map<float, int>(12).ShouldBe(12); Mapper.Map<double, int>(12).ShouldBe(12); Mapper.Map<decimal, int>(12).ShouldBe(12); Mapper.Map<float, int?>(12).ShouldBe(12); Mapper.Map<double, int?>(12).ShouldBe(12); Mapper.Map<decimal, int?>(12).ShouldBe(12); Mapper.Map<int, float>(12).ShouldBe(12); Mapper.Map<int, double>(12).ShouldBe(12); Mapper.Map<int, decimal>(12).ShouldBe(12); Mapper.Map<int, float?>(12).ShouldBe(12); Mapper.Map<int, double?>(12).ShouldBe(12); Mapper.Map<int, decimal?>(12).ShouldBe(12); } [Fact] public void From_string() { Mapper.Map<string, byte?>("12").ShouldBe((byte)12); Mapper.Map<string, sbyte>("12").ShouldBe((sbyte)12); Mapper.Map<string, float>("12").ShouldBe(12); Mapper.Map<string, double?>("12").ShouldBe(12); Mapper.Map<string, decimal?>("12").ShouldBe(12); Mapper.Map<string, ushort>("12").ShouldBe((ushort)12); Mapper.Map<string, ulong>("12").ShouldBe((ulong)12); Configuration.FindMapper(new TypePair(typeof(string), typeof(DateTime))).ShouldBeOfType<ConvertMapper>(); var date = DateTime.Now; Mapper.Map<DateTime>(date.ToString("O")).ShouldBe(date); } [Fact] public void From_null_string_to_nullable_int() { Mapper.Map<string, int?>(null).ShouldBeNull(); } [Fact] public void ParseMapper() { Configuration.FindMapper(new TypePair(typeof(string), typeof(Guid))).ShouldBeOfType<ParseStringMapper>(); var guid = Guid.NewGuid(); Mapper.Map<Guid>(guid.ToString()).ShouldBe(guid); Configuration.FindMapper(new TypePair(typeof(string), typeof(TimeSpan))).ShouldBeOfType<ParseStringMapper>(); var timeSpan = TimeSpan.FromMinutes(1); Mapper.Map<TimeSpan>(timeSpan.ToString()).ShouldBe(timeSpan); Configuration.FindMapper(new TypePair(typeof(string), typeof(DateTimeOffset))).ShouldBeOfType<ParseStringMapper>(); var dateTimeOffset = DateTimeOffset.Now; Mapper.Map<DateTimeOffset>(dateTimeOffset.ToString("O")).ShouldBe(dateTimeOffset); } }
AutoMapper
You are an expert C++ developer. Task: Write a unit test for 'ConvertMapper' using GoogleTest (gtest) and GoogleMock (gmock). Context: - Class: ConvertMapper Requirements: Use EXPECT_CALL for virtual methods.
industrial
namespace AutoMapper.Internal.Mappers; public sealed class ConstructorMapper : IObjectMapper { public bool IsMatch(TypePair context) => GetConstructor(context.SourceType, context.DestinationType) != null; private static ConstructorInfo GetConstructor(Type sourceType, Type destinationType) => destinationType.GetConstructor(TypeExtensions.InstanceFlags, null, [sourceType], null); public Expression MapExpression(IGlobalConfiguration configuration, ProfileMap profileMap, MemberMap memberMap, Expression sourceExpression, Expression destExpression) { var constructor = GetConstructor(sourceExpression.Type, destExpression.Type); return New(constructor, ToType(sourceExpression, constructor.FirstParameterType())); } #if FULL_OR_STANDARD public TypePair? GetAssociatedTypes(TypePair initialTypes) => null; #endif }
namespace AutoMapper.UnitTests.Mappers; public class ConstructorMapperTests : AutoMapperSpecBase { class Destination { public Destination(string value) { Value = value; } public string Value { get; } } protected override MapperConfiguration CreateConfiguration() => new(_=> { }); [Fact] public void Should_use_constructor() => Mapper.Map<Destination>("value").Value.ShouldBe("value"); }
AutoMapper
You are an expert C++ developer. Task: Write a unit test for 'ConstructorMapper' using GoogleTest (gtest) and GoogleMock (gmock). Context: - Class: ConstructorMapper Requirements: Use EXPECT_CALL for virtual methods.
industrial
using System.Runtime.CompilerServices; using Microsoft.CSharp.RuntimeBinder; using Binder = Microsoft.CSharp.RuntimeBinder.Binder; namespace AutoMapper.Internal.Mappers; public sealed class FromDynamicMapper : IObjectMapper { private static readonly MethodInfo MapMethodInfo = typeof(FromDynamicMapper).GetStaticMethod(nameof(Map)); private static object Map(object source, object destination, Type destinationType, ResolutionContext context, ProfileMap profileMap) { destination ??= ObjectFactory.CreateInstance(destinationType); var destinationTypeDetails = profileMap.CreateTypeDetails(destinationType); foreach (var member in destinationTypeDetails.WriteAccessors) { object sourceMemberValue; try { sourceMemberValue = GetDynamically(member.Name, source); } catch (RuntimeBinderException) { continue; } var destinationMemberValue = context.MapMember(member, sourceMemberValue, destination); member.SetMemberValue(destination, destinationMemberValue); } return destination; } private static object GetDynamically(string memberName, object target) { var binder = Binder.GetMember(CSharpBinderFlags.None, memberName, null, [CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null)]); var callsite = CallSite<Func<CallSite, object, object>>.Create(binder); return callsite.Target(callsite, target); } public bool IsMatch(TypePair context) => context.SourceType.IsDynamic() && !context.DestinationType.IsDynamic(); public Expression MapExpression(IGlobalConfiguration configuration, ProfileMap profileMap, MemberMap memberMap, Expression sourceExpression, Expression destExpression) => Call(MapMethodInfo, sourceExpression, destExpression.ToObject(), Constant(destExpression.Type), ContextParameter, Constant(profileMap)); #if FULL_OR_STANDARD public TypePair? GetAssociatedTypes(TypePair initialTypes) => null; #endif }
using System.Dynamic; namespace AutoMapper.UnitTests.Mappers.Dynamic; class Destination { public string Foo { get; set; } public string Bar { get; set; } internal string Jack { get; set; } public int[] Data { get; set; } public int Baz { get; set; } } public class DynamicDictionary : DynamicObject { private readonly Dictionary<string, object> dictionary = new Dictionary<string, object>(); public override bool TryGetMember(GetMemberBinder binder, out object result) { return dictionary.TryGetValue(binder.Name, out result); } public override bool TrySetMember(SetMemberBinder binder, object value) { dictionary[binder.Name] = value; return true; } public int Count => dictionary.Count; } public class When_mapping_to_dynamic_from_getter_only_property { class Source { public Source() { Value = 24; } public int Value { get; } } [Fact] public void Should_map_source_properties() { var config = new MapperConfiguration(cfg => { }); dynamic destination = config.CreateMapper().Map<DynamicDictionary>(new Source()); ((int)destination.Count).ShouldBe(1); Assert.Equal(24, destination.Value); } } public class When_mapping_to_dynamic { dynamic _destination; [Fact] public void Should_map_source_properties() { var config = new MapperConfiguration(cfg => { }); var data = new[] { 1, 2, 3 }; _destination = config.CreateMapper().Map<DynamicDictionary>(new Destination { Foo = "Foo", Bar = "Bar", Data = data, Baz = 12 }); ((int)_destination.Count).ShouldBe(4); Assert.Equal("Foo", _destination.Foo); Assert.Equal("Bar", _destination.Bar); Assert.Equal(12, _destination.Baz); ((int[])_destination.Data).SequenceEqual(data).ShouldBeTrue(); } [Fact] public void Should_map_to_ExpandoObject() { var config = new MapperConfiguration(cfg => { }); var data = new[] { 1, 2, 3 }; _destination = config.CreateMapper().Map<ExpandoObject>(new Destination { Foo = "Foo", Bar = "Bar", Data = data, Baz = 12 }); ((IDictionary<string, object>)_destination).Count.ShouldBe(4); Assert.Equal("Foo", _destination.Foo); Assert.Equal("Bar", _destination.Bar); Assert.Equal(12, _destination.Baz); ((int[])_destination.Data).SequenceEqual(data).ShouldBeTrue(); } } public class When_mapping_from_dynamic { Destination _destination; [Fact] public void Should_map_destination_properties() { dynamic source = new DynamicDictionary(); source.Foo = "Foo"; source.Bar = "Bar"; source.Jack = "Jack"; var config = new MapperConfiguration(cfg => { }); _destination = config.CreateMapper().Map<Destination>((object)source); _destination.Foo.ShouldBe("Foo"); _destination.Bar.ShouldBe("Bar"); _destination.Jack.ShouldBeNull(); } } public class When_mapping_struct_from_dynamic { Destination _destination; struct Destination { public string Foo { get; set; } public string Bar { get; set; } internal string Jack { get; set; } } [Fact] public void Should_map_destination_properties() { dynamic source = new DynamicDictionary(); source.Foo = "Foo"; source.Bar = "Bar"; source.Jack = "Jack"; var config = new MapperConfiguration(cfg => { }); _destination = config.CreateMapper().Map<Destination>((object)source); _destination.Foo.ShouldBe("Foo"); _destination.Bar.ShouldBe("Bar"); _destination.Jack.ShouldBeNull(); } } public class When_mapping_from_dynamic_with_missing_property { [Fact] public void Should_map_existing_properties() { dynamic source = new DynamicDictionary(); source.Foo = "Foo"; var config = new MapperConfiguration(cfg => { }); var destination = config.CreateMapper().Map<Destination>((object)source); destination.Foo.ShouldBe("Foo"); destination.Bar.ShouldBeNull(); } [Fact] public void Should_keep_existing_value() { dynamic source = new DynamicDictionary(); source.Foo = "Foo"; var config = new MapperConfiguration(cfg => { }); var destination = new Destination { Baz = 42 }; config.CreateMapper().Map((object)source, destination); destination.Foo.ShouldBe("Foo"); destination.Baz.ShouldBe(42); } } public class When_mapping_from_dynamic_null_to_int { Destination _destination; [Fact] public void Should_map_to_zero() { dynamic source = new DynamicDictionary(); source.Foo = "Foo"; source.Baz = null; var config = new MapperConfiguration(cfg => { }); _destination = config.CreateMapper().Map<Destination>((object)source); _destination.Foo.ShouldBe("Foo"); _destination.Bar.ShouldBeNull(); _destination.Baz.ShouldBe(0); } } public class When_mapping_from_dynamic_to_dynamic { dynamic _destination; [Fact] public void Should_map() { dynamic source = new DynamicDictionary(); source.Foo = "Foo"; source.Bar = "Bar"; var config = new MapperConfiguration(cfg => { }); _destination = config.CreateMapper().Map<DynamicDictionary>((object)source); Assert.Equal("Foo", _destination.Foo); Assert.Equal("Bar", _destination.Bar); } } public class When_mapping_from_dynamic_to_nullable { class DestinationWithNullable { public string StringValue { get; set; } public int? NullIntValue { get; set; } } [Fact] public void Should_map_with_non_null_source() { dynamic source = new DynamicDictionary(); source.StringValue = "Test"; source.NullIntValue = 5; var config = new MapperConfiguration(cfg => { }); var destination = config.CreateMapper().Map<DestinationWithNullable>((object)source); Assert.Equal("Test", destination.StringValue); Assert.Equal(5, destination.NullIntValue); } [Fact] public void Should_map_with_source_missing() { dynamic source = new DynamicDictionary(); source.StringValue = "Test"; var config = new MapperConfiguration(cfg => { }); var destination = config.CreateMapper().Map<DestinationWithNullable>((object)source); Assert.Equal("Test", destination.StringValue); Assert.Equal((int?)null, destination.NullIntValue); } [Fact] public void Should_map_with_null_source() { dynamic source = new DynamicDictionary(); source.StringValue = "Test"; source.NullIntValue = null; var config = new MapperConfiguration(cfg => { }); var destination = config.CreateMapper().Map<DestinationWithNullable>((object)source); Assert.Equal("Test", destination.StringValue); Assert.Equal((int?)null, destination.NullIntValue); } }
AutoMapper
You are an expert .NET (C#) developer. Task: Write a unit test for 'FromDynamicMapper' using XUnit and Moq. Context: - Class: FromDynamicMapper Requirements: Use Mock<T> interface mocking.
industrial
namespace AutoMapper.IntegrationTests.BuiltInTypes; public class ProjectEnumerableOfIntToHashSet(DatabaseFixture databaseFixture) : IntegrationTest<ProjectEnumerableOfIntToHashSet.DatabaseInitializer>(databaseFixture) { public class Customer { [Key] public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public List<Item> Items { get; set; } } public class Item { public int Id { get; set; } } public class CustomerViewModel { public string FirstName { get; set; } public string LastName { get; set; } public HashSet<int> ItemsIds { get; set; } } public class Context : LocalDbContext { public DbSet<Customer> Customers { get; set; } public DbSet<Item> Items { get; set; } } public class DatabaseInitializer : DropCreateDatabaseAlways<Context> { protected override void Seed(Context context) { context.Customers.Add(new Customer { FirstName = "Bob", LastName = "Smith", Items = new List<Item>(new[] { new Item(), new Item(), new Item() }) }); base.Seed(context); } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.CreateProjection<Customer, CustomerViewModel>().ForMember(d => d.ItemsIds, o => o.MapFrom(s => s.Items.Select(i => i.Id))); }); [Fact] public void Can_map_with_projection() { using (var context = Fixture.CreateContext()) { var customer = ProjectTo<CustomerViewModel>(context.Customers).Single(); customer.ItemsIds.SequenceEqual(new int[] { 1, 2, 3 }).ShouldBeTrue(); } } }
namespace AutoMapper.UnitTests.Projection; public class ProjectEnumTest { private MapperConfiguration _config; public ProjectEnumTest() { _config = new MapperConfiguration(cfg => { cfg.CreateProjection<Customer, CustomerDto>(); cfg.CreateProjection<CustomerType, string>().ConvertUsing(ct => ct.ToString().ToUpper()); }); } [Fact] public void ProjectingEnumToString() { var customers = new[] { new Customer() { FirstName = "Bill", LastName = "White", CustomerType = CustomerType.Vip } }.AsQueryable(); var projected = customers.ProjectTo<CustomerDto>(_config); projected.ShouldNotBeNull(); Assert.Equal(customers.Single().CustomerType.ToString(), projected.Single().CustomerType, StringComparer.OrdinalIgnoreCase); } public class Customer { public string FirstName { get; set; } public string LastName { get; set; } public CustomerType CustomerType { get; set; } } public class CustomerDto { public string FirstName { get; set; } public string LastName { get; set; } public string CustomerType { get; set; } } public enum CustomerType { Regular, Vip, } } public class ProjectionOverrides : AutoMapperSpecBase { public class Source { } public class Dest { public int Value { get; set; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.CreateProjection<Source, Dest>() .ConvertUsing(src => new Dest {Value = 10}); }); [Fact] public void Validate() => AssertConfigurationIsValid(); }
AutoMapper
You are an expert C++ developer. Task: Write a unit test for 'ProjectEnumerableOfIntToHashSet' using GoogleTest (gtest) and GoogleMock (gmock). Context: - Class: ProjectEnumerableOfIntToHashSet Requirements: Use EXPECT_CALL for virtual methods.
industrial
namespace AutoMapper.IntegrationTests; public class ICollectionAggregateProjections(DatabaseFixture databaseFixture) : IntegrationTest<ICollectionAggregateProjections.DatabaseInitializer>(databaseFixture) { public class Customer { [Key] public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public ICollection<Item> Items { get; set; } } public class Item { public int Id { get; set; } public int Code { get; set; } } public class CustomerViewModel { public int ItemCodesCount { get; set; } public int ItemCodesMin { get; set; } public int ItemCodesMax { get; set; } public int ItemCodesSum { get; set; } } public class Context : LocalDbContext { public DbSet<Customer> Customers { get; set; } } public class DatabaseInitializer : DropCreateDatabaseAlways<Context> { protected override void Seed(Context context) { context.Customers.Add(new Customer { FirstName = "Bob", LastName = "Smith", Items = new[] { new Item { Code = 1 }, new Item { Code = 3 }, new Item { Code = 5 } } }); base.Seed(context); } } public class CustomerItemCodes { public List<int> ItemCodes { get; set; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => cfg.CreateProjection<CustomerItemCodes, CustomerViewModel>()); [Fact] public void Can_map_with_projection() { using (var context = Fixture.CreateContext()) { var result = ProjectTo<CustomerViewModel>(context.Customers.Select(customer => new CustomerItemCodes { ItemCodes = customer.Items.Select(item => item.Code).ToList() })).Single(); result.ItemCodesCount.ShouldBe(3); result.ItemCodesMin.ShouldBe(1); result.ItemCodesMax.ShouldBe(5); result.ItemCodesSum.ShouldBe(9); } } }
namespace AutoMapper.UnitTests.Projection; public class ProjectWithFields : AutoMapperSpecBase { public class Foo { public int A; } public class FooDto { public int A; } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.CreateProjection<Foo, FooDto>(); }); [Fact] public void Should_work() { new[] { new Foo() }.AsQueryable().ProjectTo<FooDto>(Configuration).Single().A.ShouldBe(0); var p1 = Configuration.Internal().ProjectionBuilder; var p2 = Configuration.Internal().ProjectionBuilder; p2.ShouldBe(p1); var profile = Configuration.Internal().Profiles[0]; profile.CreateTypeDetails(typeof(DateTime)).ShouldBe(profile.CreateTypeDetails(typeof(DateTime))); } } public class ProjectTest { private MapperConfiguration _config; public ProjectTest() { _config = new MapperConfiguration(cfg => { cfg.CreateProjection<Address, AddressDto>(); cfg.CreateProjection<Customer, CustomerDto>(); }); } [Fact] public void ProjectToWithUnmappedTypeShouldThrowException() { var customers = new[] { new Customer { FirstName = "Bill", LastName = "White", Address = new Address("Street1") } } .AsQueryable(); IList<Unmapped> projected = null; typeof(InvalidOperationException).ShouldBeThrownBy(() => projected = customers.ProjectTo<Unmapped>(_config).ToList()); projected.ShouldBeNull(); } [Fact] public void DynamicProjectToShouldWork() { var customers = new[] { new Customer { FirstName = "Bill", LastName = "White", Address = new Address("Street1") } } .AsQueryable(); IQueryable projected = customers.ProjectTo(typeof(CustomerDto), _config); projected.Cast<CustomerDto>().Single().FirstName.ShouldBe("Bill"); } public class Customer { public string FirstName { get; set; } public string LastName { get; set; } public Address Address { get; set; } } public class Address { public Address(string street) { Street = street; } public string Street { get; set; } } public class CustomerDto { public string FirstName { get; set; } public AddressDto Address { get; set; } } public class AddressDto { public string Street { get; set; } } public class Unmapped { public string FirstName { get; set; } } }
AutoMapper
You are an expert C++ developer. Task: Write a unit test for 'ICollectionAggregateProjections' using GoogleTest (gtest) and GoogleMock (gmock). Context: - Class: ICollectionAggregateProjections Requirements: Use EXPECT_CALL for virtual methods.
industrial
namespace AutoMapper.UnitTests.Bug; public class MapFromClosureBug : NonValidatingSpecBase { private static readonly IDateProvider _dateProvider = new DateProvider(); class DateProvider : IDateProvider { public DateTime CurrentRestaurantTime(Restaurant restaurant) => DateTime.Now; } public interface IDateProvider { DateTime CurrentRestaurantTime(Restaurant restaurant); } public class Result { public Booking Booking { get; set; } } public class Restaurant { } public class Booking { public Restaurant Restaurant { get; set; } public int? CalculateTotal(DateTime currentTime) { return null; } } public class ResultDto { public BookingDto Booking { get; set; } } public class BookingDto { public int? Total { get; set; } } [Fact] public void Should_map_successfully() { var mapperConfiguration = new MapperConfiguration(cfg => { cfg.CreateMap<Result, ResultDto>(); cfg.CreateMap<Booking, BookingDto>() .ForMember(d => d.Total, o => o.MapFrom(b => b.CalculateTotal(_dateProvider.CurrentRestaurantTime(b.Restaurant)))); }); var mapper = mapperConfiguration.CreateMapper(); var result = new Result { Booking = new Booking() }; // Act var dto = mapper.Map<ResultDto>(result); // Assert dto.ShouldNotBeNull(); } }
namespace AutoMapper.UnitTests.Projection.MapFromTest; public class CustomMapFromExpressionTest { [Fact] public void Should_not_fail() { var config = new MapperConfiguration(cfg => { cfg.CreateProjection<UserModel, UserDto>() .ForMember(dto => dto.FullName, opt => opt.MapFrom(src => src.LastName + " " + src.FirstName)); }); typeof(System.NullReferenceException).ShouldNotBeThrownBy(() => config.Internal().ProjectionBuilder.GetMapExpression<UserModel, UserDto>()); //null reference exception here } [Fact] public void Should_map_from_String() { var config = new MapperConfiguration(cfg => cfg.CreateMap<UserModel, UserDto>() .ForMember(dto => dto.FullName, opt => opt.MapFrom("FirstName"))); var um = new UserModel(); um.FirstName = "Hallo"; var u = new UserDto(); config.CreateMapper().Map(um, u); u.FullName.ShouldBe(um.FirstName); } public class UserModel { public string FirstName { get; set; } public string LastName { get; set; } } public class UserDto { public string FullName { get; set; } } [Fact] public void Should_project_from_String() { var config = new MapperConfiguration(cfg => cfg.CreateMap<UserModel, UserDto>() .ForMember(dto => dto.FullName, opt => opt.MapFrom("FirstName"))); var result = new[] { new UserModel { FirstName = "Hallo" } }.AsQueryable().ProjectTo<UserDto>(config).Single(); result.FullName.ShouldBe("Hallo"); } } public class When_mapping_from_and_source_member_both_can_work : AutoMapperSpecBase { Dto _destination; public class Model { public string ShortDescription { get; set; } } public class Dto { public string ShortDescription { get; set; } } protected override MapperConfiguration CreateConfiguration() => new(c => c.CreateProjection<Model, Dto>().ForMember(d => d.ShortDescription, o => o.MapFrom(s => "mappedFrom"))); protected override void Because_of() { _destination = new[] { new Model() }.AsQueryable().ProjectTo<Dto>(Configuration).Single(); } [Fact] public void Map_from_should_prevail() { _destination.ShortDescription.ShouldBe("mappedFrom"); } } public class When_mapping_from_chained_properties : AutoMapperSpecBase { class Model { public InnerModel Inner { get; set; } } class InnerModel { public InnerModel(string value) => Value = value ?? throw new System.ArgumentNullException(nameof(value)); private string Value { get; set; } } class Dto { public string Value { get; set; } } protected override MapperConfiguration CreateConfiguration() => new(c => c.CreateMap<Model, Dto>().ForMember(d => d.Value, o => o.MapFrom("Inner.Value"))); [Fact] public void Should_map_ok() => Map<Dto>(new Model { Inner = new InnerModel("mappedFrom") }).Value.ShouldBe("mappedFrom"); } public class When_mapping_from_private_method : AutoMapperSpecBase { class Model { public InnerModel Inner { get; set; } } class InnerModel { public InnerModel(string value) => SomeValue = value ?? throw new System.ArgumentNullException(nameof(value)); private string SomeValue { get; set; } private string GetSomeValue() => SomeValue; } class Dto { public string Value { get; set; } } protected override MapperConfiguration CreateConfiguration() => new(c => c.CreateMap<Model, Dto>().ForMember(d => d.Value, o => o.MapFrom("Inner.GetSomeValue"))); [Fact] public void Should_map_ok() => Map<Dto>(new Model { Inner = new InnerModel("mappedFrom") }).Value.ShouldBe("mappedFrom"); }
AutoMapper
You are an expert C++ developer. Task: Write a unit test for 'MapFromClosureBug' using GoogleTest (gtest) and GoogleMock (gmock). Context: - Class: MapFromClosureBug Requirements: Use EXPECT_CALL for virtual methods.
industrial
namespace AutoMapper.UnitTests; public class ForPathGenericsSource : AutoMapperSpecBase { class Source<T> { public InnerSource Inner; } class InnerSource { public int Id; } class Destination { public int InnerId; } protected override MapperConfiguration CreateConfiguration() => new(c => c.CreateMap(typeof(Source<>), typeof(Destination)).ReverseMap()); [Fact] public void Should_work() => Map<Destination>(new Source<int> { Inner = new() { Id = 42 } }).InnerId.ShouldBe(42); } public class ForPathGenerics : AutoMapperSpecBase { class Source<T> { public InnerSource Inner; } class InnerSource { public int Id; } class Destination<T> { public int InnerId; } protected override MapperConfiguration CreateConfiguration() => new(c => c.CreateMap(typeof(Source<>), typeof(Destination<>)).ReverseMap()); [Fact] public void Should_work() => Map<Destination<int>>(new Source<int> { Inner = new() { Id = 42 } }).InnerId.ShouldBe(42); } public class ReadonlyPropertiesGenerics : AutoMapperSpecBase { class Source { public InnerSource Inner; } class InnerSource { public int Value; } class Destination<T> { public readonly InnerDestination Inner = new(); } class InnerDestination { public int Value; } protected override MapperConfiguration CreateConfiguration() => new(c => { c.CreateMap(typeof(Source), typeof(Destination<>)).ForMember("Inner", o => o.MapFrom("Inner")); c.CreateMap<InnerSource, InnerDestination>(); }); [Fact] public void Should_work() => Map<Destination<int>>(new Source { Inner = new() { Value = 42 } }).Inner.Value.ShouldBe(42); } public class ConstructorValidationGenerics : NonValidatingSpecBase { record Source<T>(T Value); record Destination<T>(T OtherValue); protected override MapperConfiguration CreateConfiguration() => new(c => c.CreateMap(typeof(Source<>), typeof(Destination<>))); [Fact] public void Should_work() { var error = new Action(AssertConfigurationIsValid).ShouldThrow<AutoMapperConfigurationException>().Errors.Single(); error.CanConstruct.ShouldBeFalse(); error.UnmappedPropertyNames.Single().ShouldBe("OtherValue"); } } public class SealGenerics : AutoMapperSpecBase { public record SourceProperty<T>(T Value, SourceProperty<T> Recursive = null); public record DestProperty<T>(T Value, DestProperty<T> Recursive = null); public record User(SourceProperty<Guid> UserStoreId); public class UserPropertiesContainer { public UserProperties User { get; set; } } public class UserProperties { public DestProperty<Guid> UserStoreId { get; set; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.CreateMap(typeof(SourceProperty<>), typeof(DestProperty<>)); cfg.CreateMap<User, UserPropertiesContainer>().ForMember(dest => dest.User, opt => opt.MapFrom(src => src)); cfg.CreateMap<User, UserProperties>(); }); [Fact] public void Should_work() { var guid = Guid.NewGuid(); Map<UserProperties>(new User(new(guid))).UserStoreId.Value.ShouldBe(guid); } } public class OpenGenerics_With_Struct : AutoMapperSpecBase { public struct Id<T> { } protected override MapperConfiguration CreateConfiguration() => new(mapper => mapper.CreateMap(typeof(Id<>), typeof(long)).ConvertUsing((_,__)=>(long)42)); [Fact] public void Should_work() => Map<long>(new Id<string>()).ShouldBe(42); } public class OpenGenerics_With_Base_Generic : AutoMapperSpecBase { public class Foo<T> { public T Value1 { get; set; } } public class BarBase<T> { public T Value2 { get; set; } } public class Bar<T> : BarBase<T> { } protected override MapperConfiguration CreateConfiguration() => new(mapper => mapper.CreateMap(typeof(Foo<>), typeof(Bar<>)).ForMember("Value2", to => to.MapFrom("Value1"))); [Fact] public void Can_map_base_members() => Map<Bar<int>>(new Foo<int> { Value1 = 5 }).Value2.ShouldBe(5); } public class GenericMapsAsNonGeneric : AutoMapperSpecBase { class Source { public int Value; } class Destination<T> { public T Value; } class NonGenericDestination : Destination<string> { } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.CreateMap(typeof(Source), typeof(Destination<>)).As(typeof(NonGenericDestination)); cfg.CreateMap(typeof(Source), typeof(NonGenericDestination)); }); [Fact] public void Should_work() => Mapper.Map<Destination<string>>(new Source { Value = 42 }).Value.ShouldBe("42"); } public class GenericMapsPriority : AutoMapperSpecBase { class Source<T> { public T Value; } class Destination<T> { public T Value; } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.CreateMap(typeof(Source<>), typeof(Destination<string>)); cfg.CreateMap(typeof(Source<>), typeof(Destination<>)).ForAllMembers(o=>o.Ignore()); cfg.CreateMap(typeof(Source<string>), typeof(Destination<>)).ForAllMembers(o => o.Ignore()); cfg.CreateMap(typeof(Source<int>), typeof(Destination<>)); }); [Fact] public void Should_work() { Mapper.Map<Destination<int>>(new Source<int> { Value = 42 }).Value.ShouldBe(42); Mapper.Map<Destination<string>>(new Source<string> { Value = "42" }).Value.ShouldBe("42"); } } public class GenericMapWithUntypedMap : AutoMapperSpecBase { class Source<T> { public T Value; } class Destination<T> { public T Value; } protected override MapperConfiguration CreateConfiguration() => new(cfg=>cfg.CreateMap(typeof(Source<>), typeof(Destination<>))); [Fact] public void Should_work() => new Action(() => Mapper.Map(new Source<int>(), null, typeof(Destination<>))) .ShouldThrow<ArgumentException>().Message.ShouldStartWith($"Type {typeof(Destination<>).FullName}[T] is a generic type definition"); } public class GenericValueResolverTypeMismatch : AutoMapperSpecBase { class Source<T> { public T Value; } class Destination { public string Value; } protected override MapperConfiguration CreateConfiguration() => new(cfg=> cfg.CreateMap(typeof(Source<>), typeof(Destination)).ForMember("Value", o => o.MapFrom(typeof(ValueResolver<>)))); class ValueResolver<T> : IValueResolver<Source<T>, Destination, object> { public object Resolve(Source<T> source, Destination destination, object destMember, ResolutionContext context) => int.MaxValue; } [Fact] public void Should_map_ok() => Map<Destination>(new Source<object>()).Value.ShouldBe(int.MaxValue.ToString()); } public class GenericValueResolver : AutoMapperSpecBase { class Destination { public string MyKey; public string MyValue; } class Destination<TKey, TValue> { public TKey MyKey; public TValue MyValue; } class Source { public IEnumerable<int> MyValues; } class Source<T> { public IEnumerable<T> MyValues; } class Destination<T> { public IEnumerable<T> MyValues; } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.CreateMap(typeof(KeyValuePair<,>), typeof(Destination)) .ForMember("MyKey", o => o.MapFrom(typeof(KeyResolver<>))) .ForMember("MyValue", o => o.MapFrom(typeof(ValueResolver<,>))); cfg.CreateMap(typeof(KeyValuePair<,>), typeof(Destination<,>)) .ForMember("MyKey", o => o.MapFrom(typeof(KeyResolver<,,>))) .ForMember("MyValue", o => o.MapFrom(typeof(ValueResolver<,,,>))); cfg.CreateMap(typeof(Source), typeof(Destination<>)) .ForMember("MyValues", o => o.MapFrom(typeof(ValuesResolver<>))); cfg.CreateMap(typeof(Source<>), typeof(Destination<>)) .ForMember("MyValues", o => o.MapFrom(typeof(ValuesResolver<,>))); }); private class KeyResolver<TKey> : IValueResolver<KeyValuePair<TKey, int>, Destination, string> { public string Resolve(KeyValuePair<TKey, int> source, Destination destination, string destMember, ResolutionContext context) => source.Key.ToString(); } private class ValueResolver<TKey, TValue> : IValueResolver<KeyValuePair<TKey, TValue>, Destination, string> { public string Resolve(KeyValuePair<TKey, TValue> source, Destination destination, string destMember, ResolutionContext context) => source.Value.ToString(); } private class KeyResolver<TKeySource, TValueSource, TKeyDestination> : IValueResolver<KeyValuePair<TKeySource, TValueSource>, Destination<TKeyDestination, string>, string> { public string Resolve(KeyValuePair<TKeySource, TValueSource> source, Destination<TKeyDestination, string> destination, string destMember, ResolutionContext context) => source.Key.ToString(); } private class ValueResolver<TKeySource, TValueSource, TKeyDestination, TValueDestination> : IValueResolver<KeyValuePair<TKeySource, TValueSource>, Destination<TKeyDestination, TValueDestination>, string> { public string Resolve(KeyValuePair<TKeySource, TValueSource> source, Destination<TKeyDestination, TValueDestination> destination, string destMember, ResolutionContext context) => source.Value.ToString(); } private class ValuesResolver<TDestination> : IValueResolver<Source, Destination<TDestination>, IEnumerable<TDestination>> { public IEnumerable<TDestination> Resolve(Source source, Destination<TDestination> destination, IEnumerable<TDestination> destMember, ResolutionContext context) { foreach (var item in source.MyValues) { yield return (TDestination)((object)item); } } } private class ValuesResolver<TSource, TDestination> : IValueResolver<Source<TSource>, Destination<TDestination>, IEnumerable<TDestination>> { public IEnumerable<TDestination> Resolve(Source<TSource> source, Destination<TDestination> destination, IEnumerable<TDestination> destMember, ResolutionContext context) { foreach (var item in source.MyValues) { yield return (TDestination)((object)item); } } } [Fact] public void Should_map_non_generic_destination() { var destination = Map<Destination>(new KeyValuePair<int, int>(1,2)); destination.MyKey.ShouldBe("1"); destination.MyValue.ShouldBe("2"); } [Fact] public void Should_map_generic_destination() { var destination = Map<Destination<string, string>>(new KeyValuePair<int, int>(1, 2)); destination.MyKey.ShouldBe("1"); destination.MyValue.ShouldBe("2"); var destinationString = Map<Destination<string, string>>(new KeyValuePair<string, string>("1", "2")); destinationString.MyKey.ShouldBe("1"); destinationString.MyValue.ShouldBe("2"); } [Fact] public void Should_map_closed_to_ienumerable_generic_destination() { var source = new Source { MyValues = new int[] { 1, 2 } }; var destination = Map<Destination<int>>(source); destination.MyValues.ShouldBe(source.MyValues); } [Fact] public void Should_map_ienumerable_generic_destination() { var source = new Source<int> { MyValues = new int[] { 1, 2 } }; var destination = Map<Destination<int>>(source); destination.MyValues.ShouldBe(source.MyValues); } } public class GenericMemberValueResolver : AutoMapperSpecBase { class Destination { public string MyKey; public string MyValue; } class Destination<TKey, TValue> { public TKey MyKey; public TValue MyValue; } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.CreateMap(typeof(KeyValuePair<,>), typeof(Destination)) .ForMember("MyKey", o => o.MapFrom(typeof(Resolver<>), "Key")) .ForMember("MyValue", o => o.MapFrom(typeof(Resolver<,>), "Value")); cfg.CreateMap(typeof(KeyValuePair<,>), typeof(Destination<,>)) .ForMember("MyKey", o => o.MapFrom(typeof(Resolver<,,>), "Key")) .ForMember("MyValue", o => o.MapFrom(typeof(Resolver<,,,>), "Value")); }); private class Resolver<TKey> : IMemberValueResolver<KeyValuePair<TKey, int>, Destination, int, string> { public string Resolve(KeyValuePair<TKey, int> source, Destination destination, int sourceMember, string destMember, ResolutionContext context) => sourceMember.ToString(); } private class Resolver<TKey, TValue> : IMemberValueResolver<KeyValuePair<TKey, TValue>, Destination, int, string> { public string Resolve(KeyValuePair<TKey, TValue> source, Destination destination, int sourceMember, string destMember, ResolutionContext context) => sourceMember.ToString(); } private class Resolver<TKey, TValue, TDestinatonKey> : IMemberValueResolver<KeyValuePair<TKey, TValue>, Destination<TDestinatonKey, string>, int, string> { public string Resolve(KeyValuePair<TKey, TValue> source, Destination<TDestinatonKey, string> destination, int sourceMember, string destMember, ResolutionContext context) => sourceMember.ToString(); } private class Resolver<TKey, TValue, TDestinatonKey, TDestinatonValue> : IMemberValueResolver<KeyValuePair<TKey, TValue>, Destination<TDestinatonKey, TDestinatonValue>, int, string> { public string Resolve(KeyValuePair<TKey, TValue> source, Destination<TDestinatonKey, TDestinatonValue> destination, int sourceMember, string destMember, ResolutionContext context) => sourceMember.ToString(); } [Fact] public void Should_map_non_generic_destination() { var destination = Map<Destination>(new KeyValuePair<int, int>(1, 2)); destination.MyKey.ShouldBe("1"); destination.MyValue.ShouldBe("2"); } [Fact] public void Should_map_generic_destination() { var destination = Map<Destination<string, string>>(new KeyValuePair<int, int>(1, 2)); destination.MyKey.ShouldBe("1"); destination.MyValue.ShouldBe("2"); } } public class RecursiveOpenGenerics : AutoMapperSpecBase { public class SourceTree<T> { public SourceTree(T value, SourceTree<T>[] children) { Value = value; Children = children; } public T Value { get; } public SourceTree<T>[] Children { get; } } public class DestinationTree<T> { public DestinationTree(T value, DestinationTree<T>[] children) { Value = value; Children = children; } public T Value { get; } public DestinationTree<T>[] Children { get; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => cfg.CreateMap(typeof(SourceTree<>), typeof(DestinationTree<>))); [Fact] public void Should_work() { var source = new SourceTree<string>("value", new SourceTree<string>[0]); Mapper.Map<DestinationTree<string>>(source).Value.ShouldBe("value"); } } public class OpenGenericsValidation : NonValidatingSpecBase { public class Source<T> { public T Value { get; set; } } public class Dest<T> { public int A { get; set; } public T Value { get; set; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => cfg.CreateMap(typeof(Source<>), typeof(Dest<>))); [Fact] public void Should_report_unmapped_property() { new Action(Configuration.AssertConfigurationIsValid) .ShouldThrow<AutoMapperConfigurationException>() .Errors.Single().UnmappedPropertyNames.Single().ShouldBe("A"); } } public class OpenGenericsProfileValidationNonGenericMembers : NonValidatingSpecBase { public class Source<T> { public T[] Value { get; set; } } public class Dest<T> { public int A { get; set; } public T[] Value { get; set; } } class MyProfile : Profile { public MyProfile() { CreateMap(typeof(Source<>), typeof(Dest<>)); } } protected override MapperConfiguration CreateConfiguration() => new(cfg => cfg.AddProfile<MyProfile>()); [Fact] public void Should_report_unmapped_property() => new Action(()=> AssertConfigurationIsValid<MyProfile>()) .ShouldThrow<AutoMapperConfigurationException>() .Errors.Single().UnmappedPropertyNames.Single().ShouldBe("A"); } public class OpenGenericsProfileValidation : AutoMapperSpecBase { public class Source<T> { public T[] Value { get; set; } } public class Dest<T> { public T[] Value { get; set; } } class MyProfile : Profile { public MyProfile() { CreateMap(typeof(Source<>), typeof(Dest<>)); } } protected override MapperConfiguration CreateConfiguration() => new(cfg => cfg.AddProfile<MyProfile>()); [Fact] public void Validate() => AssertConfigurationIsValid(); } public class OpenGenerics { public class Source<T> { public int A { get; set; } public T Value { get; set; } } public class Dest<T> { public int A { get; set; } public T Value { get; set; } } [Fact] public void Can_map_simple_generic_types() { var config = new MapperConfiguration(cfg => cfg.CreateMap(typeof(Source<>), typeof(Dest<>))); var source = new Source<int> { Value = 5 }; var dest = config.CreateMapper().Map<Source<int>, Dest<int>>(source); dest.Value.ShouldBe(5); } [Fact] public void Can_map_non_generic_members() { var config = new MapperConfiguration(cfg => cfg.CreateMap(typeof(Source<>), typeof(Dest<>))); var source = new Source<int> { A = 5 }; var dest = config.CreateMapper().Map<Source<int>, Dest<int>>(source); dest.A.ShouldBe(5); } [Fact] public void Can_map_recursive_generic_types() { var config = new MapperConfiguration(cfg => cfg.CreateMap(typeof(Source<>), typeof(Dest<>))); var source = new Source<Source<int>> { Value = new Source<int> { Value = 5, } }; var dest = config.CreateMapper().Map<Source<Source<int>>, Dest<Dest<double>>>(source); dest.Value.Value.ShouldBe(5); } } public class OpenGenerics_With_MemberConfiguration : AutoMapperSpecBase { public class Foo<T> { public int A { get; set; } public int B { get; set; } } public class Bar<T> { public int C { get; set; } public int D { get; set; } } protected override MapperConfiguration CreateConfiguration() => new(mapper => { mapper.CreateMap(typeof(Foo<>), typeof(Bar<>)) .ForMember("C", to => to.MapFrom("A")) .ForMember("D", to => to.MapFrom("B")); }); [Fact] public void Can_remap_explicit_members() { var source = new Foo<int> { A = 5, B = 10 }; var dest = Mapper.Map<Foo<int>, Bar<int>>(source); dest.C.ShouldBe(5); dest.D.ShouldBe(10); } } public class OpenGenerics_With_UntypedMapFrom : AutoMapperSpecBase { public class Foo<T> { public T Value1 { get; set; } } public class Bar<T> { public T Value2 { get; set; } } protected override MapperConfiguration CreateConfiguration() => new(mapper => { mapper.CreateMap(typeof(Foo<>), typeof(Bar<>)).ForMember("Value2", to => to.MapFrom("Value1")); }); [Fact] public void Can_remap_explicit_members() { var dest = Mapper.Map<Bar<int>>(new Foo<int> { Value1 = 5 }); dest.Value2.ShouldBe(5); } } public class OpenGenerics_With_UntypedMapFromStructs : AutoMapperSpecBase { public class Foo<T> where T : struct { public T Value1 { get; set; } } public class Bar<T> where T : struct { public T Value2 { get; set; } } protected override MapperConfiguration CreateConfiguration() => new(mapper => { mapper.CreateMap(typeof(Foo<>), typeof(Bar<>)).ForMember("Value2", to => to.MapFrom("Value1")); }); [Fact] public void Can_remap_explicit_members() { var dest = Mapper.Map<Bar<int>>(new Foo<int> { Value1 = 5 }); dest.Value2.ShouldBe(5); } }
namespace AutoMapper.UnitTests.Projection; public class GenericsTests : AutoMapperSpecBase { private Dest<string>[] _dests; public class Source<T> { public T Value { get; set; } } public class Dest<T> { public T Value { get; set; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.CreateMap(typeof (Source<>), typeof (Dest<>)); }); protected override void Because_of() { var sources = new[] { new Source<string> { Value = "5" } }.AsQueryable(); _dests = sources.ProjectTo<Dest<string>>(Configuration).ToArray(); } [Fact] public void Should_convert_even_though_mapper_not_explicitly_called_before_hand() { _dests[0].Value.ShouldBe("5"); } }
AutoMapper
You are an expert C++ developer. Task: Write a unit test for 'OpenGenerics_With_UntypedMapFromStructs' using GoogleTest (gtest) and GoogleMock (gmock). Context: - Class: OpenGenerics_With_UntypedMapFromStructs Requirements: Use EXPECT_CALL for virtual methods.
industrial
namespace AutoMapper.Internal.Mappers; public sealed class ToStringMapper : IObjectMapper { public bool IsMatch(TypePair context) => context.DestinationType == typeof(string); public Expression MapExpression(IGlobalConfiguration configuration, ProfileMap profileMap, MemberMap memberMap, Expression sourceExpression, Expression destExpression) { var sourceType = sourceExpression.Type; var toStringCall = Call(sourceExpression, ObjectToString); return sourceType.IsEnum ? StringToEnumMapper.CheckEnumMember(sourceExpression, sourceType, toStringCall) : toStringCall; } #if FULL_OR_STANDARD public TypePair? GetAssociatedTypes(TypePair initialTypes) => null; #endif }
namespace AutoMapper.UnitTests.Projection; public class ToStringTests : AutoMapperSpecBase { private Dest[] _dests; public class Source { public int Value { get; set; } } public class Dest { public string Value { get; set; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.CreateProjection<Source, Dest>(); }); protected override void Because_of() { var sources = new[] { new Source { Value = 5 } }.AsQueryable(); _dests = sources.ProjectTo<Dest>(Configuration).ToArray(); } [Fact] public void Should_convert_to_string() { _dests[0].Value.ShouldBe("5"); } } public class NullableToStringTests : AutoMapperSpecBase { private Dest[] _dests; public class Source { public int? Value { get; set; } } public class Dest { public string Value { get; set; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.CreateProjection<Source, Dest>(); }); protected override void Because_of() { var sources = new[] { new Source { Value = 5 } }.AsQueryable(); _dests = sources.ProjectTo<Dest>(Configuration).ToArray(); } [Fact] public void Should_convert_to_string() { _dests[0].Value.ShouldBe("5"); } }
AutoMapper
You are an expert C++ developer. Task: Write a unit test for 'ToStringMapper' using GoogleTest (gtest) and GoogleMock (gmock). Context: - Class: ToStringMapper Requirements: Use EXPECT_CALL for virtual methods.
industrial
namespace AutoMapper.UnitTests.Constructors; public class RecordConstructorValidation : AutoMapperSpecBase { record Destination(int Value) { } protected override MapperConfiguration CreateConfiguration() => new(c => c.CreateMap<string, Destination>()); [Fact] public void Validate() => new Action(AssertConfigurationIsValid).ShouldThrow<AutoMapperConfigurationException>().Message. ShouldContainWithoutWhitespace("When mapping to records, consider using only public constructors."); } public class RecordConstructorValidationForCtorParam : AutoMapperSpecBase { record Destination(int Value, int Other){} protected override MapperConfiguration CreateConfiguration() => new(c => c.CreateMap<string, Destination>().ForCtorParam(nameof(Destination.Value), o => o.MapFrom(s => 0))); [Fact] public void Validate() => new Action(AssertConfigurationIsValid).ShouldThrow<AutoMapperConfigurationException>().Message. ShouldContainWithoutWhitespace("When mapping to records, consider using only public constructors."); } public class ConstructorValidation : AutoMapperSpecBase { class Source { } class Destination { public Destination(int otherValue, int value = 2) { } public int Value { get; set; } public int OtherValue { get; set; } } protected override MapperConfiguration CreateConfiguration() => new(c => c.CreateMap<Source, Destination>().ForCtorParam("otherValue", o=>o.MapFrom(s=>0))); [Fact] public void Validate() => AssertConfigurationIsValid(); } public class Nullable_enum_default_value : AutoMapperSpecBase { public enum SourceEnum { A, B } public class Source { public SourceEnum? Enum { get; set; } } public enum TargetEnum { A, B } public class Target { public TargetEnum? Enum { get; set; } public Target(TargetEnum? Enum = TargetEnum.A) { this.Enum = Enum; } } protected override MapperConfiguration CreateConfiguration() => new(cfg=>cfg.CreateMap<Source, Target>()); [Fact] public void Should_work() => Mapper.Map<Target>(new Source { Enum = SourceEnum.B }).Enum.ShouldBe(TargetEnum.B); } public class Nullable_enum_default_value_null : AutoMapperSpecBase { public class Source { } public enum TargetEnum { A, B } public class Target { public TargetEnum? Enum { get; } public Target(TargetEnum? Enum = null) { this.Enum = Enum; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => cfg.CreateMap<Source, Target>()); [Fact] public void Should_work() => Mapper.Map<Target>(new Source()).Enum.ShouldBeNull(); } public class Nullable_enum_default_value_not_null : AutoMapperSpecBase { public class Source { } public enum TargetEnum { A, B } public class Target { public TargetEnum? Enum { get; } public Target(TargetEnum? Enum = TargetEnum.B) { this.Enum = Enum; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => cfg.CreateMap<Source, Target>()); [Fact] public void Should_work() => Mapper.Map<Target>(new Source()).Enum.ShouldBe(TargetEnum.B); } public class Dynamic_constructor_mapping : AutoMapperSpecBase { public class ParentDTO<T> { public ChildDTO<T> First => Children[0]; public List<ChildDTO<T>> Children { get; set; } = new List<ChildDTO<T>>(); public int IdParent { get; set; } } public class ChildDTO<T> { public int IdChild { get; set; } public ParentDTO<T> Parent { get; set; } } public class ParentModel<T> { public ChildModel<T> First { get; set; } public List<ChildModel<T>> Children { get; set; } = new List<ChildModel<T>>(); public int IdParent { get; set; } } public class ChildModel<T> { int _idChild; public ChildModel(ParentModel<T> parent) { Parent = parent; } public int IdChild { get => _idChild; set { if (_idChild != 0) { throw new Exception("Set IdChild again."); } _idChild = value; } } public ParentModel<T> Parent { get; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.CreateMap(typeof(ParentModel<>), typeof(ParentDTO<>)).ReverseMap(); cfg.CreateMap(typeof(ChildModel<>), typeof(ChildDTO<>)).ReverseMap(); }); [Fact] public void Should_work() { var parentDto = new ParentDTO<int> { IdParent = 1 }; for (var i = 0; i < 5; i++) { parentDto.Children.Add(new ChildDTO<int> { IdChild = i, Parent = parentDto }); } var parentModel = Mapper.Map<ParentModel<int>>(parentDto); var mappedChildren = Mapper.Map<List<ChildDTO<int>>, List<ChildModel<int>>>(parentDto.Children); } } public class Constructor_mapping_without_preserve_references : AutoMapperSpecBase { public class ParentDTO { public ChildDTO First => Children[0]; public List<ChildDTO> Children { get; set; } = new List<ChildDTO>(); public int IdParent { get; set; } } public class ChildDTO { public int IdChild { get; set; } public ParentDTO Parent { get; set; } } public class ParentModel { public ChildModel First { get; set; } public List<ChildModel> Children { get; set; } = new List<ChildModel>(); public int IdParent { get; set; } } public class ChildModel { int _idChild; public ChildModel(ParentModel parent) { Parent = parent; } public int IdChild { get => _idChild; set { if(_idChild != 0) { throw new Exception("Set IdChild again."); } _idChild = value; } } public ParentModel Parent { get; set; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.CreateMap<ChildDTO, ChildModel>().ForMember(c => c.Parent, o => o.Ignore()); cfg.CreateMap<ParentDTO, ParentModel>(); }); [Fact] public void Should_work() { var parentDto = new ParentDTO { IdParent = 1 }; for(var i = 0; i < 5; i++) { parentDto.Children.Add(new ChildDTO { IdChild = i, Parent = parentDto }); } var mappedChildren = Mapper.Map<List<ChildDTO>, List<ChildModel>>(parentDto.Children); } } public class Preserve_references_with_constructor_mapping : AutoMapperSpecBase { public class ParentDTO { public ChildDTO First => Children[0]; public List<ChildDTO> Children { get; set; } = new List<ChildDTO>(); public int IdParent { get; set; } } public class ChildDTO { public int IdChild { get; set; } public ParentDTO Parent { get; set; } } public class ParentModel { public ChildModel First { get; set; } public List<ChildModel> Children { get; set; } = new List<ChildModel>(); public int IdParent { get; set; } } public class ChildModel { int _idChild; public ChildModel(ParentModel parent) { Parent = parent; } public int IdChild { get => _idChild; set { if(_idChild != 0) { throw new Exception("Set IdChild again."); } _idChild = value; } } public ParentModel Parent { get; set; } } protected override MapperConfiguration CreateConfiguration() => new(cfg=> { cfg.CreateMap<ParentDTO, ParentModel>().PreserveReferences(); cfg.CreateMap<ChildDTO, ChildModel>().ForMember(c => c.Parent, o => o.Ignore()).PreserveReferences(); }); [Fact] public void Should_work() { var parentDto = new ParentDTO { IdParent = 1 }; for(var i = 0; i < 5; i++) { parentDto.Children.Add(new ChildDTO { IdChild = i, Parent = parentDto }); } var mappedChildren = Mapper.Map<List<ChildDTO>, List<ChildModel>>(parentDto.Children); var parentModel = mappedChildren.Select(c => c.Parent).Distinct().Single(); parentModel.First.ShouldBe(mappedChildren[0]); } } public class When_construct_mapping_a_struct_with_string : AutoMapperSpecBase { public struct Source { public string Property { get; set; } } public struct Destination { public Destination(string property) { Property = property; } public string Property { get; set; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.CreateMap<Source, Destination>(); }); [Fact] public void Should_map_ok() { var source = new Source { Property = "value" }; var destination = Mapper.Map<Destination>(source); destination.Property.ShouldBe("value"); } } public class When_construct_mapping_a_struct : AutoMapperSpecBase { public class Dto { public double Value { get; set; } } public class Entity { public double Value { get; set; } } public struct Source { public Dto Property { get; set; } } public struct Destination { public Destination(Entity property) { Property = property; } public Entity Property { get; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.CreateMap<Dto, Entity>().ReverseMap(); cfg.CreateMap<Source, Destination>().ReverseMap(); }); [Fact] public void Should_map_ok() { var source = new Source { Property = new Dto { Value = 5.0 } }; var destination = Mapper.Map<Destination>(source); destination.Property.Value.ShouldBe(5.0); Mapper.Map<Source>(destination).Property.Value.ShouldBe(5.0); } } public class When_mapping_to_an_abstract_type : AutoMapperSpecBase { class Source { public int Value { get; set; } } abstract class Destination { public int Value { get; set; } } protected override MapperConfiguration CreateConfiguration() => new(c=>c.CreateMap<Source, Destination>()); [Fact] public void Should_throw() { new Action(() => Mapper.Map<Destination>(new Source())).ShouldThrow<ArgumentException>($"Cannot create an instance of abstract type {typeof(Destination)}."); } } public class When_a_constructor_with_extra_parameters_doesnt_match : AutoMapperSpecBase { PersonTarget _destination; class PersonSource { public int Age { get; set; } public string Name { get; set; } } class PersonTarget { public int Age { get; set; } public string Name { get; set; } public PersonTarget(int age, string name) { this.Age = age; this.Name = name; } public PersonTarget(int age, string firstName, string lastName) { this.Age = age; this.Name = firstName + " " + lastName; } } protected override MapperConfiguration CreateConfiguration() => new(c=>c.CreateMap<PersonSource, PersonTarget>()); protected override void Because_of() { _destination = Mapper.Map<PersonTarget>(new PersonSource { Age = 23, Name = "Marc" }); } [Fact] public void We_should_choose_a_matching_constructor() { _destination.Age.ShouldBe(23); _destination.Name.ShouldBe("Marc"); } } public class When_renaming_class_constructor_parameter : AutoMapperSpecBase { Destination _destination; public class Source { public InnerSource InnerSource { get; set; } } public class InnerSource { public string Name { get; set; } } public class Destination { public Destination(InnerDestination inner) { InnerDestination = inner; } public InnerDestination InnerDestination { get; } } public class InnerDestination { public string Name { get; set; } } protected override MapperConfiguration CreateConfiguration() => new(c => { c.CreateMap<Source, Destination>().ForCtorParam("inner", o=>o.MapFrom(s=>s.InnerSource)); c.CreateMap<InnerSource, InnerDestination>(); }); protected override void Because_of() { _destination = Mapper.Map<Destination>(new Source { InnerSource = new InnerSource { Name = "Core" } }); } [Fact] public void Should_map_ok() { _destination.InnerDestination.Name.ShouldBe("Core"); } } public class When_constructor_matches_with_prefix_and_postfix : AutoMapperSpecBase { PersonDto _destination; public class Person { public string PrefixNamePostfix { get; set; } } public class PersonDto { string name; public PersonDto(string name) { this.name = name; } public string Name => name; } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.RecognizePostfixes("postfix"); cfg.RecognizePrefixes("prefix"); cfg.CreateMap<Person, PersonDto>(); }); protected override void Because_of() { _destination = Mapper.Map<PersonDto>(new Person { PrefixNamePostfix = "John" }); } [Fact] public void Should_map_from_the_property() { _destination.Name.ShouldBe("John"); } } public class When_constructor_matches_with_destination_prefix_and_postfix : AutoMapperSpecBase { PersonDto _destination; public class Person { public string Name { get; set; } } public class PersonDto { string name; public PersonDto(string prefixNamePostfix) { name = prefixNamePostfix; } public string Name => name; } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.RecognizeDestinationPostfixes("postfix"); cfg.RecognizeDestinationPrefixes("prefix"); cfg.CreateMap<Person, PersonDto>(); }); protected override void Because_of() { _destination = Mapper.Map<PersonDto>(new Person { Name = "John" }); } [Fact] public void Should_map_from_the_property() { _destination.Name.ShouldBe("John"); } } public class When_constructor_matches_but_is_overriden_by_ConstructUsing : AutoMapperSpecBase { PersonDto _destination; public class Person { public string Name { get; set; } } public class PersonDto { public PersonDto() { } public PersonDto(string name) { Name = name; } public string Name { get; set; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => cfg.CreateMap<Person, PersonDto>().ConstructUsing(p=>new PersonDto())); protected override void Because_of() { _destination = Mapper.Map<PersonDto>(new Person { Name = "John" }); } [Fact] public void Should_map_from_the_property() { var typeMap = FindTypeMapFor<Person, PersonDto>(); _destination.Name.ShouldBe("John"); } } public class When_constructor_is_match_with_default_value : AutoMapperSpecBase { PersonDto _destination; public class Person { public string Name { get; set; } } public class PersonDto { public PersonDto(string name = null) { Name = name; } public string Name { get; set; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => cfg.CreateMap<Person, PersonDto>()); protected override void Because_of() { _destination = Mapper.Map<PersonDto>(new Person { Name = "John" }); } [Fact] public void Should_map_from_the_property() { _destination.Name.ShouldBe("John"); } } public class When_constructor_is_partial_match_with_value_type : AutoMapperSpecBase { GeoCoordinate _destination; public class GeolocationDTO { public double Longitude { get; set; } public double Latitude { get; set; } public double? HorizontalAccuracy { get; set; } } public struct GeoCoordinate { public GeoCoordinate(double longitude, double latitude, double x) { Longitude = longitude; Latitude = latitude; HorizontalAccuracy = 0; } public double Longitude { get; set; } public double Latitude { get; set; } public double? HorizontalAccuracy { get; set; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.CreateMap<GeoCoordinate, GeolocationDTO>(); cfg.CreateMap<GeolocationDTO, GeoCoordinate>(); }); protected override void Because_of() { var source = new GeolocationDTO { Latitude = 34d, Longitude = -93d, HorizontalAccuracy = 100 }; _destination = Mapper.Map<GeoCoordinate>(source); } [Fact] public void Should_map_ok() { _destination.Latitude.ShouldBe(34); _destination.Longitude.ShouldBe(-93); _destination.HorizontalAccuracy.ShouldBe(100); } } public class When_constructor_is_partial_match : AutoMapperSpecBase { GeoCoordinate _destination; public class GeolocationDTO { public double Longitude { get; set; } public double Latitude { get; set; } public double? HorizontalAccuracy { get; set; } } public class GeoCoordinate { public GeoCoordinate() { } public GeoCoordinate(double longitude, double latitude, double x) { Longitude = longitude; Latitude = latitude; } public double Longitude { get; set; } public double Latitude { get; set; } public double? HorizontalAccuracy { get; set; } public double Altitude { get; set; } public double VerticalAccuracy { get; set; } public double Speed { get; set; } public double Course { get; set; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.CreateMap<GeoCoordinate, GeolocationDTO>(); cfg.CreateMap<GeolocationDTO, GeoCoordinate>() .ForMember(dest => dest.Altitude, opt => opt.Ignore()) .ForMember(dest => dest.VerticalAccuracy, opt => opt.Ignore()) .ForMember(dest => dest.Speed, opt => opt.Ignore()) .ForMember(dest => dest.Course, opt => opt.Ignore()); }); protected override void Because_of() { var source = new GeolocationDTO { Latitude = 34d, Longitude = -93d, HorizontalAccuracy = 100 }; _destination = Mapper.Map<GeoCoordinate>(source); } [Fact] public void Should_map_ok() { _destination.Latitude.ShouldBe(34); _destination.Longitude.ShouldBe(-93); _destination.HorizontalAccuracy.ShouldBe(100); } } public class When_constructor_matches_but_the_destination_is_passed : AutoMapperSpecBase { Destination _destination = new Destination(); public class Source { public int MyTypeId { get; set; } } public class MyType { } public class Destination { private MyType _myType; public Destination() { } public Destination(MyType myType) { _myType = myType; } public MyType MyType { get { return _myType; } set { _myType = value; } } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.RecognizePostfixes("Id"); cfg.CreateMap<Source, Destination>(); cfg.CreateMap<int, MyType>(); }); protected override void Because_of() { Mapper.Map(new Source(), _destination); } [Fact] public void Should_map_ok() { _destination.MyType.ShouldNotBeNull(); } } public class When_mapping_through_constructor_and_destination_has_setter : AutoMapperSpecBase { public class Source { public int MyTypeId { get; set; } } public class MyType { } Destination _destination; public class Destination { private MyType _myType; private Destination() { } public Destination(MyType myType) { _myType = myType; } public MyType MyType { get { return _myType; } private set { throw new Exception("Should not set through setter."); } } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.RecognizePostfixes("Id"); cfg.CreateMap<Source, Destination>(); cfg.CreateMap<int, MyType>(); }); protected override void Because_of() { _destination = Mapper.Map<Destination>(new Source()); } [Fact] public void Should_map_ok() { _destination.MyType.ShouldNotBeNull(); } } public class When_mapping_an_optional_GUID_constructor : AutoMapperSpecBase { Destination _destination; public class Destination { public Destination(Guid id = default(Guid)) { Id = id; } public Guid Id { get; set; } } public class Source { public Guid Id { get; set; } } protected override MapperConfiguration CreateConfiguration() => new(c=>c.CreateMap<Source, Destination>()); protected override void Because_of() { _destination = Mapper.Map<Destination>(new Source()); } [Fact] public void Should_map_ok() { _destination.Id.ShouldBe(Guid.Empty); } } public class When_mapping_a_constructor_parameter_from_nested_members : AutoMapperSpecBase { private Destination _destination; public class Source { public NestedSource Nested { get; set; } } public class NestedSource { public int Foo { get; set; } } public class Destination { public int Foo { get; } public Destination(int foo) { Foo = foo; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.CreateMap<Source, Destination>().ForCtorParam("foo", opt => opt.MapFrom(s => s.Nested.Foo)); }); protected override void Because_of() { _destination = Mapper.Map<Destination>(new Source { Nested = new NestedSource { Foo = 5 } }); } [Fact] public void Should_map_the_constructor_argument() { _destination.Foo.ShouldBe(5); } } public class When_the_destination_has_a_matching_constructor_with_optional_extra_parameters : AutoMapperSpecBase { private Destination _destination; public class Source { public int Foo { get; set; } } public class Destination { private readonly int _foo; public int Foo { get { return _foo; } } public string Bar { get;} public Destination(int foo, string bar = "bar") { _foo = foo; Bar = bar; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.CreateMap<Source, Destination>(); }); protected override void Because_of() { _destination = Mapper.Map<Source, Destination>(new Source { Foo = 5 }); } [Fact] public void Should_map_the_constructor_argument() { _destination.Foo.ShouldBe(5); _destination.Bar.ShouldBe("bar"); } } public class When_mapping_constructor_argument_fails : NonValidatingSpecBase { public class Source { public int Foo { get; set; } public int Bar { get; set; } } public class Dest { private readonly int _foo; public int Foo { get { return _foo; } } public int Bar { get; set; } public Dest(Dest foo) { } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.CreateMap<Source, Dest>(); }); [Fact] public void Should_say_what_parameter_fails() { var ex = new Action(AssertConfigurationIsValid).ShouldThrow<AutoMapperConfigurationException>(); ex.Message.ShouldContain("Void .ctor(Dest), parameter foo", Case.Sensitive); } } public class When_mapping_to_an_object_with_a_constructor_with_a_matching_argument : AutoMapperSpecBase { private Dest _dest; public class Source { public int Foo { get; set; } public int Bar { get; set; } } public class Dest { private readonly int _foo; public int Foo { get { return _foo; } } public int Bar { get; set; } public Dest(int foo) { _foo = foo; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.CreateMap<Source, Dest>(); }); protected override void Because_of() { Expression<Func<object, object>> ctor = (input) => new Dest((int)input); object o = ctor.Compile()(5); _dest = Mapper.Map<Source, Dest>(new Source { Foo = 5, Bar = 10 }); } [Fact] public void Should_map_the_constructor_argument() { _dest.Foo.ShouldBe(5); } [Fact] public void Should_map_the_existing_properties() { _dest.Bar.ShouldBe(10); } } public class When_mapping_to_an_object_with_a_private_constructor : AutoMapperSpecBase { private Dest _dest; public class Source { public int Foo { get; set; } } public class Dest { private readonly int _foo; public int Foo { get { return _foo; } } private Dest(int foo) { _foo = foo; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.CreateMap<Source, Dest>(); }); protected override void Because_of() { _dest = Mapper.Map<Source, Dest>(new Source { Foo = 5 }); } [Fact] public void Should_map_the_constructor_argument() { _dest.Foo.ShouldBe(5); } } public class When_mapping_to_an_object_using_service_location : AutoMapperSpecBase { private Dest _dest; public class Source { public int Foo { get; set; } } public class Dest { private int _foo; private readonly int _addend; public int Foo { get { return _foo + _addend; } set { _foo = value; } } public Dest(int addend) { _addend = addend; } public Dest() : this(0) { } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.ConstructServicesUsing(t => new Dest(5)); cfg.CreateMap<Source, Dest>() .ConstructUsingServiceLocator(); }); protected override void Because_of() { _dest = Mapper.Map<Source, Dest>(new Source { Foo = 5 }); } [Fact] public void Should_map_with_the_custom_constructor() { _dest.Foo.ShouldBe(10); } } public class When_mapping_to_an_object_using_contextual_service_location : AutoMapperSpecBase { private Dest _dest; public class Source { public int Foo { get; set; } } public class Dest { private int _foo; private readonly int _addend; public int Foo { get { return _foo + _addend; } set { _foo = value; } } public Dest(int addend) { _addend = addend; } public Dest() : this(0) { } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.ConstructServicesUsing(t => new Dest(5)); cfg.CreateMap<Source, Dest>() .ConstructUsingServiceLocator(); }); protected override void Because_of() { _dest = Mapper.Map<Source, Dest>(new Source { Foo = 5 }, opt => opt.ConstructServicesUsing(t => new Dest(6))); } [Fact] public void Should_map_with_the_custom_constructor() { _dest.Foo.ShouldBe(11); } } public class When_mapping_to_an_object_with_multiple_constructors_and_constructor_mapping_is_disabled : AutoMapperSpecBase { private Dest _dest; public class Source { public int Foo { get; set; } public int Bar { get; set; } } public class Dest { public int Foo { get; set; } public int Bar { get; set; } public Dest(int foo) { throw new NotImplementedException(); } public Dest() { } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.DisableConstructorMapping(); cfg.CreateMap<Source, Dest>(); }); protected override void Because_of() { _dest = Mapper.Map<Source, Dest>(new Source { Foo = 5, Bar = 10 }); } [Fact] public void Should_map_the_existing_properties() { _dest.Foo.ShouldBe(5); _dest.Bar.ShouldBe(10); } } public class When_mapping_with_optional_parameters_and_constructor_mapping_is_disabled : AutoMapperSpecBase { public class Destination { public Destination(Destination destination = null) { Dest = destination; } public Destination Dest { get; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.DisableConstructorMapping(); cfg.CreateMap<object, Destination>(); }); [Fact] public void Should_map_ok() => Mapper.Map<Destination>(new object()).Dest.ShouldBeNull(); } public class UsingMappingEngineToResolveConstructorArguments { [Fact] public void Should_resolve_constructor_arguments_using_mapping_engine() { var config = new MapperConfiguration(cfg => { cfg.CreateMap<SourceBar, DestinationBar>(); cfg.CreateMap<SourceFoo, DestinationFoo>(); }); var sourceBar = new SourceBar("fooBar"); var sourceFoo = new SourceFoo(sourceBar); var destinationFoo = config.CreateMapper().Map<DestinationFoo>(sourceFoo); destinationFoo.Bar.FooBar.ShouldBe(sourceBar.FooBar); } public class DestinationFoo { private readonly DestinationBar _bar; public DestinationBar Bar { get { return _bar; } } public DestinationFoo(DestinationBar bar) { _bar = bar; } } public class DestinationBar { private readonly string _fooBar; public string FooBar { get { return _fooBar; } } public DestinationBar(string fooBar) { _fooBar = fooBar; } } public class SourceFoo { public SourceBar Bar { get; private set; } public SourceFoo(SourceBar bar) { Bar = bar; } } public class SourceBar { public string FooBar { get; private set; } public SourceBar(string fooBar) { FooBar = fooBar; } } } public class MappingMultipleConstructorArguments { [Fact] public void Should_resolve_constructor_arguments_using_mapping_engine() { var config = new MapperConfiguration(cfg => { cfg.CreateMap<SourceBar, DestinationBar>(); cfg.CreateMap<SourceFoo, DestinationFoo>(); }); var sourceBar = new SourceBar("fooBar"); var sourceFoo = new SourceFoo(sourceBar, new SourceBar("fooBar2")); var destinationFoo = config.CreateMapper().Map<DestinationFoo>(sourceFoo); destinationFoo.Bar.FooBar.ShouldBe(sourceBar.FooBar); destinationFoo.Bar2.FooBar.ShouldBe("fooBar2"); } public class DestinationFoo { private readonly DestinationBar _bar; public DestinationBar Bar { get { return _bar; } } public DestinationBar Bar2 { get; private set; } public DestinationFoo(DestinationBar bar, DestinationBar bar2) { _bar = bar; Bar2 = bar2; } } public class DestinationBar { private readonly string _fooBar; public string FooBar { get { return _fooBar; } } public DestinationBar(string fooBar) { _fooBar = fooBar; } } public class SourceFoo { public SourceBar Bar { get; private set; } public SourceBar Bar2 { get; private set; } public SourceFoo(SourceBar bar, SourceBar bar2) { Bar = bar; Bar2 = bar2; } } public class SourceBar { public string FooBar { get; private set; } public SourceBar(string fooBar) { FooBar = fooBar; } } } public class When_mapping_to_an_object_with_a_constructor_with_multiple_optional_arguments { [Fact] public void Should_resolve_constructor_when_args_are_optional() { var config = new MapperConfiguration(cfg => { cfg.CreateMap<SourceBar, DestinationBar>(); cfg.CreateMap<SourceFoo, DestinationFoo>(); }); var sourceBar = new SourceBar("fooBar"); var sourceFoo = new SourceFoo(sourceBar); var destinationFoo = config.CreateMapper().Map<DestinationFoo>(sourceFoo); destinationFoo.Bar.FooBar.ShouldBe("fooBar"); destinationFoo.Str.ShouldBe("hello"); } public class DestinationFoo { private readonly DestinationBar _bar; private string _str; public DestinationBar Bar { get { return _bar; } } public string Str { get { return _str; } } public DestinationFoo(DestinationBar bar=null,string str="hello") { _bar = bar; _str = str; } } public class DestinationBar { private readonly string _fooBar; public string FooBar { get { return _fooBar; } } public DestinationBar(string fooBar) { _fooBar = fooBar; } } public class SourceFoo { public SourceBar Bar { get; private set; } public SourceFoo(SourceBar bar) { Bar = bar; } } public class SourceBar { public string FooBar { get; private set; } public SourceBar(string fooBar) { FooBar = fooBar; } } } public class When_mapping_to_an_object_with_a_constructor_with_single_optional_arguments { [Fact] public void Should_resolve_constructor_when_arg_is_optional() { var config = new MapperConfiguration(cfg => { cfg.CreateMap<SourceBar, DestinationBar>(); cfg.CreateMap<SourceFoo, DestinationFoo>(); }); var sourceBar = new SourceBar("fooBar"); var sourceFoo = new SourceFoo(sourceBar); var destinationFoo = config.CreateMapper().Map<DestinationFoo>(sourceFoo); destinationFoo.Bar.FooBar.ShouldBe("fooBar"); } public class DestinationFoo { private readonly DestinationBar _bar; public DestinationBar Bar { get { return _bar; } } public DestinationFoo(DestinationBar bar = null) { _bar = bar; } } public class DestinationBar { private readonly string _fooBar; public string FooBar { get { return _fooBar; } } public DestinationBar(string fooBar) { _fooBar = fooBar; } } public class SourceFoo { public SourceBar Bar { get; private set; } public SourceFoo(SourceBar bar) { Bar = bar; } } public class SourceBar { public string FooBar { get; private set; } public SourceBar(string fooBar) { FooBar = fooBar; } } } public class When_mapping_to_an_object_with_a_constructor_with_string_optional_arguments { [Fact] public void Should_resolve_constructor_when_string_args_are_optional() { var config = new MapperConfiguration(cfg => cfg.CreateMap<SourceFoo, DestinationFoo>()); var sourceBar = new SourceBar("fooBar"); var sourceFoo = new SourceFoo(sourceBar); var destinationFoo = config.CreateMapper().Map<DestinationFoo>(sourceFoo); destinationFoo.A.ShouldBe("a"); destinationFoo.B.ShouldBe("b"); destinationFoo.C.ShouldBe(3); } public class DestinationFoo { private string _a; private string _b; private int _c; public string A { get { return _a; } } public string B { get { return _b; } } public int C { get { return _c; } } public DestinationFoo(string a = "a",string b="b", int c = 3) { _a = a; _b = b; _c = c; } } public class DestinationBar { private readonly string _fooBar; public string FooBar { get { return _fooBar; } } public DestinationBar(string fooBar) { _fooBar = fooBar; } } public class SourceFoo { public SourceBar Bar { get; private set; } public SourceFoo(SourceBar bar) { Bar = bar; } } public class SourceBar { public string FooBar { get; private set; } public SourceBar(string fooBar) { FooBar = fooBar; } } } public class When_configuring_ctor_param_members : AutoMapperSpecBase { public class Source { public int Value { get; set; } } public class Dest { public Dest(int thing) { Value1 = thing; } public int Value1 { get; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.CreateMap<Source, Dest>().ForCtorParam("thing", opt => opt.MapFrom(src => src.Value)); }); [Fact] public void Should_redirect_value() { var dest = Mapper.Map<Source, Dest>(new Source {Value = 5}); dest.Value1.ShouldBe(5); } } public class When_configuring_nullable_ctor_param_members : AutoMapperSpecBase { public class Source { public int? Value { get; set; } } public class Dest { public Dest(int? thing) { Value1 = thing; } public int? Value1 { get; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.CreateMap<Source, Dest>().ForCtorParam("thing", opt => opt.MapFrom(src => src.Value)); }); [Fact] public void Should_redirect_value() { var dest = Mapper.Map<Source, Dest>(new Source()); dest.Value1.ShouldBeNull(); } } public class When_configuring_ctor_param_members_without_source_property_1 : AutoMapperSpecBase { public class Source { public string Result { get; } public Source(string result) { Result = result; } } public class Dest { public string Result{ get; } public dynamic Details { get; } public Dest(string result, DestInner1 inner1) { Result = result; Details = inner1; } public Dest(string result, DestInner2 inner2) { Result = result; Details = inner2; } public class DestInner1 { public int Value { get; } public DestInner1(int value) { Value = value; } } public class DestInner2 { public int Value { get; } public DestInner2(int value) { Value = value; } } } protected override MapperConfiguration CreateConfiguration() => new(config => { config.CreateMap<Source, Dest>() .ForCtorParam("inner1", cfg => cfg.MapFrom(_ => new Dest.DestInner1(100))); }); [Fact] public void Should_redirect_value() { var dest = Mapper.Map<Dest>(new Source("Success")); dest.ShouldNotBeNull(); Assert.Equal("100", dest.Details.Value.ToString()); } } public class When_configuring_ctor_param_members_without_source_property_2 : AutoMapperSpecBase { public class Source { public string Result { get; } public Source(string result) { Result = result; } } public class Dest { public string Result{ get; } public dynamic Details { get; } public Dest(string result, DestInner1 inner1) { Result = result; Details = inner1; } public Dest(string result, DestInner2 inner2) { Result = result; Details = inner2; } public class DestInner1 { public int Value { get; } public DestInner1(int value) { Value = value; } } public class DestInner2 { public int Value { get; } public DestInner2(int value) { Value = value; } } } protected override MapperConfiguration CreateConfiguration() => new(config => { config.CreateMap<Source, Dest>() .ForCtorParam("inner2", cfg => cfg.MapFrom(_ => new Dest.DestInner2(100))); }); [Fact] public void Should_redirect_value() { var dest = Mapper.Map<Dest>(new Source("Success")); dest.ShouldNotBeNull(); Assert.Equal("100", dest.Details.Value.ToString()); } }
namespace AutoMapper.UnitTests.Projection; public class ConstructorLetClause : AutoMapperSpecBase { class Source { public IList<SourceItem> Items { get; set; } } class SourceItem { public IList<SourceValue> Values { get; set; } } class SourceValue { public int Value1 { get; set; } public int Value2 { get; set; } } class Destination { public Destination(DestinationItem item) => Item = item; public DestinationItem Item { get; } } class DestinationValue { public DestinationValue(int value1, int value2) { Value1 = value1; Value2 = value2; } public int Value1 { get; } public int Value2 { get; } } class DestinationItem { public DestinationItem(DestinationValue destinationValue) { Value1 = destinationValue.Value1; Value2 = destinationValue.Value2; } public int Value1 { get; } public int Value2 { get; } public IList<DestinationValue> Values { get; set; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.CreateProjection<Source, Destination>().ForCtorParam("item", o => o.MapFrom(s => s.Items.FirstOrDefault())); cfg.CreateProjection<SourceItem, DestinationItem>().ForCtorParam("destinationValue", o=>o.MapFrom(s=>s.Values.FirstOrDefault())); cfg.CreateProjection<SourceValue, DestinationValue>(); }); [Fact] public void Should_construct_correctly() { var query = new[] { new Source { Items = new[] { new SourceItem { Values = new[] { new SourceValue { Value1 = 1, Value2 = 2 } } } } } }.AsQueryable().ProjectTo<Destination>(Configuration); var first = query.First(); first.Item.Value1.ShouldBe(1); first.Item.Value2.ShouldBe(2); var firstValue = first.Item.Values.Single(); firstValue.Value1.ShouldBe(1); firstValue.Value2.ShouldBe(2); } } public class ConstructorToString : AutoMapperSpecBase { class Source { public int Value { get; set; } } class Destination { public Destination(string value) => Value = value; public string Value { get; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => cfg.CreateProjection<Source, Destination>()); [Fact] public void Should_construct_correctly() => new[] { new Source { Value = 5 } }.AsQueryable().ProjectTo<Destination>(Configuration).First().Value.ShouldBe("5"); } public class ConstructorMapFrom : AutoMapperSpecBase { class Source { public int Value { get; set; } } record Destination(bool Value) { } protected override MapperConfiguration CreateConfiguration() => new(cfg => cfg.CreateProjection<Source, Destination>().ForCtorParam(nameof(Destination.Value), o=>o.MapFrom(s=>s.Value==5))); [Fact] public void Should_construct_correctly() => new[] { new Source { Value = 5 } }.AsQueryable().ProjectTo<Destination>(Configuration).First().Value.ShouldBeTrue(); } public class ConstructorIncludeMembers : AutoMapperSpecBase { class SourceWrapper { public Source Source { get; set; } } class Source { public int Value { get; set; } } class Destination { public Destination(string value) => Value = value; public string Value { get; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.CreateProjection<SourceWrapper, Destination>().IncludeMembers(s => s.Source); cfg.CreateProjection<Source, Destination>(); }); [Fact] public void Should_construct_correctly() => new[] { new SourceWrapper { Source = new Source { Value = 5 } } }.AsQueryable().ProjectTo<Destination>(Configuration).First().Value.ShouldBe("5"); } public class ConstructorsWithCollections : AutoMapperSpecBase { class Addresses { public int Id { get; set; } public string Address { get; set; } public ICollection<Users> Users { get; set; } } class Users { public int Id { get; set; } public Addresses FkAddress { get; set; } } class AddressDto { public int Id { get; } public string Address { get; } public AddressDto(int id, string address) { Id = id; Address = address; } } class UserDto { public int Id { get; set; } public AddressDto AddressDto { get; set; } } protected override MapperConfiguration CreateConfiguration() => new(cfg=> { cfg.CreateProjection<Users, UserDto>().ForMember(d => d.AddressDto, e => e.MapFrom(s => s.FkAddress)); cfg.CreateProjection<Addresses, AddressDto>().ConstructUsing(a => new AddressDto(a.Id, a.Address)); }); [Fact] public void Should_work() => ProjectTo<UserDto>(new[] { new Users { FkAddress = new Addresses { Address = "address" } } }.AsQueryable()).First().AddressDto.Address.ShouldBe("address"); } public class ConstructorTests : AutoMapperSpecBase { private Dest[] _dest; public class Source { public int Value { get; set; } } public class Dest { public Dest() { } public Dest(int other) { Other = other; } public int Value { get; set; } [IgnoreMap] public int Other { get; set; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.AddIgnoreMapAttribute(); cfg.CreateProjection<Source, Dest>() .ConstructUsing(src => new Dest(src.Value + 10)); }); protected override void Because_of() { var values = new[] { new Source() { Value = 5 } }.AsQueryable(); _dest = values.ProjectTo<Dest>(Configuration).ToArray(); } [Fact] public void Should_construct_correctly() { _dest[0].Other.ShouldBe(15); } } public class NestedConstructors : AutoMapperSpecBase { public class A { public int Id { get; set; } public B B { get; set; } } public class B { public int Id { get; set; } } public class DtoA { public DtoB B { get; } public DtoA(DtoB b) => B = b; } public class DtoB { public int Id { get; } public DtoB(int id) => Id = id; } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.CreateProjection<A, DtoA>(); cfg.CreateProjection<B, DtoB>(); }); [Fact] public void Should_project_ok() => ProjectTo<DtoA>(new[] { new A { B = new B { Id = 3 } } }.AsQueryable()).FirstOrDefault().B.Id.ShouldBe(3); } public class ConstructorLetClauseWithIheritance : AutoMapperSpecBase { class Source { public IList<SourceItem> Items { get; set; } } class SourceA : Source { public string A { get; set; } } class SourceB : Source { public string B { get; set; } } class SourceItem { public IList<SourceValue> Values { get; set; } } class SourceValue { public int Value1 { get; set; } public int Value2 { get; set; } } class Destination { public Destination(DestinationItem item) => Item = item; public DestinationItem Item { get; } } class DestinationA : Destination { public DestinationA(DestinationItem item, string a) : base(item) => A = a; public string A { get; } } class DestinationB : Destination { public DestinationB(DestinationItem item, string b) : base(item) => B = b; public string B { get; } } class DestinationValue { public DestinationValue(int value1, int value2) { Value1 = value1; Value2 = value2; } public int Value1 { get; } public int Value2 { get; } } class DestinationItem { public DestinationItem(DestinationValue destinationValue) { Value1 = destinationValue.Value1; Value2 = destinationValue.Value2; } public int Value1 { get; } public int Value2 { get; } public IList<DestinationValue> Values { get; set; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.CreateMap<Source, Destination>() .ForCtorParam("item", o => o.MapFrom(s => s.Items.FirstOrDefault())) .Include<SourceA, DestinationA>() .Include<SourceB, DestinationB>(); cfg.CreateMap<SourceA, DestinationA>() .ForCtorParam("item", o => o.MapFrom(s => s.Items.FirstOrDefault())) .ForCtorParam("a", o => o.MapFrom(s => s.A)); cfg.CreateMap<SourceB, DestinationB>() .ForCtorParam("item", o => o.MapFrom(s => s.Items.FirstOrDefault())) .ForCtorParam("b", o => o.MapFrom(s => s.B)); cfg.CreateMap<SourceItem, DestinationItem>().ForCtorParam("destinationValue", o => o.MapFrom(s => s.Values.FirstOrDefault())); cfg.CreateMap<SourceValue, DestinationValue>(); }); [Fact] public void Should_construct_correctly() { var query = new[] { new SourceA { A = "a", Items = new[] { new SourceItem { Values = new[] { new SourceValue { Value1 = 1, Value2 = 2 } } } } }, new SourceB { B = "b", Items = new[] { new SourceItem { Values = new[] { new SourceValue { Value1 = 1, Value2 = 2 } } } } }, new Source { Items = new[] { new SourceItem { Values = new[] { new SourceValue { Value1 = 1, Value2 = 2 } } } } } }.AsQueryable().ProjectTo<Destination>(Configuration); var list = query.ToList(); var first = list.First(); first.Item.Value1.ShouldBe(1); first.Item.Value2.ShouldBe(2); var firstValue = first.Item.Values.Single(); firstValue.Value1.ShouldBe(1); firstValue.Value2.ShouldBe(2); list.OfType<DestinationA>().Any(a => a.A == "a").ShouldBeTrue(); list.OfType<DestinationB>().Any(a => a.B == "b").ShouldBeTrue(); } } public class ConstructorToStringWithIheritance : AutoMapperSpecBase { class Source { public int Value { get; set; } } class SourceA : Source { public string A { get; set; } } class SourceB : Source { public string B { get; set; } } class Destination { public Destination(string value) => Value = value; public string Value { get; } } class DestinationA : Destination { public DestinationA(string value, string a) : base(value) => A = a; public string A { get; } } class DestinationB : Destination { public DestinationB(string value, string b) : base(value) => B = b; public string B { get; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.CreateMap<Source, Destination>() .Include<SourceA, DestinationA>(); cfg.CreateMap<SourceA, DestinationA>(); cfg.CreateMap<SourceB, DestinationB>(); }); [Fact] public void Should_construct_correctly() { var list = new[] { new Source { Value = 5 }, new SourceA { Value = 5, A = "a" }, new SourceB { Value = 5, B = "b" } }.AsQueryable().ProjectTo<Destination>(Configuration); list.ShouldAllBe(p => p.Value == "5"); list.OfType<DestinationA>().Any(p => p.A == "a"); list.OfType<DestinationB>().Any(p => p.B == "b"); } } public class ConstructorMapFromWithIheritance : AutoMapperSpecBase { class Source { public int Value { get; set; } } class SourceA : Source { public string A { get; set; } } class SourceB : Source { public string B { get; set; } } record Destination(bool Value) { } record DestinationA(bool Value, bool HasA) : Destination(Value) { } record DestinationB(bool Value, bool HasB) : Destination(Value) { } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.CreateMap<Source, Destination>() .ForCtorParam(nameof(Destination.Value), o => o.MapFrom(s => s.Value == 5)) .Include<SourceA, DestinationA>() .Include<SourceB, DestinationB>(); cfg.CreateMap<SourceA, DestinationA>() .ForCtorParam(nameof(Destination.Value), o => o.MapFrom(s => s.Value == 5)) .ForCtorParam(nameof(DestinationA.HasA), o => o.MapFrom(s => s.A == "a")); cfg.CreateMap<SourceB, DestinationB>() .ForCtorParam(nameof(Destination.Value), o => o.MapFrom(s => s.Value == 5)) .ForCtorParam(nameof(DestinationB.HasB), o => o.MapFrom(s => s.B == "b")); }); [Fact] public void Should_construct_correctly() { var list = new[] { new Source { Value = 5 }, new SourceA { Value = 5, A = "a" }, new SourceB { Value = 5, B = "b" } }.AsQueryable().ProjectTo<Destination>(Configuration); list.All(p => p.Value).ShouldBeTrue(); list.OfType<DestinationA>().Any(p => p.HasA).ShouldBeTrue(); list.OfType<DestinationB>().Any(p => p.HasB).ShouldBeTrue(); } } public class ConstructorIncludeMembersWithIheritance : AutoMapperSpecBase { class SourceWrapper { public Source Source { get; set; } } class SourceWrapperA : SourceWrapper { public SourceA SourceA { get; set; } } class SourceWrapperB : SourceWrapper { public SourceB SourceB { get; set; } } class Source { public int Value { get; set; } } class SourceA { public string A { get; set; } } class SourceB { public string B { get; set; } } class Destination { public Destination(string value) => Value = value; public string Value { get; } } class DestinationA : Destination { public DestinationA(string value, string a) : base(value) => A = a; public string A { get; } } class DestinationB : Destination { public DestinationB(string value, string b) : base(value) => B = b; public string B { get; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.CreateMap<SourceWrapper, Destination>() .IncludeMembers(s => s.Source) .Include<SourceWrapperA, DestinationA>() .Include<SourceWrapperB, DestinationB>(); cfg.CreateMap<SourceWrapperA, DestinationA>() .IncludeMembers(s => s.Source, s => s.SourceA); cfg.CreateMap<SourceWrapperB, DestinationB>() .IncludeMembers(s => s.Source, s => s.SourceB); cfg.CreateMap<Source, Destination>(); cfg.CreateMap<Source, DestinationA>(MemberList.None); cfg.CreateMap<Source, DestinationB>(MemberList.None); cfg.CreateMap<SourceA, DestinationA>(MemberList.None); cfg.CreateMap<SourceB, DestinationB>(MemberList.None); }); [Fact] public void Should_construct_correctly() { var list = new[] { new SourceWrapper { Source = new Source { Value = 5 } }, new SourceWrapperA { Source = new Source { Value = 5 }, SourceA = new SourceA() { A = "a" } }, new SourceWrapperB { Source = new Source { Value = 5 }, SourceB = new SourceB() { B = "b" } } }.AsQueryable().ProjectTo<Destination>(Configuration); list.All(p => p.Value == "5").ShouldBeTrue(); list.OfType<DestinationA>().Any(p => p.A == "a").ShouldBeTrue(); list.OfType<DestinationB>().Any(p => p.B == "b").ShouldBeTrue(); } } public class ConstructorsWithCollectionsWithIheritance : AutoMapperSpecBase { class Addresses { public int Id { get; set; } public string Address { get; set; } public ICollection<Users> Users { get; set; } } class Users { public int Id { get; set; } public Addresses FkAddress { get; set; } } class UsersA : Users { public string A { get; set; } } class UsersB : Users { public string B { get; set; } } class AddressDto { public int Id { get; } public string Address { get; } public AddressDto(int id, string address) { Id = id; Address = address; } } class UserDto { public int Id { get; set; } public AddressDto AddressDto { get; set; } } class UserADto : UserDto { public string A { get; set; } } class UserBDto : UserDto { public string B { get; set; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.CreateMap<Users, UserDto>() .ForMember(d => d.AddressDto, e => e.MapFrom(s => s.FkAddress)) .Include<UsersA, UserADto>() .Include<UsersB, UserBDto>(); cfg.CreateMap<UsersA, UserADto>(); cfg.CreateMap<UsersB, UserBDto>(); cfg.CreateMap<Addresses, AddressDto>().ConstructUsing(a => new AddressDto(a.Id, a.Address)); }); [Fact] public void Should_work() { var list = ProjectTo<UserDto>(new[] { new Users { FkAddress = new Addresses { Address = "address" } }, new UsersA { A = "a", FkAddress = new Addresses { Address = "address" } }, new UsersB { B = "b", FkAddress = new Addresses { Address = "address" } } }.AsQueryable()).ToList(); list.All(p => p.AddressDto.Address == "address").ShouldBeTrue(); list.OfType<UserADto>().Any(p => p.A == "a").ShouldBeTrue(); list.OfType<UserBDto>().Any(p => p.B == "b").ShouldBeTrue(); } } public class ConstructorTestsWithIheritance : AutoMapperSpecBase { private Dest[] _dest; public class Source { public int Value { get; set; } } public class SourceA : Source { public string A { get; set; } } public class SourceB : Source { public string B { get; set; } } public class Dest { public Dest() { } public Dest(int other) { Other = other; } public int Value { get; set; } [IgnoreMap] public int Other { get; set; } } public class DestA : Dest { public DestA() : base() { } public DestA(int other, string otherA) : base(other) { OtherA = otherA; } [IgnoreMap] public string OtherA { get; set; } } public class DestB : Dest { public DestB() : base() { } public DestB(int other, string otherB) : base(other) { OtherB = otherB; } [IgnoreMap] public string OtherB { get; set; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.AddIgnoreMapAttribute(); cfg.CreateMap<Source, Dest>() .ConstructUsing(src => new Dest(src.Value + 10)) .Include<SourceA, DestA>() .Include<SourceB, DestB>(); cfg.CreateMap<SourceA, DestA>() .ConstructUsing(src => new DestA(src.Value + 10, src.A + "a")); cfg.CreateMap<SourceB, DestB>() .ConstructUsing(src => new DestB(src.Value + 10, src.B + "b")); }); protected override void Because_of() { var values = new[] { new Source() { Value = 5 }, new SourceA() { Value = 5, A = "a" }, new SourceB() { Value = 5, B = "b" } }.AsQueryable(); _dest = values.ProjectTo<Dest>(Configuration).ToArray(); } [Fact] public void Should_construct_correctly() { _dest.All(p => p.Other == 15).ShouldBeTrue(); _dest.OfType<DestA>().Any(p => p.OtherA == "aa").ShouldBeTrue(); _dest.OfType<DestB>().Any(p => p.OtherB == "bb").ShouldBeTrue(); } } public class NestedConstructorsWithIheritance : AutoMapperSpecBase { public class A { public int Id { get; set; } public B B { get; set; } } public class B { public int Id { get; set; } } public class DtoA { public DtoB B { get; } public DtoA(DtoB b) => B = b; } public class DtoB { public int Id { get; } public DtoB(int id) => Id = id; } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.CreateProjection<A, DtoA>(); cfg.CreateProjection<B, DtoB>(); }); [Fact] public void Should_project_ok() => ProjectTo<DtoA>(new[] { new A { B = new B { Id = 3 } } }.AsQueryable()).FirstOrDefault().B.Id.ShouldBe(3); }
AutoMapper
You are an expert C++ developer. Task: Write a unit test for 'When_configuring_ctor_param_members_without_source_property_2' using GoogleTest (gtest) and GoogleMock (gmock). Context: - Class: When_configuring_ctor_param_members_without_source_property_2 Requirements: Use EXPECT_CALL for virtual methods.
industrial
namespace AutoMapper.IntegrationTests; public class ICollectionAggregateProjections(DatabaseFixture databaseFixture) : IntegrationTest<ICollectionAggregateProjections.DatabaseInitializer>(databaseFixture) { public class Customer { [Key] public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public ICollection<Item> Items { get; set; } } public class Item { public int Id { get; set; } public int Code { get; set; } } public class CustomerViewModel { public int ItemCodesCount { get; set; } public int ItemCodesMin { get; set; } public int ItemCodesMax { get; set; } public int ItemCodesSum { get; set; } } public class Context : LocalDbContext { public DbSet<Customer> Customers { get; set; } } public class DatabaseInitializer : DropCreateDatabaseAlways<Context> { protected override void Seed(Context context) { context.Customers.Add(new Customer { FirstName = "Bob", LastName = "Smith", Items = new[] { new Item { Code = 1 }, new Item { Code = 3 }, new Item { Code = 5 } } }); base.Seed(context); } } public class CustomerItemCodes { public List<int> ItemCodes { get; set; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => cfg.CreateProjection<CustomerItemCodes, CustomerViewModel>()); [Fact] public void Can_map_with_projection() { using (var context = Fixture.CreateContext()) { var result = ProjectTo<CustomerViewModel>(context.Customers.Select(customer => new CustomerItemCodes { ItemCodes = customer.Items.Select(item => item.Code).ToList() })).Single(); result.ItemCodesCount.ShouldBe(3); result.ItemCodesMin.ShouldBe(1); result.ItemCodesMax.ShouldBe(5); result.ItemCodesSum.ShouldBe(9); } } }
namespace AutoMapper.UnitTests.Projection; public class NonNullableToNullable : AutoMapperSpecBase { class Source { public int Id { get; set; } } class Destination { public int? Id { get; set; } } protected override MapperConfiguration CreateConfiguration() => new(c=>c.CreateProjection<Source, Destination>()); [Fact] public void Should_project() => ProjectTo<Destination>(new[] { new Source() }.AsQueryable()).First().Id.ShouldBe(0); } public class InMemoryMapObjectPropertyFromSubQuery : AutoMapperSpecBase { protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.CreateProjection<Product, ProductModel>() .ForMember(d => d.Price, o => o.MapFrom(source => source.Articles.Where(x => x.IsDefault && x.NationId == 1 && source.ECommercePublished).FirstOrDefault())); cfg.CreateProjection<Article, PriceModel>() .ForMember(d => d.RegionId, o => o.MapFrom(s => s.NationId)); }); [Fact] public void Should_cache_the_subquery() { var products = new[] { new Product { Id = 1, ECommercePublished = true, Articles = new[] { new Article { Id = 1, IsDefault = true, NationId = 1, ProductId = 1 } } } }.AsQueryable(); var projection = products.ProjectTo<ProductModel>(Configuration); var productModel = projection.First(); productModel.Price.RegionId.ShouldBe((short)1); productModel.Price.IsDefault.ShouldBeTrue(); productModel.Price.Id.ShouldBe(1); productModel.Id.ShouldBe(1); } public partial class Article { public int Id { get; set; } public int ProductId { get; set; } public bool IsDefault { get; set; } public short NationId { get; set; } public virtual Product Product { get; set; } } public partial class Product { public int Id { get; set; } public string Name { get; set; } public bool ECommercePublished { get; set; } public virtual ICollection<Article> Articles { get; set; } public int Value { get; } public int NotMappedValue { get; set; } public virtual List<Article> OtherArticles { get; } } public class PriceModel { public int Id { get; set; } public short RegionId { get; set; } public bool IsDefault { get; set; } } public class ProductModel { public int Id { get; set; } public PriceModel Price { get; set; } } }
AutoMapper
You are an expert C++ developer. Task: Write a unit test for 'ICollectionAggregateProjections' using GoogleTest (gtest) and GoogleMock (gmock). Context: - Class: ICollectionAggregateProjections Requirements: Use EXPECT_CALL for virtual methods.
industrial
namespace AutoMapper.IntegrationTests; public class ParameterizedQueries(DatabaseFixture databaseFixture) : IntegrationTest<ParameterizedQueries.DatabaseInitializer>(databaseFixture) { public class Entity { public int Id { get; set; } public string Value { get; set; } } public class EntityDto { public int Id { get; set; } public string Value { get; set; } public string UserName { get; set; } } public class ClientContext : LocalDbContext { public DbSet<Entity> Entities { get; set; } } public class DatabaseInitializer : DropCreateDatabaseAlways<ClientContext> { protected override void Seed(ClientContext context) { context.Entities.AddRange(new[] { new Entity {Value = "Value1"}, new Entity {Value = "Value2"} }); base.Seed(context); } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { string username = null; cfg.CreateProjection<Entity, EntityDto>() .ForMember(d => d.UserName, opt => opt.MapFrom(s => username)); }); [Fact] public async Task Should_parameterize_value() { List<EntityDto> dtos; string username; using (var db = Fixture.CreateContext()) { username = "Mary"; var query = ProjectTo<EntityDto>(db.Entities, new { username }); dtos = await query.ToListAsync(); var constantVisitor = new ConstantVisitor(); constantVisitor.Visit(query.Expression); constantVisitor.HasConstant.ShouldBeFalse(); dtos.All(dto => dto.UserName == username).ShouldBeTrue(); username = "Joe"; query = ProjectTo<EntityDto>(db.Entities, new Dictionary<string, object> { { "username", username }}); dtos = await query.ToListAsync(); constantVisitor = new ConstantVisitor(); constantVisitor.Visit(query.Expression); constantVisitor.HasConstant.ShouldBeTrue(); dtos.All(dto => dto.UserName == username).ShouldBeTrue(); username = "Jane"; query = db.Entities.Select(e => new EntityDto { Id = e.Id, Value = e.Value, UserName = username }); dtos = await query.ToListAsync(); dtos.All(dto => dto.UserName == username).ShouldBeTrue(); constantVisitor = new ConstantVisitor(); constantVisitor.Visit(query.Expression); constantVisitor.HasConstant.ShouldBeFalse(); } } private class ConstantVisitor : ExpressionVisitor { public bool HasConstant { get; private set; } protected override Expression VisitConstant(ConstantExpression node) { if (node.Type == typeof(string)) HasConstant = true; return base.VisitConstant(node); } } }
namespace AutoMapper.UnitTests.Projection; public class ParameterizedQueriesTests_with_anonymous_object_and_factory : AutoMapperSpecBase { private Dest[] _dests; private IQueryable<Source> _sources; public class Source { } public class Dest { public int Value { get; set; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { int value = 0; Expression<Func<Source, int>> sourceMember = src => value + 5; cfg.CreateProjection<Source, Dest>() .ForMember(dest => dest.Value, opt => opt.MapFrom(sourceMember)); }); protected override void Because_of() { _sources = new[] { new Source() }.AsQueryable(); _dests = _sources.ProjectTo<Dest>(Configuration, new { value = 10 }).ToArray(); } [Fact] public void Should_substitute_parameter_value() { _dests[0].Value.ShouldBe(15); } [Fact] public void Should_not_cache_parameter_value() { var newDests = _sources.ProjectTo<Dest>(Configuration, new { value = 15 }).ToArray(); newDests[0].Value.ShouldBe(20); } } public class ParameterizedQueriesTests_with_anonymous_object : AutoMapperSpecBase { private Dest[] _dests; private IQueryable<Source> _sources; public class Source { } public class Dest { public int Value { get; set; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { int value = 0; Expression<Func<Source, int>> sourceMember = src => value + 5; cfg.CreateProjection<Source, Dest>() .ForMember(dest => dest.Value, opt => opt.MapFrom(sourceMember)); }); protected override void Because_of() { _sources = new[] { new Source() }.AsQueryable(); _dests = _sources.ProjectTo<Dest>(Configuration, new { value = 10 }).ToArray(); } [Fact] public void Should_substitute_parameter_value() { _dests[0].Value.ShouldBe(15); } [Fact] public void Should_not_cache_parameter_value() { var newDests = _sources.ProjectTo<Dest>(Configuration, new {value = 15}).ToArray(); newDests[0].Value.ShouldBe(20); } } public class ParameterizedQueriesTests_with_dictionary_object : AutoMapperSpecBase { private Dest[] _dests; private IQueryable<Source> _sources; public class Source { } public class Dest { public int Value { get; set; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { int value = 0; Expression<Func<Source, int>> sourceMember = src => value + 5; cfg.CreateProjection<Source, Dest>() .ForMember(dest => dest.Value, opt => opt.MapFrom(sourceMember)); }); protected override void Because_of() { _sources = new[] { new Source() }.AsQueryable(); _dests = _sources.ProjectTo<Dest>(Configuration, new Dictionary<string, object>{{"value", 10}}).ToArray(); } [Fact] public void Should_substitute_parameter_value() { _dests[0].Value.ShouldBe(15); } [Fact] public void Should_not_cache_parameter_value() { var newDests = _sources.ProjectTo<Dest>(Configuration, new Dictionary<string, object> { { "value", 15 } }).ToArray(); newDests[0].Value.ShouldBe(20); } } public class ParameterizedQueriesTests_with_filter : AutoMapperSpecBase { public class User { public int Id { get; set; } public string Name { get; set; } public DateTime? DateActivated { get; set; } } public class UserViewModel { public int Id { get; set; } public string Name { get; set; } public DateTime? DateActivated { get; set; } public int position { get; set; } } public class DB { public DB() { Users = new List<User>() { new User {DateActivated = new DateTime(2000, 1, 1), Id = 1, Name = "Joe Schmoe"}, new User {DateActivated = new DateTime(2000, 2, 1), Id = 2, Name = "John Schmoe"}, new User {DateActivated = new DateTime(2000, 3, 1), Id = 3, Name = "Jim Schmoe"}, }.AsQueryable(); } public IQueryable<User> Users { get; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { DB db = null; cfg.CreateProjection<User, UserViewModel>() .ForMember(a => a.position, opt => opt.MapFrom(src => db.Users.Count(u => u.DateActivated < src.DateActivated))); }); [Fact] public void Should_only_replace_outer_parameters() { var db = new DB(); var user = db.Users.ProjectTo<UserViewModel>(Configuration, new { db }).FirstOrDefault(a => a.Id == 2); user.position.ShouldBe(1); } }
AutoMapper
You are an expert C++ developer. Task: Write a unit test for 'ParameterizedQueries' using GoogleTest (gtest) and GoogleMock (gmock). Context: - Class: ParameterizedQueries Requirements: Use EXPECT_CALL for virtual methods.
industrial
namespace Dapper.Tests { internal enum AnEnum { A = 2, B = 1 } internal enum AnotherEnum : byte { A = 2, B = 1 } }
using System.Data; using System.Linq; using Xunit; namespace Dapper.Tests { [Collection("EnumTests")] public sealed class SystemSqlClientEnumTests : EnumTests<SystemSqlClientProvider> { } #if MSSQLCLIENT [Collection("EnumTests")] public sealed class MicrosoftSqlClientEnumTests : EnumTests<MicrosoftSqlClientProvider> { } #endif public abstract class EnumTests<TProvider> : TestBase<TProvider> where TProvider : DatabaseProvider { [Fact] public void TestEnumWeirdness() { Assert.Null(connection.Query<TestEnumClass>("select null as [EnumEnum]").First().EnumEnum); Assert.Equal(TestEnum.Bla, connection.Query<TestEnumClass>("select cast(1 as tinyint) as [EnumEnum]").First().EnumEnum); } [Fact] public void TestEnumStrings() { Assert.Equal(TestEnum.Bla, connection.Query<TestEnumClassNoNull>("select 'BLA' as [EnumEnum]").First().EnumEnum); Assert.Equal(TestEnum.Bla, connection.Query<TestEnumClassNoNull>("select 'bla' as [EnumEnum]").First().EnumEnum); Assert.Equal(TestEnum.Bla, connection.Query<TestEnumClass>("select 'BLA' as [EnumEnum]").First().EnumEnum); Assert.Equal(TestEnum.Bla, connection.Query<TestEnumClass>("select 'bla' as [EnumEnum]").First().EnumEnum); } [Fact] public void TestEnumParamsWithNullable() { const EnumParam a = EnumParam.A; EnumParam? b = EnumParam.B, c = null; var obj = connection.Query<EnumParamObject>("select @a as A, @b as B, @c as C", new { a, b, c }).Single(); Assert.Equal(EnumParam.A, obj.A); Assert.Equal(EnumParam.B, obj.B); Assert.Null(obj.C); } [Fact] public void TestEnumParamsWithoutNullable() { const EnumParam a = EnumParam.A; const EnumParam b = EnumParam.B, c = 0; var obj = connection.Query<EnumParamObjectNonNullable>("select @a as A, @b as B, @c as C", new { a, b, c }).Single(); Assert.Equal(EnumParam.A, obj.A); Assert.Equal(EnumParam.B, obj.B); Assert.Equal(obj.C, (EnumParam)0); } private enum EnumParam : short { None = 0, A = 1, B = 2 } private class EnumParamObject { public EnumParam A { get; set; } public EnumParam? B { get; set; } public EnumParam? C { get; set; } } private class EnumParamObjectNonNullable { public EnumParam A { get; set; } public EnumParam? B { get; set; } public EnumParam? C { get; set; } } private enum TestEnum : byte { Bla = 1 } private class TestEnumClass { public TestEnum? EnumEnum { get; set; } } private class TestEnumClassNoNull { public TestEnum EnumEnum { get; set; } } [Fact] public void AdoNetEnumValue() { using var cmd = connection.CreateCommand(); cmd.CommandText = "select @foo"; var p = cmd.CreateParameter(); p.ParameterName = "@foo"; p.DbType = DbType.Int32; // it turns out that this is the key piece; setting the DbType p.Value = AnEnum.B; cmd.Parameters.Add(p); object? value = cmd.ExecuteScalar(); Assert.NotNull(value); AnEnum val = (AnEnum)value; Assert.Equal(AnEnum.B, val); } [Fact] public void DapperEnumValue_SqlServer() => Common.DapperEnumValue(connection); private enum SO27024806Enum { Foo = 0, Bar = 1 } private class SO27024806Class { public SO27024806Class(SO27024806Enum myField) { MyField = myField; } public SO27024806Enum MyField { get; set; } } [Fact] public void SO27024806_TestVarcharEnumMemberWithExplicitConstructor() { var foo = connection.Query<SO27024806Class>("SELECT 'Foo' AS myField").Single(); Assert.Equal(SO27024806Enum.Foo, foo.MyField); } } }
Dapper
You are an expert C++ developer. Task: Write a unit test for 'TargetModule' using GoogleTest (gtest) and GoogleMock (gmock). Context: - Class: TargetModule Requirements: Use EXPECT_CALL for virtual methods.
industrial
using System; using System.ComponentModel; using System.Data; namespace Dapper { public static partial class SqlMapper { /// <summary> /// Not intended for direct usage /// </summary> /// <typeparam name="T">The type to have a cache for.</typeparam> [Obsolete(ObsoleteInternalUsageOnly, false)] [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public static class TypeHandlerCache<T> { /// <summary> /// Not intended for direct usage. /// </summary> /// <param name="value">The object to parse.</param> [Obsolete(ObsoleteInternalUsageOnly, true)] public static T? Parse(object value) => (T?)handler.Parse(typeof(T), value); /// <summary> /// Not intended for direct usage. /// </summary> /// <param name="parameter">The parameter to set a value for.</param> /// <param name="value">The value to set.</param> [Obsolete(ObsoleteInternalUsageOnly, true)] public static void SetValue(IDbDataParameter parameter, object value) => handler.SetValue(parameter, value); internal static void SetHandler(ITypeHandler handler) { TypeHandlerCache<T>.handler = handler; } private static ITypeHandler handler = null!; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Linq; using System.Reflection; using Xunit; namespace Dapper.Tests { [Collection(NonParallelDefinition.Name)] public sealed class SystemSqlClientTypeHandlerTests : TypeHandlerTests<SystemSqlClientProvider> { } #if MSSQLCLIENT [Collection(NonParallelDefinition.Name)] public sealed class MicrosoftSqlClientTypeHandlerTests : TypeHandlerTests<MicrosoftSqlClientProvider> { } #endif public abstract class TypeHandlerTests<TProvider> : TestBase<TProvider> where TProvider : DatabaseProvider { [Fact] public void TestChangingDefaultStringTypeMappingToAnsiString() { const string sql = "SELECT SQL_VARIANT_PROPERTY(CONVERT(sql_variant, @testParam),'BaseType') AS BaseType"; var param = new { testParam = "TestString" }; var result01 = connection.Query<string>(sql, param).FirstOrDefault(); Assert.Equal("nvarchar", result01); SqlMapper.PurgeQueryCache(); SqlMapper.AddTypeMap(typeof(string), DbType.AnsiString, false); // Change Default String Handling to AnsiString try { var result02 = connection.Query<string>(sql, param).FirstOrDefault(); Assert.Equal("varchar", result02); SqlMapper.PurgeQueryCache(); } finally { SqlMapper.AddTypeMap(typeof(string), DbType.String, false); // Restore Default to Unicode String } } [Fact] public void TestChangingDefaultStringTypeMappingToAnsiStringFirstOrDefault() { const string sql = "SELECT SQL_VARIANT_PROPERTY(CONVERT(sql_variant, @testParam),'BaseType') AS BaseType"; var param = new { testParam = "TestString" }; var result01 = connection.QueryFirstOrDefault<string>(sql, param); Assert.Equal("nvarchar", result01); SqlMapper.PurgeQueryCache(); SqlMapper.AddTypeMap(typeof(string), DbType.AnsiString, false); // Change Default String Handling to AnsiString try { var result02 = connection.QueryFirstOrDefault<string>(sql, param); Assert.Equal("varchar", result02); SqlMapper.PurgeQueryCache(); } finally { SqlMapper.AddTypeMap(typeof(string), DbType.String, false); // Restore Default to Unicode String } } [Fact] public void TestCustomTypeMap() { // default mapping var item = connection.Query<TypeWithMapping>("Select 'AVal' as A, 'BVal' as B").Single(); Assert.Equal("AVal", item.A); Assert.Equal("BVal", item.B); // custom mapping var map = new CustomPropertyTypeMap(typeof(TypeWithMapping), (type, columnName) => type.GetProperties().FirstOrDefault(prop => GetDescriptionFromAttribute(prop) == columnName)!); SqlMapper.SetTypeMap(typeof(TypeWithMapping), map); item = connection.Query<TypeWithMapping>("Select 'AVal' as A, 'BVal' as B").Single(); Assert.Equal("BVal", item.A); Assert.Equal("AVal", item.B); // reset to default SqlMapper.SetTypeMap(typeof(TypeWithMapping), null); item = connection.Query<TypeWithMapping>("Select 'AVal' as A, 'BVal' as B").Single(); Assert.Equal("AVal", item.A); Assert.Equal("BVal", item.B); } private static string? GetDescriptionFromAttribute(MemberInfo member) { if (member == null) return null; var attrib = (DescriptionAttribute?)Attribute.GetCustomAttribute(member, typeof(DescriptionAttribute), false); return attrib?.Description; } public class TypeWithMapping { [Description("B")] public string? A { get; set; } [Description("A")] public string? B { get; set; } } [Fact] public void Issue136_ValueTypeHandlers() { SqlMapper.ResetTypeHandlers(); SqlMapper.AddTypeHandler(typeof(LocalDate), LocalDateHandler.Default); var param = new LocalDateResult { NotNullable = new LocalDate { Year = 2014, Month = 7, Day = 25 }, NullableNotNull = new LocalDate { Year = 2014, Month = 7, Day = 26 }, NullableIsNull = null, }; var result = connection.Query<LocalDateResult>("SELECT @NotNullable AS NotNullable, @NullableNotNull AS NullableNotNull, @NullableIsNull AS NullableIsNull", param).Single(); SqlMapper.ResetTypeHandlers(); SqlMapper.AddTypeHandler(typeof(LocalDate?), LocalDateHandler.Default); result = connection.Query<LocalDateResult>("SELECT @NotNullable AS NotNullable, @NullableNotNull AS NullableNotNull, @NullableIsNull AS NullableIsNull", param).Single(); } public class LocalDateHandler : SqlMapper.TypeHandler<LocalDate> { private LocalDateHandler() { /* private constructor */ } // Make the field type ITypeHandler to ensure it cannot be used with SqlMapper.AddTypeHandler<T>(TypeHandler<T>) // by mistake. public static readonly SqlMapper.ITypeHandler Default = new LocalDateHandler(); public override LocalDate Parse(object? value) { var date = (DateTime)value!; return new LocalDate { Year = date.Year, Month = date.Month, Day = date.Day }; } public override void SetValue(IDbDataParameter parameter, LocalDate value) { parameter.DbType = DbType.DateTime; parameter.Value = new DateTime(value.Year, value.Month, value.Day); } } public struct LocalDate { public int Year { get; set; } public int Month { get; set; } public int Day { get; set; } } public class LocalDateResult { public LocalDate NotNullable { get; set; } public LocalDate? NullableNotNull { get; set; } public LocalDate? NullableIsNull { get; set; } } public class LotsOfNumerics { public enum E_Byte : byte { A = 0, B = 1 } public enum E_SByte : sbyte { A = 0, B = 1 } public enum E_Short : short { A = 0, B = 1 } public enum E_UShort : ushort { A = 0, B = 1 } public enum E_Int : int { A = 0, B = 1 } public enum E_UInt : uint { A = 0, B = 1 } public enum E_Long : long { A = 0, B = 1 } public enum E_ULong : ulong { A = 0, B = 1 } public E_Byte P_Byte { get; set; } public E_SByte P_SByte { get; set; } public E_Short P_Short { get; set; } public E_UShort P_UShort { get; set; } public E_Int P_Int { get; set; } public E_UInt P_UInt { get; set; } public E_Long P_Long { get; set; } public E_ULong P_ULong { get; set; } public bool N_Bool { get; set; } public byte N_Byte { get; set; } public sbyte N_SByte { get; set; } public short N_Short { get; set; } public ushort N_UShort { get; set; } public int N_Int { get; set; } public uint N_UInt { get; set; } public long N_Long { get; set; } public ulong N_ULong { get; set; } public float N_Float { get; set; } public double N_Double { get; set; } public decimal N_Decimal { get; set; } public E_Byte? N_P_Byte { get; set; } public E_SByte? N_P_SByte { get; set; } public E_Short? N_P_Short { get; set; } public E_UShort? N_P_UShort { get; set; } public E_Int? N_P_Int { get; set; } public E_UInt? N_P_UInt { get; set; } public E_Long? N_P_Long { get; set; } public E_ULong? N_P_ULong { get; set; } public bool? N_N_Bool { get; set; } public byte? N_N_Byte { get; set; } public sbyte? N_N_SByte { get; set; } public short? N_N_Short { get; set; } public ushort? N_N_UShort { get; set; } public int? N_N_Int { get; set; } public uint? N_N_UInt { get; set; } public long? N_N_Long { get; set; } public ulong? N_N_ULong { get; set; } public float? N_N_Float { get; set; } public double? N_N_Double { get; set; } public decimal? N_N_Decimal { get; set; } } [Fact] public void TestBigIntForEverythingWorks() { TestBigIntForEverythingWorks_ByDataType<long>("bigint"); TestBigIntForEverythingWorks_ByDataType<int>("int"); TestBigIntForEverythingWorks_ByDataType<byte>("tinyint"); TestBigIntForEverythingWorks_ByDataType<short>("smallint"); TestBigIntForEverythingWorks_ByDataType<bool>("bit"); TestBigIntForEverythingWorks_ByDataType<float>("float(24)"); TestBigIntForEverythingWorks_ByDataType<double>("float(53)"); } private void TestBigIntForEverythingWorks_ByDataType<T>(string dbType) { using (var reader = connection.ExecuteReader("select cast(1 as " + dbType + ")")) { Assert.True(reader.Read()); reader.GetFieldType(0).Equals(typeof(T)); Assert.False(reader.Read()); Assert.False(reader.NextResult()); } string sql = "select " + string.Join(",", typeof(LotsOfNumerics).GetProperties().Select( x => "cast (1 as " + dbType + ") as [" + x.Name + "]")); var row = connection.Query<LotsOfNumerics>(sql).Single(); Assert.True(row.N_Bool); Assert.Equal((sbyte)1, row.N_SByte); Assert.Equal((byte)1, row.N_Byte); Assert.Equal((int)1, row.N_Int); Assert.Equal((uint)1, row.N_UInt); Assert.Equal((short)1, row.N_Short); Assert.Equal((ushort)1, row.N_UShort); Assert.Equal((long)1, row.N_Long); Assert.Equal((ulong)1, row.N_ULong); Assert.Equal((float)1, row.N_Float); Assert.Equal((double)1, row.N_Double); Assert.Equal((decimal)1, row.N_Decimal); Assert.Equal(LotsOfNumerics.E_Byte.B, row.P_Byte); Assert.Equal(LotsOfNumerics.E_SByte.B, row.P_SByte); Assert.Equal(LotsOfNumerics.E_Short.B, row.P_Short); Assert.Equal(LotsOfNumerics.E_UShort.B, row.P_UShort); Assert.Equal(LotsOfNumerics.E_Int.B, row.P_Int); Assert.Equal(LotsOfNumerics.E_UInt.B, row.P_UInt); Assert.Equal(LotsOfNumerics.E_Long.B, row.P_Long); Assert.Equal(LotsOfNumerics.E_ULong.B, row.P_ULong); Assert.True(row.N_N_Bool!.Value); Assert.Equal((sbyte)1, row.N_N_SByte!.Value); Assert.Equal((byte)1, row.N_N_Byte!.Value); Assert.Equal((int)1, row.N_N_Int!.Value); Assert.Equal((uint)1, row.N_N_UInt!.Value); Assert.Equal((short)1, row.N_N_Short!.Value); Assert.Equal((ushort)1, row.N_N_UShort!.Value); Assert.Equal((long)1, row.N_N_Long!.Value); Assert.Equal((ulong)1, row.N_N_ULong!.Value); Assert.Equal((float)1, row.N_N_Float!.Value); Assert.Equal((double)1, row.N_N_Double!.Value); Assert.Equal((decimal)1, row.N_N_Decimal); Assert.Equal(LotsOfNumerics.E_Byte.B, row.N_P_Byte!.Value); Assert.Equal(LotsOfNumerics.E_SByte.B, row.N_P_SByte!.Value); Assert.Equal(LotsOfNumerics.E_Short.B, row.N_P_Short!.Value); Assert.Equal(LotsOfNumerics.E_UShort.B, row.N_P_UShort!.Value); Assert.Equal(LotsOfNumerics.E_Int.B, row.N_P_Int!.Value); Assert.Equal(LotsOfNumerics.E_UInt.B, row.N_P_UInt!.Value); Assert.Equal(LotsOfNumerics.E_Long.B, row.N_P_Long!.Value); Assert.Equal(LotsOfNumerics.E_ULong.B, row.N_P_ULong!.Value); TestBigIntForEverythingWorksGeneric<bool>(true, dbType); TestBigIntForEverythingWorksGeneric<sbyte>((sbyte)1, dbType); TestBigIntForEverythingWorksGeneric<byte>((byte)1, dbType); TestBigIntForEverythingWorksGeneric<int>((int)1, dbType); TestBigIntForEverythingWorksGeneric<uint>((uint)1, dbType); TestBigIntForEverythingWorksGeneric<short>((short)1, dbType); TestBigIntForEverythingWorksGeneric<ushort>((ushort)1, dbType); TestBigIntForEverythingWorksGeneric<long>((long)1, dbType); TestBigIntForEverythingWorksGeneric<ulong>((ulong)1, dbType); TestBigIntForEverythingWorksGeneric<float>((float)1, dbType); TestBigIntForEverythingWorksGeneric<double>((double)1, dbType); TestBigIntForEverythingWorksGeneric<decimal>((decimal)1, dbType); TestBigIntForEverythingWorksGeneric(LotsOfNumerics.E_Byte.B, dbType); TestBigIntForEverythingWorksGeneric(LotsOfNumerics.E_SByte.B, dbType); TestBigIntForEverythingWorksGeneric(LotsOfNumerics.E_Int.B, dbType); TestBigIntForEverythingWorksGeneric(LotsOfNumerics.E_UInt.B, dbType); TestBigIntForEverythingWorksGeneric(LotsOfNumerics.E_Short.B, dbType); TestBigIntForEverythingWorksGeneric(LotsOfNumerics.E_UShort.B, dbType); TestBigIntForEverythingWorksGeneric(LotsOfNumerics.E_Long.B, dbType); TestBigIntForEverythingWorksGeneric(LotsOfNumerics.E_ULong.B, dbType); TestBigIntForEverythingWorksGeneric<bool?>(true, dbType); TestBigIntForEverythingWorksGeneric<sbyte?>((sbyte)1, dbType); TestBigIntForEverythingWorksGeneric<byte?>((byte)1, dbType); TestBigIntForEverythingWorksGeneric<int?>((int)1, dbType); TestBigIntForEverythingWorksGeneric<uint?>((uint)1, dbType); TestBigIntForEverythingWorksGeneric<short?>((short)1, dbType); TestBigIntForEverythingWorksGeneric<ushort?>((ushort)1, dbType); TestBigIntForEverythingWorksGeneric<long?>((long)1, dbType); TestBigIntForEverythingWorksGeneric<ulong?>((ulong)1, dbType); TestBigIntForEverythingWorksGeneric<float?>((float)1, dbType); TestBigIntForEverythingWorksGeneric<double?>((double)1, dbType); TestBigIntForEverythingWorksGeneric<decimal?>((decimal)1, dbType); TestBigIntForEverythingWorksGeneric<LotsOfNumerics.E_Byte?>(LotsOfNumerics.E_Byte.B, dbType); TestBigIntForEverythingWorksGeneric<LotsOfNumerics.E_SByte?>(LotsOfNumerics.E_SByte.B, dbType); TestBigIntForEverythingWorksGeneric<LotsOfNumerics.E_Int?>(LotsOfNumerics.E_Int.B, dbType); TestBigIntForEverythingWorksGeneric<LotsOfNumerics.E_UInt?>(LotsOfNumerics.E_UInt.B, dbType); TestBigIntForEverythingWorksGeneric<LotsOfNumerics.E_Short?>(LotsOfNumerics.E_Short.B, dbType); TestBigIntForEverythingWorksGeneric<LotsOfNumerics.E_UShort?>(LotsOfNumerics.E_UShort.B, dbType); TestBigIntForEverythingWorksGeneric<LotsOfNumerics.E_Long?>(LotsOfNumerics.E_Long.B, dbType); TestBigIntForEverythingWorksGeneric<LotsOfNumerics.E_ULong?>(LotsOfNumerics.E_ULong.B, dbType); } private void TestBigIntForEverythingWorksGeneric<T>(T expected, string dbType) { var query = connection.Query<T>("select cast(1 as " + dbType + ")").Single(); Assert.Equal(query, expected); var scalar = connection.ExecuteScalar<T>("select cast(1 as " + dbType + ")"); Assert.Equal(scalar, expected); } [Fact] public void TestSubsequentQueriesSuccess() { var data0 = connection.Query<Fooz0>("select 1 as [Id] where 1 = 0").ToList(); Assert.Empty(data0); var data1 = connection.Query<Fooz1>(new CommandDefinition("select 1 as [Id] where 1 = 0", flags: CommandFlags.Buffered)).ToList(); Assert.Empty(data1); var data2 = connection.Query<Fooz2>(new CommandDefinition("select 1 as [Id] where 1 = 0", flags: CommandFlags.None)).ToList(); Assert.Empty(data2); data0 = connection.Query<Fooz0>("select 1 as [Id] where 1 = 0").ToList(); Assert.Empty(data0); data1 = connection.Query<Fooz1>(new CommandDefinition("select 1 as [Id] where 1 = 0", flags: CommandFlags.Buffered)).ToList(); Assert.Empty(data1); data2 = connection.Query<Fooz2>(new CommandDefinition("select 1 as [Id] where 1 = 0", flags: CommandFlags.None)).ToList(); Assert.Empty(data2); } private class Fooz0 { public int Id { get; set; } } private class Fooz1 { public int Id { get; set; } } private class Fooz2 { public int Id { get; set; } } public class RatingValueHandler : SqlMapper.TypeHandler<RatingValue> { private RatingValueHandler() { } public static readonly RatingValueHandler Default = new(); public override RatingValue Parse(object? value) { if (value is int i) { return new RatingValue() { Value = i }; } throw new FormatException("Invalid conversion to RatingValue"); } public override void SetValue(IDbDataParameter parameter, RatingValue? value) { // ... null, range checks etc ... parameter.DbType = System.Data.DbType.Int32; parameter.Value = value?.Value; } } public class RatingValue { public int Value { get; set; } // ... some other properties etc ... } public class MyResult { public string? CategoryName { get; set; } public RatingValue? CategoryRating { get; set; } } [Fact] public void SO24740733_TestCustomValueHandler() { SqlMapper.AddTypeHandler(RatingValueHandler.Default); var foo = connection.Query<MyResult>("SELECT 'Foo' AS CategoryName, 200 AS CategoryRating").Single(); Assert.Equal("Foo", foo.CategoryName); Assert.Equal(200, foo.CategoryRating?.Value); } [Fact] public void SO24740733_TestCustomValueSingleColumn() { SqlMapper.AddTypeHandler(RatingValueHandler.Default); var foo = connection.Query<RatingValue>("SELECT 200 AS CategoryRating").Single(); Assert.Equal(200, foo.Value); } public class StringListTypeHandler : SqlMapper.TypeHandler<List<string>> { private StringListTypeHandler() { } public static readonly StringListTypeHandler Default = new(); //Just a simple List<string> type handler implementation public override void SetValue(IDbDataParameter parameter, List<string>? value) { parameter.Value = string.Join(",", value ?? new()); } public override List<string> Parse(object? value) { return ((value as string) ?? "").Split(',').ToList(); } } public class MyObjectWithStringList { public List<string>? Names { get; set; } } [Fact] public void Issue253_TestIEnumerableTypeHandlerParsing() { SqlMapper.ResetTypeHandlers(); SqlMapper.AddTypeHandler(StringListTypeHandler.Default); var foo = connection.Query<MyObjectWithStringList>("SELECT 'Sam,Kyro' AS Names").Single(); Assert.Equal(new[] { "Sam", "Kyro" }, foo.Names); } [Fact] public void Issue253_TestIEnumerableTypeHandlerSetParameterValue() { SqlMapper.ResetTypeHandlers(); SqlMapper.AddTypeHandler(StringListTypeHandler.Default); connection.Execute("CREATE TABLE #Issue253 (Names VARCHAR(50) NOT NULL);"); try { const string names = "Sam,Kyro"; List<string> names_list = names.Split(',').ToList(); var foo = connection.Query<string>("INSERT INTO #Issue253 (Names) VALUES (@Names); SELECT Names FROM #Issue253;", new { Names = names_list }).Single(); Assert.Equal(names, foo); } finally { connection.Execute("DROP TABLE #Issue253;"); } } public class RecordingTypeHandler<T> : SqlMapper.TypeHandler<T> { public override void SetValue(IDbDataParameter parameter, T? value) { SetValueWasCalled = true; parameter.Value = value; } public override T Parse(object? value) { ParseWasCalled = true; return (T)value!; } public bool SetValueWasCalled { get; set; } public bool ParseWasCalled { get; set; } } [Fact] public void Test_RemoveTypeMap() { SqlMapper.ResetTypeHandlers(); SqlMapper.RemoveTypeMap(typeof(DateTime)); var dateTimeHandler = new RecordingTypeHandler<DateTime>(); SqlMapper.AddTypeHandler(dateTimeHandler); connection.Execute("CREATE TABLE #Test_RemoveTypeMap (x datetime NOT NULL);"); try { connection.Execute("INSERT INTO #Test_RemoveTypeMap VALUES (@Now)", new { DateTime.Now }); connection.Query<DateTime>("SELECT * FROM #Test_RemoveTypeMap"); Assert.True(dateTimeHandler.ParseWasCalled); Assert.True(dateTimeHandler.SetValueWasCalled); } finally { connection.Execute("DROP TABLE #Test_RemoveTypeMap"); SqlMapper.AddTypeMap(typeof(DateTime), DbType.DateTime); // or an option to reset type map? } } [Fact] public void TestReaderWhenResultsChange() { try { connection.Execute("create table #ResultsChange (X int);create table #ResultsChange2 (Y int);insert #ResultsChange (X) values(1);insert #ResultsChange2 (Y) values(1);"); var obj1 = connection.Query<ResultsChangeType>("select * from #ResultsChange").Single(); Assert.Equal(1, obj1.X); Assert.Equal(0, obj1.Y); Assert.Equal(0, obj1.Z); var obj2 = connection.Query<ResultsChangeType>("select * from #ResultsChange rc inner join #ResultsChange2 rc2 on rc2.Y=rc.X").Single(); Assert.Equal(1, obj2.X); Assert.Equal(1, obj2.Y); Assert.Equal(0, obj2.Z); connection.Execute("alter table #ResultsChange add Z int null"); connection.Execute("update #ResultsChange set Z = 2"); var obj3 = connection.Query<ResultsChangeType>("select * from #ResultsChange").Single(); Assert.Equal(1, obj3.X); Assert.Equal(0, obj3.Y); Assert.Equal(2, obj3.Z); var obj4 = connection.Query<ResultsChangeType>("select * from #ResultsChange rc inner join #ResultsChange2 rc2 on rc2.Y=rc.X").Single(); Assert.Equal(1, obj4.X); Assert.Equal(1, obj4.Y); Assert.Equal(2, obj4.Z); } finally { connection.Execute("drop table #ResultsChange;drop table #ResultsChange2;"); } } private class ResultsChangeType { public int X { get; set; } public int Y { get; set; } public int Z { get; set; } } public class WrongTypes { public int A { get; set; } public double B { get; set; } public long C { get; set; } public bool D { get; set; } } [Fact] public void TestWrongTypes_WithRightTypes() { var item = connection.Query<WrongTypes>("select 1 as A, cast(2.0 as float) as B, cast(3 as bigint) as C, cast(1 as bit) as D").Single(); Assert.Equal(1, item.A); Assert.Equal(2.0, item.B); Assert.Equal(3L, item.C); Assert.True(item.D); } [Fact] public void TestWrongTypes_WithWrongTypes() { var item = connection.Query<WrongTypes>("select cast(1.0 as float) as A, 2 as B, 3 as C, cast(1 as bigint) as D").Single(); Assert.Equal(1, item.A); Assert.Equal(2.0, item.B); Assert.Equal(3L, item.C); Assert.True(item.D); } [Fact] public void TestTreatIntAsABool() { Assert.True(connection.Query<bool>("select CAST(1 AS BIT)").Single()); Assert.True(connection.Query<bool>("select 1").Single()); } [Fact] public void SO24607639_NullableBools() { var obj = connection.Query<HazBools>( @"declare @vals table (A bit null, B bit null, C bit null); insert @vals (A,B,C) values (1,0,null); select * from @vals").Single(); Assert.NotNull(obj); Assert.True(obj.A.HasValue); Assert.True(obj.A.Value); Assert.True(obj.B.HasValue); Assert.False(obj.B.Value); Assert.Null(obj.C); } private class HazBools { public bool? A { get; set; } public bool? B { get; set; } public bool? C { get; set; } } [Fact] public void Issue130_IConvertible() { dynamic row = connection.Query("select 1 as [a], '2' as [b]").Single(); int a = row.a; string b = row.b; Assert.Equal(1, a); Assert.Equal("2", b); row = connection.Query<dynamic>("select 3 as [a], '4' as [b]").Single(); a = row.a; b = row.b; Assert.Equal(3, a); Assert.Equal("4", b); } [Fact] public void Issue149_TypeMismatch_SequentialAccess() { Guid guid = Guid.Parse("cf0ef7ac-b6fe-4e24-aeda-a2b45bb5654e"); var ex = Assert.ThrowsAny<Exception>(() => connection.Query<Issue149_Person>("select @guid as Id", new { guid }).First()); Assert.Equal("Error parsing column 0 (Id=cf0ef7ac-b6fe-4e24-aeda-a2b45bb5654e - Guid)", ex.Message); } public class Issue149_Person { public string? Id { get; set; } } [Fact] public void Issue295_NullableDateTime_SqlServer() => Common.TestDateTime(connection); [Fact] public void SO29343103_UtcDates() { const string sql = "select @date"; var date = DateTime.UtcNow; var returned = connection.Query<DateTime>(sql, new { date }).Single(); var delta = returned - date; Assert.True(delta.TotalMilliseconds >= -10 && delta.TotalMilliseconds <= 10); } [Fact] public void Issue461_TypeHandlerWorksInConstructor() { SqlMapper.AddTypeHandler(new Issue461_BlargHandler()); connection.Execute(@"CREATE TABLE #Issue461 ( Id int not null IDENTITY(1,1), SomeValue nvarchar(50), SomeBlargValue nvarchar(200), )"); const string Expected = "abc123def"; var blarg = new Blarg(Expected); connection.Execute( "INSERT INTO #Issue461 (SomeValue, SomeBlargValue) VALUES (@value, @blarg)", new { value = "what up?", blarg }); // test: without constructor var parameterlessWorks = connection.QuerySingle<Issue461_ParameterlessTypeConstructor>("SELECT * FROM #Issue461"); Assert.Equal(1, parameterlessWorks.Id); Assert.Equal("what up?", parameterlessWorks.SomeValue); Assert.Equal(Expected, parameterlessWorks.SomeBlargValue?.Value); // test: via constructor var parameterDoesNot = connection.QuerySingle<Issue461_ParameterisedTypeConstructor>("SELECT * FROM #Issue461"); Assert.Equal(1, parameterDoesNot.Id); Assert.Equal("what up?", parameterDoesNot.SomeValue); Assert.Equal(Expected, parameterDoesNot.SomeBlargValue?.Value); } // I would usually expect this to be a struct; using a class // so that we can't pass unexpectedly due to forcing an unsafe cast - want // to see an InvalidCastException if it is wrong private class Blarg { public Blarg(string? value) { Value = value; } public string? Value { get; } public override string ToString() { return Value!; } } private class Issue461_BlargHandler : SqlMapper.TypeHandler<Blarg> { public override void SetValue(IDbDataParameter parameter, Blarg? value) { parameter.Value = ((object?)value?.Value) ?? DBNull.Value; } public override Blarg? Parse(object? value) { string? s = (value == null || value is DBNull) ? null : Convert.ToString(value); return new Blarg(s); } } private class Issue461_ParameterlessTypeConstructor { public int Id { get; set; } public string? SomeValue { get; set; } public Blarg? SomeBlargValue { get; set; } } private class Issue461_ParameterisedTypeConstructor { public Issue461_ParameterisedTypeConstructor(int id, string someValue, Blarg someBlargValue) { Id = id; SomeValue = someValue; SomeBlargValue = someBlargValue; } public int Id { get; } public string SomeValue { get; } public Blarg SomeBlargValue { get; } } [Theory] [InlineData(true)] [InlineData(false)] public void Issue1959_TypeHandlerNullability_Subclass(bool isNull) { Issue1959_Subclass_Handler.Register(); Issue1959_Subclass? when = isNull ? null : new(DateTime.Today); var whenNotNull = when ?? new(new DateTime(1753, 1, 1)); var args = new HazIssue1959_Subclass { Id = 42, Nullable = when, NonNullable = whenNotNull }; var row = connection.QuerySingle<HazIssue1959_Subclass>( "select @Id as [Id], @NonNullable as [NonNullable], @Nullable as [Nullable]", args); Assert.NotNull(row); Assert.Equal(42, row.Id); Assert.Equal(when, row.Nullable); Assert.Equal(whenNotNull, row.NonNullable); } [Theory] [InlineData(true)] [InlineData(false)] public void Issue1959_TypeHandlerNullability_Raw(bool isNull) { Issue1959_Raw_Handler.Register(); Issue1959_Raw? when = isNull ? null : new(DateTime.Today); var whenNotNull = when ?? new(new DateTime(1753, 1, 1)); var args = new HazIssue1959_Raw { Id = 42, Nullable = when, NonNullable = whenNotNull }; var row = connection.QuerySingle<HazIssue1959_Raw>( "select @Id as [Id], @NonNullable as [NonNullable], @Nullable as [Nullable]", args); Assert.NotNull(row); Assert.Equal(42, row.Id); Assert.Equal(when, row.Nullable); Assert.Equal(whenNotNull, row.NonNullable); } public class HazIssue1959_Subclass { public int Id { get; set; } public Issue1959_Subclass NonNullable { get; set; } public Issue1959_Subclass? Nullable { get; set; } } public class HazIssue1959_Raw { public int Id { get; set; } public Issue1959_Raw NonNullable { get; set; } public Issue1959_Raw? Nullable { get; set; } } public class Issue1959_Subclass_Handler : SqlMapper.TypeHandler<Issue1959_Subclass> { public static void Register() => SqlMapper.AddTypeHandler<Issue1959_Subclass>(Instance); private Issue1959_Subclass_Handler() { } private static readonly Issue1959_Subclass_Handler Instance = new(); public override Issue1959_Subclass Parse(object value) { Assert.NotNull(value); Assert.IsType<DateTime>(value); // checking not DbNull etc return new Issue1959_Subclass((DateTime)value); } public override void SetValue(IDbDataParameter parameter, TypeHandlerTests<TProvider>.Issue1959_Subclass value) => parameter.Value = value.Value; } public class Issue1959_Raw_Handler : SqlMapper.ITypeHandler { public static void Register() => SqlMapper.AddTypeHandler(typeof(Issue1959_Raw), Instance); private Issue1959_Raw_Handler() { } private static readonly Issue1959_Raw_Handler Instance = new(); void SqlMapper.ITypeHandler.SetValue(IDbDataParameter parameter, object value) { Assert.NotNull(value); if (value is DBNull) { parameter.Value = value; } else { Assert.IsType<Issue1959_Raw>(value); // checking not DbNull etc parameter.Value = ((Issue1959_Raw)value).Value; } } object? SqlMapper.ITypeHandler.Parse(Type destinationType, object value) { Assert.NotNull(value); Assert.IsType<DateTime>(value); // checking not DbNull etc return new Issue1959_Raw((DateTime)value); } } #pragma warning disable CA2231 // Overload operator equals on overriding value type Equals public readonly struct Issue1959_Subclass : IEquatable<Issue1959_Subclass> #pragma warning restore CA2231 // Overload operator equals on overriding value type Equals { public Issue1959_Subclass(DateTime value) => Value = value; public readonly DateTime Value; public override int GetHashCode() => Value.GetHashCode(); public override bool Equals(object? obj) => obj is Issue1959_Subclass other && Equals(other); public bool Equals(Issue1959_Subclass other) => other.Value == Value; public override string ToString() => Value.ToString(); } #pragma warning disable CA2231 // Overload operator equals on overriding value type Equals public readonly struct Issue1959_Raw : IEquatable<Issue1959_Raw> #pragma warning restore CA2231 // Overload operator equals on overriding value type Equals { public Issue1959_Raw(DateTime value) => Value = value; public readonly DateTime Value; public override int GetHashCode() => Value.GetHashCode(); public override bool Equals(object? obj) => obj is Issue1959_Raw other && Equals(other); public bool Equals(Issue1959_Raw other) => other.Value == Value; public override string ToString() => Value.ToString(); } } }
Dapper
You are an expert .NET (C#) developer. Task: Write a unit test for 'TargetModule' using XUnit and Moq. Context: - Class: TargetModule Requirements: Use Mock<T> interface mocking.
industrial
using System.Data; using System.Xml; using System.Xml.Linq; namespace Dapper { internal abstract class XmlTypeHandler<T> : SqlMapper.StringTypeHandler<T> { public override void SetValue(IDbDataParameter parameter, T? value) { base.SetValue(parameter, value); parameter.DbType = DbType.Xml; } } internal sealed class XmlDocumentHandler : XmlTypeHandler<XmlDocument> { protected override XmlDocument Parse(string xml) { var doc = new XmlDocument(); doc.LoadXml(xml); return doc; } protected override string Format(XmlDocument xml) => xml.OuterXml; } internal sealed class XDocumentHandler : XmlTypeHandler<XDocument> { protected override XDocument Parse(string xml) => XDocument.Parse(xml); protected override string Format(XDocument xml) => xml.ToString(); } internal sealed class XElementHandler : XmlTypeHandler<XElement> { protected override XElement Parse(string xml) => XElement.Parse(xml); protected override string Format(XElement xml) => xml.ToString(); } }
using System.Xml; using System.Xml.Linq; using Xunit; namespace Dapper.Tests { [Collection("XmlTests")] public sealed class SystemSqlClientXmlTests : XmlTests<SystemSqlClientProvider> { } #if MSSQLCLIENT [Collection("XmlTests")] public sealed class MicrosoftSqlClientXmlTests : XmlTests<MicrosoftSqlClientProvider> { } #endif public abstract class XmlTests<TProvider> : TestBase<TProvider> where TProvider : DatabaseProvider { [Fact] public void CommonXmlTypesSupported() { var xml = new XmlDocument(); xml.LoadXml("<abc/>"); var foo = new Foo { A = xml, B = XDocument.Parse("<def/>"), C = XElement.Parse("<ghi/>") }; var bar = connection.QuerySingle<Foo>("select @a as [A], @b as [B], @c as [C]", new { a = foo.A, b = foo.B, c = foo.C }); Assert.Equal("abc", bar.A?.DocumentElement?.Name); Assert.Equal("def", bar.B?.Root?.Name.LocalName); Assert.Equal("ghi", bar.C?.Name.LocalName); } public class Foo { public XmlDocument? A { get; set; } public XDocument? B { get; set; } public XElement? C { get; set; } } } }
Dapper
You are an expert .NET (C#) developer. Task: Write a unit test for 'TargetModule' using XUnit and Moq. Context: - Class: TargetModule Requirements: Use Mock<T> interface mocking.
industrial
using System; using System.Collections; using System.Collections.ObjectModel; using System.Data; using System.Data.Common; using System.Diagnostics; using System.IO; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; namespace Dapper { internal sealed class DisposedReader : DbDataReader { internal static readonly DisposedReader Instance = new(); private DisposedReader() { } public override int Depth => 0; public override int FieldCount => 0; public override bool IsClosed => true; public override bool HasRows => false; public override int RecordsAffected => -1; public override int VisibleFieldCount => 0; [MethodImpl(MethodImplOptions.NoInlining)] private static T ThrowDisposed<T>() => throw new ObjectDisposedException(nameof(DbDataReader)); [MethodImpl(MethodImplOptions.NoInlining)] private async static Task<T> ThrowDisposedAsync<T>() { var result = ThrowDisposed<T>(); await Task.Yield(); // will never hit this - already thrown and handled return result; } public override void Close() { } public override DataTable GetSchemaTable() => ThrowDisposed<DataTable>(); #if NET5_0_OR_GREATER [Obsolete("This Remoting API is not supported and throws PlatformNotSupportedException.", DiagnosticId = "SYSLIB0010", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] #endif public override object InitializeLifetimeService() => ThrowDisposed<object>(); protected override void Dispose(bool disposing) { } public override bool GetBoolean(int ordinal) => ThrowDisposed<bool>(); public override long GetBytes(int ordinal, long dataOffset, byte[]? buffer, int bufferOffset, int length) => ThrowDisposed<long>(); public override float GetFloat(int ordinal) => ThrowDisposed<float>(); public override short GetInt16(int ordinal) => ThrowDisposed<short>(); public override byte GetByte(int ordinal) => ThrowDisposed<byte>(); public override char GetChar(int ordinal) => ThrowDisposed<char>(); public override long GetChars(int ordinal, long dataOffset, char[]? buffer, int bufferOffset, int length) => ThrowDisposed<long>(); public override string GetDataTypeName(int ordinal) => ThrowDisposed<string>(); public override DateTime GetDateTime(int ordinal) => ThrowDisposed<DateTime>(); protected override DbDataReader GetDbDataReader(int ordinal) => ThrowDisposed<DbDataReader>(); public override decimal GetDecimal(int ordinal) => ThrowDisposed<decimal>(); public override double GetDouble(int ordinal) => ThrowDisposed<double>(); public override IEnumerator GetEnumerator() => ThrowDisposed<IEnumerator>(); public override Type GetFieldType(int ordinal) => ThrowDisposed<Type>(); public override T GetFieldValue<T>(int ordinal) => ThrowDisposed<T>(); public override Task<T> GetFieldValueAsync<T>(int ordinal, CancellationToken cancellationToken) => ThrowDisposedAsync<T>(); public override Guid GetGuid(int ordinal) => ThrowDisposed<Guid>(); public override int GetInt32(int ordinal) => ThrowDisposed<int>(); public override long GetInt64(int ordinal) => ThrowDisposed<long>(); public override string GetName(int ordinal) => ThrowDisposed<string>(); public override int GetOrdinal(string name) => ThrowDisposed<int>(); public override Type GetProviderSpecificFieldType(int ordinal) => ThrowDisposed<Type>(); public override object GetProviderSpecificValue(int ordinal) => ThrowDisposed<object>(); public override int GetProviderSpecificValues(object[] values) => ThrowDisposed<int>(); public override Stream GetStream(int ordinal) => ThrowDisposed<Stream>(); public override string GetString(int ordinal) => ThrowDisposed<string>(); public override TextReader GetTextReader(int ordinal) => ThrowDisposed<TextReader>(); public override object GetValue(int ordinal) => ThrowDisposed<object>(); public override int GetValues(object[] values) => ThrowDisposed<int>(); public override bool IsDBNull(int ordinal) => ThrowDisposed<bool>(); public override Task<bool> IsDBNullAsync(int ordinal, CancellationToken cancellationToken) => ThrowDisposedAsync<bool>(); public override bool NextResult() => ThrowDisposed<bool>(); public override bool Read() => ThrowDisposed<bool>(); public override Task<bool> NextResultAsync(CancellationToken cancellationToken) => ThrowDisposedAsync<bool>(); public override Task<bool> ReadAsync(CancellationToken cancellationToken) => ThrowDisposedAsync<bool>(); public override object this[int ordinal] => ThrowDisposed<object>(); public override object this[string name] => ThrowDisposed<object>(); } internal sealed class DbWrappedReader : DbDataReader, IWrappedDataReader { // the purpose of wrapping here is to allow closing a reader to *also* close // the command, without having to explicitly hand the command back to the // caller public static DbDataReader Create(IDbCommand? cmd, DbDataReader reader) { if (cmd is null) return reader; // no need to wrap if no command if (reader is not null) return new DbWrappedReader(cmd, reader); cmd.Dispose(); return null!; // GIGO } private DbDataReader _reader; private IDbCommand _cmd; IDataReader IWrappedDataReader.Reader => _reader; IDbCommand IWrappedDataReader.Command => _cmd; public DbWrappedReader(IDbCommand cmd, DbDataReader reader) { _cmd = cmd; _reader = reader; } public override bool HasRows => _reader.HasRows; public override void Close() => _reader.Close(); public override DataTable? GetSchemaTable() => _reader.GetSchemaTable(); #if NET5_0_OR_GREATER [Obsolete("This Remoting API is not supported and throws PlatformNotSupportedException.", DiagnosticId = "SYSLIB0010", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] #endif public override object InitializeLifetimeService() => _reader.InitializeLifetimeService(); public override int Depth => _reader.Depth; public override bool IsClosed => _reader.IsClosed; public override bool NextResult() => _reader.NextResult(); public override bool Read() => _reader.Read(); public override int RecordsAffected => _reader.RecordsAffected; protected override void Dispose(bool disposing) { if (disposing) { _reader.Dispose(); _reader = DisposedReader.Instance; // all future ops are no-ops _cmd?.Dispose(); _cmd = null!; } } public override int FieldCount => _reader.FieldCount; public override bool GetBoolean(int i) => _reader.GetBoolean(i); public override byte GetByte(int i) => _reader.GetByte(i); public override long GetBytes(int i, long fieldOffset, byte[]? buffer, int bufferoffset, int length) => _reader.GetBytes(i, fieldOffset, buffer, bufferoffset, length); public override char GetChar(int i) => _reader.GetChar(i); public override long GetChars(int i, long fieldoffset, char[]? buffer, int bufferoffset, int length) => _reader.GetChars(i, fieldoffset, buffer, bufferoffset, length); public override string GetDataTypeName(int i) => _reader.GetDataTypeName(i); public override DateTime GetDateTime(int i) => _reader.GetDateTime(i); public override decimal GetDecimal(int i) => _reader.GetDecimal(i); public override double GetDouble(int i) => _reader.GetDouble(i); public override Type GetFieldType(int i) => _reader.GetFieldType(i); public override float GetFloat(int i) => _reader.GetFloat(i); public override Guid GetGuid(int i) => _reader.GetGuid(i); public override short GetInt16(int i) => _reader.GetInt16(i); public override int GetInt32(int i) => _reader.GetInt32(i); public override long GetInt64(int i) => _reader.GetInt64(i); public override string GetName(int i) => _reader.GetName(i); public override int GetOrdinal(string name) => _reader.GetOrdinal(name); public override string GetString(int i) => _reader.GetString(i); public override object GetValue(int i) => _reader.GetValue(i); public override int GetValues(object[] values) => _reader.GetValues(values); public override bool IsDBNull(int i) => _reader.IsDBNull(i); public override object this[string name] => _reader[name]; public override object this[int i] => _reader[i]; public override T GetFieldValue<T>(int ordinal) => _reader.GetFieldValue<T>(ordinal); public override Task<T> GetFieldValueAsync<T>(int ordinal, CancellationToken cancellationToken) => _reader.GetFieldValueAsync<T>(ordinal, cancellationToken); public override IEnumerator GetEnumerator() => _reader.GetEnumerator(); public override Type GetProviderSpecificFieldType(int ordinal) => _reader.GetProviderSpecificFieldType(ordinal); public override object GetProviderSpecificValue(int ordinal) => _reader.GetProviderSpecificValue(ordinal); public override int GetProviderSpecificValues(object[] values) => _reader.GetProviderSpecificValues(values); public override Stream GetStream(int ordinal) => _reader.GetStream(ordinal); public override TextReader GetTextReader(int ordinal) => _reader.GetTextReader(ordinal); public override Task<bool> IsDBNullAsync(int ordinal, CancellationToken cancellationToken) => _reader.IsDBNullAsync(ordinal, cancellationToken); public override Task<bool> NextResultAsync(CancellationToken cancellationToken) => _reader.NextResultAsync(cancellationToken); public override Task<bool> ReadAsync(CancellationToken cancellationToken) => _reader.ReadAsync(cancellationToken); public override int VisibleFieldCount => _reader.VisibleFieldCount; protected override DbDataReader GetDbDataReader(int ordinal) => _reader.GetData(ordinal); #if NET5_0_OR_GREATER public override Task CloseAsync() => _reader.CloseAsync(); public override ValueTask DisposeAsync() => _reader.DisposeAsync(); public override Task<ReadOnlyCollection<DbColumn>> GetColumnSchemaAsync(CancellationToken cancellationToken = default) => _reader.GetColumnSchemaAsync(cancellationToken); public override Task<DataTable?> GetSchemaTableAsync(CancellationToken cancellationToken = default) => base.GetSchemaTableAsync(cancellationToken); #endif } internal sealed class WrappedBasicReader : DbDataReader { private IDataReader _reader; public WrappedBasicReader(IDataReader reader) { Debug.Assert(reader is not DbDataReader); // or we wouldn't be here! _reader = reader ?? throw new ArgumentNullException(nameof(reader)); } public override bool HasRows => true; // have to assume that we do public override void Close() => _reader.Close(); public override DataTable? GetSchemaTable() => _reader.GetSchemaTable(); #if NET5_0_OR_GREATER [Obsolete("This Remoting API is not supported and throws PlatformNotSupportedException.", DiagnosticId = "SYSLIB0010", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] #endif public override object InitializeLifetimeService() => throw new NotSupportedException(); public override int Depth => _reader.Depth; public override bool IsClosed => _reader.IsClosed; public override bool NextResult() => _reader.NextResult(); public override bool Read() => _reader.Read(); public override int RecordsAffected => _reader.RecordsAffected; protected override void Dispose(bool disposing) { if (disposing) { _reader.Dispose(); _reader = DisposedReader.Instance; // all future ops are no-ops } } public override int FieldCount => _reader.FieldCount; public override bool GetBoolean(int i) => _reader.GetBoolean(i); public override byte GetByte(int i) => _reader.GetByte(i); public override long GetBytes(int i, long fieldOffset, byte[]? buffer, int bufferoffset, int length) => _reader.GetBytes(i, fieldOffset, buffer!, bufferoffset, length); public override char GetChar(int i) => _reader.GetChar(i); public override long GetChars(int i, long fieldoffset, char[]? buffer, int bufferoffset, int length) => _reader.GetChars(i, fieldoffset, buffer!, bufferoffset, length); public override string GetDataTypeName(int i) => _reader.GetDataTypeName(i); public override DateTime GetDateTime(int i) => _reader.GetDateTime(i); public override decimal GetDecimal(int i) => _reader.GetDecimal(i); public override double GetDouble(int i) => _reader.GetDouble(i); public override Type GetFieldType(int i) => _reader.GetFieldType(i); public override float GetFloat(int i) => _reader.GetFloat(i); public override Guid GetGuid(int i) => _reader.GetGuid(i); public override short GetInt16(int i) => _reader.GetInt16(i); public override int GetInt32(int i) => _reader.GetInt32(i); public override long GetInt64(int i) => _reader.GetInt64(i); public override string GetName(int i) => _reader.GetName(i); public override int GetOrdinal(string name) => _reader.GetOrdinal(name); public override string GetString(int i) => _reader.GetString(i); public override object GetValue(int i) => _reader.GetValue(i); public override int GetValues(object[] values) => _reader.GetValues(values); public override bool IsDBNull(int i) => _reader.IsDBNull(i); public override object this[string name] => _reader[name]; public override object this[int i] => _reader[i]; public override T GetFieldValue<T>(int ordinal) { var value = _reader.GetValue(ordinal); if (value is DBNull) { value = null; } return (T)value!; } public override Task<T> GetFieldValueAsync<T>(int ordinal, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return Task.FromResult(GetFieldValue<T>(ordinal)); } public override IEnumerator GetEnumerator() => _reader is IEnumerable e ? e.GetEnumerator() : throw new NotImplementedException(); public override Type GetProviderSpecificFieldType(int ordinal) => _reader.GetFieldType(ordinal); public override object GetProviderSpecificValue(int ordinal) => _reader.GetValue(ordinal); public override int GetProviderSpecificValues(object[] values) => _reader.GetValues(values); public override Stream GetStream(int ordinal) => throw new NotSupportedException(); public override TextReader GetTextReader(int ordinal) => throw new NotSupportedException(); public override Task<bool> IsDBNullAsync(int ordinal, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return Task.FromResult(_reader.IsDBNull(ordinal)); } public override Task<bool> NextResultAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return Task.FromResult(_reader.NextResult()); } public override Task<bool> ReadAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return Task.FromResult(_reader.Read()); } public override int VisibleFieldCount => _reader.FieldCount; protected override DbDataReader GetDbDataReader(int ordinal) => throw new NotSupportedException(); #if NET5_0_OR_GREATER public override Task CloseAsync() { _reader.Close(); return Task.CompletedTask; } public override ValueTask DisposeAsync() { _reader.Dispose(); return default; } public override Task<ReadOnlyCollection<DbColumn>> GetColumnSchemaAsync(CancellationToken cancellationToken = default) => throw new NotSupportedException(); public override Task<DataTable?> GetSchemaTableAsync(CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); return Task.FromResult(_reader.GetSchemaTable()); } #endif } }
using System; using System.Collections; using System.Data; using System.Data.Common; using Xunit.Abstractions; namespace Dapper.Tests; public class WrappedReaderTests(ITestOutputHelper testOutputHelper) { [Fact] public void DbWrappedReader_Dispose_DoesNotThrow() { var reader = new DbWrappedReader(new DummyDbCommand(), new ThrowOnCloseDbDataReader(testOutputHelper)); reader.Dispose(); } #if !NETFRAMEWORK [Fact] public async System.Threading.Tasks.Task DbWrappedReader_DisposeAsync_DoesNotThrow() { var reader = new DbWrappedReader(new DummyDbCommand(), new ThrowOnCloseDbDataReader(testOutputHelper)); await reader.DisposeAsync(); } #endif [Fact] public void WrappedBasicReader_Dispose_DoesNotThrow() { var reader = new WrappedBasicReader(new ThrowOnCloseIDataReader()); reader.Dispose(); } #if !NETFRAMEWORK [Fact] public async System.Threading.Tasks.Task WrappedBasicReader_DisposeAsync_DoesNotThrow() { var reader = new WrappedBasicReader(new ThrowOnCloseIDataReader()); await reader.DisposeAsync(); } #endif private class DummyDbCommand : DbCommand { public override void Cancel() => throw new NotSupportedException(); public override int ExecuteNonQuery() => throw new NotSupportedException(); public override object ExecuteScalar() => throw new NotSupportedException(); public override void Prepare() => throw new NotSupportedException(); #pragma warning disable CS8765 // nullability of value public override string CommandText { get; set; } = ""; #pragma warning restore CS8765 // nullability of value public override int CommandTimeout { get; set; } public override CommandType CommandType { get; set; } public override UpdateRowSource UpdatedRowSource { get; set; } protected override DbConnection? DbConnection { get; set; } protected override DbParameterCollection DbParameterCollection => throw new NotSupportedException(); protected override DbTransaction? DbTransaction { get; set; } public override bool DesignTimeVisible { get; set; } protected override DbParameter CreateDbParameter() => throw new NotSupportedException(); protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior) => throw new NotSupportedException(); } private class DummyDbException(string message) : DbException(message); private class ThrowOnCloseDbDataReader(ITestOutputHelper testOutputHelper) : DbDataReader { // This is basically what SqlClient does, see https://github.com/dotnet/SqlClient/blob/v5.2.1/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDataReader.cs#L835-L849 protected override void Dispose(bool disposing) { try { if (disposing) { Close(); } base.Dispose(disposing); } catch (DbException e) { testOutputHelper.WriteLine($"Ignored exception when disposing {e}"); } } public override void Close() => throw new DummyDbException("Exception during Close()"); public override bool GetBoolean(int ordinal) => throw new NotSupportedException(); public override byte GetByte(int ordinal) => throw new NotSupportedException(); public override long GetBytes(int ordinal, long dataOffset, byte[]? buffer, int bufferOffset, int length) => throw new NotSupportedException(); public override char GetChar(int ordinal) => throw new NotSupportedException(); public override long GetChars(int ordinal, long dataOffset, char[]? buffer, int bufferOffset, int length) => throw new NotSupportedException(); public override string GetDataTypeName(int ordinal) => throw new NotSupportedException(); public override DateTime GetDateTime(int ordinal) => throw new NotSupportedException(); public override decimal GetDecimal(int ordinal) => throw new NotSupportedException(); public override double GetDouble(int ordinal) => throw new NotSupportedException(); public override Type GetFieldType(int ordinal) => throw new NotSupportedException(); public override float GetFloat(int ordinal) => throw new NotSupportedException(); public override Guid GetGuid(int ordinal) => throw new NotSupportedException(); public override short GetInt16(int ordinal) => throw new NotSupportedException(); public override int GetInt32(int ordinal) => throw new NotSupportedException(); public override long GetInt64(int ordinal) => throw new NotSupportedException(); public override string GetName(int ordinal) => throw new NotSupportedException(); public override int GetOrdinal(string name) => throw new NotSupportedException(); public override string GetString(int ordinal) => throw new NotSupportedException(); public override object GetValue(int ordinal) => throw new NotSupportedException(); public override int GetValues(object[] values) => throw new NotSupportedException(); public override bool IsDBNull(int ordinal) => throw new NotSupportedException(); public override int FieldCount => throw new NotSupportedException(); public override object this[int ordinal] => throw new NotSupportedException(); public override object this[string name] => throw new NotSupportedException(); public override int RecordsAffected => throw new NotSupportedException(); public override bool HasRows => throw new NotSupportedException(); public override bool IsClosed => throw new NotSupportedException(); public override bool NextResult() => throw new NotSupportedException(); public override bool Read() => throw new NotSupportedException(); public override int Depth => throw new NotSupportedException(); public override IEnumerator GetEnumerator() => throw new NotSupportedException(); } private class ThrowOnCloseIDataReader : IDataReader { public void Dispose() { // Assume that IDataReader Dispose implementation does not throw } public void Close() => throw new DummyDbException("Exception during Close()"); public bool GetBoolean(int i) => throw new NotSupportedException(); public byte GetByte(int i) => throw new NotSupportedException(); public long GetBytes(int i, long fieldOffset, byte[]? buffer, int bufferoffset, int length) => throw new NotSupportedException(); public char GetChar(int i) => throw new NotSupportedException(); public long GetChars(int i, long fieldoffset, char[]? buffer, int bufferoffset, int length) => throw new NotSupportedException(); public IDataReader GetData(int i) => throw new NotSupportedException(); public string GetDataTypeName(int i) => throw new NotSupportedException(); public DateTime GetDateTime(int i) => throw new NotSupportedException(); public decimal GetDecimal(int i) => throw new NotSupportedException(); public double GetDouble(int i) => throw new NotSupportedException(); public Type GetFieldType(int i) => throw new NotSupportedException(); public float GetFloat(int i) => throw new NotSupportedException(); public Guid GetGuid(int i) => throw new NotSupportedException(); public short GetInt16(int i) => throw new NotSupportedException(); public int GetInt32(int i) => throw new NotSupportedException(); public long GetInt64(int i) => throw new NotSupportedException(); public string GetName(int i) => throw new NotSupportedException(); public int GetOrdinal(string name) => throw new NotSupportedException(); public string GetString(int i) => throw new NotSupportedException(); public object GetValue(int i) => throw new NotSupportedException(); public int GetValues(object[] values) => throw new NotSupportedException(); public bool IsDBNull(int i) => throw new NotSupportedException(); public int FieldCount => throw new NotSupportedException(); public object this[int i] => throw new NotSupportedException(); public object this[string name] => throw new NotSupportedException(); public DataTable? GetSchemaTable() => throw new NotSupportedException(); public bool NextResult() => throw new NotSupportedException(); public bool Read() => throw new NotSupportedException(); public int Depth => throw new NotSupportedException(); public bool IsClosed => throw new NotSupportedException(); public int RecordsAffected => throw new NotSupportedException(); } }
Dapper
You are an expert .NET (C#) developer. Task: Write a unit test for 'TargetModule' using XUnit and Moq. Context: - Class: TargetModule Requirements: Use Mock<T> interface mocking.
industrial
using System; using Microsoft.Data.SqlClient; using System.Runtime.CompilerServices; namespace Dapper.Tests.Performance { public static class SqlDataReaderHelper { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static string GetNullableString(this SqlDataReader reader, int index) { object tmp = reader.GetValue(index); if (tmp != DBNull.Value) { return (string)tmp; } return null; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static T? GetNullableValue<T>(this SqlDataReader reader, int index) where T : struct { object tmp = reader.GetValue(index); if (tmp != DBNull.Value) { return (T)tmp; } return null; } } }
using System.Collections.Generic; using System.Data.Common; using System.Linq; using Xunit; namespace Dapper.Tests { [Collection("DataReaderTests")] public sealed class SystemSqlClientDataReaderTests : DataReaderTests<SystemSqlClientProvider> { } #if MSSQLCLIENT [Collection("DataReaderTests")] public sealed class MicrosoftSqlClientDataReaderTests : DataReaderTests<MicrosoftSqlClientProvider> { } #endif public abstract class DataReaderTests<TProvider> : TestBase<TProvider> where TProvider : DatabaseProvider { [Fact] public void GetSameReaderForSameShape_IDataReader() { var origReader = connection.ExecuteReader("select 'abc' as Name, 123 as Id"); #pragma warning disable CS0618 // Type or member is obsolete var origParser = origReader.GetRowParser(typeof(HazNameId)); var typedParser = origReader.GetRowParser<HazNameId>(); #pragma warning restore CS0618 // Type or member is obsolete // because wrapped for IDataReader, not same instance each time Assert.False(ReferenceEquals(origParser, typedParser)); var list = origReader.Parse<HazNameId>().ToList(); Assert.Single(list); Assert.Equal("abc", list[0].Name); Assert.Equal(123, list[0].Id); origReader.Dispose(); var secondReader = connection.ExecuteReader("select 'abc' as Name, 123 as Id"); #pragma warning disable CS0618 // Type or member is obsolete var secondParser = secondReader.GetRowParser(typeof(HazNameId)); var thirdParser = secondReader.GetRowParser(typeof(HazNameId), 1); #pragma warning restore CS0618 // Type or member is obsolete list = secondReader.Parse<HazNameId>().ToList(); Assert.Single(list); Assert.Equal("abc", list[0].Name); Assert.Equal(123, list[0].Id); secondReader.Dispose(); // now: should be different readers, and because wrapped for IDataReader, not same parser Assert.False(ReferenceEquals(origReader, secondReader)); Assert.False(ReferenceEquals(origParser, secondParser)); Assert.False(ReferenceEquals(secondParser, thirdParser)); } [Fact] public void GetSameReaderForSameShape_DbDataReader() { var origReader = Assert.IsAssignableFrom<DbDataReader>(connection.ExecuteReader("select 'abc' as Name, 123 as Id")); var origParser = origReader.GetRowParser(typeof(HazNameId)); var typedParser = origReader.GetRowParser<HazNameId>(); Assert.True(ReferenceEquals(origParser, typedParser)); var list = origReader.Parse<HazNameId>().ToList(); Assert.Single(list); Assert.Equal("abc", list[0].Name); Assert.Equal(123, list[0].Id); origReader.Dispose(); var secondReader = Assert.IsAssignableFrom<DbDataReader>(connection.ExecuteReader("select 'abc' as Name, 123 as Id")); var secondParser = secondReader.GetRowParser(typeof(HazNameId)); var thirdParser = secondReader.GetRowParser(typeof(HazNameId), 1); list = secondReader.Parse<HazNameId>().ToList(); Assert.Single(list); Assert.Equal("abc", list[0].Name); Assert.Equal(123, list[0].Id); secondReader.Dispose(); // now: should be different readers, but same parser Assert.False(ReferenceEquals(origReader, secondReader)); Assert.True(ReferenceEquals(origParser, secondParser)); Assert.False(ReferenceEquals(secondParser, thirdParser)); } [Fact] public void TestTreatIntAsABool() { // Test we are consistent with direct call to database, see TypeHandlerTests.TestTreatIntAsABool using(var reader = connection.ExecuteReader("select CAST(1 AS BIT)")) Assert.True(SqlMapper.Parse<bool>(reader).Single()); using (var reader = connection.ExecuteReader("select 1")) Assert.True(SqlMapper.Parse<bool>(reader).Single()); } [Fact] public void DiscriminatedUnion_IDataReader() { var result = new List<Discriminated_BaseType>(); using (var reader = connection.ExecuteReader(@" select 'abc' as Name, 1 as Type, 3.0 as Value union all select 'def' as Name, 2 as Type, 4.0 as Value")) { if (reader.Read()) { #pragma warning disable CS0618 var toFoo = reader.GetRowParser<Discriminated_BaseType>(typeof(Discriminated_Foo)); var toBar = reader.GetRowParser<Discriminated_BaseType>(typeof(Discriminated_Bar)); #pragma warning restore CS0618 var col = reader.GetOrdinal("Type"); do { switch (reader.GetInt32(col)) { case 1: result.Add(toFoo(reader)); break; case 2: result.Add(toBar(reader)); break; } } while (reader.Read()); } } Assert.Equal(2, result.Count); Assert.Equal(1, result[0].Type); Assert.Equal(2, result[1].Type); var foo = (Discriminated_Foo)result[0]; Assert.Equal("abc", foo.Name); var bar = (Discriminated_Bar)result[1]; Assert.Equal((float)4.0, bar.Value); } [Fact] public void DiscriminatedUnion_DbDataReader() { var result = new List<Discriminated_BaseType>(); using (var reader = Assert.IsAssignableFrom<DbDataReader>(connection.ExecuteReader(@" select 'abc' as Name, 1 as Type, 3.0 as Value union all select 'def' as Name, 2 as Type, 4.0 as Value"))) { if (reader.Read()) { var toFoo = reader.GetRowParser<Discriminated_BaseType>(typeof(Discriminated_Foo)); var toBar = reader.GetRowParser<Discriminated_BaseType>(typeof(Discriminated_Bar)); var col = reader.GetOrdinal("Type"); do { switch (reader.GetInt32(col)) { case 1: result.Add(toFoo(reader)); break; case 2: result.Add(toBar(reader)); break; } } while (reader.Read()); } } Assert.Equal(2, result.Count); Assert.Equal(1, result[0].Type); Assert.Equal(2, result[1].Type); var foo = (Discriminated_Foo)result[0]; Assert.Equal("abc", foo.Name); var bar = (Discriminated_Bar)result[1]; Assert.Equal((float)4.0, bar.Value); } [Fact] public void DiscriminatedUnionWithMultiMapping_IDataReader() { var result = new List<DiscriminatedWithMultiMapping_BaseType>(); using (var reader = connection.ExecuteReader(@" select 'abc' as Name, 1 as Type, 3.0 as Value, 1 as Id, 'zxc' as Name union all select 'def' as Name, 2 as Type, 4.0 as Value, 2 as Id, 'qwe' as Name")) { if (reader.Read()) { var col = reader.GetOrdinal("Type"); var splitOn = reader.GetOrdinal("Id"); #pragma warning disable CS0618 var toFoo = reader.GetRowParser<DiscriminatedWithMultiMapping_BaseType>(typeof(DiscriminatedWithMultiMapping_Foo), 0, splitOn); var toBar = reader.GetRowParser<DiscriminatedWithMultiMapping_BaseType>(typeof(DiscriminatedWithMultiMapping_Bar), 0, splitOn); var toHaz = reader.GetRowParser<HazNameId>(typeof(HazNameId), splitOn, reader.FieldCount - splitOn); #pragma warning restore CS0618 do { DiscriminatedWithMultiMapping_BaseType? obj = null; switch (reader.GetInt32(col)) { case 1: obj = toFoo(reader); break; case 2: obj = toBar(reader); break; } Assert.NotNull(obj); obj!.HazNameIdObject = toHaz(reader); result.Add(obj); } while (reader.Read()); } } Assert.Equal(2, result.Count); Assert.Equal(1, result[0].Type); Assert.Equal(2, result[1].Type); var foo = (DiscriminatedWithMultiMapping_Foo)result[0]; Assert.Equal("abc", foo.Name); Assert.NotNull(foo.HazNameIdObject); Assert.Equal(1, foo.HazNameIdObject.Id); Assert.Equal("zxc", foo.HazNameIdObject!.Name); var bar = (DiscriminatedWithMultiMapping_Bar)result[1]; Assert.Equal((float)4.0, bar.Value); Assert.NotNull(bar.HazNameIdObject); Assert.Equal(2, bar.HazNameIdObject.Id); Assert.Equal("qwe", bar.HazNameIdObject.Name); } [Fact] public void DiscriminatedUnionWithMultiMapping_DbDataReader() { var result = new List<DiscriminatedWithMultiMapping_BaseType>(); using (var reader = Assert.IsAssignableFrom<DbDataReader>(connection.ExecuteReader(@" select 'abc' as Name, 1 as Type, 3.0 as Value, 1 as Id, 'zxc' as Name union all select 'def' as Name, 2 as Type, 4.0 as Value, 2 as Id, 'qwe' as Name"))) { if (reader.Read()) { var col = reader.GetOrdinal("Type"); var splitOn = reader.GetOrdinal("Id"); var toFoo = reader.GetRowParser<DiscriminatedWithMultiMapping_BaseType>(typeof(DiscriminatedWithMultiMapping_Foo), 0, splitOn); var toBar = reader.GetRowParser<DiscriminatedWithMultiMapping_BaseType>(typeof(DiscriminatedWithMultiMapping_Bar), 0, splitOn); var toHaz = reader.GetRowParser<HazNameId>(typeof(HazNameId), splitOn, reader.FieldCount - splitOn); do { DiscriminatedWithMultiMapping_BaseType? obj = null; switch (reader.GetInt32(col)) { case 1: obj = toFoo(reader); break; case 2: obj = toBar(reader); break; } Assert.NotNull(obj); obj.HazNameIdObject = toHaz(reader); result.Add(obj); } while (reader.Read()); } } Assert.Equal(2, result.Count); Assert.Equal(1, result[0].Type); Assert.Equal(2, result[1].Type); var foo = (DiscriminatedWithMultiMapping_Foo)result[0]; Assert.Equal("abc", foo.Name); Assert.NotNull(foo.HazNameIdObject); Assert.Equal(1, foo.HazNameIdObject.Id); Assert.Equal("zxc", foo.HazNameIdObject.Name); var bar = (DiscriminatedWithMultiMapping_Bar)result[1]; Assert.Equal((float)4.0, bar.Value); Assert.NotNull(bar.HazNameIdObject); Assert.Equal(2, bar.HazNameIdObject.Id); Assert.Equal("qwe", bar.HazNameIdObject.Name); } private abstract class Discriminated_BaseType { public abstract int Type { get; } } private class Discriminated_Foo : Discriminated_BaseType { public string? Name { get; set; } public override int Type => 1; } private class Discriminated_Bar : Discriminated_BaseType { public float Value { get; set; } public override int Type => 2; } private abstract class DiscriminatedWithMultiMapping_BaseType : Discriminated_BaseType { public abstract HazNameId? HazNameIdObject { get; set; } } private class DiscriminatedWithMultiMapping_Foo : DiscriminatedWithMultiMapping_BaseType { public override HazNameId? HazNameIdObject { get; set; } public string? Name { get; set; } public override int Type => 1; } private class DiscriminatedWithMultiMapping_Bar : DiscriminatedWithMultiMapping_BaseType { public override HazNameId? HazNameIdObject { get; set; } public float Value { get; set; } public override int Type => 2; } } }
Dapper
You are an expert .NET (C#) developer. Task: Write a unit test for 'TargetModule' using XUnit and Moq. Context: - Class: TargetModule Requirements: Use Mock<T> interface mocking.
industrial
using System; namespace Dapper { /// <summary> /// Tell Dapper to use an explicit constructor, passing nulls or 0s for all parameters /// </summary> /// <remarks> /// Usage on methods is limited to the usage with Dapper.AOT (https://github.com/DapperLib/DapperAOT) /// </remarks> [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method, AllowMultiple = false)] public sealed class ExplicitConstructorAttribute : Attribute { } }
using System; using System.Linq; using Xunit; namespace Dapper.Tests { [Collection("ConstructorTests")] public sealed class SystemSqlClientConstructorTests : ConstructorTests<SystemSqlClientProvider> { } #if MSSQLCLIENT [Collection("ConstructorTests")] public sealed class MicrosoftSqlClientConstructorTests : ConstructorTests<MicrosoftSqlClientProvider> { } #endif public abstract class ConstructorTests<TProvider> : TestBase<TProvider> where TProvider : DatabaseProvider { [Fact] public void TestAbstractInheritance() { var order = connection.Query<AbstractInheritance.ConcreteOrder>("select 1 Internal,2 Protected,3 [Public],4 Concrete").First(); Assert.Equal(1, order.Internal); Assert.Equal(2, order.ProtectedVal); Assert.Equal(3, order.Public); Assert.Equal(4, order.Concrete); } [Fact] public void TestMultipleConstructors() { MultipleConstructors mult = connection.Query<MultipleConstructors>("select 0 A, 'Dapper' b").First(); Assert.Equal(0, mult.A); Assert.Equal("Dapper", mult.B); } [Fact] public void TestConstructorsWithAccessModifiers() { ConstructorsWithAccessModifiers value = connection.Query<ConstructorsWithAccessModifiers>("select 0 A, 'Dapper' b").First(); Assert.Equal(1, value.A); Assert.Equal("Dapper!", value.B); } [Fact] public void TestNoDefaultConstructor() { var guid = Guid.NewGuid(); NoDefaultConstructor nodef = connection.Query<NoDefaultConstructor>("select CAST(NULL AS integer) A1, CAST(NULL AS integer) b1, CAST(NULL AS real) f1, 'Dapper' s1, G1 = @id", new { id = guid }).First(); Assert.Equal(0, nodef.A); Assert.Null(nodef.B); Assert.Equal(0, nodef.F); Assert.Equal("Dapper", nodef.S); Assert.Equal(nodef.G, guid); } [Fact] public void TestNoDefaultConstructorWithChar() { const char c1 = 'ą'; const char c3 = 'ó'; NoDefaultConstructorWithChar nodef = connection.Query<NoDefaultConstructorWithChar>("select @c1 c1, @c2 c2, @c3 c3", new { c1 = c1, c2 = (char?)null, c3 = c3 }).First(); Assert.Equal(c1, nodef.Char1); Assert.Null(nodef.Char2); Assert.Equal(c3, nodef.Char3); } [Fact] public void TestNoDefaultConstructorWithEnum() { NoDefaultConstructorWithEnum nodef = connection.Query<NoDefaultConstructorWithEnum>("select cast(2 as smallint) E1, cast(5 as smallint) n1, cast(null as smallint) n2").First(); Assert.Equal(ShortEnum.Two, nodef.E); Assert.Equal(ShortEnum.Five, nodef.NE1); Assert.Null(nodef.NE2); } [Fact] public void ExplicitConstructors() { var rows = connection.Query<_ExplicitConstructors>(@" declare @ExplicitConstructors table ( Field INT NOT NULL PRIMARY KEY IDENTITY(1,1), Field_1 INT NOT NULL); insert @ExplicitConstructors(Field_1) values (1); SELECT * FROM @ExplicitConstructors" ).ToList(); Assert.Single(rows); Assert.Equal(1, rows[0].Field); Assert.Equal(1, rows[0].Field_1); Assert.True(rows[0].GetWentThroughProperConstructor()); } private class _ExplicitConstructors { public int Field { get; set; } public int Field_1 { get; set; } private readonly bool WentThroughProperConstructor; public _ExplicitConstructors() { /* yep */ } [ExplicitConstructor] public _ExplicitConstructors(string foo, int bar) { WentThroughProperConstructor = true; } public bool GetWentThroughProperConstructor() { return WentThroughProperConstructor; } } public static class AbstractInheritance { public abstract class Order { internal int Internal { get; set; } protected int Protected { get; set; } public int Public { get; set; } public int ProtectedVal => Protected; } public class ConcreteOrder : Order { public int Concrete { get; set; } } } private class MultipleConstructors { public MultipleConstructors() { B = default!; } public MultipleConstructors(int a, string b) { A = a + 1; B = b + "!"; } public int A { get; set; } public string B { get; set; } } private class ConstructorsWithAccessModifiers { private ConstructorsWithAccessModifiers() { } public ConstructorsWithAccessModifiers(int a, string b) { A = a + 1; B = b + "!"; } public int A { get; set; } public string? B { get; set; } } private class NoDefaultConstructor { public NoDefaultConstructor(int a1, int? b1, float f1, string s1, Guid G1) { A = a1; B = b1; F = f1; S = s1; G = G1; } public int A { get; set; } public int? B { get; set; } public float F { get; set; } public string S { get; set; } public Guid G { get; set; } } private class NoDefaultConstructorWithChar { public NoDefaultConstructorWithChar(char c1, char? c2, char? c3) { Char1 = c1; Char2 = c2; Char3 = c3; } public char Char1 { get; set; } public char? Char2 { get; set; } public char? Char3 { get; set; } } private class NoDefaultConstructorWithEnum { public NoDefaultConstructorWithEnum(ShortEnum e1, ShortEnum? n1, ShortEnum? n2) { E = e1; NE1 = n1; NE2 = n2; } public ShortEnum E { get; set; } public ShortEnum? NE1 { get; set; } public ShortEnum? NE2 { get; set; } } private class WithPrivateConstructor { public int Foo { get; set; } private WithPrivateConstructor() { } } [Fact] public void TestWithNonPublicConstructor() { var output = connection.Query<WithPrivateConstructor>("select 1 as Foo").First(); Assert.Equal(1, output.Foo); } [Fact] public void CtorWithUnderscores() { var obj = connection.QueryFirst<Type_ParamsWithUnderscores>("select 'abc' as FIRST_NAME, 'def' as LAST_NAME"); Assert.NotNull(obj); Assert.Equal("abc", obj.FirstName); Assert.Equal("def", obj.LastName); } [Fact] public void CtorWithoutUnderscores() { DefaultTypeMap.MatchNamesWithUnderscores = true; var obj = connection.QueryFirst<Type_ParamsWithoutUnderscores>("select 'abc' as FIRST_NAME, 'def' as LAST_NAME"); Assert.NotNull(obj); Assert.Equal("abc", obj.FirstName); Assert.Equal("def", obj.LastName); } [Fact] public void Issue1993_PreferPropertyOverField() // https://github.com/DapperLib/Dapper/issues/1993 { var oldValue = DefaultTypeMap.MatchNamesWithUnderscores; try { DefaultTypeMap.MatchNamesWithUnderscores = true; var map = new DefaultTypeMap(typeof(ShowIssue1993)); var first = map.GetMember("field_first"); Assert.NotNull(first); Assert.Null(first.Field); Assert.Equal(nameof(ShowIssue1993.FieldFirst), first.Property?.Name); var last = map.GetMember("field_last"); Assert.NotNull(last); Assert.Null(last.Field); Assert.Equal(nameof(ShowIssue1993.FieldLast), last.Property?.Name); } finally { DefaultTypeMap.MatchNamesWithUnderscores = oldValue; } } [Fact] public void Issue1993_Query() { var oldValue = DefaultTypeMap.MatchNamesWithUnderscores; try { DefaultTypeMap.MatchNamesWithUnderscores = true; var obj = connection.QueryFirst<ShowIssue1993>("select 'abc' as field_first, 'def' as field_last"); Assert.Equal("abc", obj.FieldFirst); Assert.Equal("def", obj.FieldLast); Assert.Equal("abc", obj.AltFieldFirst); Assert.Equal("def", obj.AltFieldLast); } finally { DefaultTypeMap.MatchNamesWithUnderscores = oldValue; } } public class ShowIssue1993 { private string _fieldFirst { get; set; } = null!; // not actually a field public string FieldFirst { get => _fieldFirst; set => _fieldFirst = AltFieldFirst = value; } public string FieldLast { get => _fieldLast; set => _fieldLast = AltFieldLast = value; } private string _fieldLast { get; set; } = null!;// not actually a field public string AltFieldFirst { get; set; } = null!; public string AltFieldLast { get; set; } = null!; } class Type_ParamsWithUnderscores { public string FirstName { get; } public string LastName { get; } public Type_ParamsWithUnderscores(string first_name, string last_name) { FirstName = first_name; LastName = last_name; } } class Type_ParamsWithoutUnderscores { public string FirstName { get; } public string LastName { get; } public Type_ParamsWithoutUnderscores(string firstName, string lastName) { FirstName = firstName; LastName = lastName; } } } }
Dapper
You are an expert .NET (C#) developer. Task: Write a unit test for 'TargetModule' using XUnit and Moq. Context: - Class: TargetModule Requirements: Use Mock<T> interface mocking.
industrial
using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text.RegularExpressions; namespace Dapper { public class SqlBuilder { private readonly Dictionary<string, Clauses> _data = new Dictionary<string, Clauses>(); private int _seq; private class Clause { public Clause(string sql, object? parameters, bool isInclusive) { Sql = sql; Parameters = parameters; IsInclusive = isInclusive; } public string Sql { get; } public object? Parameters { get; } public bool IsInclusive { get; } } private class Clauses : List<Clause> { private readonly string _joiner, _prefix, _postfix; public Clauses(string joiner, string prefix = "", string postfix = "") { _joiner = joiner; _prefix = prefix; _postfix = postfix; } public string ResolveClauses(DynamicParameters p) { foreach (var item in this) { p.AddDynamicParams(item.Parameters); } return this.Any(a => a.IsInclusive) ? _prefix + string.Join(_joiner, this.Where(a => !a.IsInclusive) .Select(c => c.Sql) .Union(new[] { " ( " + string.Join(" OR ", this.Where(a => a.IsInclusive).Select(c => c.Sql).ToArray()) + " ) " }).ToArray()) + _postfix : _prefix + string.Join(_joiner, this.Select(c => c.Sql).ToArray()) + _postfix; } } public class Template { private readonly string _sql; private readonly SqlBuilder _builder; private readonly object? _initParams; private int _dataSeq = -1; // Unresolved public Template(SqlBuilder builder, string sql, dynamic? parameters) { _initParams = parameters; _sql = sql; _builder = builder; } private static readonly Regex _regex = new Regex(@"\/\*\*.+?\*\*\/", RegexOptions.Compiled | RegexOptions.Multiline); private void ResolveSql() { if (_dataSeq != _builder._seq) { var p = new DynamicParameters(_initParams); rawSql = _sql; foreach (var pair in _builder._data) { rawSql = rawSql.Replace("/**" + pair.Key + "**/", pair.Value.ResolveClauses(p)); } parameters = p; // replace all that is left with empty rawSql = _regex.Replace(rawSql, ""); _dataSeq = _builder._seq; } } private string? rawSql; private object? parameters; public string RawSql { get { ResolveSql(); return rawSql!; } } public object? Parameters { get { ResolveSql(); return parameters; } } } public Template AddTemplate(string sql, dynamic? parameters = null) => new Template(this, sql, (object?)parameters); protected SqlBuilder AddClause(string name, string sql, object? parameters, string joiner, string prefix = "", string postfix = "", bool isInclusive = false) { if (!_data.TryGetValue(name, out var clauses)) { clauses = new Clauses(joiner, prefix, postfix); _data[name] = clauses; } clauses.Add(new Clause(sql, parameters, isInclusive)); _seq++; return this; } public SqlBuilder Intersect(string sql, dynamic? parameters = null) => AddClause("intersect", sql, (object?)parameters, "\nINTERSECT\n ", "\n ", "\n", false); public SqlBuilder InnerJoin(string sql, dynamic? parameters = null) => AddClause("innerjoin", sql, (object?)parameters, "\nINNER JOIN ", "\nINNER JOIN ", "\n", false); public SqlBuilder LeftJoin(string sql, dynamic? parameters = null) => AddClause("leftjoin", sql, (object?)parameters, "\nLEFT JOIN ", "\nLEFT JOIN ", "\n", false); public SqlBuilder RightJoin(string sql, dynamic? parameters = null) => AddClause("rightjoin", sql, (object?)parameters, "\nRIGHT JOIN ", "\nRIGHT JOIN ", "\n", false); public SqlBuilder Where(string sql, dynamic? parameters = null) => AddClause("where", sql, (object?)parameters, " AND ", "WHERE ", "\n", false); public SqlBuilder OrWhere(string sql, dynamic? parameters = null) => AddClause("where", sql, (object?)parameters, " OR ", "WHERE ", "\n", true); public SqlBuilder OrderBy(string sql, dynamic? parameters = null) => AddClause("orderby", sql, (object?)parameters, " , ", "ORDER BY ", "\n", false); public SqlBuilder Select(string sql, dynamic? parameters = null) => AddClause("select", sql, (object?)parameters, " , ", "", "\n", false); public SqlBuilder AddParameters(dynamic parameters) => AddClause("--parameters", "", (object?)parameters, "", "", "", false); public SqlBuilder Join(string sql, dynamic? parameters = null) => AddClause("join", sql, (object?)parameters, "\nJOIN ", "\nJOIN ", "\n", false); public SqlBuilder GroupBy(string sql, dynamic? parameters = null) => AddClause("groupby", sql, (object?)parameters, " , ", "\nGROUP BY ", "\n", false); public SqlBuilder Having(string sql, dynamic? parameters = null) => AddClause("having", sql, (object?)parameters, "\nAND ", "HAVING ", "\n", false); public SqlBuilder Set(string sql, dynamic? parameters = null) => AddClause("set", sql, (object?)parameters, " , ", "SET ", "\n", false); } }
using System; using System.Linq; using Xunit; namespace Dapper.Tests { [Collection("SqlBuilderTests")] public sealed class SystemSqlClientSqlBuilderTests : SqlBuilderTests<SystemSqlClientProvider> { } #if MSSQLCLIENT [Collection("SqlBuilderTests")] public sealed class MicrosoftSqlClientSqlBuilderTests : SqlBuilderTests<MicrosoftSqlClientProvider> { } #endif public abstract class SqlBuilderTests<TProvider> : TestBase<TProvider> where TProvider : DatabaseProvider { [Fact] public void TestSqlBuilderWithDapperQuery() { var sb = new SqlBuilder(); var template = sb.AddTemplate("SELECT /**select**/ FROM #Users /**where**/"); sb.Where("Age <= @Age", new { Age = 18 }) .Where("Country = @Country", new { Country = "USA" }) .Select("Name,Age,Country"); const string createSql = @" create table #Users (Name varchar(20),Age int,Country nvarchar(5)); insert #Users values('Sam',16,'USA'),('Tom',25,'UK'),('Henry',14,'UK')"; try { connection.Execute(createSql); var result = connection.Query(template.RawSql,template.Parameters).ToArray(); Assert.Equal("SELECT Name,Age,Country\n FROM #Users WHERE Age <= @Age AND Country = @Country\n", template.RawSql); Assert.Single(result); Assert.Equal(16, (int)result[0].Age); Assert.Equal("Sam", (string)result[0].Name); Assert.Equal("USA", (string)result[0].Country); } finally { connection.Execute("drop table #Users"); } } [Fact] public void TestSqlBuilderUpdateSet() { var id = 1; var vip = true; var updatetime = DateTime.Parse("2020/01/01"); var sb = new SqlBuilder() .Set("Vip = @vip", new { vip }) .Set("Updatetime = @updatetime", new { updatetime }) .Where("Id = @id", new { id }) ; var template = sb.AddTemplate("update #Users /**set**/ /**where**/"); const string createSql = @" create table #Users (Id int,Name varchar(20),Age int,Country nvarchar(5),Vip bit,Updatetime datetime); insert #Users (Id,Name,Age,Country) values(1,'Sam',16,'USA'),(2,'Tom',25,'UK'),(3,'Henry',14,'UK')"; try { connection.Execute(createSql); var effectCount = connection.Execute(template.RawSql, template.Parameters); var result = connection.QueryFirst("select * from #Users where Id = 1"); Assert.Equal("update #Users SET Vip = @vip , Updatetime = @updatetime\n WHERE Id = @id\n", template.RawSql); Assert.True((bool)result.Vip); Assert.Equal(updatetime, (DateTime)result.Updatetime); } finally { connection.Execute("drop table #Users"); } } } }
Dapper
You are an expert .NET (C#) developer. Task: Write a unit test for 'TargetModule' using XUnit and Moq. Context: - Class: TargetModule Requirements: Use Mock<T> interface mocking.
industrial
using System; using System.Collections.Generic; namespace Dapper { public static partial class SqlMapper { /// <summary> /// Represents a placeholder for a value that should be replaced as a literal value in the resulting sql /// </summary> internal readonly struct LiteralToken { /// <summary> /// The text in the original command that should be replaced /// </summary> public string Token { get; } /// <summary> /// The name of the member referred to by the token /// </summary> public string Member { get; } internal LiteralToken(string token, string member) { Token = token; Member = member; } internal static IList<LiteralToken> None => Array.Empty<LiteralToken>(); } } }
using System.Linq; using Xunit; namespace Dapper.Tests { [Collection("LiteralTests")] public sealed class SystemSqlClientLiteralTests : LiteralTests<SystemSqlClientProvider> { } #if MSSQLCLIENT [Collection("LiteralTests")] public sealed class MicrosoftSqlClientLiteralTests : LiteralTests<MicrosoftSqlClientProvider> { } #endif public abstract class LiteralTests<TProvider> : TestBase<TProvider> where TProvider : DatabaseProvider { [Fact] public void LiteralReplacementEnumAndString() { var args = new { x = AnEnum.B, y = 123.45M, z = AnotherEnum.A }; var row = connection.Query("select {=x} as x,{=y} as y,cast({=z} as tinyint) as z", args).Single(); AnEnum x = (AnEnum)(int)row.x; decimal y = row.y; AnotherEnum z = (AnotherEnum)(byte)row.z; Assert.Equal(AnEnum.B, x); Assert.Equal(123.45M, y); Assert.Equal(AnotherEnum.A, z); } [Fact] public void LiteralReplacementDynamicEnumAndString() { var args = new DynamicParameters(); args.Add("x", AnEnum.B); args.Add("y", 123.45M); args.Add("z", AnotherEnum.A); var row = connection.Query("select {=x} as x,{=y} as y,cast({=z} as tinyint) as z", args).Single(); AnEnum x = (AnEnum)(int)row.x; decimal y = row.y; AnotherEnum z = (AnotherEnum)(byte)row.z; Assert.Equal(AnEnum.B, x); Assert.Equal(123.45M, y); Assert.Equal(AnotherEnum.A, z); } [Fact] public void LiteralReplacementBoolean() { var row = connection.Query<int?>("select 42 where 1 = {=val}", new { val = true }).SingleOrDefault(); Assert.NotNull(row); Assert.Equal(42, row); row = connection.Query<int?>("select 42 where 1 = {=val}", new { val = false }).SingleOrDefault(); Assert.Null(row); } [Fact] public void LiteralReplacementWithIn() { var data = connection.Query<MyRow>("select @x where 1 in @ids and 1 ={=a}", new { x = 1, ids = new[] { 1, 2, 3 }, a = 1 }).ToList(); } private class MyRow { public int x { get; set; } } [Fact] public void LiteralIn() { connection.Execute("create table #literalin(id int not null);"); connection.Execute("insert #literalin (id) values (@id)", new[] { new { id = 1 }, new { id = 2 }, new { id = 3 }, }); var count = connection.Query<int>("select count(1) from #literalin where id in {=ids}", new { ids = new[] { 1, 3, 4 } }).Single(); Assert.Equal(2, count); } [Fact] public void LiteralReplacement() { connection.Execute("create table #literal1 (id int not null, foo int not null)"); connection.Execute("insert #literal1 (id,foo) values ({=id}, @foo)", new { id = 123, foo = 456 }); var rows = new[] { new { id = 1, foo = 2 }, new { id = 3, foo = 4 } }; connection.Execute("insert #literal1 (id,foo) values ({=id}, @foo)", rows); var count = connection.Query<int>("select count(1) from #literal1 where id={=foo}", new { foo = 123 }).Single(); Assert.Equal(1, count); int sum = connection.Query<int>("select sum(id) + sum(foo) from #literal1").Single(); Assert.Equal(123 + 456 + 1 + 2 + 3 + 4, sum); } [Fact] public void LiteralReplacementDynamic() { var args = new DynamicParameters(); args.Add("id", 123); connection.Execute("create table #literal2 (id int not null)"); connection.Execute("insert #literal2 (id) values ({=id})", args); args = new DynamicParameters(); args.Add("foo", 123); var count = connection.Query<int>("select count(1) from #literal2 where id={=foo}", args).Single(); Assert.Equal(1, count); } } }
Dapper
You are an expert .NET (C#) developer. Task: Write a unit test for 'TargetModule' using XUnit and Moq. Context: - Class: TargetModule Requirements: Use Mock<T> interface mocking.
industrial
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Dapper { public abstract partial class Database<TDatabase> where TDatabase : Database<TDatabase>, new() { public partial class Table<T, TId> { /// <summary> /// Insert a row into the db asynchronously. /// </summary> /// <param name="data">Either DynamicParameters or an anonymous type or concrete type.</param> /// <returns>The Id of the inserted row.</returns> public virtual async Task<int?> InsertAsync(dynamic data) { var o = (object)data; List<string> paramNames = GetParamNames(o); paramNames.Remove("Id"); string cols = string.Join(",", paramNames); string colsParams = string.Join(",", paramNames.Select(p => "@" + p)); var sql = "set nocount on insert " + TableName + " (" + cols + ") values (" + colsParams + ") select cast(scope_identity() as int)"; return (await database.QueryAsync<int?>(sql, o).ConfigureAwait(false)).Single(); } /// <summary> /// Update a record in the DB asynchronously. /// </summary> /// <param name="id">The Id of the record to update.</param> /// <param name="data">The new record.</param> /// <returns>The number of affected rows.</returns> public Task<int> UpdateAsync(TId id, dynamic data) { List<string> paramNames = GetParamNames((object)data); var builder = new StringBuilder(); builder.Append("update ").Append(TableName).Append(" set "); builder.AppendLine(string.Join(",", paramNames.Where(n => n != "Id").Select(p => p + "= @" + p))); builder.Append("where Id = @Id"); var parameters = new DynamicParameters(data); parameters.Add("Id", id); return database.ExecuteAsync(builder.ToString(), parameters); } /// <summary> /// Asynchronously deletes a record for the DB. /// </summary> /// <param name="id">The Id of the record to delete.</param> /// <returns>The number of rows affected.</returns> public async Task<bool> DeleteAsync(TId id) => (await database.ExecuteAsync("delete from " + TableName + " where Id = @id", new { id }).ConfigureAwait(false)) > 0; /// <summary> /// Asynchronously gets a record with a particular Id from the DB. /// </summary> /// <param name="id">The primary key of the table to fetch.</param> /// <returns>The record with the specified Id.</returns> public Task<T> GetAsync(TId id) => database.QueryFirstOrDefaultAsync<T>("select * from " + TableName + " where Id = @id", new { id }); /// <summary> /// Asynchronously gets the first row from this table (order determined by the database provider). /// </summary> /// <returns>Data from the first table row.</returns> public virtual Task<T> FirstAsync() => database.QueryFirstOrDefaultAsync<T>("select top 1 * from " + TableName); /// <summary> /// Asynchronously gets the all rows from this table. /// </summary> /// <returns>Data from all table rows.</returns> public Task<IEnumerable<T>> AllAsync() => database.QueryAsync<T>("select * from " + TableName); } /// <summary> /// Asynchronously executes SQL against the current database. /// </summary> /// <param name="sql">The SQL to execute.</param> /// <param name="param">The parameters to use.</param> /// <returns>The number of rows affected.</returns> public Task<int> ExecuteAsync(string sql, dynamic param = null) => _connection.ExecuteAsync(sql, param as object, Transaction, _commandTimeout); /// <summary> /// Asynchronously queries the current database. /// </summary> /// <typeparam name="T">The type to return.</typeparam> /// <param name="sql">The SQL to execute.</param> /// <param name="param">The parameters to use.</param> /// <returns>An enumerable of <typeparamref name="T"/> for the rows fetched.</returns> public Task<IEnumerable<T>> QueryAsync<T>(string sql, dynamic param = null) => _connection.QueryAsync<T>(sql, param as object, Transaction, _commandTimeout); /// <summary> /// Asynchronously queries the current database for a single record. /// </summary> /// <typeparam name="T">The type to return.</typeparam> /// <param name="sql">The SQL to execute.</param> /// <param name="param">The parameters to use.</param> /// <returns>An enumerable of <typeparamref name="T"/> for the rows fetched.</returns> public Task<T> QueryFirstOrDefaultAsync<T>(string sql, dynamic param = null) => _connection.QueryFirstOrDefaultAsync<T>(sql, param as object, Transaction, _commandTimeout); /// <summary> /// Perform an asynchronous multi-mapping query with 2 input types. /// This returns a single type, combined from the raw types via <paramref name="map"/>. /// </summary> /// <typeparam name="TFirst">The first type in the recordset.</typeparam> /// <typeparam name="TSecond">The second type in the recordset.</typeparam> /// <typeparam name="TReturn">The combined type to return.</typeparam> /// <param name="sql">The SQL to execute for this query.</param> /// <param name="map">The function to map row types to the return type.</param> /// <param name="param">The parameters to use for this query.</param> /// <param name="transaction">The transaction to use for this query.</param> /// <param name="buffered">Whether to buffer the results in memory.</param> /// <param name="splitOn">The field we should split and read the second object from (default: "Id").</param> /// <param name="commandTimeout">Number of seconds before command execution timeout.</param> /// <returns>An enumerable of <typeparamref name="TReturn"/>.</returns> public Task<IEnumerable<TReturn>> QueryAsync<TFirst, TSecond, TReturn>(string sql, Func<TFirst, TSecond, TReturn> map, dynamic param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null) => _connection.QueryAsync(sql, map, param as object, transaction, buffered, splitOn, commandTimeout); /// <summary> /// Perform an asynchronous multi-mapping query with 3 input types. /// This returns a single type, combined from the raw types via <paramref name="map"/>. /// </summary> /// <typeparam name="TFirst">The first type in the recordset.</typeparam> /// <typeparam name="TSecond">The second type in the recordset.</typeparam> /// <typeparam name="TThird">The third type in the recordset.</typeparam> /// <typeparam name="TReturn">The combined type to return.</typeparam> /// <param name="sql">The SQL to execute for this query.</param> /// <param name="map">The function to map row types to the return type.</param> /// <param name="param">The parameters to use for this query.</param> /// <param name="transaction">The transaction to use for this query.</param> /// <param name="buffered">Whether to buffer the results in memory.</param> /// <param name="splitOn">The field we should split and read the second object from (default: "Id").</param> /// <param name="commandTimeout">Number of seconds before command execution timeout.</param> /// <returns>An enumerable of <typeparamref name="TReturn"/>.</returns> public Task<IEnumerable<TReturn>> QueryAsync<TFirst, TSecond, TThird, TReturn>(string sql, Func<TFirst, TSecond, TThird, TReturn> map, dynamic param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null) => _connection.QueryAsync(sql, map, param as object, transaction, buffered, splitOn, commandTimeout); /// <summary> /// Perform an asynchronous multi-mapping query with 4 input types. /// This returns a single type, combined from the raw types via <paramref name="map"/>. /// </summary> /// <typeparam name="TFirst">The first type in the recordset.</typeparam> /// <typeparam name="TSecond">The second type in the recordset.</typeparam> /// <typeparam name="TThird">The third type in the recordset.</typeparam> /// <typeparam name="TFourth">The fourth type in the recordset.</typeparam> /// <typeparam name="TReturn">The combined type to return.</typeparam> /// <param name="sql">The SQL to execute for this query.</param> /// <param name="map">The function to map row types to the return type.</param> /// <param name="param">The parameters to use for this query.</param> /// <param name="transaction">The transaction to use for this query.</param> /// <param name="buffered">Whether to buffer the results in memory.</param> /// <param name="splitOn">The field we should split and read the second object from (default: "Id").</param> /// <param name="commandTimeout">Number of seconds before command execution timeout.</param> /// <returns>An enumerable of <typeparamref name="TReturn"/>.</returns> public Task<IEnumerable<TReturn>> QueryAsync<TFirst, TSecond, TThird, TFourth, TReturn>(string sql, Func<TFirst, TSecond, TThird, TFourth, TReturn> map, dynamic param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null) => _connection.QueryAsync(sql, map, param as object, transaction, buffered, splitOn, commandTimeout); /// <summary> /// Perform an asynchronous multi-mapping query with 5 input types. /// This returns a single type, combined from the raw types via <paramref name="map"/>. /// </summary> /// <typeparam name="TFirst">The first type in the recordset.</typeparam> /// <typeparam name="TSecond">The second type in the recordset.</typeparam> /// <typeparam name="TThird">The third type in the recordset.</typeparam> /// <typeparam name="TFourth">The fourth type in the recordset.</typeparam> /// <typeparam name="TFifth">The fifth type in the recordset.</typeparam> /// <typeparam name="TReturn">The combined type to return.</typeparam> /// <param name="sql">The SQL to execute for this query.</param> /// <param name="map">The function to map row types to the return type.</param> /// <param name="param">The parameters to use for this query.</param> /// <param name="transaction">The transaction to use for this query.</param> /// <param name="buffered">Whether to buffer the results in memory.</param> /// <param name="splitOn">The field we should split and read the second object from (default: "Id").</param> /// <param name="commandTimeout">Number of seconds before command execution timeout.</param> /// <returns>An enumerable of <typeparamref name="TReturn"/>.</returns> public Task<IEnumerable<TReturn>> QueryAsync<TFirst, TSecond, TThird, TFourth, TFifth, TReturn>(string sql, Func<TFirst, TSecond, TThird, TFourth, TFifth, TReturn> map, dynamic param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null) => _connection.QueryAsync(sql, map, param as object, transaction, buffered, splitOn, commandTimeout); /// <summary> /// Execute a query asynchronously using Task. /// </summary> /// <param name="sql">The SQL to execute.</param> /// <param name="param">The parameters to use.</param> /// <remarks>Note: each row can be accessed via "dynamic", or by casting to an IDictionary&lt;string,object&gt;</remarks> public Task<IEnumerable<dynamic>> QueryAsync(string sql, dynamic param = null) => _connection.QueryAsync(sql, param as object, Transaction); /// <summary> /// Execute a command that returns multiple result sets, and access each in turn. /// </summary> /// <param name="sql">The SQL to execute for this query.</param> /// <param name="param">The parameters to use for this query.</param> /// <param name="transaction">The transaction to use for this query.</param> /// <param name="commandTimeout">Number of seconds before command execution timeout.</param> /// <param name="commandType">Is it a stored proc or a batch?</param> public Task<SqlMapper.GridReader> QueryMultipleAsync(string sql, dynamic param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null) => SqlMapper.QueryMultipleAsync(_connection, sql, param, transaction, commandTimeout, commandType); } }
using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace Dapper.Tests { [Collection(NonParallelDefinition.Name)] public sealed class SystemSqlClientAsyncTests : AsyncTests<SystemSqlClientProvider> { } #if MSSQLCLIENT [Collection(NonParallelDefinition.Name)] public sealed class MicrosoftSqlClientAsyncTests : AsyncTests<MicrosoftSqlClientProvider> { } #endif [Collection(NonParallelDefinition.Name)] public sealed class SystemSqlClientAsyncQueryCacheTests : AsyncQueryCacheTests<SystemSqlClientProvider> { public SystemSqlClientAsyncQueryCacheTests(ITestOutputHelper log) : base(log) { } } #if MSSQLCLIENT [Collection(NonParallelDefinition.Name)] public sealed class MicrosoftSqlClientAsyncQueryCacheTests : AsyncQueryCacheTests<MicrosoftSqlClientProvider> { public MicrosoftSqlClientAsyncQueryCacheTests(ITestOutputHelper log) : base(log) { } } #endif public abstract class AsyncTests<TProvider> : TestBase<TProvider> where TProvider : SqlServerDatabaseProvider { private DbConnection? _marsConnection; private DbConnection MarsConnection => _marsConnection ??= Provider.GetOpenConnection(true); [Fact] public async Task TestBasicStringUsageAsync() { var query = await connection.QueryAsync<string>("select 'abc' as [Value] union all select @txt", new { txt = "def" }).ConfigureAwait(false); var arr = query.ToArray(); Assert.Equal(new[] { "abc", "def" }, arr); } [Fact] public async Task TestBasicStringUsageUnbufferedDynamicAsync() { var results = new List<string>(); await foreach (var row in connection.QueryUnbufferedAsync("select 'abc' as [Value] union all select @txt", new { txt = "def" }) .ConfigureAwait(false)) { string value = row.Value; results.Add(value); } var arr = results.ToArray(); Assert.Equal(new[] { "abc", "def" }, arr); } [Fact] public async Task TestBasicStringUsageUnbufferedAsync() { var results = new List<string>(); await foreach (var value in connection.QueryUnbufferedAsync<string>("select 'abc' as [Value] union all select @txt", new { txt = "def" }) .ConfigureAwait(false)) { results.Add(value); } var arr = results.ToArray(); Assert.Equal(new[] { "abc", "def" }, arr); } [Fact] public async Task TestBasicStringUsageUnbufferedAsync_Cancellation() { using var cts = new CancellationTokenSource(); var results = new List<string>(); await Assert.ThrowsAnyAsync<OperationCanceledException>(async () => { await foreach (var value in connection.QueryUnbufferedAsync<string>("select 'abc' as [Value] union all select @txt", new { txt = "def" }) .ConfigureAwait(false).WithCancellation(cts.Token)) { results.Add(value); cts.Cancel(); // cancel after first item } }); var arr = results.ToArray(); Assert.Equal(new[] { "abc" }, arr); // we don't expect the "def" because of the cancellation } [Fact] public async Task TestBasicStringUsageViaGridReaderUnbufferedAsync() { var results = new List<string>(); await using (var grid = await connection.QueryMultipleAsync("select 'abc' union select 'def'; select @txt", new { txt = "ghi" }) .ConfigureAwait(false)) { while (!grid.IsConsumed) { await foreach (var value in grid.ReadUnbufferedAsync<string>() .ConfigureAwait(false)) { results.Add(value); } } } var arr = results.ToArray(); Assert.Equal(new[] { "abc", "def", "ghi" }, arr); } [Fact] public async Task TestBasicStringUsageViaGridReaderUnbufferedDynamicAsync() { var results = new List<string>(); await using (var grid = await connection.QueryMultipleAsync("select 'abc' as [Foo] union select 'def'; select @txt as [Foo]", new { txt = "ghi" }) .ConfigureAwait(false)) { while (!grid.IsConsumed) { await foreach (var value in grid.ReadUnbufferedAsync() .ConfigureAwait(false)) { results.Add((string)value.Foo); } } } var arr = results.ToArray(); Assert.Equal(new[] { "abc", "def", "ghi" }, arr); } [Fact] public async Task TestBasicStringUsageViaGridReaderUnbufferedAsync_Cancellation() { using var cts = new CancellationTokenSource(); var results = new List<string>(); await using (var grid = await connection.QueryMultipleAsync("select 'abc' union select 'def'; select @txt", new { txt = "ghi" }) .ConfigureAwait(false)) { var ex = await Assert.ThrowsAnyAsync<Exception>(async () => { while (!grid.IsConsumed) { await foreach (var value in grid.ReadUnbufferedAsync<string>() .ConfigureAwait(false) .WithCancellation(cts.Token)) { results.Add(value); } cts.Cancel(); } }); Assert.True(ex is OperationCanceledException or DbException { Message: "Operation cancelled by user." }); } var arr = results.ToArray(); Assert.Equal(new[] { "abc", "def" }, arr); // don't expect the ghi because of cancellation } [Fact] public async Task TestBasicStringUsageQueryFirstAsync() { var str = await connection.QueryFirstAsync<string>(new CommandDefinition("select 'abc' as [Value] union all select @txt", new { txt = "def" })).ConfigureAwait(false); Assert.Equal("abc", str); } [Fact] public async Task TestBasicStringUsageQueryFirstAsyncDynamic() { var str = await connection.QueryFirstAsync("select 'abc' as [Value] union all select @txt", new { txt = "def" }).ConfigureAwait(false); Assert.Equal("abc", str.Value); } [Fact] public async Task TestBasicStringUsageQueryFirstOrDefaultAsync() { var str = await connection.QueryFirstOrDefaultAsync<string>(new CommandDefinition("select null as [Value] union all select @txt", new { txt = "def" })).ConfigureAwait(false); Assert.Null(str); } [Fact] public async Task TestBasicStringUsageQueryFirstOrDefaultAsyncDynamic() { var str = await connection.QueryFirstOrDefaultAsync("select null as [Value] union all select @txt", new { txt = "def" }).ConfigureAwait(false); Assert.Null(str!.Value); } [Fact] public async Task TestBasicStringUsageQuerySingleAsyncDynamic() { var str = await connection.QuerySingleAsync<string>(new CommandDefinition("select 'abc' as [Value]")).ConfigureAwait(false); Assert.Equal("abc", str); } [Fact] public async Task TestBasicStringUsageQuerySingleAsync() { var str = await connection.QuerySingleAsync("select 'abc' as [Value]").ConfigureAwait(false); Assert.Equal("abc", str.Value); } [Fact] public async Task TestBasicStringUsageQuerySingleOrDefaultAsync() { var str = await connection.QuerySingleOrDefaultAsync<string>(new CommandDefinition("select null as [Value]")).ConfigureAwait(false); Assert.Null(str); } [Fact] public async Task TestBasicStringUsageQuerySingleOrDefaultAsyncDynamic() { var str = (await connection.QuerySingleOrDefaultAsync("select null as [Value]").ConfigureAwait(false))!; Assert.Null(str.Value); } [Fact] public async Task TestBasicStringUsageAsyncNonBuffered() { var query = await connection.QueryAsync<string>(new CommandDefinition("select 'abc' as [Value] union all select @txt", new { txt = "def" }, flags: CommandFlags.None)).ConfigureAwait(false); var arr = query.ToArray(); Assert.Equal(new[] { "abc", "def" }, arr); } [Fact] public void TestLongOperationWithCancellation() { CancellationTokenSource cancel = new(TimeSpan.FromSeconds(5)); var task = connection.QueryAsync<int>(new CommandDefinition("waitfor delay '00:00:10';select 1", cancellationToken: cancel.Token)); try { if (!task.Wait(TimeSpan.FromSeconds(7))) { throw new TimeoutException(); // should have cancelled } } catch (AggregateException agg) { Assert.Equal("SqlException", agg.InnerException?.GetType().Name); } } [Fact] public async Task TestBasicStringUsageClosedAsync() { using var conn = GetClosedConnection(); var query = await conn.QueryAsync<string>("select 'abc' as [Value] union all select @txt", new { txt = "def" }).ConfigureAwait(false); var arr = query.ToArray(); Assert.Equal(new[] { "abc", "def" }, arr); } [Fact] public async Task TestQueryDynamicAsync() { var row = (await connection.QueryAsync("select 'abc' as [Value]").ConfigureAwait(false)).Single(); string value = row.Value; Assert.Equal("abc", value); } [Fact] public async Task TestClassWithStringUsageAsync() { var query = await connection.QueryAsync<BasicType>("select 'abc' as [Value] union all select @txt", new { txt = "def" }).ConfigureAwait(false); var arr = query.ToArray(); Assert.Equal(new[] { "abc", "def" }, arr.Select(x => x.Value)); } [Fact] public async Task TestExecuteAsync() { var val = await connection.ExecuteAsync("declare @foo table(id int not null); insert @foo values(@id);", new { id = 1 }).ConfigureAwait(false); Assert.Equal(1, val); } [Fact] public void TestExecuteClosedConnAsyncInner() { using var conn = GetClosedConnection(); var query = conn.ExecuteAsync("declare @foo table(id int not null); insert @foo values(@id);", new { id = 1 }); var val = query.Result; Assert.Equal(1, val); } [Fact] public async Task TestMultiMapWithSplitAsync() { const string sql = "select 1 as id, 'abc' as name, 2 as id, 'def' as name"; var productQuery = await connection.QueryAsync<Product, Category, Product>(sql, (prod, cat) => { prod.Category = cat; return prod; }).ConfigureAwait(false); var product = productQuery.First(); // assertions Assert.Equal(1, product.Id); Assert.Equal("abc", product.Name); Assert.NotNull(product.Category); Assert.Equal(2, product.Category.Id); Assert.Equal("def", product.Category.Name); } [Fact] public async Task TestMultiMapArbitraryWithSplitAsync() { const string sql = "select 1 as id, 'abc' as name, 2 as id, 'def' as name"; var productQuery = await connection.QueryAsync<Product>(sql, new[] { typeof(Product), typeof(Category) }, (objects) => { var prod = (Product)objects[0]; prod.Category = (Category)objects[1]; return prod; }).ConfigureAwait(false); var product = productQuery.First(); // assertions Assert.Equal(1, product.Id); Assert.Equal("abc", product.Name); Assert.NotNull(product.Category); Assert.Equal(2, product.Category.Id); Assert.Equal("def", product.Category.Name); } [Fact] public async Task TestMultiMapWithSplitClosedConnAsync() { const string sql = "select 1 as id, 'abc' as name, 2 as id, 'def' as name"; using var conn = GetClosedConnection(); var productQuery = await conn.QueryAsync<Product, Category, Product>(sql, (prod, cat) => { prod.Category = cat; return prod; }).ConfigureAwait(false); var product = productQuery.First(); // assertions Assert.Equal(1, product.Id); Assert.Equal("abc", product.Name); Assert.NotNull(product.Category); Assert.Equal(2, product.Category.Id); Assert.Equal("def", product.Category.Name); } [Fact] public async Task TestMultiAsync() { using SqlMapper.GridReader multi = await connection.QueryMultipleAsync("select 1; select 2").ConfigureAwait(false); Assert.Equal(1, multi.ReadAsync<int>().Result.Single()); Assert.Equal(2, multi.ReadAsync<int>().Result.Single()); } [Fact] public async Task TestMultiConversionAsync() { using SqlMapper.GridReader multi = await connection.QueryMultipleAsync("select Cast(1 as BigInt) Col1; select Cast(2 as BigInt) Col2").ConfigureAwait(false); Assert.Equal(1, multi.ReadAsync<int>().Result.Single()); Assert.Equal(2, multi.ReadAsync<int>().Result.Single()); } [Fact] public async Task TestMultiAsyncViaFirstOrDefault() { using SqlMapper.GridReader multi = await connection.QueryMultipleAsync("select 1; select 2; select 3; select 4; select 5").ConfigureAwait(false); Assert.Equal(1, multi.ReadFirstOrDefaultAsync<int>().Result); Assert.Equal(2, multi.ReadAsync<int>().Result.Single()); Assert.Equal(3, multi.ReadFirstOrDefaultAsync<int>().Result); Assert.Equal(4, multi.ReadAsync<int>().Result.Single()); Assert.Equal(5, multi.ReadFirstOrDefaultAsync<int>().Result); } [Fact] public async Task TestMultiClosedConnAsync() { using var conn = GetClosedConnection(); using SqlMapper.GridReader multi = await conn.QueryMultipleAsync("select 1; select 2").ConfigureAwait(false); Assert.Equal(1, multi.ReadAsync<int>().Result.Single()); Assert.Equal(2, multi.ReadAsync<int>().Result.Single()); } [Fact] public async Task TestMultiClosedConnAsyncViaFirstOrDefault() { using var conn = GetClosedConnection(); using SqlMapper.GridReader multi = await conn.QueryMultipleAsync("select 1; select 2; select 3; select 4; select 5").ConfigureAwait(false); Assert.Equal(1, multi.ReadFirstOrDefaultAsync<int>().Result); Assert.Equal(2, multi.ReadAsync<int>().Result.Single()); Assert.Equal(3, multi.ReadFirstOrDefaultAsync<int>().Result); Assert.Equal(4, multi.ReadAsync<int>().Result.Single()); Assert.Equal(5, multi.ReadFirstOrDefaultAsync<int>().Result); } [Fact] public async Task ExecuteReaderOpenAsync() { var dt = new DataTable(); dt.Load(await connection.ExecuteReaderAsync("select 3 as [three], 4 as [four]").ConfigureAwait(false)); Assert.Equal(2, dt.Columns.Count); Assert.Equal("three", dt.Columns[0].ColumnName); Assert.Equal("four", dt.Columns[1].ColumnName); Assert.Equal(1, dt.Rows.Count); Assert.Equal(3, (int)dt.Rows[0][0]); Assert.Equal(4, (int)dt.Rows[0][1]); } [Fact] public async Task ExecuteReaderClosedAsync() { using var conn = GetClosedConnection(); var dt = new DataTable(); dt.Load(await conn.ExecuteReaderAsync("select 3 as [three], 4 as [four]").ConfigureAwait(false)); Assert.Equal(2, dt.Columns.Count); Assert.Equal("three", dt.Columns[0].ColumnName); Assert.Equal("four", dt.Columns[1].ColumnName); Assert.Equal(1, dt.Rows.Count); Assert.Equal(3, (int)dt.Rows[0][0]); Assert.Equal(4, (int)dt.Rows[0][1]); } [Fact] public async Task LiteralReplacementOpen() { await LiteralReplacement(connection).ConfigureAwait(false); } [Fact] public async Task LiteralReplacementClosed() { using var conn = GetClosedConnection(); await LiteralReplacement(conn).ConfigureAwait(false); } private static async Task LiteralReplacement(IDbConnection conn) { try { await conn.ExecuteAsync("drop table literal1").ConfigureAwait(false); } catch { /* don't care */ } await conn.ExecuteAsync("create table literal1 (id int not null, foo int not null)").ConfigureAwait(false); await conn.ExecuteAsync("insert literal1 (id,foo) values ({=id}, @foo)", new { id = 123, foo = 456 }).ConfigureAwait(false); var rows = new[] { new { id = 1, foo = 2 }, new { id = 3, foo = 4 } }; await conn.ExecuteAsync("insert literal1 (id,foo) values ({=id}, @foo)", rows).ConfigureAwait(false); var count = (await conn.QueryAsync<int>("select count(1) from literal1 where id={=foo}", new { foo = 123 }).ConfigureAwait(false)).Single(); Assert.Equal(1, count); int sum = (await conn.QueryAsync<int>("select sum(id) + sum(foo) from literal1").ConfigureAwait(false)).Single(); Assert.Equal(123 + 456 + 1 + 2 + 3 + 4, sum); } [Fact] public async Task LiteralReplacementDynamicOpen() { await LiteralReplacementDynamic(connection).ConfigureAwait(false); } [Fact] public async Task LiteralReplacementDynamicClosed() { using var conn = GetClosedConnection(); await LiteralReplacementDynamic(conn).ConfigureAwait(false); } private static async Task LiteralReplacementDynamic(IDbConnection conn) { var args = new DynamicParameters(); args.Add("id", 123); try { await conn.ExecuteAsync("drop table literal2").ConfigureAwait(false); } catch { /* don't care */ } await conn.ExecuteAsync("create table literal2 (id int not null)").ConfigureAwait(false); await conn.ExecuteAsync("insert literal2 (id) values ({=id})", args).ConfigureAwait(false); args = new DynamicParameters(); args.Add("foo", 123); var count = (await conn.QueryAsync<int>("select count(1) from literal2 where id={=foo}", args).ConfigureAwait(false)).Single(); Assert.Equal(1, count); } [Fact] public async Task LiteralInAsync() { await connection.ExecuteAsync("create table #literalin(id int not null);").ConfigureAwait(false); await connection.ExecuteAsync("insert #literalin (id) values (@id)", new[] { new { id = 1 }, new { id = 2 }, new { id = 3 }, }).ConfigureAwait(false); var count = (await connection.QueryAsync<int>("select count(1) from #literalin where id in {=ids}", new { ids = new[] { 1, 3, 4 } }).ConfigureAwait(false)).Single(); Assert.Equal(2, count); } [FactLongRunning] public async Task RunSequentialVersusParallelAsync() { var ids = Enumerable.Range(1, 20000).Select(id => new { id }).ToArray(); await MarsConnection.ExecuteAsync(new CommandDefinition("select @id", ids.Take(5), flags: CommandFlags.None)).ConfigureAwait(false); var watch = Stopwatch.StartNew(); await MarsConnection.ExecuteAsync(new CommandDefinition("select @id", ids, flags: CommandFlags.None)).ConfigureAwait(false); watch.Stop(); Console.WriteLine("No pipeline: {0}ms", watch.ElapsedMilliseconds); watch = Stopwatch.StartNew(); await MarsConnection.ExecuteAsync(new CommandDefinition("select @id", ids, flags: CommandFlags.Pipelined)).ConfigureAwait(false); watch.Stop(); Console.WriteLine("Pipeline: {0}ms", watch.ElapsedMilliseconds); } [FactLongRunning] public void RunSequentialVersusParallelSync() { var ids = Enumerable.Range(1, 20000).Select(id => new { id }).ToArray(); MarsConnection.Execute(new CommandDefinition("select @id", ids.Take(5), flags: CommandFlags.None)); var watch = Stopwatch.StartNew(); MarsConnection.Execute(new CommandDefinition("select @id", ids, flags: CommandFlags.None)); watch.Stop(); Console.WriteLine("No pipeline: {0}ms", watch.ElapsedMilliseconds); watch = Stopwatch.StartNew(); MarsConnection.Execute(new CommandDefinition("select @id", ids, flags: CommandFlags.Pipelined)); watch.Stop(); Console.WriteLine("Pipeline: {0}ms", watch.ElapsedMilliseconds); } private class BasicType { public string? Value { get; set; } } [Fact] public async Task TypeBasedViaTypeAsync() { Type type = Common.GetSomeType(); dynamic actual = (await MarsConnection.QueryAsync(type, "select @A as [A], @B as [B]", new { A = 123, B = "abc" }).ConfigureAwait(false)).FirstOrDefault()!; Assert.Equal(((object)actual).GetType(), type); int a = actual.A; string b = actual.B; Assert.Equal(123, a); Assert.Equal("abc", b); } [Fact] public async Task TypeBasedViaTypeAsyncFirstOrDefault() { Type type = Common.GetSomeType(); dynamic actual = (await MarsConnection.QueryFirstOrDefaultAsync(type, "select @A as [A], @B as [B]", new { A = 123, B = "abc" }).ConfigureAwait(false))!; Assert.Equal(((object)actual).GetType(), type); int a = actual.A; string b = actual.B; Assert.Equal(123, a); Assert.Equal("abc", b); } [Fact] public async Task Issue22_ExecuteScalarAsync() { int i = await connection.ExecuteScalarAsync<int>("select 123").ConfigureAwait(false); Assert.Equal(123, i); i = await connection.ExecuteScalarAsync<int>("select cast(123 as bigint)").ConfigureAwait(false); Assert.Equal(123, i); long j = await connection.ExecuteScalarAsync<long>("select 123").ConfigureAwait(false); Assert.Equal(123L, j); j = await connection.ExecuteScalarAsync<long>("select cast(123 as bigint)").ConfigureAwait(false); Assert.Equal(123L, j); int? k = await connection.ExecuteScalarAsync<int?>("select @i", new { i = default(int?) }).ConfigureAwait(false); Assert.Null(k); } [Fact] public async Task Issue346_QueryAsyncConvert() { int i = (await connection.QueryAsync<int>("Select Cast(123 as bigint)").ConfigureAwait(false)).First(); Assert.Equal(123, i); } [Fact] public async Task TestSupportForDynamicParametersOutputExpressionsAsync() { { var bob = new Person { Name = "bob", PersonId = 1, Address = new Address { PersonId = 2, Index = new Index() } }; var p = new DynamicParameters(bob); p.Output(bob, b => b.PersonId); p.Output(bob, b => b.Occupation); p.Output(bob, b => b.NumberOfLegs); p.Output(bob, b => b.Address!.Name); p.Output(bob, b => b.Address!.PersonId); p.Output(bob, b => b.Address!.Index!.Id); await connection.ExecuteAsync(@" SET @Occupation = 'grillmaster' SET @PersonId = @PersonId + 1 SET @NumberOfLegs = @NumberOfLegs - 1 SET @AddressName = 'bobs burgers' SET @AddressPersonId = @PersonId SET @AddressIndexId = '01088'", p).ConfigureAwait(false); Assert.Equal("grillmaster", bob.Occupation); Assert.Equal(2, bob.PersonId); Assert.Equal(1, bob.NumberOfLegs); Assert.Equal("bobs burgers", bob.Address.Name); Assert.Equal(2, bob.Address.PersonId); Assert.Equal("01088", bob.Address.Index.Id); } } [Fact] public async Task TestSupportForDynamicParametersOutputExpressions_ScalarAsync() { var bob = new Person { Name = "bob", PersonId = 1, Address = new Address { PersonId = 2 } }; var p = new DynamicParameters(bob); p.Output(bob, b => b.PersonId); p.Output(bob, b => b.Occupation); p.Output(bob, b => b.NumberOfLegs); p.Output(bob, b => b.Address!.Name); p.Output(bob, b => b.Address!.PersonId); var result = (int)(await connection.ExecuteScalarAsync(@" SET @Occupation = 'grillmaster' SET @PersonId = @PersonId + 1 SET @NumberOfLegs = @NumberOfLegs - 1 SET @AddressName = 'bobs burgers' SET @AddressPersonId = @PersonId select 42", p).ConfigureAwait(false))!; Assert.Equal("grillmaster", bob.Occupation); Assert.Equal(2, bob.PersonId); Assert.Equal(1, bob.NumberOfLegs); Assert.Equal("bobs burgers", bob.Address.Name); Assert.Equal(2, bob.Address.PersonId); Assert.Equal(42, result); } [Fact] public async Task TestSupportForDynamicParametersOutputExpressions_Query_Default() { var bob = new Person { Name = "bob", PersonId = 1, Address = new Address { PersonId = 2 } }; var p = new DynamicParameters(bob); p.Output(bob, b => b.PersonId); p.Output(bob, b => b.Occupation); p.Output(bob, b => b.NumberOfLegs); p.Output(bob, b => b.Address!.Name); p.Output(bob, b => b.Address!.PersonId); var result = (await connection.QueryAsync<int>(@" SET @Occupation = 'grillmaster' SET @PersonId = @PersonId + 1 SET @NumberOfLegs = @NumberOfLegs - 1 SET @AddressName = 'bobs burgers' SET @AddressPersonId = @PersonId select 42", p).ConfigureAwait(false)).Single(); Assert.Equal("grillmaster", bob.Occupation); Assert.Equal(2, bob.PersonId); Assert.Equal(1, bob.NumberOfLegs); Assert.Equal("bobs burgers", bob.Address.Name); Assert.Equal(2, bob.Address.PersonId); Assert.Equal(42, result); } [Fact] public async Task TestSupportForDynamicParametersOutputExpressions_QueryFirst() { var bob = new Person { Name = "bob", PersonId = 1, Address = new Address { PersonId = 2 } }; var p = new DynamicParameters(bob); p.Output(bob, b => b.PersonId); p.Output(bob, b => b.Occupation); p.Output(bob, b => b.NumberOfLegs); p.Output(bob, b => b.Address!.Name); p.Output(bob, b => b.Address!.PersonId); var result = (await connection.QueryFirstAsync<int>(@" SET @Occupation = 'grillmaster' SET @PersonId = @PersonId + 1 SET @NumberOfLegs = @NumberOfLegs - 1 SET @AddressName = 'bobs burgers' SET @AddressPersonId = @PersonId select 42", p).ConfigureAwait(false)); Assert.Equal("grillmaster", bob.Occupation); Assert.Equal(2, bob.PersonId); Assert.Equal(1, bob.NumberOfLegs); Assert.Equal("bobs burgers", bob.Address.Name); Assert.Equal(2, bob.Address.PersonId); Assert.Equal(42, result); } [Fact] public async Task TestSupportForDynamicParametersOutputExpressions_Query_BufferedAsync() { var bob = new Person { Name = "bob", PersonId = 1, Address = new Address { PersonId = 2 } }; var p = new DynamicParameters(bob); p.Output(bob, b => b.PersonId); p.Output(bob, b => b.Occupation); p.Output(bob, b => b.NumberOfLegs); p.Output(bob, b => b.Address!.Name); p.Output(bob, b => b.Address!.PersonId); var result = (await connection.QueryAsync<int>(new CommandDefinition(@" SET @Occupation = 'grillmaster' SET @PersonId = @PersonId + 1 SET @NumberOfLegs = @NumberOfLegs - 1 SET @AddressName = 'bobs burgers' SET @AddressPersonId = @PersonId select 42", p, flags: CommandFlags.Buffered)).ConfigureAwait(false)).Single(); Assert.Equal("grillmaster", bob.Occupation); Assert.Equal(2, bob.PersonId); Assert.Equal(1, bob.NumberOfLegs); Assert.Equal("bobs burgers", bob.Address.Name); Assert.Equal(2, bob.Address.PersonId); Assert.Equal(42, result); } [Fact] public async Task TestSupportForDynamicParametersOutputExpressions_Query_NonBufferedAsync() { var bob = new Person { Name = "bob", PersonId = 1, Address = new Address { PersonId = 2 } }; var p = new DynamicParameters(bob); p.Output(bob, b => b.PersonId); p.Output(bob, b => b.Occupation); p.Output(bob, b => b.NumberOfLegs); p.Output(bob, b => b.Address!.Name); p.Output(bob, b => b.Address!.PersonId); var result = (await connection.QueryAsync<int>(new CommandDefinition(@" SET @Occupation = 'grillmaster' SET @PersonId = @PersonId + 1 SET @NumberOfLegs = @NumberOfLegs - 1 SET @AddressName = 'bobs burgers' SET @AddressPersonId = @PersonId select 42", p, flags: CommandFlags.None)).ConfigureAwait(false)).Single(); Assert.Equal("grillmaster", bob.Occupation); Assert.Equal(2, bob.PersonId); Assert.Equal(1, bob.NumberOfLegs); Assert.Equal("bobs burgers", bob.Address.Name); Assert.Equal(2, bob.Address.PersonId); Assert.Equal(42, result); } [Fact] public async Task TestSupportForDynamicParametersOutputExpressions_QueryMultipleAsync() { var bob = new Person { Name = "bob", PersonId = 1, Address = new Address { PersonId = 2 } }; var p = new DynamicParameters(bob); p.Output(bob, b => b.PersonId); p.Output(bob, b => b.Occupation); p.Output(bob, b => b.NumberOfLegs); p.Output(bob, b => b.Address!.Name); p.Output(bob, b => b.Address!.PersonId); int x, y; using (var multi = await connection.QueryMultipleAsync(@" SET @Occupation = 'grillmaster' SET @PersonId = @PersonId + 1 SET @NumberOfLegs = @NumberOfLegs - 1 SET @AddressName = 'bobs burgers' select 42 select 17 SET @AddressPersonId = @PersonId", p).ConfigureAwait(false)) { x = multi.ReadAsync<int>().Result.Single(); y = multi.ReadAsync<int>().Result.Single(); } Assert.Equal("grillmaster", bob.Occupation); Assert.Equal(2, bob.PersonId); Assert.Equal(1, bob.NumberOfLegs); Assert.Equal("bobs burgers", bob.Address.Name); Assert.Equal(2, bob.Address.PersonId); Assert.Equal(42, x); Assert.Equal(17, y); } [Fact] public async Task TestSubsequentQueriesSuccessAsync() { var data0 = (await connection.QueryAsync<AsyncFoo0>("select 1 as [Id] where 1 = 0").ConfigureAwait(false)).ToList(); Assert.Empty(data0); var data1 = (await connection.QueryAsync<AsyncFoo1>(new CommandDefinition("select 1 as [Id] where 1 = 0", flags: CommandFlags.Buffered)).ConfigureAwait(false)).ToList(); Assert.Empty(data1); var data2 = (await connection.QueryAsync<AsyncFoo2>(new CommandDefinition("select 1 as [Id] where 1 = 0", flags: CommandFlags.None)).ConfigureAwait(false)).ToList(); Assert.Empty(data2); data0 = (await connection.QueryAsync<AsyncFoo0>("select 1 as [Id] where 1 = 0").ConfigureAwait(false)).ToList(); Assert.Empty(data0); data1 = (await connection.QueryAsync<AsyncFoo1>(new CommandDefinition("select 1 as [Id] where 1 = 0", flags: CommandFlags.Buffered)).ConfigureAwait(false)).ToList(); Assert.Empty(data1); data2 = (await connection.QueryAsync<AsyncFoo2>(new CommandDefinition("select 1 as [Id] where 1 = 0", flags: CommandFlags.None)).ConfigureAwait(false)).ToList(); Assert.Empty(data2); } private class AsyncFoo0 { public int Id { get; set; } } private class AsyncFoo1 { public int Id { get; set; } } private class AsyncFoo2 { public int Id { get; set; } } [Fact] public async Task TestSchemaChangedViaFirstOrDefaultAsync() { await connection.ExecuteAsync("create table #dog(Age int, Name nvarchar(max)) insert #dog values(1, 'Alf')").ConfigureAwait(false); try { var d = await connection.QueryFirstOrDefaultAsync<Dog>("select * from #dog").ConfigureAwait(false); Assert.NotNull(d); Assert.Equal("Alf", d.Name); Assert.Equal(1, d.Age); connection.Execute("alter table #dog drop column Name"); d = await connection.QueryFirstOrDefaultAsync<Dog>("select * from #dog").ConfigureAwait(false); Assert.NotNull(d); Assert.Null(d.Name); Assert.Equal(1, d.Age); } finally { await connection.ExecuteAsync("drop table #dog").ConfigureAwait(false); } } [Fact] public async Task TestMultiMapArbitraryMapsAsync() { // please excuse the trite example, but it is easier to follow than a more real-world one const string createSql = @" create table #ReviewBoards (Id int, Name varchar(20), User1Id int, User2Id int, User3Id int, User4Id int, User5Id int, User6Id int, User7Id int, User8Id int, User9Id int) create table #Users (Id int, Name varchar(20)) insert #Users values(1, 'User 1') insert #Users values(2, 'User 2') insert #Users values(3, 'User 3') insert #Users values(4, 'User 4') insert #Users values(5, 'User 5') insert #Users values(6, 'User 6') insert #Users values(7, 'User 7') insert #Users values(8, 'User 8') insert #Users values(9, 'User 9') insert #ReviewBoards values(1, 'Review Board 1', 1, 2, 3, 4, 5, 6, 7, 8, 9) "; await connection.ExecuteAsync(createSql).ConfigureAwait(false); try { const string sql = @" select rb.Id, rb.Name, u1.*, u2.*, u3.*, u4.*, u5.*, u6.*, u7.*, u8.*, u9.* from #ReviewBoards rb inner join #Users u1 on u1.Id = rb.User1Id inner join #Users u2 on u2.Id = rb.User2Id inner join #Users u3 on u3.Id = rb.User3Id inner join #Users u4 on u4.Id = rb.User4Id inner join #Users u5 on u5.Id = rb.User5Id inner join #Users u6 on u6.Id = rb.User6Id inner join #Users u7 on u7.Id = rb.User7Id inner join #Users u8 on u8.Id = rb.User8Id inner join #Users u9 on u9.Id = rb.User9Id "; var types = new[] { typeof(ReviewBoard), typeof(User), typeof(User), typeof(User), typeof(User), typeof(User), typeof(User), typeof(User), typeof(User), typeof(User) }; Func<object[], ReviewBoard> mapper = (objects) => { var board = (ReviewBoard)objects[0]; board.User1 = (User)objects[1]; board.User2 = (User)objects[2]; board.User3 = (User)objects[3]; board.User4 = (User)objects[4]; board.User5 = (User)objects[5]; board.User6 = (User)objects[6]; board.User7 = (User)objects[7]; board.User8 = (User)objects[8]; board.User9 = (User)objects[9]; return board; }; var data = (await connection.QueryAsync<ReviewBoard>(sql, types, mapper).ConfigureAwait(false)).ToList(); var p = data[0]; Assert.Equal(1, p.Id); Assert.Equal("Review Board 1", p.Name); Assert.NotNull(p.User1); Assert.NotNull(p.User2); Assert.NotNull(p.User3); Assert.NotNull(p.User4); Assert.NotNull(p.User5); Assert.NotNull(p.User6); Assert.NotNull(p.User7); Assert.NotNull(p.User8); Assert.NotNull(p.User9); Assert.Equal(1, p.User1.Id); Assert.Equal(2, p.User2.Id); Assert.Equal(3, p.User3.Id); Assert.Equal(4, p.User4.Id); Assert.Equal(5, p.User5.Id); Assert.Equal(6, p.User6.Id); Assert.Equal(7, p.User7.Id); Assert.Equal(8, p.User8.Id); Assert.Equal(9, p.User9.Id); Assert.Equal("User 1", p.User1.Name); Assert.Equal("User 2", p.User2.Name); Assert.Equal("User 3", p.User3.Name); Assert.Equal("User 4", p.User4.Name); Assert.Equal("User 5", p.User5.Name); Assert.Equal("User 6", p.User6.Name); Assert.Equal("User 7", p.User7.Name); Assert.Equal("User 8", p.User8.Name); Assert.Equal("User 9", p.User9.Name); } finally { connection.Execute("drop table #Users drop table #ReviewBoards"); } } [Fact] public async Task Issue157_ClosedReaderAsync() { var args = new { x = 42 }; const string sql = "select 123 as [A], 'abc' as [B] where @x=42"; var row = (await connection.QueryAsync<SomeType>(new CommandDefinition( sql, args, flags: CommandFlags.None)).ConfigureAwait(false)).Single(); Assert.NotNull(row); Assert.Equal(123, row.A); Assert.Equal("abc", row.B); args = new { x = 5 }; Assert.False((await connection.QueryAsync<SomeType>(new CommandDefinition(sql, args, flags: CommandFlags.None)).ConfigureAwait(false)).Any()); } [Fact] public async Task TestAtEscaping() { var id = (await connection.QueryAsync<int>(@" declare @@Name int select @@Name = @Id+1 select @@Name ", new Product { Id = 1 }).ConfigureAwait(false)).Single(); Assert.Equal(2, id); } [Fact] public async Task Issue1281_DataReaderOutOfOrderAsync() { using var reader = await connection.ExecuteReaderAsync("Select 0, 1, 2").ConfigureAwait(false); Assert.True(reader.Read()); Assert.Equal(2, reader.GetInt32(2)); Assert.Equal(0, reader.GetInt32(0)); Assert.Equal(1, reader.GetInt32(1)); Assert.False(reader.Read()); } [Fact] public async Task Issue563_QueryAsyncShouldThrowException() { try { var data = (await connection.QueryAsync<int>("select 1 union all select 2; RAISERROR('after select', 16, 1);").ConfigureAwait(false)).ToList(); Assert.Fail("Expected Exception"); } catch (Exception ex) when (ex.GetType().Name == "SqlException" && ex.Message == "after select") { /* swallow only this */ } } } [Collection(NonParallelDefinition.Name)] public abstract class AsyncQueryCacheTests<TProvider> : TestBase<TProvider> where TProvider : SqlServerDatabaseProvider { private readonly ITestOutputHelper _log; public AsyncQueryCacheTests(ITestOutputHelper log) => _log = log; private DbConnection? _marsConnection; private DbConnection MarsConnection => _marsConnection ??= Provider.GetOpenConnection(true); public override void Dispose() { _marsConnection?.Dispose(); _marsConnection = null; base.Dispose(); } [Fact] public void AssertNoCacheWorksForQueryMultiple() { const int a = 123, b = 456; var cmdDef = new CommandDefinition("select @a; select @b;", new { a, b }, commandType: CommandType.Text, flags: CommandFlags.NoCache); int c, d; SqlMapper.PurgeQueryCache(); int before = SqlMapper.GetCachedSQLCount(); using (var multi = MarsConnection.QueryMultiple(cmdDef)) { c = multi.Read<int>().Single(); d = multi.Read<int>().Single(); } int after = SqlMapper.GetCachedSQLCount(); _log?.WriteLine($"before: {before}; after: {after}"); // too brittle in concurrent tests to assert // Assert.Equal(0, before); // Assert.Equal(0, after); Assert.Equal(123, c); Assert.Equal(456, d); } [Fact] public async Task AssertNoCacheWorksForMultiMap() { const int a = 123, b = 456; var cmdDef = new CommandDefinition("select @a as a, @b as b;", new { a, b }, commandType: CommandType.Text, flags: CommandFlags.NoCache | CommandFlags.Buffered); SqlMapper.PurgeQueryCache(); var before = SqlMapper.GetCachedSQLCount(); Assert.Equal(0, before); await MarsConnection.QueryAsync<int, int, (int, int)>(cmdDef, splitOn: "b", map: (a, b) => (a, b)); Assert.Equal(0, SqlMapper.GetCachedSQLCount()); } [Fact] public async Task AssertNoCacheWorksForQueryAsync() { const int a = 123, b = 456; var cmdDef = new CommandDefinition("select @a as a, @b as b;", new { a, b }, commandType: CommandType.Text, flags: CommandFlags.NoCache | CommandFlags.Buffered); SqlMapper.PurgeQueryCache(); var before = SqlMapper.GetCachedSQLCount(); Assert.Equal(0, before); await MarsConnection.QueryAsync<(int, int)>(cmdDef); Assert.Equal(0, SqlMapper.GetCachedSQLCount()); } } }
Dapper
You are an expert .NET (C#) developer. Task: Write a unit test for 'TargetModule' using XUnit and Moq. Context: - Class: TargetModule Requirements: Use Mock<T> interface mocking.
industrial
using System.Collections; namespace Dapper { public partial class DynamicParameters { // The type here is used to differentiate the cache by type via generics // ReSharper disable once UnusedTypeParameter internal static class CachedOutputSetters<T> { // Intentional, abusing generics to get our cache splits // ReSharper disable once StaticMemberInGenericType public static readonly Hashtable Cache = new Hashtable(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.Common; using System.Data.SqlTypes; using System.Diagnostics; using System.Dynamic; using System.Globalization; using System.Linq; using System.Text.RegularExpressions; using Xunit; #if ENTITY_FRAMEWORK using System.Data.Entity.Spatial; using Microsoft.SqlServer.Types; #endif [assembly: CollectionBehavior(DisableTestParallelization = true)] namespace Dapper.Tests { [Collection(NonParallelDefinition.Name)] // because it creates SQL types that compete between the two providers public sealed class SystemSqlClientParameterTests : ParameterTests<SystemSqlClientProvider> { } #if MSSQLCLIENT [Collection(NonParallelDefinition.Name)] // because it creates SQL types that compete between the two providers public sealed class MicrosoftSqlClientParameterTests : ParameterTests<MicrosoftSqlClientProvider> { } #endif public abstract class ParameterTests<TProvider> : TestBase<TProvider> where TProvider : DatabaseProvider { public class DbDynamicParams : SqlMapper.IDynamicParameters, IEnumerable<IDbDataParameter> { private readonly List<IDbDataParameter> parameters = new List<IDbDataParameter>(); public IEnumerator<IDbDataParameter> GetEnumerator() { return parameters.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public void Add(IDbDataParameter value) { parameters.Add(value); } void SqlMapper.IDynamicParameters.AddParameters(IDbCommand command, SqlMapper.Identity identity) { foreach (IDbDataParameter parameter in parameters) command.Parameters.Add(parameter); } } public class DbCustomParam : SqlMapper.ICustomQueryParameter { private readonly IDbDataParameter _sqlParameter; public DbCustomParam(IDbDataParameter sqlParameter) { _sqlParameter = sqlParameter; } public void AddParameter(IDbCommand command, string name) { command.Parameters.Add(_sqlParameter); } } private static IEnumerable<IDataRecord> CreateSqlDataRecordList(IDbCommand command, IEnumerable<int> numbers) { #pragma warning disable CS0618 // Type or member is obsolete if (command is System.Data.SqlClient.SqlCommand) return CreateSqlDataRecordList_SD(numbers); #pragma warning restore CS0618 // Type or member is obsolete if (command is Microsoft.Data.SqlClient.SqlCommand) return CreateSqlDataRecordList_MD(numbers); throw new ArgumentException(nameof(command)); } private static IEnumerable<IDataRecord> CreateSqlDataRecordList(IDbConnection connection, IEnumerable<int> numbers) { #pragma warning disable CS0618 // Type or member is obsolete if (connection is System.Data.SqlClient.SqlConnection) return CreateSqlDataRecordList_SD(numbers); #pragma warning restore CS0618 // Type or member is obsolete if (connection is Microsoft.Data.SqlClient.SqlConnection) return CreateSqlDataRecordList_MD(numbers); throw new ArgumentException(nameof(connection)); } #pragma warning disable CS0618 // Type or member is obsolete private static List<Microsoft.SqlServer.Server.SqlDataRecord> CreateSqlDataRecordList_SD(IEnumerable<int> numbers) { var number_list = new List<Microsoft.SqlServer.Server.SqlDataRecord>(); // Create an SqlMetaData object that describes our table type. Microsoft.SqlServer.Server.SqlMetaData[] tvp_definition = { new Microsoft.SqlServer.Server.SqlMetaData("n", SqlDbType.Int) }; foreach (int n in numbers) { // Create a new record, using the metadata array above. var rec = new Microsoft.SqlServer.Server.SqlDataRecord(tvp_definition); rec.SetInt32(0, n); // Set the value. number_list.Add(rec); // Add it to the list. } return number_list; } #pragma warning restore CS0618 // Type or member is obsolete private static List<Microsoft.Data.SqlClient.Server.SqlDataRecord> CreateSqlDataRecordList_MD(IEnumerable<int> numbers) { var number_list = new List<Microsoft.Data.SqlClient.Server.SqlDataRecord>(); // Create an SqlMetaData object that describes our table type. Microsoft.Data.SqlClient.Server.SqlMetaData[] tvp_definition = { new Microsoft.Data.SqlClient.Server.SqlMetaData("n", SqlDbType.Int) }; foreach (int n in numbers) { // Create a new record, using the metadata array above. var rec = new Microsoft.Data.SqlClient.Server.SqlDataRecord(tvp_definition); rec.SetInt32(0, n); // Set the value. number_list.Add(rec); // Add it to the list. } return number_list; } private class IntDynamicParam : SqlMapper.IDynamicParameters { private readonly IEnumerable<int> numbers; public IntDynamicParam(IEnumerable<int> numbers) { this.numbers = numbers; } public void AddParameters(IDbCommand command, SqlMapper.Identity identity) { command.CommandType = CommandType.StoredProcedure; var number_list = CreateSqlDataRecordList(command, numbers); AddStructured(command, number_list); } } private class IntCustomParam : SqlMapper.ICustomQueryParameter { private readonly IEnumerable<int> numbers; public IntCustomParam(IEnumerable<int> numbers) { this.numbers = numbers; } public void AddParameter(IDbCommand command, string name) { command.CommandType = CommandType.StoredProcedure; var number_list = CreateSqlDataRecordList(command, numbers); // Add the table parameter. AddStructured(command, number_list); } } private static IDbDataParameter AddStructured(IDbCommand command, object value) { #pragma warning disable CS0618 // Type or member is obsolete if (command is System.Data.SqlClient.SqlCommand sdcmd) { var p = sdcmd.Parameters.Add("integers", SqlDbType.Structured); p.Direction = ParameterDirection.Input; p.TypeName = "int_list_type"; p.Value = value; return p; } #pragma warning restore CS0618 // Type or member is obsolete else if (command is Microsoft.Data.SqlClient.SqlCommand mdcmd) { var p = mdcmd.Parameters.Add("integers", SqlDbType.Structured); p.Direction = ParameterDirection.Input; p.TypeName = "int_list_type"; p.Value = value; return p; } else throw new ArgumentException(nameof(command)); } /* TODO: * public void TestMagicParam() { // magic params allow you to pass in single params without using an anon class // this test fails for now, but I would like to support a single param by parsing the sql with regex and remapping. var first = connection.Query("select @a as a", 1).First(); Assert.Equal(first.a, 1); } * */ [Fact] public void TestDoubleParam() { Assert.Equal(0.1d, connection.Query<double>("select @d", new { d = 0.1d }).First()); } [Fact] public void TestBoolParam() { Assert.False(connection.Query<bool>("select @b", new { b = false }).First()); } // http://code.google.com/p/dapper-dot-net/issues/detail?id=70 // https://connect.microsoft.com/VisualStudio/feedback/details/381934/sqlparameter-dbtype-dbtype-time-sets-the-parameter-to-sqldbtype-datetime-instead-of-sqldbtype-time [Fact] public void TestTimeSpanParam() { Assert.Equal(connection.Query<TimeSpan>("select @ts", new { ts = TimeSpan.FromMinutes(42) }).First(), TimeSpan.FromMinutes(42)); } [Fact] public void PassInIntArray() { Assert.Equal( new[] { 1, 2, 3 }, connection.Query<int>("select * from (select 1 as Id union all select 2 union all select 3) as X where Id in @Ids", new { Ids = new int[] { 1, 2, 3 }.AsEnumerable() }) ); } [Fact] public void PassInEmptyIntArray() { Assert.Equal( Array.Empty<int>(), connection.Query<int>("select * from (select 1 as Id union all select 2 union all select 3) as X where Id in @Ids", new { Ids = Array.Empty<int>() }) ); } [Fact] public void TestExecuteCommandWithHybridParameters() { var p = new DynamicParameters(new { a = 1, b = 2 }); p.Add("c", dbType: DbType.Int32, direction: ParameterDirection.Output); connection.Execute("set @c = @a + @b", p); Assert.Equal(3, p.Get<int>("@c")); } [Fact] public void GuidIn_SO_24177902() { // invent and populate Guid a = Guid.NewGuid(), b = Guid.NewGuid(), c = Guid.NewGuid(), d = Guid.NewGuid(); connection.Execute("create table #foo (i int, g uniqueidentifier)"); connection.Execute("insert #foo(i,g) values(@i,@g)", new[] { new { i = 1, g = a }, new { i = 2, g = b }, new { i = 3, g = c },new { i = 4, g = d }}); // check that rows 2&3 yield guids b&c var guids = connection.Query<Guid>("select g from #foo where i in (2,3)").ToArray(); Assert.Equal(2, guids.Length); Assert.DoesNotContain(a, guids); Assert.Contains(b, guids); Assert.Contains(c, guids); Assert.DoesNotContain(d, guids); // in query on the guids var rows = connection.Query("select * from #foo where g in @guids order by i", new { guids }) .Select(row => new { i = (int)row.i, g = (Guid)row.g }).ToArray(); Assert.Equal(2, rows.Length); Assert.Equal(2, rows[0].i); Assert.Equal(b, rows[0].g); Assert.Equal(3, rows[1].i); Assert.Equal(c, rows[1].g); } [FactUnlessCaseSensitiveDatabase] public void TestParameterInclusionNotSensitiveToCurrentCulture() { // note this might fail if your database server is case-sensitive CultureInfo current = ActiveCulture; try { ActiveCulture = new CultureInfo("tr-TR"); connection.Query<int>("select @pid", new { PId = 1 }).Single(); } finally { ActiveCulture = current; } } [Fact] public void TestMassiveStrings() { var str = new string('X', 20000); Assert.Equal(connection.Query<string>("select @a", new { a = str }).First(), str); } [Fact] public void TestTVPWithAnonymousObject() { try { connection.Execute("CREATE TYPE int_list_type AS TABLE (n int NOT NULL PRIMARY KEY)"); connection.Execute("CREATE PROC get_ints @integers int_list_type READONLY AS select * from @integers"); var nums = connection.Query<int>("get_ints", new { integers = new IntCustomParam(new int[] { 1, 2, 3 }) }, commandType: CommandType.StoredProcedure).ToList(); Assert.Equal(1, nums[0]); Assert.Equal(2, nums[1]); Assert.Equal(3, nums[2]); Assert.Equal(3, nums.Count); } finally { try { connection.Execute("DROP PROC get_ints"); } finally { connection.Execute("DROP TYPE int_list_type"); } } } [Fact] public void TestTVPWithAnonymousEmptyObject() { try { connection.Execute("CREATE TYPE int_list_type AS TABLE (n int NOT NULL PRIMARY KEY)"); connection.Execute("CREATE PROC get_ints @integers int_list_type READONLY AS select * from @integers"); var nums = connection.Query<int>("get_ints", new { integers = new IntCustomParam(new int[] { }) }, commandType: CommandType.StoredProcedure).ToList(); Assert.Equal(1, nums[0]); Assert.Equal(2, nums[1]); Assert.Equal(3, nums[2]); Assert.Equal(3, nums.Count); } catch (ArgumentException ex) { Assert.True(string.Compare(ex.Message, "There are no records in the SqlDataRecord enumeration. To send a table-valued parameter with no rows, use a null reference for the value instead.") == 0); } finally { try { connection.Execute("DROP PROC get_ints"); } finally { connection.Execute("DROP TYPE int_list_type"); } } } // SQL Server specific test to demonstrate TVP [Fact] public void TestTVP() { try { connection.Execute("CREATE TYPE int_list_type AS TABLE (n int NOT NULL PRIMARY KEY)"); connection.Execute("CREATE PROC get_ints @integers int_list_type READONLY AS select * from @integers"); var nums = connection.Query<int>("get_ints", new IntDynamicParam(new int[] { 1, 2, 3 })).ToList(); Assert.Equal(1, nums[0]); Assert.Equal(2, nums[1]); Assert.Equal(3, nums[2]); Assert.Equal(3, nums.Count); } finally { try { try { connection.Execute("DROP PROC get_ints"); } catch { } } finally { try { connection.Execute("DROP TYPE int_list_type"); } catch { } } } } private class DynamicParameterWithIntTVP : DynamicParameters, SqlMapper.IDynamicParameters { private readonly IEnumerable<int> numbers; public DynamicParameterWithIntTVP(IEnumerable<int> numbers) { this.numbers = numbers; } public new void AddParameters(IDbCommand command, SqlMapper.Identity identity) { base.AddParameters(command, identity); command.CommandType = CommandType.StoredProcedure; var number_list = CreateSqlDataRecordList(command, numbers); // Add the table parameter. AddStructured(command, number_list); } } [Fact] public void TestTVPWithAdditionalParams() { try { connection.Execute("CREATE TYPE int_list_type AS TABLE (n int NOT NULL PRIMARY KEY)"); connection.Execute("CREATE PROC get_values @integers int_list_type READONLY, @stringParam varchar(20), @dateParam datetime AS select i.*, @stringParam as stringParam, @dateParam as dateParam from @integers i"); var dynamicParameters = new DynamicParameterWithIntTVP(new int[] { 1, 2, 3 }); dynamicParameters.AddDynamicParams(new { stringParam = "stringParam", dateParam = new DateTime(2012, 1, 1) }); var results = connection.Query("get_values", dynamicParameters, commandType: CommandType.StoredProcedure).ToList(); Assert.Equal(3, results.Count); for (int i = 0; i < results.Count; i++) { var result = results[i]; Assert.Equal(i + 1, result.n); Assert.Equal("stringParam", result.stringParam); Assert.Equal(new DateTime(2012, 1, 1), result.dateParam); } } finally { try { connection.Execute("DROP PROC get_values"); } finally { connection.Execute("DROP TYPE int_list_type"); } } } [Fact] public void TestSqlDataRecordListParametersWithAsTableValuedParameter() { try { connection.Execute("CREATE TYPE int_list_type AS TABLE (n int NOT NULL PRIMARY KEY)"); connection.Execute("CREATE PROC get_ints @integers int_list_type READONLY AS select * from @integers"); var records = CreateSqlDataRecordList(connection, new int[] { 1, 2, 3 }); var nums = connection.Query<int>("get_ints", new { integers = records.AsTableValuedParameter() }, commandType: CommandType.StoredProcedure).ToList(); Assert.Equal(new int[] { 1, 2, 3 }, nums); nums = connection.Query<int>("select * from @integers", new { integers = records.AsTableValuedParameter("int_list_type") }).ToList(); Assert.Equal(new int[] { 1, 2, 3 }, nums); try { connection.Query<int>("select * from @integers", new { integers = records.AsTableValuedParameter() }).First(); throw new InvalidOperationException(); } catch (Exception ex) { ex.Message.Equals("The table type parameter 'ids' must have a valid type name."); } } finally { try { connection.Execute("DROP PROC get_ints"); } finally { connection.Execute("DROP TYPE int_list_type"); } } } [Fact] public void TestEmptySqlDataRecordListParametersWithAsTableValuedParameter() { try { connection.Execute("CREATE TYPE int_list_type AS TABLE (n int NOT NULL PRIMARY KEY)"); connection.Execute("CREATE PROC get_ints @integers int_list_type READONLY AS select * from @integers"); var emptyRecord = CreateSqlDataRecordList(connection, Enumerable.Empty<int>()); var nums = connection.Query<int>("get_ints", new { integers = emptyRecord.AsTableValuedParameter() }, commandType: CommandType.StoredProcedure).ToList(); Assert.True(nums.Count == 0); } finally { try { connection.Execute("DROP PROC get_ints"); } finally { connection.Execute("DROP TYPE int_list_type"); } } } [Fact] public void TestSqlDataRecordListParametersWithTypeHandlers() { try { connection.Execute("CREATE TYPE int_list_type AS TABLE (n int NOT NULL PRIMARY KEY)"); connection.Execute("CREATE PROC get_ints @integers int_list_type READONLY AS select * from @integers"); // Variable type has to be IEnumerable<SqlDataRecord> for TypeHandler to kick in. object args; #pragma warning disable CS0618 // Type or member is obsolete if (connection is System.Data.SqlClient.SqlConnection) { IEnumerable<Microsoft.SqlServer.Server.SqlDataRecord> records = CreateSqlDataRecordList_SD(new int[] { 1, 2, 3 }); args = new { integers = records }; } #pragma warning restore CS0618 // Type or member is obsolete else if (connection is Microsoft.Data.SqlClient.SqlConnection) { IEnumerable<Microsoft.Data.SqlClient.Server.SqlDataRecord> records = CreateSqlDataRecordList_MD(new int[] { 1, 2, 3 }); args = new { integers = records }; } else { throw new ArgumentException(nameof(connection)); } var nums = connection.Query<int>("get_ints", args, commandType: CommandType.StoredProcedure).ToList(); Assert.Equal(new int[] { 1, 2, 3 }, nums); try { connection.Query<int>("select * from @integers", args).First(); throw new InvalidOperationException(); } catch (Exception ex) { ex.Message.Equals("The table type parameter 'ids' must have a valid type name."); } } finally { try { connection.Execute("DROP PROC get_ints"); } finally { connection.Execute("DROP TYPE int_list_type"); } } } [Fact] public void DataTableParameters() { try { connection.Execute("drop proc #DataTableParameters"); } catch { /* don't care */ } try { connection.Execute("drop table #DataTableParameters"); } catch { /* don't care */ } try { connection.Execute("drop type MyTVPType"); } catch { /* don't care */ } connection.Execute("create type MyTVPType as table (id int)"); connection.Execute("create proc #DataTableParameters @ids MyTVPType readonly as select count(1) from @ids"); var table = new DataTable { Columns = { { "id", typeof(int) } }, Rows = { { 1 }, { 2 }, { 3 } } }; int count = connection.Query<int>("#DataTableParameters", new { ids = table.AsTableValuedParameter() }, commandType: CommandType.StoredProcedure).First(); Assert.Equal(3, count); count = connection.Query<int>("select count(1) from @ids", new { ids = table.AsTableValuedParameter("MyTVPType") }).First(); Assert.Equal(3, count); try { connection.Query<int>("select count(1) from @ids", new { ids = table.AsTableValuedParameter() }).First(); throw new InvalidOperationException(); } catch (Exception ex) { ex.Message.Equals("The table type parameter 'ids' must have a valid type name."); } } [Fact] public void SO29533765_DataTableParametersViaDynamicParameters() { try { connection.Execute("drop proc #DataTableParameters"); } catch { /* don't care */ } try { connection.Execute("drop table #DataTableParameters"); } catch { /* don't care */ } try { connection.Execute("drop type MyTVPType"); } catch { /* don't care */ } connection.Execute("create type MyTVPType as table (id int)"); connection.Execute("create proc #DataTableParameters @ids MyTVPType readonly as select count(1) from @ids"); var table = new DataTable { TableName = "MyTVPType", Columns = { { "id", typeof(int) } }, Rows = { { 1 }, { 2 }, { 3 } } }; table.SetTypeName(table.TableName); // per SO29533765 IDictionary<string, object> args = new Dictionary<string, object>(1) { ["ids"] = table }; int count = connection.Query<int>("#DataTableParameters", args, commandType: CommandType.StoredProcedure).First(); Assert.Equal(3, count); count = connection.Query<int>("select count(1) from @ids", args).First(); Assert.Equal(3, count); } [Fact] public void SO26468710_InWithTVPs() { // this is just to make it re-runnable; normally you only do this once try { connection.Execute("drop type MyIdList"); } catch { /* don't care */ } connection.Execute("create type MyIdList as table(id int);"); var ids = new DataTable { Columns = { { "id", typeof(int) } }, Rows = { { 1 }, { 3 }, { 5 } } }; ids.SetTypeName("MyIdList"); int sum = connection.Query<int>(@" declare @tmp table(id int not null); insert @tmp (id) values(1), (2), (3), (4), (5), (6), (7); select * from @tmp t inner join @ids i on i.id = t.id", new { ids }).Sum(); Assert.Equal(9, sum); } [Fact] public void DataTableParametersWithExtendedProperty() { try { connection.Execute("drop proc #DataTableParameters"); } catch { /* don't care */ } try { connection.Execute("drop table #DataTableParameters"); } catch { /* don't care */ } try { connection.Execute("drop type MyTVPType"); } catch { /* don't care */ } connection.Execute("create type MyTVPType as table (id int)"); connection.Execute("create proc #DataTableParameters @ids MyTVPType readonly as select count(1) from @ids"); var table = new DataTable { Columns = { { "id", typeof(int) } }, Rows = { { 1 }, { 2 }, { 3 } } }; table.SetTypeName("MyTVPType"); // <== extended metadata int count = connection.Query<int>("#DataTableParameters", new { ids = table }, commandType: CommandType.StoredProcedure).First(); Assert.Equal(3, count); count = connection.Query<int>("select count(1) from @ids", new { ids = table }).First(); Assert.Equal(3, count); try { connection.Query<int>("select count(1) from @ids", new { ids = table }).First(); throw new InvalidOperationException(); } catch (Exception ex) { ex.Message.Equals("The table type parameter 'ids' must have a valid type name."); } } [Fact] public void SupportInit() { var obj = connection.Query<WithInit>("select 'abc' as Value").Single(); Assert.Equal("abc", obj.Value); Assert.Equal(31, obj.Flags); } public class WithInit : ISupportInitialize { public string? Value { get; set; } public int Flags { get; set; } void ISupportInitialize.BeginInit() => Flags++; void ISupportInitialize.EndInit() => Flags += 30; } [Fact] public void SO29596645_TvpProperty() { try { connection.Execute("CREATE TYPE SO29596645_ReminderRuleType AS TABLE (id int NOT NULL)"); } catch { /* don't care */ } connection.Execute(@"create proc #SO29596645_Proc (@Id int, @Rules SO29596645_ReminderRuleType READONLY) as begin select @Id + ISNULL((select sum(id) from @Rules), 0); end"); var obj = new SO29596645_OrganisationDTO(); int val = connection.Query<int>("#SO29596645_Proc", obj.Rules, commandType: CommandType.StoredProcedure).Single(); // 4 + 9 + 7 = 20 Assert.Equal(20, val); } private class SO29596645_RuleTableValuedParameters : SqlMapper.IDynamicParameters { private readonly string parameterName; public SO29596645_RuleTableValuedParameters(string parameterName) { this.parameterName = parameterName; } public void AddParameters(IDbCommand command, SqlMapper.Identity identity) { Debug.WriteLine("> AddParameters"); var p = command.CreateParameter(); p.ParameterName = "Id"; p.Value = 7; command.Parameters.Add(p); var table = new DataTable { Columns = { { "Id", typeof(int) } }, Rows = { { 4 }, { 9 } } }; p = command.CreateParameter(); p.ParameterName = "Rules"; p.Value = table; command.Parameters.Add(p); Debug.WriteLine("< AddParameters"); } } private class SO29596645_OrganisationDTO { public SO29596645_RuleTableValuedParameters Rules { get; } public SO29596645_OrganisationDTO() { Rules = new SO29596645_RuleTableValuedParameters("@Rules"); } } #if ENTITY_FRAMEWORK private class HazGeo { public int Id { get; set; } public DbGeography? Geo { get; set; } public DbGeometry? Geometry { get; set; } } private class HazSqlGeo { public int Id { get; set; } public SqlGeography? Geo { get; set; } public SqlGeometry? Geometry { get; set; } } [Fact] public void DBGeography_SO24405645_SO24402424() { SkipIfMsDataClient(); EntityFramework.Handlers.Register(); connection.Execute("create table #Geo (id int, geo geography, geometry geometry)"); var obj = new HazGeo { Id = 1, Geo = DbGeography.LineFromText("LINESTRING(-122.360 47.656, -122.343 47.656 )", 4326), Geometry = DbGeometry.LineFromText("LINESTRING (100 100, 20 180, 180 180)", 0) }; connection.Execute("insert #Geo(id, geo, geometry) values (@Id, @Geo, @Geometry)", obj); var row = connection.Query<HazGeo>("select * from #Geo where id=1").SingleOrDefault(); Assert.NotNull(row); Assert.Equal(1, row.Id); Assert.NotNull(row.Geo); Assert.NotNull(row.Geometry); } [Fact] public void SqlGeography_SO25538154() { SkipIfMsDataClient(); SqlMapper.ResetTypeHandlers(); connection.Execute("create table #SqlGeo (id int, geo geography, geometry geometry)"); var obj = new HazSqlGeo { Id = 1, Geo = SqlGeography.STLineFromText(new SqlChars(new SqlString("LINESTRING(-122.360 47.656, -122.343 47.656 )")), 4326), Geometry = SqlGeometry.STLineFromText(new SqlChars(new SqlString("LINESTRING (100 100, 20 180, 180 180)")), 0) }; connection.Execute("insert #SqlGeo(id, geo, geometry) values (@Id, @Geo, @Geometry)", obj); var row = connection.Query<HazSqlGeo>("select * from #SqlGeo where id=1").SingleOrDefault(); Assert.NotNull(row); Assert.Equal(1, row.Id); Assert.NotNull(row.Geo); Assert.NotNull(row.Geometry); } [Fact] public void NullableSqlGeometry() { SqlMapper.ResetTypeHandlers(); connection.Execute("create table #SqlNullableGeo (id int, geometry geometry null)"); var obj = new HazSqlGeo { Id = 1, Geometry = null }; connection.Execute("insert #SqlNullableGeo(id, geometry) values (@Id, @Geometry)", obj); var row = connection.Query<HazSqlGeo>("select * from #SqlNullableGeo where id=1").SingleOrDefault(); Assert.NotNull(row); Assert.Equal(1, row.Id); Assert.Null(row.Geometry); } [Fact] public void SqlHierarchyId_SO18888911() { SkipIfMsDataClient(); SqlMapper.ResetTypeHandlers(); var row = connection.Query<HazSqlHierarchy>("select 3 as [Id], hierarchyid::Parse('/1/2/3/') as [Path]").Single(); Assert.Equal(3, row.Id); Assert.NotEqual(default(SqlHierarchyId), row.Path); var val = connection.Query<SqlHierarchyId>("select @Path", row).Single(); Assert.NotEqual(default(SqlHierarchyId), val); } public class HazSqlHierarchy { public int Id { get; set; } public SqlHierarchyId Path { get; set; } } #endif [Fact] public void TestDynamicParameters() { var args = new DbDynamicParams { Provider.CreateRawParameter("foo", 123), Provider.CreateRawParameter("bar", "abc") }; var result = connection.Query("select Foo=@foo, Bar=@bar", args).Single(); int foo = result.Foo; string bar = result.Bar; Assert.Equal(123, foo); Assert.Equal("abc", bar); } [Fact] public void TestDynamicParametersReuse() { var args = new DbDynamicParams { Provider.CreateRawParameter("foo", 123), Provider.CreateRawParameter("bar", "abc") }; var result1 = connection.Query("select Foo=@foo, Bar=@bar", args).Single(); var result2 = connection.Query("select Foo=@foo, Bar=@bar", args).Single(); Assert.Equal(123, result1.Foo); Assert.Equal("abc", result1.Bar); Assert.Equal(123, result2.Foo); Assert.Equal("abc", result2.Bar); } [Fact] public void TestCustomParameter() { var args = new { foo = new DbCustomParam(Provider.CreateRawParameter("foo", 123)), bar = "abc" }; var result = connection.Query("select Foo=@foo, Bar=@bar", args).Single(); int foo = result.Foo; string bar = result.Bar; Assert.Equal(123, foo); Assert.Equal("abc", bar); } [Fact] public void TestCustomParameterReuse() { var args = new { foo = new DbCustomParam(Provider.CreateRawParameter("foo", 123)), bar = "abc" }; var result1 = connection.Query("select Foo=@foo, Bar=@bar", args).Single(); var result2 = connection.Query("select Foo=@foo, Bar=@bar", args).Single(); Assert.Equal(123, result1.Foo); Assert.Equal("abc", result1.Bar); Assert.Equal(123, result2.Foo); Assert.Equal("abc", result2.Bar); } [Fact] public void TestDynamicParamNullSupport() { var p = new DynamicParameters(); p.Add("@b", dbType: DbType.Int32, direction: ParameterDirection.Output); connection.Execute("select @b = null", p); Assert.Null(p.Get<int?>("@b")); } [Fact] public void TestAppendingAnonClasses() { var p = new DynamicParameters(); p.AddDynamicParams(new { A = 1, B = 2 }); p.AddDynamicParams(new { C = 3, D = 4 }); var result = connection.Query("select @A a,@B b,@C c,@D d", p).Single(); Assert.Equal(1, (int)result.a); Assert.Equal(2, (int)result.b); Assert.Equal(3, (int)result.c); Assert.Equal(4, (int)result.d); } [Fact] public void TestAppendingADictionary() { var dictionary = new Dictionary<string, object>(2) { ["A"] = 1, ["B"] = "two" }; var p = new DynamicParameters(); p.AddDynamicParams(dictionary); var result = connection.Query("select @A a, @B b", p).Single(); Assert.Equal(1, (int)result.a); Assert.Equal("two", (string)result.b); } [Fact] public void TestAppendingAnExpandoObject() { dynamic expando = new ExpandoObject(); expando.A = 1; expando.B = "two"; var p = new DynamicParameters(); p.AddDynamicParams(expando); var result = connection.Query("select @A a, @B b", p).Single(); Assert.Equal(1, (int)result.a); Assert.Equal("two", (string)result.b); } [Fact] public void TestAppendingAList() { var p = new DynamicParameters(); var list = new int[] { 1, 2, 3 }; p.AddDynamicParams(new { list }); var result = connection.Query<int>("select * from (select 1 A union all select 2 union all select 3) X where A in @list", p).ToList(); Assert.Equal(1, result[0]); Assert.Equal(2, result[1]); Assert.Equal(3, result[2]); } [Fact] public void TestAppendingAListAsDictionary() { var p = new DynamicParameters(); var list = new int[] { 1, 2, 3 }; var args = new Dictionary<string, object>(1) { ["ids"] = list }; p.AddDynamicParams(args); var result = connection.Query<int>("select * from (select 1 A union all select 2 union all select 3) X where A in @ids", p).ToList(); Assert.Equal(1, result[0]); Assert.Equal(2, result[1]); Assert.Equal(3, result[2]); } [Fact] public void TestAppendingAListByName() { DynamicParameters p = new DynamicParameters(); var list = new int[] { 1, 2, 3 }; p.Add("ids", list); var result = connection.Query<int>("select * from (select 1 A union all select 2 union all select 3) X where A in @ids", p).ToList(); Assert.Equal(1, result[0]); Assert.Equal(2, result[1]); Assert.Equal(3, result[2]); } [Fact] public void ParameterizedInWithOptimizeHint() { const string sql = @" select count(1) from( select 1 as x union all select 2 union all select 5) y where y.x in @vals option (optimize for (@vals unKnoWn))"; int count = connection.Query<int>(sql, new { vals = new[] { 1, 2, 3, 4 } }).Single(); Assert.Equal(2, count); count = connection.Query<int>(sql, new { vals = new[] { 1 } }).Single(); Assert.Equal(1, count); count = connection.Query<int>(sql, new { vals = new int[0] }).Single(); Assert.Equal(0, count); } [Fact] public void TestProcedureWithTimeParameter() { var p = new DynamicParameters(); p.Add("a", TimeSpan.FromHours(10), dbType: DbType.Time); connection.Execute(@"CREATE PROCEDURE #TestProcWithTimeParameter @a TIME AS BEGIN SELECT @a END"); Assert.Equal(connection.Query<TimeSpan>("#TestProcWithTimeParameter", p, commandType: CommandType.StoredProcedure).First(), new TimeSpan(10, 0, 0)); } [Fact] public void TestUniqueIdentifier() { var guid = Guid.NewGuid(); var result = connection.Query<Guid>("declare @foo uniqueidentifier set @foo = @guid select @foo", new { guid }).Single(); Assert.Equal(guid, result); } [Fact] public void TestNullableUniqueIdentifierNonNull() { Guid? guid = Guid.NewGuid(); var result = connection.Query<Guid?>("declare @foo uniqueidentifier set @foo = @guid select @foo", new { guid }).Single(); Assert.Equal(guid, result); } [Fact] public void TestNullableUniqueIdentifierNull() { Guid? guid = null; var result = connection.Query<Guid?>("declare @foo uniqueidentifier set @foo = @guid select @foo", new { guid }).Single(); Assert.Equal(guid, result); } [Fact] public void TestSupportForDynamicParameters() { var p = new DynamicParameters(); p.Add("name", "bob"); p.Add("age", dbType: DbType.Int32, direction: ParameterDirection.Output); Assert.Equal("bob", connection.Query<string>("set @age = 11 select @name", p).First()); Assert.Equal(11, p.Get<int>("age")); } [Fact] public void TestSupportForDynamicParametersOutputExpressions() { var bob = new Person { Name = "bob", PersonId = 1, Address = new Address { PersonId = 2 } }; var p = new DynamicParameters(bob); p.Output(bob, b => b.PersonId); p.Output(bob, b => b.Occupation); p.Output(bob, b => b.NumberOfLegs); p.Output(bob, b => b.Address!.Name); p.Output(bob, b => b.Address!.PersonId); connection.Execute(@" SET @Occupation = 'grillmaster' SET @PersonId = @PersonId + 1 SET @NumberOfLegs = @NumberOfLegs - 1 SET @AddressName = 'bobs burgers' SET @AddressPersonId = @PersonId", p); Assert.Equal("grillmaster", bob.Occupation); Assert.Equal(2, bob.PersonId); Assert.Equal(1, bob.NumberOfLegs); Assert.Equal("bobs burgers", bob.Address.Name); Assert.Equal(2, bob.Address.PersonId); } [Fact] public void TestSupportForDynamicParametersOutputExpressions_Scalar() { using (var connection = GetOpenConnection()) { var bob = new Person { Name = "bob", PersonId = 1, Address = new Address { PersonId = 2 } }; var p = new DynamicParameters(bob); p.Output(bob, b => b.PersonId); p.Output(bob, b => b.Occupation); p.Output(bob, b => b.NumberOfLegs); p.Output(bob, b => b.Address!.Name); p.Output(bob, b => b.Address!.PersonId); var result = (int)connection.ExecuteScalar(@" SET @Occupation = 'grillmaster' SET @PersonId = @PersonId + 1 SET @NumberOfLegs = @NumberOfLegs - 1 SET @AddressName = 'bobs burgers' SET @AddressPersonId = @PersonId select 42", p)!; Assert.Equal("grillmaster", bob.Occupation); Assert.Equal(2, bob.PersonId); Assert.Equal(1, bob.NumberOfLegs); Assert.Equal("bobs burgers", bob.Address.Name); Assert.Equal(2, bob.Address.PersonId); Assert.Equal(42, result); } } [Fact] public void TestSupportForDynamicParametersOutputExpressions_Query_Buffered() { using (var connection = GetOpenConnection()) { var bob = new Person { Name = "bob", PersonId = 1, Address = new Address { PersonId = 2 } }; var p = new DynamicParameters(bob); p.Output(bob, b => b.PersonId); p.Output(bob, b => b.Occupation); p.Output(bob, b => b.NumberOfLegs); p.Output(bob, b => b.Address!.Name); p.Output(bob, b => b.Address!.PersonId); var result = connection.Query<int>(@" SET @Occupation = 'grillmaster' SET @PersonId = @PersonId + 1 SET @NumberOfLegs = @NumberOfLegs - 1 SET @AddressName = 'bobs burgers' SET @AddressPersonId = @PersonId select 42", p, buffered: true).Single(); Assert.Equal("grillmaster", bob.Occupation); Assert.Equal(2, bob.PersonId); Assert.Equal(1, bob.NumberOfLegs); Assert.Equal("bobs burgers", bob.Address.Name); Assert.Equal(2, bob.Address.PersonId); Assert.Equal(42, result); } } [Fact] public void TestSupportForDynamicParametersOutputExpressions_Query_NonBuffered() { using (var connection = GetOpenConnection()) { var bob = new Person { Name = "bob", PersonId = 1, Address = new Address { PersonId = 2 } }; var p = new DynamicParameters(bob); p.Output(bob, b => b.PersonId); p.Output(bob, b => b.Occupation); p.Output(bob, b => b.NumberOfLegs); p.Output(bob, b => b.Address!.Name); p.Output(bob, b => b.Address!.PersonId); var result = connection.Query<int>(@" SET @Occupation = 'grillmaster' SET @PersonId = @PersonId + 1 SET @NumberOfLegs = @NumberOfLegs - 1 SET @AddressName = 'bobs burgers' SET @AddressPersonId = @PersonId select 42", p, buffered: false).Single(); Assert.Equal("grillmaster", bob.Occupation); Assert.Equal(2, bob.PersonId); Assert.Equal(1, bob.NumberOfLegs); Assert.Equal("bobs burgers", bob.Address.Name); Assert.Equal(2, bob.Address.PersonId); Assert.Equal(42, result); } } [Fact] public void TestSupportForDynamicParametersOutputExpressions_QueryMultiple() { using (var connection = GetOpenConnection()) { var bob = new Person { Name = "bob", PersonId = 1, Address = new Address { PersonId = 2 } }; var p = new DynamicParameters(bob); p.Output(bob, b => b.PersonId); p.Output(bob, b => b.Occupation); p.Output(bob, b => b.NumberOfLegs); p.Output(bob, b => b.Address!.Name); p.Output(bob, b => b.Address!.PersonId); int x, y; using (var multi = connection.QueryMultiple(@" SET @Occupation = 'grillmaster' SET @PersonId = @PersonId + 1 SET @NumberOfLegs = @NumberOfLegs - 1 SET @AddressName = 'bobs burgers' select 42 select 17 SET @AddressPersonId = @PersonId", p)) { x = multi.Read<int>().Single(); y = multi.Read<int>().Single(); } Assert.Equal("grillmaster", bob.Occupation); Assert.Equal(2, bob.PersonId); Assert.Equal(1, bob.NumberOfLegs); Assert.Equal("bobs burgers", bob.Address.Name); Assert.Equal(2, bob.Address.PersonId); Assert.Equal(42, x); Assert.Equal(17, y); } } [Fact] public void TestSupportForExpandoObjectParameters() { dynamic p = new ExpandoObject(); p.name = "bob"; object parameters = p; string result = connection.Query<string>("select @name", parameters).First(); Assert.Equal("bob", result); } [Fact] public void SO25069578_DynamicParams_Procs() { var parameters = new DynamicParameters(); parameters.Add("foo", "bar"); // parameters = new DynamicParameters(parameters); try { connection.Execute("drop proc SO25069578"); } catch { /* don't care */ } connection.Execute("create proc SO25069578 @foo nvarchar(max) as select @foo as [X]"); var tran = connection.BeginTransaction(); // gist used transaction; behaves the same either way, though var row = connection.Query<HazX>("SO25069578", parameters, commandType: CommandType.StoredProcedure, transaction: tran).Single(); tran.Rollback(); Assert.Equal("bar", row.X); } public class HazX { public string? X { get; set; } } [Fact] public void SO25297173_DynamicIn() { const string query = @" declare @table table(value int not null); insert @table values(1); insert @table values(2); insert @table values(3); insert @table values(4); insert @table values(5); insert @table values(6); insert @table values(7); SELECT value FROM @table WHERE value IN @myIds"; var queryParams = new Dictionary<string, object>(1) { ["myIds"] = new[] { 5, 6 } }; var dynamicParams = new DynamicParameters(queryParams); List<int> result = connection.Query<int>(query, dynamicParams).ToList(); Assert.Equal(2, result.Count); Assert.Contains(5, result); Assert.Contains(6, result); } [Fact] public void Test_AddDynamicParametersRepeatedShouldWork() { var args = new DynamicParameters(); args.AddDynamicParams(new { Foo = 123 }); args.AddDynamicParams(new { Foo = 123 }); int i = connection.Query<int>("select @Foo", args).Single(); Assert.Equal(123, i); } [Fact] public void Test_AddDynamicParametersRepeatedIfParamTypeIsDbStiringShouldWork() { var foo = new DbString() { Value = "123" }; var args = new DynamicParameters(); args.AddDynamicParams(new { Foo = foo }); args.AddDynamicParams(new { Foo = foo }); int i = connection.Query<int>("select @Foo", args).Single(); Assert.Equal(123, i); } [Fact] public void AllowIDictionaryParameters() { var parameters = new Dictionary<string, object>(1) { ["param1"] = 0 }; connection.Query("SELECT @param1", parameters); } [Fact] public void TestParameterWithIndexer() { connection.Execute(@"create proc #TestProcWithIndexer @A int as begin select @A end"); var item = connection.Query<int>("#TestProcWithIndexer", new ParameterWithIndexer(), commandType: CommandType.StoredProcedure).Single(); } public class ParameterWithIndexer { public int A { get; set; } public virtual string? this[string columnName] { get { return null; } set { } } } [Fact] public void TestMultipleParametersWithIndexer() { var order = connection.Query<MultipleParametersWithIndexer>("select 1 A,2 B").First(); Assert.Equal(1, order.A); Assert.Equal(2, order.B); } public class MultipleParametersWithIndexer : MultipleParametersWithIndexerDeclaringType { public int A { get; set; } } public class MultipleParametersWithIndexerDeclaringType { public object? this[object field] { get { return null; } set { } } public object? this[object field, int index] { get { return null; } set { } } public int B { get; set; } } [Fact] public void Issue182_BindDynamicObjectParametersAndColumns() { connection.Execute("create table #Dyno ([Id] uniqueidentifier primary key, [Name] nvarchar(50) not null, [Foo] bigint not null);"); var guid = Guid.NewGuid(); var orig = new Dyno { Name = "T Rex", Id = guid, Foo = 123L }; var result = connection.Execute("insert into #Dyno ([Id], [Name], [Foo]) values (@Id, @Name, @Foo);", orig); var fromDb = connection.Query<Dyno>("select * from #Dyno where Id=@Id", orig).Single(); Assert.Equal((Guid)fromDb.Id, guid); Assert.Equal("T Rex", fromDb.Name); Assert.NotNull(fromDb.Foo); Assert.Equal(123L, (long)fromDb.Foo); } public class Dyno { public dynamic? Id { get; set; } public string? Name { get; set; } public object? Foo { get; set; } } [Fact] public void Issue151_ExpandoObjectArgsQuery() { dynamic args = new ExpandoObject(); args.Id = 123; args.Name = "abc"; var row = connection.Query("select @Id as [Id], @Name as [Name]", (object)args).Single(); Assert.Equal(123, (int)row.Id); Assert.Equal("abc", (string)row.Name); } [Fact] public void Issue151_ExpandoObjectArgsExec() { dynamic args = new ExpandoObject(); args.Id = 123; args.Name = "abc"; connection.Execute("create table #issue151 (Id int not null, Name nvarchar(20) not null)"); Assert.Equal(1, connection.Execute("insert #issue151 values(@Id, @Name)", (object)args)); var row = connection.Query("select Id, Name from #issue151").Single(); Assert.Equal(123, (int)row.Id); Assert.Equal("abc", (string)row.Name); } [Fact] public void Issue192_InParameterWorksWithSimilarNames() { var rows = connection.Query(@" declare @Issue192 table ( Field INT NOT NULL PRIMARY KEY IDENTITY(1,1), Field_1 INT NOT NULL); insert @Issue192(Field_1) values (1), (2), (3); SELECT * FROM @Issue192 WHERE Field IN @Field AND Field_1 IN @Field_1", new { Field = new[] { 1, 2 }, Field_1 = new[] { 2, 3 } }).Single(); Assert.Equal(2, (int)rows.Field); Assert.Equal(2, (int)rows.Field_1); } [Fact] public void Issue192_InParameterWorksWithSimilarNamesWithUnicode() { var rows = connection.Query(@" declare @Issue192 table ( Field INT NOT NULL PRIMARY KEY IDENTITY(1,1), Field_1 INT NOT NULL); insert @Issue192(Field_1) values (1), (2), (3); SELECT * FROM @Issue192 WHERE Field IN @µ AND Field_1 IN @µµ", new { µ = new[] { 1, 2 }, µµ = new[] { 2, 3 } }).Single(); Assert.Equal(2, (int)rows.Field); Assert.Equal(2, (int)rows.Field_1); } [FactUnlessCaseSensitiveDatabase] public void Issue220_InParameterCanBeSpecifiedInAnyCase() { // note this might fail if your database server is case-sensitive Assert.Equal( new[] { 1 }, connection.Query<int>("select * from (select 1 as Id) as X where Id in @ids", new { Ids = new[] { 1 } }) ); } [Fact] public void SO30156367_DynamicParamsWithoutExec() { var dbParams = new DynamicParameters(); dbParams.Add("Field1", 1); var value = dbParams.Get<int>("Field1"); Assert.Equal(1, value); } [Fact] public void RunAllStringSplitTestsDisabled() { RunAllStringSplitTests(-1, 1500); } [FactRequiredCompatibilityLevel(FactRequiredCompatibilityLevelAttribute.SqlServer2016)] public void RunAllStringSplitTestsEnabled() { RunAllStringSplitTests(10, 4500); } private void RunAllStringSplitTests(int stringSplit, int max = 150) { int oldVal = SqlMapper.Settings.InListStringSplitCount; try { SqlMapper.Settings.InListStringSplitCount = stringSplit; try { connection.Execute("drop table #splits"); } catch { /* don't care */ } int count = connection.QuerySingle<int>("create table #splits (i int not null);" + string.Concat(Enumerable.Range(-max, max * 3).Select(i => $"insert #splits (i) values ({i});")) + "select count(1) from #splits"); Assert.Equal(count, 3 * max); for (int i = 0; i < max; Incr(ref i)) { try { var vals = Enumerable.Range(1, i); var list = connection.Query<int>("select i from #splits where i in @vals", new { vals }).AsList(); Assert.Equal(list.Count, i); Assert.Equal(list.Sum(), vals.Sum()); } catch (Exception ex) { throw new InvalidOperationException($"Error when i={i}: {ex.Message}", ex); } } } finally { SqlMapper.Settings.InListStringSplitCount = oldVal; } } private static void Incr(ref int i) { if (i <= 15) i++; else if (i <= 80) i += 5; else if (i <= 200) i += 10; else if (i <= 1000) i += 50; else i += 100; } [Fact] public void Issue601_InternationalParameterNamesWork() { // regular parameter var result = connection.QuerySingle<int>("select @æøå٦", new { æøå٦ = 42 }); Assert.Equal(42, result); } [FactLongRunning] public void TestListExpansionPadding_Enabled() => TestListExpansionPadding(true); [FactLongRunning] public void TestListExpansionPadding_Disabled() => TestListExpansionPadding(false); [Theory] [InlineData(true)] [InlineData(false)] public void OleDbParamFilterFails(bool legacyParameterToken) { SqlMapper.PurgeQueryCache(); var oldValue = SqlMapper.Settings.SupportLegacyParameterTokens; try { SqlMapper.Settings.SupportLegacyParameterTokens = legacyParameterToken; if (legacyParameterToken) // OLE DB parameter support enabled; can false-positive { Assert.Throws<NotSupportedException>(() => GetValue(connection)); } else // OLE DB parameter support disabled; more reliable { Assert.Equal("this ? could be awkward", GetValue(connection)); } } finally { SqlMapper.Settings.SupportLegacyParameterTokens = oldValue; } static string GetValue(DbConnection connection) => connection.QuerySingle<string>("select 'this ? could be awkward'", new TypeWithDodgyProperties()); } private void TestListExpansionPadding(bool enabled) { bool oldVal = SqlMapper.Settings.PadListExpansions; try { SqlMapper.Settings.PadListExpansions = enabled; Assert.Equal(4096, connection.ExecuteScalar<int>(@" create table #ListExpansion(id int not null identity(1,1), value int null); insert #ListExpansion (value) values (null); declare @loop int = 0; while (@loop < 12) begin -- double it insert #ListExpansion (value) select value from #ListExpansion; set @loop = @loop + 1; end select count(1) as [Count] from #ListExpansion")); var list = new List<int>(); int nextId = 1, batchCount; var rand = new Random(12345); const int SQL_SERVER_MAX_PARAMS = 2095; TestListForExpansion(list, enabled); // test while empty while (list.Count < SQL_SERVER_MAX_PARAMS) { try { if (list.Count <= 20) batchCount = 1; else if (list.Count <= 200) batchCount = rand.Next(1, 40); else batchCount = rand.Next(1, 100); for (int j = 0; j < batchCount && list.Count < SQL_SERVER_MAX_PARAMS; j++) list.Add(nextId++); TestListForExpansion(list, enabled); } catch (Exception ex) { throw new InvalidOperationException($"Failure with {list.Count} items: {ex.Message}", ex); } } } finally { SqlMapper.Settings.PadListExpansions = oldVal; } } private void TestListForExpansion(List<int> list, bool enabled) { var row = connection.QuerySingle(@" declare @hits int, @misses int, @count int; select @count = count(1) from #ListExpansion; select @hits = count(1) from #ListExpansion where id in @ids ; select @misses = count(1) from #ListExpansion where not id in @ids ; declare @query nvarchar(max) = N' in @ids '; -- ok, I confess to being pleased with this hack ;p select @hits as [Hits], (@count - @misses) as [Misses], @query as [Query]; ", new { ids = list }); int hits = row.Hits, misses = row.Misses; string query = row.Query; int argCount = Regex.Matches(query, "@ids[0-9]").Count; int expectedCount = GetExpectedListExpansionCount(list.Count, enabled); Assert.Equal(hits, list.Count); Assert.Equal(misses, list.Count); Assert.Equal(argCount, expectedCount); } private static int GetExpectedListExpansionCount(int count, bool enabled) { if (!enabled) return count; if (count <= 5 || count > 2070) return count; int padFactor; if (count <= 150) padFactor = 10; else if (count <= 750) padFactor = 50; else if (count <= 2000) padFactor = 100; else if (count <= 2070) padFactor = 10; else padFactor = 200; int blocks = count / padFactor, delta = count % padFactor; if (delta != 0) blocks++; return blocks * padFactor; } [Fact] public void Issue1907_SqlDecimalPreciseValues() { bool close = false; try { if (connection.State != ConnectionState.Open) { connection.Open(); close = true; } connection.Execute(@" create table #Issue1907 ( Id int not null primary key identity(1,1), Value numeric(30,15) not null);"); const string PreciseValue = "999999999999999.999999999999999"; SqlDecimal sentValue = SqlDecimal.Parse(PreciseValue), recvValue; connection.Execute("insert #Issue1907 (Value) values (@value)", new { value = sentValue }); // access via vendor-specific API; if this fails, nothing else can work using (var wrappedReader = connection.ExecuteReader("select Id, Value from #Issue1907")) { var reader = Assert.IsAssignableFrom<IWrappedDataReader>(wrappedReader).Reader; Assert.True(reader.Read()); if (reader is Microsoft.Data.SqlClient.SqlDataReader msReader) { recvValue = msReader.GetSqlDecimal(1); } #pragma warning disable CS0618 // Type or member is obsolete else if (reader is System.Data.SqlClient.SqlDataReader sdReader) { recvValue = sdReader.GetSqlDecimal(1); } #pragma warning restore CS0618 // Type or member is obsolete else { throw new InvalidOperationException($"unexpected reader type: {reader.GetType().FullName}"); } Assert.Equal(sentValue, recvValue); Assert.Equal(PreciseValue, recvValue.ToString()); Assert.False(reader.Read()); Assert.False(reader.NextResult()); } // access via generic API using (var wrappedReader = connection.ExecuteReader("select Id, Value from #Issue1907")) { var reader = Assert.IsAssignableFrom<DbDataReader>(Assert.IsAssignableFrom<IWrappedDataReader>(wrappedReader).Reader); Assert.True(reader.Read()); recvValue = reader.GetFieldValue<SqlDecimal>(1); Assert.Equal(sentValue, recvValue); Assert.Equal(PreciseValue, recvValue.ToString()); Assert.False(reader.Read()); Assert.False(reader.NextResult()); } // prove that we **cannot** fix ExecuteScalar, because ADO.NET itself doesn't work for that Assert.Throws<OverflowException>(() => { using var cmd = connection.CreateCommand(); cmd.CommandText = "select Value from #Issue1907"; cmd.CommandType = CommandType.Text; _ = cmd.ExecuteScalar(); }); // prove that simple read: works recvValue = connection.QuerySingle<SqlDecimal>("select Value from #Issue1907"); Assert.Equal(sentValue, recvValue); Assert.Equal(PreciseValue, recvValue.ToString()); recvValue = connection.QuerySingle<SqlDecimal?>("select Value from #Issue1907")!.Value; Assert.Equal(sentValue, recvValue); Assert.Equal(PreciseValue, recvValue.ToString()); // prove that object read: works recvValue = connection.QuerySingle<HazSqlDecimal>("select Id, Value from #Issue1907").Value; Assert.Equal(sentValue, recvValue); Assert.Equal(PreciseValue, recvValue.ToString()); recvValue = connection.QuerySingle<HazNullableSqlDecimal>("select Id, Value from #Issue1907").Value!.Value; Assert.Equal(sentValue, recvValue); Assert.Equal(PreciseValue, recvValue.ToString()); // prove that value-tuple read: works recvValue = connection.QuerySingle<(int Id, SqlDecimal Value)>("select Id, Value from #Issue1907").Value; Assert.Equal(sentValue, recvValue); Assert.Equal(PreciseValue, recvValue.ToString()); recvValue = connection.QuerySingle<(int Id, SqlDecimal? Value)>("select Id, Value from #Issue1907").Value!.Value; Assert.Equal(sentValue, recvValue); Assert.Equal(PreciseValue, recvValue.ToString()); } finally { if (close) connection.Close(); } } class HazSqlDecimal { public int Id { get; set; } public SqlDecimal Value { get; set; } } class HazNullableSqlDecimal { public int Id { get; set; } public SqlDecimal? Value { get; set; } } class TypeWithDodgyProperties { public string Name => throw new NotSupportedException(); } } }
Dapper
You are an expert .NET (C#) developer. Task: Write a unit test for 'TargetModule' using XUnit and Moq. Context: - Class: TargetModule Requirements: Use Mock<T> interface mocking.
industrial
using BenchmarkDotNet.Attributes; using Dapper.Tests.Performance.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using System; using System.ComponentModel; using System.Linq; namespace Dapper.Tests.Performance { [Description("EF Core")] public class EFCoreBenchmarks : BenchmarkBase { private EFCoreContext Context; private static readonly Func<EFCoreContext, int, Post> compiledQuery = EF.CompileQuery((EFCoreContext ctx, int id) => ctx.Posts.First(p => p.Id == id)); [GlobalSetup] public void Setup() { BaseSetup(); Context = new EFCoreContext(ConnectionString); } [Benchmark(Description = "First")] public Post First() { Step(); return Context.Posts.First(p => p.Id == i); } [Benchmark(Description = "First (Compiled)")] public Post Compiled() { Step(); return compiledQuery(Context, i); } [Benchmark(Description = "SqlQuery")] public Post SqlQuery() { Step(); return Context.Posts.FromSqlRaw("select * from Posts where Id = {0}", i).First(); } [Benchmark(Description = "First (No Tracking)")] public Post NoTracking() { Step(); return Context.Posts.AsNoTracking().First(p => p.Id == i); } } }
#if ENTITY_FRAMEWORK using System; using System.Data.Entity.Spatial; using System.Linq; using Xunit; namespace Dapper.Tests.Providers { public sealed class SystemSqlClientEntityFrameworkTests : EntityFrameworkTests<SystemSqlClientProvider> { } #if MSSQLCLIENT public sealed class MicrosoftSqlClientEntityFrameworkTests : EntityFrameworkTests<MicrosoftSqlClientProvider> { } #endif [Collection("TypeHandlerTests")] public abstract class EntityFrameworkTests<TProvider> : TestBase<TProvider> where TProvider : DatabaseProvider { public EntityFrameworkTests() { EntityFramework.Handlers.Register(); } [Fact] public void Issue570_DbGeo_HasValues() { SkipIfMsDataClient(); EntityFramework.Handlers.Register(); const string redmond = "POINT (-122.1215 47.6740)"; DbGeography point = DbGeography.PointFromText(redmond, DbGeography.DefaultCoordinateSystemId); DbGeography orig = point.Buffer(20); var fromDb = connection.QuerySingle<DbGeography>("declare @geos table(geo geography); insert @geos(geo) values(@val); select * from @geos", new { val = orig }); Assert.NotNull(fromDb.Area); Assert.Equal(orig.Area, fromDb.Area); } [Fact] public void Issue22_ExecuteScalar_EntityFramework() { SkipIfMsDataClient(); var geo = DbGeography.LineFromText("LINESTRING(-122.360 47.656, -122.343 47.656 )", 4326); var geo2 = connection.ExecuteScalar<DbGeography>("select @geo", new { geo }); Assert.NotNull(geo2); } [Fact] public void TestGeometryParsingRetainsSrid() { const int srid = 27700; var s = $@"DECLARE @EdinburghPoint GEOMETRY = geometry::STPointFromText('POINT(258647 665289)', {srid}); SELECT @EdinburghPoint"; var edinPoint = connection.Query<DbGeometry>(s).Single(); Assert.NotNull(edinPoint); Assert.Equal(srid, edinPoint.CoordinateSystemId); } [Fact] public void TestGeographyParsingRetainsSrid() { const int srid = 4324; var s = $@"DECLARE @EdinburghPoint GEOGRAPHY = geography::STPointFromText('POINT(-3.19 55.95)', {srid}); SELECT @EdinburghPoint"; var edinPoint = connection.Query<DbGeography>(s).Single(); Assert.NotNull(edinPoint); Assert.Equal(srid, edinPoint.CoordinateSystemId); } } } #endif
Dapper
You are an expert .NET (C#) developer. Task: Write a unit test for 'TargetModule' using XUnit and Moq. Context: - Class: TargetModule Requirements: Use Mock<T> interface mocking.
industrial
#if NET4X using BenchmarkDotNet.Attributes; using Dapper.Tests.Performance.Linq2Sql; using System; using System.ComponentModel; using System.Data.Linq; using System.Linq; namespace Dapper.Tests.Performance { [Description("LINQ to SQL")] public class LinqToSqlBenchmarks : BenchmarkBase // note To not 2 because the "2" confuses BDN CLI { private DataClassesDataContext Linq2SqlContext; private static readonly Func<DataClassesDataContext, int, Linq2Sql.Post> compiledQuery = CompiledQuery.Compile((DataClassesDataContext ctx, int id) => ctx.Posts.First(p => p.Id == id)); [GlobalSetup] public void Setup() { BaseSetup(); Linq2SqlContext = new DataClassesDataContext(_connection); } [Benchmark(Description = "First")] public Linq2Sql.Post First() { Step(); return Linq2SqlContext.Posts.First(p => p.Id == i); } [Benchmark(Description = "First (Compiled)")] public Linq2Sql.Post Compiled() { Step(); return compiledQuery(Linq2SqlContext, i); } [Benchmark(Description = "ExecuteQuery")] public Post ExecuteQuery() { Step(); return Linq2SqlContext.ExecuteQuery<Post>("select * from Posts where Id = {0}", i).First(); } } } #endif
#if LINQ2SQL using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; namespace Dapper.Tests { public sealed class SystemSqlClientLinq2SqlTests : Linq2SqlTests<SystemSqlClientProvider> { } #if MSSQLCLIENT public sealed class MicrosoftSqlClientLinq2SqlTests : Linq2SqlTests<MicrosoftSqlClientProvider> { } #endif public abstract class Linq2SqlTests<TProvider> : TestBase<TProvider> where TProvider : DatabaseProvider { [Fact] public void TestLinqBinaryToClass() { byte[] orig = new byte[20]; new Random(123456).NextBytes(orig); var input = new System.Data.Linq.Binary(orig); var output = connection.Query<WithBinary>("select @input as [Value]", new { input }).First().Value; Assert.Equal(orig, output?.ToArray()); } [Fact] public void TestLinqBinaryRaw() { byte[] orig = new byte[20]; new Random(123456).NextBytes(orig); var input = new System.Data.Linq.Binary(orig); var output = connection.Query<System.Data.Linq.Binary>("select @input as [Value]", new { input }).First(); Assert.Equal(orig, output.ToArray()); } private class WithBinary { public System.Data.Linq.Binary? Value { get; set; } } private class NoDefaultConstructorWithBinary { public System.Data.Linq.Binary Value { get; set; } public int Ynt { get; set; } public NoDefaultConstructorWithBinary(System.Data.Linq.Binary val) { Value = val; } } [Fact] public void TestNoDefaultConstructorBinary() { byte[] orig = new byte[20]; new Random(123456).NextBytes(orig); var input = new System.Data.Linq.Binary(orig); var output = connection.Query<NoDefaultConstructorWithBinary>("select @input as val", new { input }).First().Value; Assert.Equal(orig, output.ToArray()); } } } #endif
Dapper
You are an expert .NET (C#) developer. Task: Write a unit test for 'TargetModule' using XUnit and Moq. Context: - Class: TargetModule Requirements: Use Mock<T> interface mocking.