forked from devlooped/moq
-
Notifications
You must be signed in to change notification settings - Fork 1
/
InterceptionAspects.cs
289 lines (254 loc) · 8.32 KB
/
InterceptionAspects.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
// Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors.
// All rights reserved. Licensed under the BSD 3-Clause License; see License.txt.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Moq.Behaviors;
namespace Moq
{
internal static class HandleWellKnownMethods
{
private static Dictionary<string, Func<Invocation, Mock, bool>> specialMethods = new Dictionary<string, Func<Invocation, Mock, bool>>()
{
["Equals"] = HandleEquals,
["Finalize"] = HandleFinalize,
["GetHashCode"] = HandleGetHashCode,
["get_" + nameof(IMocked.Mock)] = HandleMockGetter,
["ToString"] = HandleToString,
};
public static bool Handle(Invocation invocation, Mock mock)
{
return specialMethods.TryGetValue(invocation.Method.Name, out var handler)
&& handler.Invoke(invocation, mock);
}
private static bool HandleEquals(Invocation invocation, Mock mock)
{
if (IsObjectMethod(invocation.Method) && !mock.MutableSetups.Any(c => IsObjectMethod(c.Method, "Equals")))
{
invocation.ReturnValue = ReferenceEquals(invocation.Arguments.First(), mock.Object);
return true;
}
else
{
return false;
}
}
private static bool HandleFinalize(Invocation invocation, Mock mock)
{
return IsFinalizer(invocation.Method);
}
private static bool HandleGetHashCode(Invocation invocation, Mock mock)
{
// Only if there is no corresponding setup for `GetHashCode()`
if (IsObjectMethod(invocation.Method) && !mock.MutableSetups.Any(c => IsObjectMethod(c.Method, "GetHashCode")))
{
invocation.ReturnValue = mock.GetHashCode();
return true;
}
else
{
return false;
}
}
private static bool HandleToString(Invocation invocation, Mock mock)
{
// Only if there is no corresponding setup for `ToString()`
if (IsObjectMethod(invocation.Method) && !mock.MutableSetups.Any(c => IsObjectMethod(c.Method, "ToString")))
{
invocation.ReturnValue = mock.ToString() + ".Object";
return true;
}
else
{
return false;
}
}
private static bool HandleMockGetter(Invocation invocation, Mock mock)
{
if (typeof(IMocked).IsAssignableFrom(invocation.Method.DeclaringType))
{
invocation.ReturnValue = mock;
return true;
}
else
{
return false;
}
}
private static bool IsFinalizer(MethodInfo method)
{
return method.GetBaseDefinition() == typeof(object).GetMethod("Finalize", BindingFlags.NonPublic | BindingFlags.Instance);
}
private static bool IsObjectMethod(MethodInfo method) => method.DeclaringType == typeof(object);
private static bool IsObjectMethod(MethodInfo method, string name) => IsObjectMethod(method) && method.Name == name;
}
internal static class FindAndExecuteMatchingSetup
{
public static bool Handle(Invocation invocation, Mock mock)
{
var matchingSetup = mock.MutableSetups.FindMatchFor(invocation);
if (matchingSetup != null)
{
matchingSetup.Execute(invocation);
return true;
}
else
{
return false;
}
}
}
internal static class HandleEventSubscription
{
public static bool Handle(Invocation invocation, Mock mock)
{
const BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly;
var methodName = invocation.Method.Name;
// Special case for event accessors. The following, seemingly random character checks are guards against
// more expensive checks (for the common case where the invoked method is *not* an event accessor).
if (methodName.Length > 4)
{
if (methodName[0] == 'a' && methodName[3] == '_' && invocation.Method.IsEventAddAccessor())
{
var implementingMethod = invocation.Method.GetImplementingMethod(invocation.ProxyType);
var @event = implementingMethod.DeclaringType.GetEvents(bindingFlags).SingleOrDefault(e => e.GetAddMethod(true) == implementingMethod);
if (@event != null)
{
if (mock.CallBase && !invocation.Method.IsAbstract)
{
invocation.ReturnValue = invocation.CallBase();
return true;
}
else if (invocation.Arguments.Length > 0 && invocation.Arguments[0] is Delegate delegateInstance)
{
mock.EventHandlers.Add(@event, delegateInstance);
return true;
}
}
}
else if (methodName[0] == 'r' && methodName.Length > 7 && methodName[6] == '_' && invocation.Method.IsEventRemoveAccessor())
{
var implementingMethod = invocation.Method.GetImplementingMethod(invocation.ProxyType);
var @event = implementingMethod.DeclaringType.GetEvents(bindingFlags).SingleOrDefault(e => e.GetRemoveMethod(true) == implementingMethod);
if (@event != null)
{
if (mock.CallBase && !invocation.Method.IsAbstract)
{
invocation.ReturnValue = invocation.CallBase();
return true;
}
else if (invocation.Arguments.Length > 0 && invocation.Arguments[0] is Delegate delegateInstance)
{
mock.EventHandlers.Remove(@event, delegateInstance);
return true;
}
}
}
}
return false;
}
}
internal static class RecordInvocation
{
public static void Handle(Invocation invocation, Mock mock)
{
// Save to support Verify[expression] pattern.
mock.MutableInvocations.Add(invocation);
}
}
internal static class Return
{
public static void Handle(Invocation invocation, Mock mock)
{
new ReturnBaseOrDefaultValue(mock).Execute(invocation);
}
}
internal static class HandleAutoSetupProperties
{
private static readonly int AccessorPrefixLength = "?et_".Length; // get_ or set_
public static bool Handle(Invocation invocation, Mock mock)
{
if (mock.AutoSetupPropertiesDefaultValueProvider == null)
{
return false;
}
MethodInfo invocationMethod = invocation.Method;
if (invocationMethod.IsPropertyAccessor())
{
string propertyNameToSearch = invocationMethod.Name.Substring(AccessorPrefixLength);
PropertyInfo property = invocationMethod.DeclaringType.GetProperty(propertyNameToSearch);
if (property == null)
{
return false;
}
var expression = GetPropertyExpression(invocationMethod.DeclaringType, property);
object propertyValue;
Setup getterSetup = null;
if (property.CanRead(out var getter))
{
if (ProxyFactory.Instance.IsMethodVisible(getter, out _))
{
propertyValue = CreateInitialPropertyValue(mock, getter);
getterSetup = new AutoImplementedPropertyGetterSetup(mock, expression, getter, () => propertyValue);
mock.MutableSetups.Add(getterSetup);
}
// If we wanted to optimise for speed, we'd probably be forgiven
// for removing the above `IsMethodVisible` guard, as it's rather
// unlikely to encounter non-public getters such as the following
// in real-world code:
//
// public T Property { internal get; set; }
//
// Usually, it's only the setters that are made non-public. For
// now however, we prefer correctness.
}
Setup setterSetup = null;
if (property.CanWrite(out var setter))
{
if (ProxyFactory.Instance.IsMethodVisible(setter, out _))
{
setterSetup = new AutoImplementedPropertySetterSetup(mock, expression, setter, (newValue) =>
{
propertyValue = newValue;
});
mock.MutableSetups.Add(setterSetup);
}
}
Setup setupToExecute = invocationMethod.IsGetAccessor() ? getterSetup : setterSetup;
setupToExecute.Execute(invocation);
return true;
}
else
{
return false;
}
}
private static object CreateInitialPropertyValue(Mock mock, MethodInfo getter)
{
object initialValue = mock.GetDefaultValue(getter, out Mock innerMock,
useAlternateProvider: mock.AutoSetupPropertiesDefaultValueProvider);
if (innerMock != null)
{
Mock.SetupAllProperties(innerMock, mock.AutoSetupPropertiesDefaultValueProvider);
}
return initialValue;
}
private static LambdaExpression GetPropertyExpression(Type mockType, PropertyInfo property)
{
var param = Expression.Parameter(mockType, "m");
return Expression.Lambda(Expression.MakeMemberAccess(param, property), param);
}
}
internal static class FailForStrictMock
{
public static void Handle(Invocation invocation, Mock mock)
{
if (mock.Behavior == MockBehavior.Strict)
{
throw MockException.NoSetup(invocation);
}
}
}
}