Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fill Readonly Collection Properties Behavior #1177

Merged
merged 15 commits into from
Apr 14, 2021
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions Src/AutoFixture/FillReadonlyCollectionPropertiesBehavior.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
using System;
using AutoFixture.Kernel;

namespace AutoFixture
{
/// <summary>
/// Decorates <see cref="ISpecimenBuilder"/> with a <see cref="Postprocessor"/> which invokes
/// <see cref="FillReadonlyCollectionPropertiesCommand"/> if the specimen meets the
/// <see cref="ReadonlyCollectionPropertiesSpecification"/>.
/// </summary>
public class FillReadonlyCollectionPropertiesBehavior : ISpecimenBuilderTransformation
charles-salmon marked this conversation as resolved.
Show resolved Hide resolved
{
/// <summary>
/// Decorates the supplied <see cref="ISpecimenBuilder"/> with a <see cref="Postprocessor"/> which invokes
/// <see cref="FillReadonlyCollectionPropertiesCommand"/> if the specimen meets the
/// <see cref="ReadonlyCollectionPropertiesSpecification"/>.
/// </summary>
/// <param name="builder">
/// The builder to decorate.
/// </param>
/// <returns>
/// <paramref name="builder"/> decorated with a <see cref="Postprocessor"/>.
/// </returns>
/// <exception cref="ArgumentNullException">
/// Thrown if <paramref name="builder"/> is <see langword="null"/>.
/// </exception>
public ISpecimenBuilderNode Transform(ISpecimenBuilder builder)
{
if (builder == null) throw new ArgumentNullException(nameof(builder));

return new Postprocessor(
builder,
new FillReadonlyCollectionPropertiesCommand(),
new ReadonlyCollectionPropertiesSpecification());
}
}
}
1 change: 1 addition & 0 deletions Src/AutoFixture/Fixture.cs
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,7 @@ public Fixture(ISpecimenBuilder engine, MultipleRelay multiple)
this.UpdateGraphAndSetupAdapters(newGraph, Enumerable.Empty<ISpecimenBuilderTransformation>());

this.Behaviors.Add(new ThrowingRecursionBehavior());
this.Behaviors.Add(new FillReadonlyCollectionPropertiesBehavior());
}

/// <inheritdoc />
Expand Down
73 changes: 73 additions & 0 deletions Src/AutoFixture/Kernel/FillReadonlyCollectionPropertiesCommand.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;

namespace AutoFixture.Kernel
{
/// <summary>
/// A command which invokes <see cref="ICollection{T}.Add"/> to fill all readonly properties in a specimen that
/// implement <see cref="ICollection{T}"/>.
/// </summary>
public class FillReadonlyCollectionPropertiesCommand : ISpecimenCommand
{
/// <summary>
/// Invokes <see cref="ICollection{T}.Add"/> to fill all readonly properties in a specimen that implement
/// <see cref="ICollection{T}"/>.
/// </summary>
/// <param name="specimen">
/// The specimen on which readonly collection properties should be filled.
/// </param>
/// <param name="context">
/// An <see cref="ISpecimenContext"/> that is used to create the elements used to fill collections.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown if <paramref name="specimen"/> or <paramref name="context"/> is <see langword="null"/>.
/// </exception>
public void Execute(object specimen, ISpecimenContext context)
{
if (specimen == null) throw new ArgumentNullException(nameof(specimen));
if (context == null) throw new ArgumentNullException(nameof(context));

var specimenType = specimen.GetType();
foreach (var pi in GetReadonlyCollectionProperties(specimenType))
{
var propertyType = pi.PropertyType;
var collectionTypeGenericArgument = propertyType.GenericTypeArguments[0];
charles-salmon marked this conversation as resolved.
Show resolved Hide resolved

var addMethod = propertyType.GetTypeInfo().GetMethod(nameof(ICollection<object>.Add));
aivascu marked this conversation as resolved.
Show resolved Hide resolved
if (addMethod == null) continue;

var valuesToAdd = CreateMany(context, collectionTypeGenericArgument);

foreach (var valueToAdd in valuesToAdd)
{
addMethod.Invoke(pi.GetValue(specimen), new[] { valueToAdd });
}
}
}

private static IEnumerable<PropertyInfo> GetReadonlyCollectionProperties(Type type)
charles-salmon marked this conversation as resolved.
Show resolved Hide resolved
{
return type.GetTypeInfo()
.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty)
charles-salmon marked this conversation as resolved.
Show resolved Hide resolved
.Where(pi => pi.GetSetMethod() == null
&& pi.PropertyType.GenericTypeArguments?.Length == 1
&& (pi.PropertyType.Name == typeof(ICollection<>).Name
|| pi.PropertyType.GetTypeInfo().GetInterface(typeof(ICollection<>).Name) != null));
}

private static IEnumerable<object> CreateMany(ISpecimenContext context, Type type)
charles-salmon marked this conversation as resolved.
Show resolved Hide resolved
{
return ((IEnumerable<object>)context.Resolve(
new MultipleRequest(new SeededRequest(type, GetDefaultValue(type)))))
.Select(v => Convert.ChangeType(v, type, CultureInfo.CurrentCulture));
charles-salmon marked this conversation as resolved.
Show resolved Hide resolved
}

private static object GetDefaultValue(Type type)
charles-salmon marked this conversation as resolved.
Show resolved Hide resolved
{
return type.GetTypeInfo().IsValueType ? Activator.CreateInstance(type) : null;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

namespace AutoFixture.Kernel
{
/// <summary>
/// A specification that evaluates whether or not a request is for a type containing readonly properties that
/// implement <see cref="ICollection{T}"/>.
/// </summary>
public class ReadonlyCollectionPropertiesSpecification : IRequestSpecification
{
/// <summary>
/// Evaluates whether or not the <paramref name="request"/> is for a type containing readonly properties that
/// implement <see cref="ICollection{T}"/>.
/// </summary>
/// <param name="request">
/// The specimen request.
/// </param>
/// <returns>
/// <see langword="true"/> if the <paramref name="request"/> is for a type containing readonly properties that
/// implement <see cref="ICollection{T}"/>; <see langword="false"/> otherwise.
/// </returns>
public bool IsSatisfiedBy(object request)
{
if (!(request is Type requestType)) return false;
charles-salmon marked this conversation as resolved.
Show resolved Hide resolved
if (typeof(Expression).GetTypeInfo().IsAssignableFrom(requestType)) return false;
charles-salmon marked this conversation as resolved.
Show resolved Hide resolved

return requestType.GetTypeInfo()
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Any(pi => pi.GetSetMethod() == null
charles-salmon marked this conversation as resolved.
Show resolved Hide resolved
&& pi.PropertyType.GenericTypeArguments?.Length == 1
&& (pi.PropertyType.Name == typeof(ICollection<>).Name
|| pi.PropertyType.GetTypeInfo().GetInterface(typeof(ICollection<>).Name) != null));
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
using System;
using AutoFixture;
using AutoFixture.Kernel;
using AutoFixtureUnitTest.Kernel;
using Xunit;

namespace AutoFixtureUnitTest
{
public class FillReadonlyCollectionPropertiesBehaviorTest
{
[Fact]
public void SutIsBuilderTransformation()
{
// Arrange
// Act
var sut = new FillReadonlyCollectionPropertiesBehavior();

// Assert
Assert.IsAssignableFrom<ISpecimenBuilderTransformation>(sut);
}

[Fact]
public void TransformNullBuilderThrows()
{
// Arrange
var sut = new FillReadonlyCollectionPropertiesBehavior();

// Act
// Assert
Assert.Throws<ArgumentNullException>(() => sut.Transform(null));
}

[Fact]
public void TransformReturnsPostprocessor()
{
// Arrange
var sut = new FillReadonlyCollectionPropertiesBehavior();
var dummyBuilder = new DelegatingSpecimenBuilder();

// Act
var result = sut.Transform(dummyBuilder);

// Assert
Assert.IsAssignableFrom<Postprocessor>(result);
}

[Fact]
public void TransformReturnsPostprocessorWhichDecoratesInput()
{
// Arrange
var sut = new FillReadonlyCollectionPropertiesBehavior();
var expectedBuilder = new DelegatingSpecimenBuilder();

// Act
var result = sut.Transform(expectedBuilder);

// Assert
var p = Assert.IsAssignableFrom<Postprocessor>(result);
Assert.IsAssignableFrom<ISpecimenBuilder>(p.Builder);
}

[Fact]
public void TransformReturnsPostprocessorWhichContainsAppropriateCommand()
{
// Arrange
var sut = new FillReadonlyCollectionPropertiesBehavior();
var dummyBuilder = new DelegatingSpecimenBuilder();

// Act
var result = sut.Transform(dummyBuilder);

// Assert
var p = Assert.IsAssignableFrom<Postprocessor>(result);
Assert.IsAssignableFrom<FillReadonlyCollectionPropertiesCommand>(p.Command);
}

[Fact]
public void TransformReturnsPostprocessorWhichContainsAppropriateSpecification()
{
// Arrange
var sut = new FillReadonlyCollectionPropertiesBehavior();
var dummyBuilder = new DelegatingSpecimenBuilder();

// Act
var result = sut.Transform(dummyBuilder);

// Assert
var p = Assert.IsAssignableFrom<Postprocessor>(result);
Assert.IsAssignableFrom<ReadonlyCollectionPropertiesSpecification>(p.Specification);
}
}
}
35 changes: 35 additions & 0 deletions Src/AutoFixtureUnitTest/FixtureTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,17 @@ public void BehaviorsContainsCorrectRecursionBehavior()
Assert.True(result.OfType<ThrowingRecursionBehavior>().Any());
}

[Fact]
public void BehaviorsContainsFillReadonlyCollectionPropertiesBehavior()
{
// Arrange
var sut = new Fixture();
// Act
var result = sut.Behaviors;
// Assert
Assert.True(result.OfType<FillReadonlyCollectionPropertiesBehavior>().Any());
}

[Fact]
public void SutIsCustomizableComposer()
{
Expand Down Expand Up @@ -766,6 +777,30 @@ public void CreateAnonymousWithDoubleMixedNumericPropertiesWillAssignDifferentVa
Assert.NotEqual(result.Property1, result.Property2);
}

[Fact]
public void CreateAnonymousWithReadonlyCollectionPropertiesFillsCollections()
{
// Arrange
var sut = new Fixture();
// Act
var result = sut.Create<CollectionHolder<string>>();
// Assert
Assert.NotEmpty(result.Collection);
}

[Fact]
public void CreateAnonymousWithReadonlyCollectionPropertiesFillsCollectionsWithRepeatCount()
{
// Arrange
var sut = new Fixture();
var expectedCount = 6;
sut.RepeatCount = expectedCount;
// Act
var result = sut.Create<CollectionHolder<string>>();
// Assert
Assert.Equal(expectedCount, result.Collection.Count);
}

[Fact]
public void CreateAnonymousWithNumericSequenceCustomizationAndDoubleMixedWholeNumericPropertiesWillAssignSameValue()
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
using System;
using AutoFixture;
using AutoFixture.Kernel;
using TestTypeFoundation;
using Xunit;

namespace AutoFixtureUnitTest.Kernel
{
public class FillReadonlyCollectionPropertiesCommandTest
{
[Fact]
public void SutIsCommand()
{
// Arrange
// Act
var sut = new FillReadonlyCollectionPropertiesCommand();

// Assert
Assert.IsAssignableFrom<ISpecimenCommand>(sut);
}

[Fact]
public void ExecuteNullSpecimenThrows()
{
// Arrange
var sut = new FillReadonlyCollectionPropertiesCommand();
var dummyContainer = new DelegatingSpecimenContext();

// Act
// Assert
Assert.Throws<ArgumentNullException>(() => sut.Execute(null, dummyContainer));
}

[Fact]
public void ExecuteNullContextThrows()
{
// Arrange
var sut = new FillReadonlyCollectionPropertiesCommand();
var dummySpecimen = new object();

// Act
// Assert
Assert.Throws<ArgumentNullException>(() => sut.Execute(dummySpecimen, null));
}

[Fact]
public void ExecuteFillsReadonlyCollectionProperty()
{
// Arrange
var sut = new FillReadonlyCollectionPropertiesCommand();
var specimen = new CollectionHolder<string>();
var container = new DelegatingSpecimenContext
{
OnResolve = r => new Fixture().CreateMany<string>()
};

// Act
sut.Execute(specimen, container);

// Assert
Assert.NotEmpty(specimen.Collection);
}

[Fact]
public void ExecuteDoesNotFillNonCompliantCollectionProperty()
{
// Arrange
var sut = new FillReadonlyCollectionPropertiesCommand();
var specimen = new NonCompliantCollectionHolder<string>();
var container = new DelegatingSpecimenContext
{
OnResolve = r => new Fixture().CreateMany<string>()
};

// Act
sut.Execute(specimen, container);

// Assert
Assert.Empty(specimen.Collection);
}
}
}
Loading