forked from libgit2/libgit2sharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMetaFixture.cs
426 lines (354 loc) · 17.6 KB
/
MetaFixture.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using LibGit2Sharp.Tests.TestHelpers;
using Xunit;
using Xunit.Extensions;
using Moq;
namespace LibGit2Sharp.Tests
{
public class MetaFixture
{
private static readonly HashSet<Type> explicitOnlyInterfaces = new HashSet<Type>
{
typeof(IBelongToARepository), typeof(IDiffResult),
};
[Fact]
public void LibGit2SharpPublicInterfacesCoverAllPublicMembers()
{
var methodsMissingFromInterfaces =
from t in typeof(IRepository).GetTypeInfo().Assembly.GetExportedTypes()
where !t.GetTypeInfo().IsInterface
where t.GetTypeInfo().GetInterfaces().Any(i => i.GetTypeInfo().IsPublic && i.Namespace == typeof(IRepository).Namespace && !explicitOnlyInterfaces.Contains(i))
let interfaceTargetMethods = from i in t.GetTypeInfo().GetInterfaces()
from im in t.GetInterfaceMap(i).TargetMethods
select im
from tm in t.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance)
where !interfaceTargetMethods.Contains(tm)
select t.Name + " has extra method " + tm.Name;
Assert.Equal("", string.Join(Environment.NewLine,
methodsMissingFromInterfaces.ToArray()));
}
[Fact]
public void LibGit2SharpExplicitOnlyInterfacesAreIndeedExplicitOnly()
{
var methodsMissingFromInterfaces =
from t in typeof(IRepository).GetTypeInfo().Assembly.GetExportedTypes()
where t.GetInterfaces().Any(explicitOnlyInterfaces.Contains)
let interfaceTargetMethods = from i in t.GetInterfaces()
where explicitOnlyInterfaces.Contains(i)
from im in t.GetTypeInfo().GetInterfaceMap(i).TargetMethods
select im
from tm in t.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance)
where interfaceTargetMethods.Contains(tm)
select t.Name + " has public method " + tm.Name + " which should be explicitly implemented.";
Assert.Equal("", string.Join(Environment.NewLine,
methodsMissingFromInterfaces.ToArray()));
}
[Fact]
public void PublicTestMethodsAreFactsOrTheories()
{
var exceptions = new[]
{
"LibGit2Sharp.Tests.FilterBranchFixture.Dispose",
};
var fixtures = from t in typeof(MetaFixture).GetTypeInfo().Assembly.GetExportedTypes()
where t.GetTypeInfo().IsPublic && !t.IsNested
where t.Namespace != typeof(BaseFixture).Namespace // Exclude helpers
let methods = t.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public)
from m in methods
where !m.GetCustomAttributes(typeof(FactAttribute), false)
.Concat(m.GetCustomAttributes(typeof(TheoryAttribute), false))
.Any()
let name = t.FullName + "." + m.Name
where !exceptions.Contains(name)
select name;
Assert.Equal("", string.Join(Environment.NewLine, fixtures.ToArray()));
}
// Related to https://github.com/libgit2/libgit2sharp/pull/251
[Fact]
public void TypesInLibGit2DecoratedWithDebuggerDisplayMustFollowTheStandardImplPattern()
{
var typesWithDebuggerDisplayAndInvalidImplPattern = new List<Type>();
IEnumerable<Type> libGit2SharpTypes = typeof(IRepository).GetTypeInfo().Assembly.GetExportedTypes()
.Where(t => t.GetTypeInfo().GetCustomAttributes(typeof(DebuggerDisplayAttribute), false).Any());
foreach (Type type in libGit2SharpTypes)
{
var debuggerDisplayAttribute = (DebuggerDisplayAttribute)type.GetTypeInfo().GetCustomAttributes(typeof(DebuggerDisplayAttribute), false).Single();
if (debuggerDisplayAttribute.Value != "{DebuggerDisplay,nq}")
{
typesWithDebuggerDisplayAndInvalidImplPattern.Add(type);
continue;
}
PropertyInfo debuggerDisplayProperty = type.GetProperty("DebuggerDisplay",
BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);
if (debuggerDisplayProperty == null)
{
typesWithDebuggerDisplayAndInvalidImplPattern.Add(type);
continue;
}
if (debuggerDisplayProperty.PropertyType != typeof(string))
{
typesWithDebuggerDisplayAndInvalidImplPattern.Add(type);
}
}
if (typesWithDebuggerDisplayAndInvalidImplPattern.Any())
{
Assert.True(false, Environment.NewLine + BuildMissingDebuggerDisplayPropertyMessage(typesWithDebuggerDisplayAndInvalidImplPattern));
}
}
// Related to https://github.com/libgit2/libgit2sharp/pull/185
[Fact]
public void TypesInLibGit2SharpMustBeExtensibleInATestingContext()
{
var nonTestableTypes = new Dictionary<Type, IEnumerable<string>>();
IEnumerable<Type> libGit2SharpTypes = typeof(IRepository).GetTypeInfo().Assembly.GetExportedTypes()
.Where(t => MustBeMockable(t) && t.Namespace == typeof(IRepository).Namespace);
foreach (Type type in libGit2SharpTypes)
{
if (type.GetTypeInfo().IsInterface || type.GetTypeInfo().IsEnum || IsStatic(type))
continue;
var nonVirtualMethodNamesForType = GetNonVirtualPublicMethodsNames(type).ToList();
if (nonVirtualMethodNamesForType.Any())
{
nonTestableTypes.Add(type, nonVirtualMethodNamesForType);
continue;
}
if (!HasEmptyPublicOrProtectedConstructor(type))
{
nonTestableTypes.Add(type, new List<string>());
}
if (type.GetTypeInfo().IsAbstract)
{
continue;
}
try
{
if (type.GetTypeInfo().ContainsGenericParameters)
{
var constructType = type.MakeGenericType(Enumerable.Repeat(typeof(object), type.GetGenericArguments().Length).ToArray());
Activator.CreateInstance(constructType, true);
}
else
{
Activator.CreateInstance(type, true);
}
}
catch
{
nonTestableTypes.Add(type, new List<string>());
}
}
if (nonTestableTypes.Any())
{
Assert.True(false, Environment.NewLine + BuildNonTestableTypesMessage(nonTestableTypes));
}
}
private static bool MustBeMockable(Type type)
{
if (type.GetTypeInfo().IsSealed)
{
return false;
}
if (type.GetTypeInfo().IsAbstract)
{
return !type.GetTypeInfo().Assembly.GetExportedTypes()
.Where(t => t.GetTypeInfo().IsSubclassOf(type))
.All(t => t.GetTypeInfo().IsAbstract || t.GetTypeInfo().IsSealed);
}
return true;
}
[Fact]
public void EnumsWithFlagsHaveMutuallyExclusiveValues()
{
var flagsEnums = typeof(IRepository).GetTypeInfo().Assembly.GetExportedTypes()
.Where(t => t.GetTypeInfo().IsEnum && t.GetTypeInfo().GetCustomAttributes(typeof(FlagsAttribute), false).Any());
var overlaps = from t in flagsEnums
from int x in Enum.GetValues(t)
where x != 0
from int y in Enum.GetValues(t)
where y != 0
where x != y && (x & y) == y
select string.Format("{0}.{1} overlaps with {0}.{2}", t.Name, Enum.ToObject(t, x), Enum.ToObject(t, y));
var message = string.Join(Environment.NewLine, overlaps.ToArray());
Assert.Equal("", message);
}
private string BuildMissingDebuggerDisplayPropertyMessage(IEnumerable<Type> typesWithDebuggerDisplayAndInvalidImplPattern)
{
var sb = new StringBuilder();
foreach (Type type in typesWithDebuggerDisplayAndInvalidImplPattern)
{
sb.AppendFormat("'{0}' is decorated with the DebuggerDisplayAttribute, but does not follow LibGit2Sharp implementation pattern.{1}" +
" Please make sure that the type is decorated with `[DebuggerDisplay(\"{{DebuggerDisplay,nq}}\")]`,{1}" +
" and that the type implements a private property named `DebuggerDisplay`, returning a string.{1}",
type.Name, Environment.NewLine);
}
return sb.ToString();
}
private static string BuildNonTestableTypesMessage(Dictionary<Type, IEnumerable<string>> nonTestableTypes)
{
var sb = new StringBuilder();
foreach (var kvp in nonTestableTypes)
{
sb.AppendFormat("'{0}' cannot be easily abstracted in a testing context. Please make sure it either has a public constructor, or an empty protected constructor.{1}",
kvp.Key, Environment.NewLine);
foreach (string methodName in kvp.Value)
{
sb.AppendFormat(" - Method '{0}' must be virtual{1}", methodName, Environment.NewLine);
}
}
return sb.ToString();
}
private static IEnumerable<string> GetNonVirtualPublicMethodsNames(Type type)
{
var publicMethods = type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
return from mi in publicMethods where !mi.IsVirtual && !mi.IsStatic select mi.ToString();
}
private static bool HasEmptyPublicOrProtectedConstructor(Type type)
{
ConstructorInfo[] constructors = type.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
return constructors.Any(ci => ci.GetParameters().Length == 0 && (ci.IsPublic || ci.IsFamily || ci.IsFamilyOrAssembly));
}
private static bool IsStatic(Type type)
{
return type.GetTypeInfo().IsAbstract && type.GetTypeInfo().IsSealed;
}
// Related to https://github.com/libgit2/libgit2sharp/issues/644 and https://github.com/libgit2/libgit2sharp/issues/645
[Fact]
public void GetEnumeratorMethodsInLibGit2SharpMustBeVirtualForTestability()
{
var nonVirtualGetEnumeratorMethods = typeof(IRepository).GetTypeInfo().Assembly
.GetExportedTypes()
.Where(t =>
t.Namespace == typeof(IRepository).Namespace &&
!t.GetTypeInfo().IsSealed &&
!t.GetTypeInfo().IsAbstract &&
t.GetInterfaces().Any(i => i.IsAssignableFrom(typeof(IEnumerable<>))))
.Select(t => t.GetMethod("GetEnumerator"))
.Where(m =>
m.ReturnType.Name == "IEnumerator`1" &&
(!m.IsVirtual || m.IsFinal))
.ToList();
if (nonVirtualGetEnumeratorMethods.Any())
{
var sb = new StringBuilder();
foreach (var method in nonVirtualGetEnumeratorMethods)
{
sb.AppendFormat("GetEnumerator in type '{0}' isn't virtual.{1}",
method.DeclaringType, Environment.NewLine);
}
Assert.True(false, Environment.NewLine + sb.ToString());
}
}
[Fact]
public void NoPublicTypesUnderLibGit2SharpCoreNamespace()
{
const string coreNamespace = "LibGit2Sharp.Core";
var types = typeof(IRepository).GetTypeInfo().Assembly
.GetExportedTypes()
.Where(t => t.FullName.StartsWith(coreNamespace + "."))
// Ugly hack to circumvent a Mono bug
// cf. https://bugzilla.xamarin.com/show_bug.cgi?id=27010
.Where(t => !t.FullName.Contains("+"))
.Where(t => t.FullName != "LibGit2Sharp.Core.LeaksContainer")
.ToList();
if (types.Any())
{
var sb = new StringBuilder();
foreach (var type in types)
{
sb.AppendFormat("Public type '{0}' under the '{1}' namespace.{2}",
type.FullName, coreNamespace, Environment.NewLine);
}
Assert.True(false, Environment.NewLine + sb.ToString());
}
}
[Fact]
public void NoOptionalParametersinMethods()
{
IEnumerable<string> mis =
from t in typeof(IRepository).GetTypeInfo().Assembly
.GetExportedTypes()
from m in t.GetMethods()
where !m.IsObsolete()
from p in m.GetParameters()
where p.IsOptional
select m.DeclaringType + "." + m.Name;
var sb = new StringBuilder();
foreach (var method in mis.Distinct())
{
sb.AppendFormat("At least one overload of method '{0}' accepts an optional parameter.{1}",
method, Environment.NewLine);
}
Assert.Equal("", sb.ToString());
}
[Fact]
public void NoOptionalParametersinConstructors()
{
IEnumerable<string> mis =
from t in typeof(IRepository).GetTypeInfo().Assembly
.GetExportedTypes()
from c in t.GetConstructors()
from p in c.GetParameters()
where p.IsOptional
select c.DeclaringType.Name;
var sb = new StringBuilder();
foreach (var method in mis.Distinct())
{
sb.AppendFormat("At least one constructor of type '{0}' accepts an optional parameter.{1}",
method, Environment.NewLine);
}
Assert.Equal("", sb.ToString());
}
[Fact]
public void PublicExtensionMethodsShouldonlyTargetInterfacesOrEnums()
{
IEnumerable<string> mis =
from m in GetInvalidPublicExtensionMethods()
select m.DeclaringType + "." + m.Name;
var sb = new StringBuilder();
foreach (var method in mis.Distinct())
{
sb.AppendFormat("'{0}' is a public extension method that doesn't target an interface or an enum.{1}",
method, Environment.NewLine);
}
Assert.Equal("", sb.ToString());
}
// Inspired from http://stackoverflow.com/a/299526
static IEnumerable<MethodInfo> GetInvalidPublicExtensionMethods()
{
var query = from type in typeof(IRepository).GetTypeInfo().Assembly.GetTypes()
where type.GetTypeInfo().IsSealed && !type.GetTypeInfo().IsGenericType && !type.IsNested && type.GetTypeInfo().IsPublic
from method in type.GetMethods(BindingFlags.Static | BindingFlags.Public)
where method.IsDefined(typeof(ExtensionAttribute), false)
let parameterType = method.GetParameters()[0].ParameterType
where parameterType != null && !parameterType.GetTypeInfo().IsInterface && !parameterType.GetTypeInfo().IsEnum
select method;
return query;
}
[Fact]
public void AllIDiffResultsAreInChangesBuilder()
{
var diff = typeof(Diff).GetField("ChangesBuilders", BindingFlags.NonPublic | BindingFlags.Static);
var changesBuilders = (System.Collections.IDictionary)diff.GetValue(null);
IEnumerable<Type> diffResults = typeof(Diff).GetTypeInfo().Assembly.GetExportedTypes()
.Where(type => type.GetTypeInfo().GetInterface("IDiffResult") != null);
var nonBuilderTypes = diffResults.Where(diffResult => !changesBuilders.Contains(diffResult));
Assert.False(nonBuilderTypes.Any(), "Classes which implement IDiffResult but are not registered under ChangesBuilders in Diff:" + Environment.NewLine +
string.Join(Environment.NewLine, nonBuilderTypes.Select(type => type.FullName)));
}
}
internal static class TypeExtensions
{
internal static bool IsObsolete(this MethodInfo methodInfo)
{
var attributes = methodInfo.GetCustomAttributes(false);
return attributes.Any(a => a is ObsoleteAttribute);
}
}
}