Welcome to mirror list, hosted at ThFree Co, Russian Federation.

MetaFixture.cs « LibGit2Sharp.Tests - github.com/mono/libgit2sharp.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 685ff5f45992d5b9b4ccae4dd7e3fe125acc986e (plain)
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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using LibGit2Sharp.Tests.TestHelpers;
using Xunit;
using Xunit.Extensions;

namespace LibGit2Sharp.Tests
{
    public class MetaFixture
    {
        private static readonly HashSet<Type> explicitOnlyInterfaces = new HashSet<Type>
        {
            typeof(IBelongToARepository),
        };

        [Fact]
        public void PublicTestMethodsAreFactsOrTheories()
        {
            var exceptions = new[]
            {
                "LibGit2Sharp.Tests.FilterBranchFixture.Dispose",
            };

            var fixtures = from t in Assembly.GetAssembly(typeof(MetaFixture)).GetExportedTypes()
                           where t.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 = Assembly.GetAssembly(typeof(IRepository)).GetExportedTypes()
                .Where(t => t.GetCustomAttributes(typeof(DebuggerDisplayAttribute), false).Any());

            foreach (Type type in libGit2SharpTypes)
            {
                var debuggerDisplayAttribute = (DebuggerDisplayAttribute)type.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 = Assembly.GetAssembly(typeof(IRepository)).GetExportedTypes()
                .Where(t => MustBeMockable(t) && t.Namespace == typeof(IRepository).Namespace);

            foreach (Type type in libGit2SharpTypes)
            {
                if (type.IsInterface || type.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 (nonTestableTypes.Any())
            {
                Assert.True(false, Environment.NewLine + BuildNonTestableTypesMessage(nonTestableTypes));
            }
        }

        private static bool MustBeMockable(Type type)
        {
            if (type.IsSealed)
            {
                return false;
            }

            if (type.IsAbstract)
            {
                return !type.Assembly.GetExportedTypes()
                            .Where(t => t.IsSubclassOf(type))
                            .All(t => t.IsAbstract || t.IsSealed);
            }

            return true;
        }

        [Fact]
        public void LibGit2SharpPublicInterfacesCoverAllPublicMembers()
        {
            var methodsMissingFromInterfaces =
                from t in Assembly.GetAssembly(typeof(IRepository)).GetExportedTypes()
                where !t.IsInterface
                where t.GetInterfaces().Any(i => i.IsPublic && i.Namespace == typeof(IRepository).Namespace && !explicitOnlyInterfaces.Contains(i))
                let interfaceTargetMethods = from i in t.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 Assembly.GetAssembly(typeof(IRepository)).GetExportedTypes()
                where t.GetInterfaces().Any(explicitOnlyInterfaces.Contains)
                let interfaceTargetMethods = from i in t.GetInterfaces()
                                             where explicitOnlyInterfaces.Contains(i)
                                             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 public method " + tm.Name + " which should be explicitly implemented.";

            Assert.Equal("", string.Join(Environment.NewLine,
                                         methodsMissingFromInterfaces.ToArray()));
        }

        [Fact]
        public void EnumsWithFlagsHaveMutuallyExclusiveValues()
        {
            var flagsEnums = Assembly.GetAssembly(typeof(IRepository)).GetExportedTypes()
                                     .Where(t => t.IsEnum && t.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.IsAbstract && type.IsSealed;
        }

        // Related to https://github.com/libgit2/libgit2sharp/issues/644 and https://github.com/libgit2/libgit2sharp/issues/645
        [Fact]
        public void GetEnumeratorMethodsInLibGit2SharpMustBeVirtualForTestability()
        {
            var nonVirtualGetEnumeratorMethods = Assembly.GetAssembly(typeof(IRepository))
                .GetExportedTypes()
                .Where(t =>
                    t.Namespace == typeof (IRepository).Namespace &&
                    !t.IsSealed &&
                    !t.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 = Assembly.GetAssembly(typeof(IRepository))
                .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("+"))

#if LEAKS_IDENTIFYING
                .Where(t => t != typeof(LibGit2Sharp.Core.LeaksContainer))
#endif
                .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 Assembly.GetAssembly(typeof(IRepository))
                    .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 Assembly.GetAssembly(typeof(IRepository))
                    .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());
        }
    }

    internal static class TypeExtensions
    {
        internal static bool IsObsolete(this MethodInfo methodInfo)
        {
            var attributes = methodInfo.GetCustomAttributes(false);
            return attributes.Any(a => a is ObsoleteAttribute);
        }
    }
}