Files
octokit.net/Octokit.Tests.Conventions/ModelTests.cs
Mickaël Derriey 9c80b00e6f Merge master into dotnetcore (#1599)
* bugfix - PUT should have a payload for Mark as Read (#1579)

* bugfix - PUT should have a payload for Mark as Read

* also fix the Observable client test

* add integration tests for MarkRead methods

* Fixup MarkReadForRepository methods to specify a body in the PUT request

* Fix unit tests for regular and observable client

* helps if the new files are included in the test project :)

* Cloning ApiInfo object should work when some fields are null (#1580)

* Adjust ApiInfo.Clone() to work even if some elements (eg ETag) are null

* Remove c# 6 language feature and do it the old school way

* Add a test for cloning ApiInfo when some fields are null

* The 3 lists can never be null anyway so remove some un-needed statements

* Add test for null RateLimit

* Remove Rx-Main dependency from samples
This resolves #1592 - LINQPad doesn't understand how to restore this unlisted package and it's not actually needed in the samples.

* Adding RemovedFromProject and other missing EventInfoState types. (#1591)

* Adding missing review types to event info.

* Fixing whitespace.

* Reword `BaseRefChanged` comment

* Adding missing event types.

* Change response models 'Url' properties from `Uri` to `string` (#1585)

* Add convention test to ensure 'Url' properties are of type string

Closes #1582

* Change 'Url' properties from Uri to string

Global Find/Replace FTW!

* fix compilation errors in the integration tests project

* Extend 'Url' properties type check to request models

* Stick to convention tests naming convention

* Remove unused using directives in models

Changing from `Uri` to `string` means the `using System;`
directive was not needed anymore in some files

* Update exception message wording

* empty commit to trigger a new build - hopefully Travis passes

* add convention test to ensure request models have Uri 'Url' properties

* make request models 'Url' properties Uri

fix typo in convention test name

* revert some request models 'Url' properties as `string`

see https://github.com/octokit/octokit.net/pull/1585#issuecomment-297186728

* Change test so that all model types must have 'Url' properties of type string

 - Filter test input to only get types which have 'Url' properties
 - Merge response and request model types tests into one
 - Unparameterize the exception since we only check for the string type now

* Fix string.Format tokens

If this PR doesn't get rebased, it'll be my wall of shame FOREVER!

* and then it's even more embarrassing when the commit message says rebased but you really meant squashed

* Remove exclusion of `Release` from request models
2017-05-02 21:55:30 +10:00

252 lines
8.0 KiB
C#

using System;
using System.Collections;
using System.Diagnostics;
using System.Linq;
using Xunit;
using System.Collections.Generic;
using System.Reflection;
namespace Octokit.Tests.Conventions
{
public class ModelTests
{
[Theory]
[MemberData("ModelTypes")]
public void AllModelsHaveDebuggerDisplayAttribute(Type modelType)
{
var attribute = modelType.GetTypeInfo().GetCustomAttribute<DebuggerDisplayAttribute>(inherit: false);
if (attribute == null)
{
throw new MissingDebuggerDisplayAttributeException(modelType);
}
if (attribute.Value != "{DebuggerDisplay,nq}")
{
throw new InvalidDebuggerDisplayAttributeValueException(modelType, attribute.Value);
}
var property = modelType.GetProperty("DebuggerDisplay", BindingFlags.Instance | BindingFlags.NonPublic);
if (property == null)
{
throw new MissingDebuggerDisplayPropertyException(modelType);
}
if (property.PropertyType != typeof(string))
{
throw new InvalidDebuggerDisplayReturnType(modelType, property.PropertyType);
}
}
[Theory]
[MemberData("ResponseModelTypes")]
public void AllResponseModelsHavePublicParameterlessCtors(Type modelType)
{
var ctor = modelType.GetConstructor(Type.EmptyTypes);
if (ctor == null || !ctor.IsPublic)
{
throw new MissingPublicParameterlessCtorException(modelType);
}
}
[Theory]
[MemberData("ResponseModelTypes")]
public void ResponseModelsHaveGetterOnlyProperties(Type modelType)
{
var mutableProperties = new List<PropertyInfo>();
foreach (var property in modelType.GetProperties())
{
var setter = property.GetSetMethod(nonPublic: true);
if (setter == null || !setter.IsPublic)
{
continue;
}
mutableProperties.Add(property);
}
if (mutableProperties.Any())
{
throw new MutableModelPropertiesException(modelType, mutableProperties);
}
}
[Theory]
[MemberData("ResponseModelTypes")]
public void ResponseModelsHaveReadOnlyCollections(Type modelType)
{
var mutableCollectionProperties = new List<PropertyInfo>();
foreach (var property in modelType.GetProperties())
{
var propertyType = property.PropertyType;
if (typeof(IEnumerable).IsAssignableFrom(propertyType))
{
// Let's skip arrays as well for now.
// There seems to be some special array handling in the Gist model.
if (propertyType == typeof(string) || propertyType.IsArray)
{
continue;
}
if (propertyType.IsReadOnlyCollection())
{
continue;
}
mutableCollectionProperties.Add(property);
}
}
if (mutableCollectionProperties.Any())
{
throw new MutableModelPropertiesException(modelType, mutableCollectionProperties);
}
}
[Theory]
[MemberData("ModelTypesWithUrlProperties")]
public void ModelsHaveUrlPropertiesOfTypeString(Type modelType)
{
var propertiesWithInvalidType = modelType
.GetProperties()
.Where(IsUrlProperty)
.Where(x => x.PropertyType != typeof(string))
.ToList();
if (propertiesWithInvalidType.Count > 0)
{
throw new InvalidUrlPropertyTypeException(modelType, propertiesWithInvalidType);
}
}
public static IEnumerable<object[]> GetClientInterfaces()
{
return typeof(IGitHubClient)
.GetTypeInfo()
.Assembly
.ExportedTypes
.Where(TypeExtensions.IsClientInterface)
.Where(t => t != typeof(IStatisticsClient)) // This convention doesn't apply to this one type.
.Select(type => new[] { type });
}
public static IEnumerable<object[]> ModelTypes
{
get { return GetModelTypes(includeRequestModels: true).Select(type => new[] { type }); }
}
public static IEnumerable<object[]> ModelTypesWithUrlProperties
{
get
{
return GetModelTypes(includeRequestModels: true)
.Where(type => type.GetProperties().Any(IsUrlProperty))
.Select(type => new[] { type });
}
}
public static IEnumerable<object[]> ResponseModelTypes
{
get { return GetModelTypes(includeRequestModels: false).Select(type => new[] { type }); }
}
private static IEnumerable<Type> GetModelTypes(bool includeRequestModels)
{
var allModelTypes = new HashSet<Type>();
var clientInterfaces = typeof(IGitHubClient).GetTypeInfo().Assembly.ExportedTypes
.Where(type => type.IsClientInterface());
foreach (var exportedType in clientInterfaces)
{
var methods = exportedType.GetMethods();
var modelTypes = methods.SelectMany(method => UnwrapGenericArguments(method.ReturnType));
if (includeRequestModels)
{
var requestModels = methods.SelectMany(method => method.GetParameters(),
(method, parameter) => parameter.ParameterType);
modelTypes = modelTypes.Union(requestModels);
}
foreach (var modelType in modelTypes.Where(type => type.IsModel()))
{
allModelTypes.Add(modelType);
}
}
return GetAllModelTypes(allModelTypes);
}
static IEnumerable<Type> GetAllModelTypes(ISet<Type> allModelTypes)
{
foreach (var modelType in allModelTypes.ToList())
{
GetPropertyModelTypes(modelType, allModelTypes);
}
return allModelTypes;
}
static void GetPropertyModelTypes(Type modelType, ISet<Type> allModelTypes)
{
var properties = modelType.GetProperties();
foreach (var propertyType in properties.SelectMany(x => UnwrapGenericArguments(x.PropertyType)))
{
if (allModelTypes.Contains(propertyType))
{
continue;
}
if (!propertyType.IsModel())
{
continue;
}
allModelTypes.Add(propertyType);
GetPropertyModelTypes(propertyType, allModelTypes);
}
}
private static IEnumerable<Type> UnwrapGenericArguments(Type returnType)
{
if (returnType.GetTypeInfo().IsGenericType)
{
var arguments = returnType.GetGenericArguments();
foreach (var argument in arguments)
{
if (argument.IsModel())
{
yield return argument;
}
else
{
foreach (var unwrappedTypes in UnwrapGenericArguments(argument))
{
yield return unwrappedTypes;
}
}
}
}
else
{
yield return returnType;
}
}
private static bool IsUrlProperty(PropertyInfo property)
{
return property.Name.EndsWith("Url");
}
}
}