How can I customize a property's regex for AutoFixture? - autofixture

I just changed my [RegularExpression] validation and a third of my unit tests broke!
It turns out AutoFixture is generating values based on that regex, which is cool, but it doesn't understand all regexs, so I'd like to supply it with a simpler one:
Fixtures.Customize<Details>(c => c.With(d => d.PhoneNumber,
new SpecimenContext(Fixtures).Resolve(
new RegularExpressionRequest(#"[2-9]\d{2}-\d{3}-\d{4}"))));
This ends up giving me a generic LINQ error ("Sequence contains no elements.") at object creation time. What am I doing wrong?
Alternatively, is there any way I can just turn this feature off? Customize() is helpful, but it prevents me from using Build() without repeating all the same logic. (Doesn't it?)

You can't easily turn that feature off, but you can easily override it:
public class Details
{
[RegularExpression(#"?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$")]
public string PhoneNumber { get; set; }
}
public class DetailsTests
{
[Fact]
public void OverridePhoneNumberRegularExpression()
{
var fixture = new Fixture();
var pattern = #"[2-9]\d{2}-\d{3}-\d{4}";
var phoneNumber =
new SpecimenContext(fixture).Resolve(
new RegularExpressionRequest(pattern));
fixture.Customize<Details>(c => c
.With(x => x.PhoneNumber, phoneNumber));
var sut = fixture.Create<Details>();
var actual = sut.PhoneNumber;
Assert.True(Regex.IsMatch(actual, pattern));
}
}
This test passes and looks similar to the one shown in the question. – What other members are defined in Details class?

Related

How to mock Prisms IContainerRegistry

Prism.Ninject 7.1.0.431
Prism 7.1.0.431
NUnit 3.3.3
NSubstitute
Previously using Prism 6.3 we had a set of unit test to confirm that we had all of our bindings in place as follows
protected IKernel TestKernel;
[SetUp]
public void Given
{
TestKernel = new StandardKernel();
SUT = new MyModule( TestKernel );
Core = Assembly.Load( "MyDLL.Core" ).GetTypes();
Common = Assembly.Load( "MyDLL.Common" ).GetTypes();
SUT.Initialize();
}
[ Test ]
public void Then_ViewModels_Will_Be_Bound()
{
var testCollection = Common
.Where( item => item.IsPublic )
.Where( item => item.Name.EndsWith( "ViewModel" ) );
foreach ( var item in testCollection )
{
Assert.That( TestKernel.GetBindings( item ).Any, $"Test Failed: {item.Name}" );
}
}
However in Ninject 7.1, the IModule interface has changed somewhat, so now parts are registered differently in
public void RegisterTypes(
IContainerRegistry containerRegistry )
I'm just trying to get my unit tests up and running again with this new IModule format. I had tried changing my given to be as follows
protected override void Given()
{
TestKernel = new StandardKernel();
TestContainerRegistry = Substitute.For<IContainerRegistry>();
TestContainerRegistry.GetContainer().Returns( TestKernel );
SUT = new MyModule();
}
However I get the following when I attempt to run my tests.
System.InvalidCastException : Unable to cast object of type 'Castle.Proxies.IContainerRegistryProxy' to type 'Prism.Ioc.IContainerExtension`1[Ninject.IKernel]'.
If anyone has any idea how I might be able to mock this it would be appreciated, as I'm currently at an impasse.
How you should test is always a hot topic full of disagreement, so I will try to give you some general information here. Prism.Ninject implements the container abstractions with the Prism.Ninject.Ioc.NinjectContainerExtension. This has two constructors, a default and one that allows you to pass in a specific Kernel.
Prism also implements extension methods for each of the containers to pull the container from the abstraction. You can achieve this in a couple of ways:
containerRegistry.GetContainer().SomeContainerSpecificApi()
Alternatively you could do:
var app = new MyApp();
app.Container.GetContainer().SomeContainerSpecificApi();
Again there are a variety of ways that you could implement your tests and I'm not about to get into how you should test. I will however say that in the event you don't want to create an app and you're just looking to validate that your types are registered for a Prism Module you might try something like:
var containerExtension = new NinjectContainerExtension();
var module = new MyModule();
module.RegisterTypes(containerExtension);
Assert.IsTrue(containerExtension.Instance.IsRegistered<MyType>());
I think I've figured it out (or made progress at least)
Instead of substituting with IContainerRegistry I had to use the following
protected override void Given()
{
TestKernel = new StandardKernel();
TestContainerRegistry = Substitute.For<IContainerExtension<IKernel>>();
TestContainerRegistry.GetContainer().Returns( TestKernel );
SUT = new MyModule();
}
Although it looks like I'm going to have to make more substitutes etc in order to have the containerRegistry.Register (etc) wind up in my TestKernel for verification.

Generating complex types with all properties equivalent

Does AutoFixture have a facility to create multiple instances of a given type with all the same data? My classes are not serializable and I need two models which are not reference equivalent, but instead have matching properties.
public class Foo
{
// Many more properties and similar models needing the same semantics.
public string Name { get; set; }
}
var a = fixture.Create<Foo>();
var b = fixture.Create<Foo>();
Assert.False(ReferenceEquals(a, b));
Assert.Equal(a.Name, b.Name);
I don't think that AutoFixture can do this, but Albedo can. While this is only proof-of-concept code, it should illustrate the general idea, I hope.
Create a new class, deriving from ReflectionVisitor<T>:
public class PropertyCopyVisitor<T> : ReflectionVisitor<T>
{
private readonly T source;
private readonly T destination;
public PropertyCopyVisitor(T source, T destination)
{
this.source = source;
this.destination = destination;
}
public override IReflectionVisitor<T> Visit(
PropertyInfoElement propertyInfoElement)
{
var pi = propertyInfoElement.PropertyInfo;
pi.SetValue(this.destination, pi.GetValue(this.source));
return this;
}
public override T Value
{
get { return this.destination; }
}
}
The pivotal part of the implementation is the Visit overload where it uses Reflection to copy each property from source to destination object.
Since this implementation mutates destination, the Value property is never used, but it has to be there because it's abstract in ReflectionVisitor<T>...
You can now write your test as:
var fixture = new Fixture();
var a = fixture.Create<Foo>();
var b = fixture.Create<Foo>(); // Or just create a new, empty Foo...
// This copies all properties from a to b:
new TypeElement(typeof(Foo)).Accept(new PropertyCopyVisitor<Foo>(a, b));
Assert.False(ReferenceEquals(a, b));
Assert.Equal(a.Name, b.Name);
Here, I still used fixture to create b, but you don't have to do that, because all properties are going to be overwritten anyway. If Foo has a parameterless constructor, you could instead simply use new Foo(); it'd make no difference.
This proof-of-concept explicitly only copies properties. If you need to copy fields as well, you'll have to override the appropriate Visit method as well. Furthermore, if the objects in question take constructor arguments, you'll need to deal with those explicitly as well.
If you find it tedious to write new TypeElement(typeof(Foo)).Accept(new PropertyCopyVisitor<Foo>(a, b));, I'm sure you can figure out a way to write a helper method around it.
As an additional note, PropertyCopyVisitor doesn't have to be generic, because it doesn't actually use the T type argument for anything. I just like the type safety that this gives the constructor...

Dapper Extension Get & Update returns errors

I tried to play with Dapper Extension & MS Access and succeeded up to certain extent. My code is listed below. All the functions works properly (Insert/Count/GetList/Delete) except Get & Update. I have summarised the code below. If anybody wants I can paste all the code here
My Product class
public class Products
{
public string ProductNumber { get; set; }
public string Description { get; set; }
}
And in my main class. I tried to get the product and update it as below. con.Get<Products> function returns an exception with "Sequence contains more than one element" message and con.Update<Products> returns an exception with "At least one Key column must be defined".
using (var con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=test.mdb"))
{
string ProductNumber = "12";
var product4 = con.Get<Products>(ProductNumber);
product4.ProductNumber = "Baz";
con.Update<Products>(product4);
Console.ReadLine();
}
Even though con.Get<Products> fails con.GetList<Products>(predicate) works perfectly. I did follow this link for setup
If DapperExtensions can't infer a key property called ID from your class, you'll need to explicitly specify one via a class mapper. Assuming the ProductNumber is the primary key in the database, the following example class mapper should set the ProductNumber to be the primary key for DapperExtensions.
using Dapper;
using DapperExtensions;
using DapperExtensions.Mapper;
public class ProductsMapper : ClassMapper<Products>
{
public ProductsMapper()
{
Map(x => x.ProductNumber).Key(KeyType.Assigned);
AutoMap();
}
}
This class can sit somewhere within the same assembly as the rest of your code. Dapper Extensions will automatically pick it up. If you have your classes and Dapper code in separate assemblies, you can point it to your mapper with the following line:
DapperExtensions.DapperExtensions.SetMappingAssemblies({ typeof(ProductsMapper).Assembly })

How to use Dapper's SqlBuilder?

I can't find any documentation or examples I can follow to use the SqlBuilder class.
I need to generate sql queries dynamically and I found this class. Would this be the best option?
the best place to start is to checkout the dapper source code from its github repo and have a look at the SqlBuilder code. The SqlBuilder class is only a 200 lines or so and you should be able to make an informed choice on whether it is right for your needed.
An other option is to build your own. I personally went down this route as it made sense. Dapper maps select querys directly to a class if you name your class properties the same as your database or add an attribute such as displayName to map from you can use reflection to get the property names. Put there names and values into a dictionary and you can genarate sql fairly easy from there.
here is something to get you started:
first an example class that you can pass to your sqlbuilder.
public class Foo
{
public Foo()
{
TableName = "Foo";
}
public string TableName { get; set; }
[DisplayName("name")]
public string Name { get; set; }
[SearchField("fooId")]
public int Id { get; set; }
}
This is fairly basic. Idea behind the DisplayName attribute is you can separate the properties out that you want to include in your auto generation. in this case TableName does not have a DisplayName attribute so will not be picked up by the next class. however you can manually use it when generating your sql to get your table name.
public Dictionary<string, object> GetPropertyDictionary()
{
var propDictionary = new Dictionary<string, object>();
var passedType = this.GetType();
foreach (var propertyInfo in passedType.GetProperties())
{
var isDef = Attribute.IsDefined(propertyInfo, typeof(DisplayNameAttribute));
if (isDef)
{
var value = propertyInfo.GetValue(this, null);
if (value != null)
{
var displayNameAttribute =
(DisplayNameAttribute)
Attribute.GetCustomAttribute(propertyInfo, typeof(DisplayNameAttribute));
var displayName = displayNameAttribute.DisplayName;
propDictionary.Add(displayName, value);
}
}
}
return propDictionary;
}
This method looks at the properties for its class and if they are not null and have a displayname attribute will add them to a dictionary with the displayname value as the string component.
This method is designed to work as part of the model class and would need to be modified to work from a separate helper class. Personally I have it and all my other sql generation methods in a Base class that all my models inherit from.
once you have the values in the dictionary you can use this to dynamically generate sql based on the model you pass in. and you can also use it to populate your dapper DynamicParamaters for use with paramiterized sql.
I hope this helps put you on the right path to solving your problems.

How to achieve "Blendability" when using DataServiceCollection in my ViewModel

I'm looking at using oData endpoints in my Silverlight client. Naturally, I'm doing MVVM and I want the project to be nice and "Blendable" (i.e. I must be able to cleanly use static data instead of the oData endpoints when in design mode.)
Now to the problem. I'd like to use the DataServiceCollection in my ViewModels, since it allows for nice bindable collections without having to worry too much with BeginExecute/EndExecute etc.
Now, let's look at some code. My Model interface looks like this:
public interface ITasksModel
{
IQueryable<Task> Tasks { get; }
}
The oData endpoint implementation of that interface:
public class TasksModel : ITasksModel
{
Uri svcUri = new Uri("http://localhost:2404/Services/TasksDataService.svc");
TaskModelContainer _container;
public TasksModel()
{
_container = new TaskModelContainer(svcUri);
}
public IQueryable<Task> Tasks
{
get
{
return _container.TaskSet;
}
}
}
And the "Blendable" design-time implementation:
public class DesignModeTasksModel : ITasksModel
{
private List<Task> _taskCollection = new List<Task>();
public DesignModeTasksModel()
{
_taskCollection.Add(new Task() { Id = 1, Title = "Task 1" });
_taskCollection.Add(new Task() { Id = 2, Title = "Task 2" });
_taskCollection.Add(new Task() { Id = 3, Title = "Task 3" });
}
public IQueryable<Task> Tasks
{
get {
return _taskCollection.AsQueryable();
}
}
}
However, when I try to use this last one in my ViewModel constructor:
public TaskListViewModel(ITasksModel tasksModel)
{
_tasksModel = tasksModel;
_tasks = new DataServiceCollection<Task>();
_tasks.LoadAsync(_tasksModel.Tasks);
}
I get an exception:
Only a typed DataServiceQuery object can be supplied when calling the LoadAsync method on DataServiceCollection.
First of all, if this is the case, why not make the input parameter of LoadAsync be typed as DataServiceQuery?
Second, what is the "proper" way of doing what I'm trying to accomplish?
The reason LoadAsync requires DataServiceQuery is that just plain IQueryable doesn't define asynchronous way of executing the query. The reason the method takes IQueryable type as its parameter is so that users don't have to cast the query object to DataServiceQuery explicitely (makes the code shorter) and since we assume that users will try to run their code at least once, they would see the error immediately (as you did).
LoadAsync only supports asynchronous operations, so it needs the DataServiceQuery. If you already have the results (without a need to execute async request) you can call the Load method instead. Which is the answer to your second question. Instead of calling LoadAsync for both desing time and run time, you could use Load for design time and LoadAsync for run time. But due to tracking constrains you might need to create the DataServiceCollection in different way.
Something like this:
DataServiceCollection<Task> dsc;
DataServiceQuery<Task> dsq = _tasksModel as DataServiceQuery<Task>;
if (dsq != null)
{
dsc = new DataServiceCollection<Task>();
dsc.LoadAsync(dsq);
}
else
{
dsc = new DataServiceCollection<Task>(myDataServiceContext);
dsc.Load(_tasksModel);
// Invoke the LoadAsyncCompleted handler here
}
If you pass the DataServiceContext to the constructor before caling Load the entities will be tracked (just like in the LoadAsync case). If you don't need that you can call the constructor which takes IEnumerable and TrackingMode and turn off tracking on it.

Resources