-
Notifications
You must be signed in to change notification settings - Fork 179
/
BuildableCallRule.cs
281 lines (242 loc) · 10.4 KB
/
BuildableCallRule.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
namespace FakeItEasy.Configuration
{
using System;
using System.Collections.Generic;
using System.Linq;
using FakeItEasy.Core;
/// <summary>
/// Provides the base for rules that can be built using the FakeConfiguration.
/// </summary>
internal abstract class BuildableCallRule
: IFakeObjectCallRule
{
private readonly List<WherePredicate> wherePredicates;
private Action<IInterceptedFakeObjectCall> applicator;
private bool wasApplicatorSet;
private Func<IFakeObjectCall, ICollection<object>> outAndRefParametersValueProducer;
private bool canSetOutAndRefParametersValueProducer;
protected BuildableCallRule()
{
this.Actions = new LinkedList<Action<IFakeObjectCall>>();
this.UseDefaultApplicator();
this.wasApplicatorSet = false;
this.canSetOutAndRefParametersValueProducer = true;
this.wherePredicates = new List<WherePredicate>();
}
/// <summary>
/// Gets a collection of actions that should be invoked when the configured
/// call is made.
/// </summary>
public virtual ICollection<Action<IFakeObjectCall>> Actions { get; }
/// <summary>
/// Gets or sets a function that provides values to apply to output and reference variables.
/// </summary>
public Func<IFakeObjectCall, ICollection<object>> OutAndRefParametersValueProducer
{
get
{
return this.outAndRefParametersValueProducer;
}
set
{
if (!this.canSetOutAndRefParametersValueProducer)
{
throw new InvalidOperationException("How to assign out and ref parameters has already been defined for this call");
}
this.outAndRefParametersValueProducer = value;
this.canSetOutAndRefParametersValueProducer = false;
}
}
/// <summary>
/// Gets or sets a value indicating whether the base method of the fake object call should be
/// called when the fake object call is made.
/// </summary>
public bool CallBaseMethod { get; set; }
/// <summary>
/// Gets or sets the number of times the configured rule should be used.
/// </summary>
public virtual int? NumberOfTimesToCall { get; set; }
/// <summary>
/// Writes a description of calls the rule is applicable to.
/// </summary>
/// <param name="writer">The writer on which to describe the call.</param>
public abstract void DescribeCallOn(IOutputWriter writer);
/// <summary>
/// Sets an action that is called by the <see cref="Apply"/> method to apply this
/// rule to a fake object call.
/// </summary>
/// <param name="newApplicator">The action to use.</param>
public void UseApplicator(Action<IInterceptedFakeObjectCall> newApplicator)
{
if (this.wasApplicatorSet)
{
throw new InvalidOperationException("The behavior for this call has already been defined");
}
this.applicator = newApplicator;
this.wasApplicatorSet = true;
}
/// <summary>
/// Sets (or resets) the applicator (see <see cref="UseApplicator"/>) to the default action:
/// the same as a newly-created rule would have.
/// </summary>
public void UseDefaultApplicator()
{
this.UseApplicator(call => call.SetReturnValue(call.GetDefaultReturnValue()));
}
public virtual void Apply(IInterceptedFakeObjectCall fakeObjectCall)
{
Guard.AgainstNull(fakeObjectCall, nameof(fakeObjectCall));
foreach (var action in this.Actions)
{
action.Invoke(fakeObjectCall);
}
this.applicator.Invoke(fakeObjectCall);
this.ApplyOutAndRefParametersValueProducer(fakeObjectCall);
if (this.CallBaseMethod)
{
fakeObjectCall.CallBaseMethod();
}
}
/// <summary>
/// Gets if this rule is applicable to the specified call.
/// </summary>
/// <param name="fakeObjectCall">The call to validate.</param>
/// <returns>True if the rule applies to the call.</returns>
public virtual bool IsApplicableTo(IFakeObjectCall fakeObjectCall)
{
return this.wherePredicates.All(x => x.Matches(fakeObjectCall))
&& this.OnIsApplicableTo(fakeObjectCall);
}
/// <summary>
/// Writes a description of calls the rule is applicable to.
/// </summary>
/// <param name="writer">The writer to write the description to.</param>
public void WriteDescriptionOfValidCall(IOutputWriter writer)
{
Guard.AgainstNull(writer, nameof(writer));
this.DescribeCallOn(writer);
Func<string> wherePrefix = () =>
{
wherePrefix = () => "and";
return "where";
};
using (writer.Indent())
{
foreach (var wherePredicate in this.wherePredicates)
{
writer.WriteLine();
writer.Write(wherePrefix.Invoke());
writer.Write(" ");
wherePredicate.WriteDescription(writer);
}
}
}
public virtual void ApplyWherePredicate(Func<IFakeObjectCall, bool> predicate, Action<IOutputWriter> descriptionWriter)
{
this.wherePredicates.Add(new WherePredicate(predicate, descriptionWriter));
}
public abstract void UsePredicateToValidateArguments(Func<ArgumentCollection, bool> predicate);
/// <summary>
/// Clones the part of the rule that describes which call is being configured.
/// </summary>
/// <returns>The cloned rule.</returns>
public BuildableCallRule CloneCallSpecification()
{
var clone = this.CloneCallSpecificationCore();
clone.wherePredicates.AddRange(this.wherePredicates);
return clone;
}
/// <summary>
/// When overridden in a derived class, returns a new instance of the same type and copies the call
/// specification members for that type.
/// </summary>
/// <returns>The cloned rule.</returns>
protected abstract BuildableCallRule CloneCallSpecificationCore();
protected abstract bool OnIsApplicableTo(IFakeObjectCall fakeObjectCall);
/// <summary>
/// Sets the OutAndRefParametersValueProducer directly, bypassing the public setter logic, hence allowing
/// it to be set again later.
/// </summary>
/// <param name="value">The new value for OutAndRefParametersValueProducer.</param>
protected void SetOutAndRefParametersValueProducer(Func<IFakeObjectCall, ICollection<object>> value)
{
this.outAndRefParametersValueProducer = value;
}
private static ICollection<int> GetIndexesOfOutAndRefParameters(IInterceptedFakeObjectCall fakeObjectCall)
{
var indexes = new List<int>();
var arguments = fakeObjectCall.Method.GetParameters();
for (var i = 0; i < arguments.Length; i++)
{
if (arguments[i].IsOutOrRef())
{
indexes.Add(i);
}
}
return indexes;
}
private void ApplyOutAndRefParametersValueProducer(IInterceptedFakeObjectCall fakeObjectCall)
{
if (this.OutAndRefParametersValueProducer == null)
{
return;
}
var indexes = GetIndexesOfOutAndRefParameters(fakeObjectCall);
ICollection<object> values;
try
{
values = this.OutAndRefParametersValueProducer(fakeObjectCall);
}
catch (Exception ex) when (!(ex is FakeConfigurationException))
{
throw new UserCallbackException(ExceptionMessages.UserCallbackThrewAnException("Out and ref parameter value producer"), ex);
}
if (values.Count != indexes.Count)
{
throw new InvalidOperationException(ExceptionMessages.NumberOfOutAndRefParametersDoesNotMatchCall);
}
foreach (var argument in indexes.Zip(values, (index, value) => new { Index = index, Value = value }))
{
fakeObjectCall.SetArgumentValue(argument.Index, argument.Value);
}
}
private class WherePredicate
{
private readonly Func<IFakeObjectCall, bool> predicate;
private readonly Action<IOutputWriter> descriptionWriter;
public WherePredicate(Func<IFakeObjectCall, bool> predicate, Action<IOutputWriter> descriptionWriter)
{
this.predicate = predicate;
this.descriptionWriter = descriptionWriter;
}
public void WriteDescription(IOutputWriter writer)
{
try
{
this.descriptionWriter.Invoke(writer);
}
catch (Exception ex)
{
throw new UserCallbackException(ExceptionMessages.UserCallbackThrewAnException("Call filter description"), ex);
}
}
public bool Matches(IFakeObjectCall call)
{
try
{
return this.predicate.Invoke(call);
}
catch (Exception ex)
{
throw new UserCallbackException(ExceptionMessages.UserCallbackThrewAnException($"Call filter <{this.GetDescription()}>"), ex);
}
}
private string GetDescription()
{
var writer = ServiceLocator.Current.Resolve<StringBuilderOutputWriter>();
this.WriteDescription(writer);
return writer.Builder.ToString();
}
}
}
}