Skip to content

Commit

Permalink
some refactoring, bool value generator added and subitem list size pr…
Browse files Browse the repository at this point in the history
…operty added
  • Loading branch information
MCKanpolat committed Feb 27, 2018
1 parent 03fad72 commit f370af1
Show file tree
Hide file tree
Showing 10 changed files with 69 additions and 52 deletions.
5 changes: 1 addition & 4 deletions src/StubGenerator.Test/CacheManagerTests.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using System.Threading.Tasks;
using StubGenerator.Caching;
using StubGenerator.Core;
using StubGenerator.Test.Models;
using Xunit;

Expand All @@ -17,13 +16,11 @@ public CacheManagerTests()
_stubTypeMemoryCache = new MemoryStubTypeCache(_cacheKeyGenerator);
}



[Fact(DisplayName = "Cache_Key_Generator_Test")]
public void CacheKeyGeneratorTest()
{
var cacheKey = _cacheKeyGenerator.GenerateKey<PersonDto>();

Assert.NotEmpty(cacheKey);
}

[Fact(DisplayName = "Should add PropertyInfo Cache Successfully")]
Expand Down
6 changes: 2 additions & 4 deletions src/StubGenerator.Test/StubManagerTests.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
using System;
using System.Globalization;
using System.Linq;
using StubGenerator.Caching;
using StubGenerator.Core;
using StubGenerator.Defaults;
using StubGenerator.Test.Models;
using Xunit;
using System;

namespace StubGenerator.Test
{
Expand Down Expand Up @@ -136,7 +134,7 @@ public void Should_Set_Given_Values_While_Generating_Data()
var givenDataTime = new DateTime(2017, 1, 1);
var givenEnum = EnTestEnum.Option3;
var givenInteger = 31;
var generatedStubData = _stubManager.CreateNew<InnerComplexType>(x => { x.DateTimeProperty = givenDataTime; x.EnumProperty = givenEnum; x.IntegerProperty = givenInteger; });
var generatedStubData = _stubManager.CreateNew<InnerComplexType>(setDefaults: x => { x.DateTimeProperty = givenDataTime; x.EnumProperty = givenEnum; x.IntegerProperty = givenInteger; });
Assert.Equal(givenDataTime, generatedStubData.DateTimeProperty);
Assert.Equal(givenEnum, generatedStubData.EnumProperty);
Assert.Equal(givenInteger, generatedStubData.IntegerProperty);
Expand Down
24 changes: 10 additions & 14 deletions src/StubMiddleware.Core/Caching/MemoryStubTypeCache.cs
Original file line number Diff line number Diff line change
@@ -1,49 +1,45 @@
using System.Collections.Concurrent;
using StubGenerator.Core;
using System;
using System.Collections.Concurrent;
using System.Reflection;

namespace StubGenerator.Caching
{
public class MemoryStubTypeCache : IStubTypeCache
{
private readonly ConcurrentDictionary<string, PropertyInfo[]> Cache;
private readonly ConcurrentDictionary<string, PropertyInfo[]> _cache = new ConcurrentDictionary<string, PropertyInfo[]>();
private readonly IStubTypeCacheKeyGenerator _cacheKeyGenerator;

public MemoryStubTypeCache()
:this(new DefaultStubTypeCacheKeyGenerator())
: this(new DefaultStubTypeCacheKeyGenerator())
{
}

public MemoryStubTypeCache(IStubTypeCacheKeyGenerator cacheKeyGenerator)
{
Cache = new ConcurrentDictionary<string, PropertyInfo[]>();
_cacheKeyGenerator = cacheKeyGenerator;
_cacheKeyGenerator = cacheKeyGenerator ?? throw new ArgumentNullException(nameof(cacheKeyGenerator));
}

public PropertyInfo[] Get<T>(T instance) where T : class
{
string cacheKey = _cacheKeyGenerator.GenerateKey<T>();
Cache.TryGetValue(cacheKey, out PropertyInfo[] result);
_cache.TryGetValue(cacheKey, out PropertyInfo[] result);
return result;
}

public PropertyInfo[] GetOrAdd<T>(T instance, PropertyInfo[] propertyInfos) where T : class
{
var cacheKey = _cacheKeyGenerator.GenerateKey<T>();
return Cache.GetOrAdd(cacheKey, i => { return propertyInfos; });
return _cache.GetOrAdd(cacheKey, i => { return propertyInfos; });
}

public bool Set<T>(T instance, PropertyInfo[] stubTypeItem) where T : class
{
string cacheKey = _cacheKeyGenerator.GenerateKey<T>();
return Cache.TryAdd(cacheKey, stubTypeItem);
return _cache.TryAdd(cacheKey, stubTypeItem);
}

public void Clear() => Cache.Clear();
public void Clear() => _cache.Clear();

public bool IsEmpty()
{
return Cache.Count == 0;
}
public bool IsEmpty() => _cache.Count == 0;
}
}
10 changes: 6 additions & 4 deletions src/StubMiddleware.Core/Core/FakeDataFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,29 +13,29 @@ public class FakeDataFactory : IFakeDataFactory
private readonly IConventionMappingProfile _stubDataMappingProfile;

public FakeDataFactory()
:this(new DefaultConventionMappingProfile())
: this(new DefaultConventionMappingProfile())
{
}

public FakeDataFactory(IConventionMappingProfile stubDataMappingProfile)
{
_stubDataMappingProfile = stubDataMappingProfile;
_stubDataMappingProfile = stubDataMappingProfile ?? throw new ArgumentNullException(nameof(stubDataMappingProfile));
}

public object ProvideValue(PropertyInfo propertyInfo)
{
if (!propertyInfo.PropertyType.IsSimple())
return null;

var matchingConvetion = _stubDataMappingProfile.Conventions.Where(c => c.Condition(propertyInfo)).FirstOrDefault();
var matchingConvetion = _stubDataMappingProfile.Conventions.FirstOrDefault(c => c.Condition(propertyInfo));
if (matchingConvetion != null)
return matchingConvetion.Generator.Generate();

var propertyType = propertyInfo.PropertyType;

if (propertyInfo.PropertyType.IsGenericType && propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
propertyType = propertyInfo.PropertyType.GetGenericArguments()[0];

return GenerateValueByType(propertyType);
}

Expand All @@ -53,6 +53,8 @@ private static object GenerateValueByType(Type propertyType)
return new EnumValueGenerator(propertyType).Generate();
else if (propertyType == typeof(Guid))
return new GuidValueGenerator().Generate();
else if (propertyType == typeof(bool))
return new BoolValueGenerator().Generate();
else
return null;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
using System;

namespace StubGenerator.Core.FakeDataGenerators
{
public class BoolValueGenerator : IValueGenerator
{
private readonly Random _random;
public BoolValueGenerator()
{
_random = new Random();
}
public object Generate()
{
return _random.NextDouble() >= 0.5;
}
}
}
4 changes: 2 additions & 2 deletions src/StubMiddleware.Core/Core/Interfaces/IStubManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ namespace StubGenerator.Core
{
public interface IStubManager
{
IList<T> CreateListOfSize<T>(int size, Action<T> setDefaults = null) where T : class, new();
T CreateNew<T>(Action<T> setDefaults = null) where T : class, new();
IList<T> CreateListOfSize<T>(int size, int subItemSize = 3, Action<T> setDefaults = null) where T : class, new();
T CreateNew<T>(int subItemSize = 3, Action<T> setDefaults = null) where T : class, new();
}
}
25 changes: 11 additions & 14 deletions src/StubMiddleware.Core/Core/StubManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,9 @@
using System.Linq;
using System.Reflection;
using StubGenerator.Caching;
using StubGenerator.Extensions;
using System.Collections;
using StubGenerator.Core.Interfaces;
using StubGenerator.Core.FakeDataProvider;
using StubGenerator.Core.Interfaces;
using StubGenerator.Extensions;

namespace StubGenerator.Core
{
Expand All @@ -16,9 +15,8 @@ public class StubManager : IStubManager
private readonly IStubTypeCache _stubTypeCache;

public StubManager(StubManagerOptions stubManagerOptions)
:this(stubManagerOptions, new MemoryStubTypeCache(), new FakeDataFactory())
: this(stubManagerOptions, new MemoryStubTypeCache(), new FakeDataFactory())
{

}

public StubManager(StubManagerOptions stubManagerOptions, IStubTypeCache stubTypeCache, IFakeDataFactory fakeDataFactory)
Expand All @@ -30,7 +28,7 @@ public StubManager(StubManagerOptions stubManagerOptions, IStubTypeCache stubTyp

public StubManagerOptions StubManagerOptions { get; private set; }

public T CreateNew<T>(Action<T> setDefaults = null) where T : class, new()
public T CreateNew<T>(int subItemSize = 3, Action<T> setDefaults = null) where T : class, new()
{
var instance = new T();
var cachedPropertyInfo = _stubTypeCache.Get(instance);
Expand All @@ -40,35 +38,35 @@ public StubManager(StubManagerOptions stubManagerOptions, IStubTypeCache stubTyp
_stubTypeCache.Set(instance, cachedPropertyInfo);
}

FillPropertiesWithFakeData(instance, cachedPropertyInfo);
FillPropertiesWithFakeData(instance, cachedPropertyInfo, subItemSize);

setDefaults?.Invoke(instance);

return instance;
}

public IList<T> CreateListOfSize<T>(int size, Action<T> setDefaults = null) where T : class, new()
public IList<T> CreateListOfSize<T>(int size, int subItemSize = 3, Action<T> setDefaults = null) where T : class, new()
{
var result = new List<T>();
for (int i = 0; i < size; i++)
{
result.Add(CreateNew<T>(setDefaults));
result.Add(CreateNew(subItemSize, setDefaults));
}
return result;
}

private void FillPropertiesWithFakeData<TObject>(TObject obj, PropertyInfo[] propertyInfos)
private void FillPropertiesWithFakeData<TObject>(TObject obj, PropertyInfo[] propertyInfos, int listItemSize = 3)
{
foreach (PropertyInfo property in propertyInfos)
{
if(property.PropertyType.IsCollectionType())
if (property.PropertyType.IsCollectionType())
{
var collectionTypeInstance = Activator.CreateInstance(property.PropertyType);
var complexType = property.PropertyType.GetGenericArguments()[0];
property.SetValue(obj, collectionTypeInstance);
for(var i = 0; i < 3; i++)
for (var i = 0; i < listItemSize; i++)
{
var item = Activator.CreateInstance(complexType);
var item = Activator.CreateInstance(complexType);
FillPropertiesWithFakeData(item, _stubTypeCache.GetOrAdd(item, property.PropertyType.GetGenericArguments()[0].GetProperties()));
collectionTypeInstance.GetType().GetMethod("Add").Invoke(collectionTypeInstance, new[] { item });
}
Expand All @@ -89,6 +87,5 @@ private void FillPropertiesWithFakeData<TObject>(TObject obj, PropertyInfo[] pro
}
}
}

}
}
18 changes: 14 additions & 4 deletions src/StubMiddleware.Core/Extensions/StubManagerExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ private static Type LoadType(string typeName)
return result;
}

public static object InvokeCreateNew(this IStubManager stubManager, string typeName)
public static object InvokeCreateNew(this IStubManager stubManager, string typeName, int subItemSize = 3)
{
if (stubManager == null)
{
Expand All @@ -29,15 +29,20 @@ public static object InvokeCreateNew(this IStubManager stubManager, string typeN
throw new ArgumentException("message", nameof(typeName));
}

if (subItemSize <= 0)
{
throw new ArgumentOutOfRangeException(nameof(subItemSize), "Subitem Size must be positive number!");
}

var type = LoadType(typeName);


MethodInfo method = typeof(IStubManager).GetMethod("CreateNew");
MethodInfo genericMethod = method.MakeGenericMethod(type);
return genericMethod.Invoke(stubManager, null);
return genericMethod.Invoke(stubManager, new object[] { subItemSize, null });
}

public static object InvokeCreateListOfSize(this IStubManager stubManager, string typeName, int size)
public static object InvokeCreateListOfSize(this IStubManager stubManager, string typeName, int size, int subItemSize)
{
if (stubManager == null)
{
Expand All @@ -49,10 +54,15 @@ public static object InvokeCreateListOfSize(this IStubManager stubManager, strin
throw new ArgumentOutOfRangeException(nameof(size), "List Size must be positive number!");
}

if (subItemSize <= 0)
{
throw new ArgumentOutOfRangeException(nameof(subItemSize), "Subitem Size must be positive number!");
}

var type = LoadType(typeName);
MethodInfo method = typeof(IStubManager).GetMethod("CreateListOfSize");
MethodInfo genericMethod = method.MakeGenericMethod(type);
return genericMethod.Invoke(stubManager, parameters: new object[] { size });
return genericMethod.Invoke(stubManager, parameters: new object[] { size, subItemSize, null });
}
}
}
4 changes: 2 additions & 2 deletions src/StubMiddleware.Web.Test/Controllers/ValuesController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@ public IActionResult Get()
var testModelNs = typeof(PersonDto).FullName;
var testModelAsmName = typeof(PersonDto).Assembly.GetName().Name;
var result = new RestApiResult();
var url = Url.Action("get", "stubmiddleware", new { className = $"{testModelNs}, {testModelAsmName}", culture = "en-us" });
var url = Url.Action("get", "stubmiddleware", new { className = $"{testModelNs}, {testModelAsmName}", subItemlistSize = 3, culture = "en-us" });
result.Links.Add(new LinkInfo() { Href = url, Method = "GET", Rel = "self" });

var urlList = Url.Action("list", "stubmiddleware", new { className = $"{testModelNs}, {testModelAsmName}", culture = "en-us", listSize = 10 });
var urlList = Url.Action("list", "stubmiddleware", new { className = $"{testModelNs}, {testModelAsmName}", subItemlistSize = 3, culture = "en-us", listSize = 10 });
result.Links.Add(new LinkInfo() { Href = urlList, Method = "GET", Rel = "self" });

return Ok(result);
Expand Down
8 changes: 4 additions & 4 deletions src/StubMiddleware/StubMiddlewareController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,15 @@ public StubMiddlewareController(IStubManager stubManager) =>


[HttpGet, Route("list")]
public async Task<IActionResult> list([FromQuery]string className, [FromQuery]int listSize, [FromQuery]string culture)
public async Task<IActionResult> list([FromQuery]string className, [FromQuery]int listSize, [FromQuery]int subItemlistSize, [FromQuery]string culture)
{
if (!string.IsNullOrWhiteSpace(culture))
{
var cultureInfo = new CultureInfo(culture);
CultureInfo.CurrentCulture = cultureInfo;
CultureInfo.CurrentUICulture = cultureInfo;
}
var instance = _stubManager.InvokeCreateListOfSize(className, listSize);
var instance = _stubManager.InvokeCreateListOfSize(className, listSize, subItemlistSize == 0 ? 3 : subItemlistSize);
if (instance == null)
{
return NotFound(className);
Expand All @@ -34,7 +34,7 @@ public async Task<IActionResult> list([FromQuery]string className, [FromQuery]in


[HttpGet, Route("get")]
public async Task<IActionResult> get([FromQuery]string className, [FromQuery]string culture)
public async Task<IActionResult> get([FromQuery]string className, [FromQuery]int subItemlistSize, [FromQuery]string culture)
{
if (!string.IsNullOrWhiteSpace(culture))
{
Expand All @@ -43,7 +43,7 @@ public async Task<IActionResult> get([FromQuery]string className, [FromQuery]str
CultureInfo.CurrentUICulture = cultureInfo;
}

var instance = _stubManager.InvokeCreateNew(className);
var instance = _stubManager.InvokeCreateNew(className, subItemlistSize == 0 ? 3 : subItemlistSize);
if (instance == null)
{
return NotFound(className);
Expand Down

0 comments on commit f370af1

Please sign in to comment.