Source

SubSpec / src / SubSpec.cs

Full commit
  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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
using System;
using System.Collections.Generic;
using System.Text;
using Xunit;
using Xunit.Sdk;
using System.Xml;
using System.Diagnostics;
using System.Reflection;
using System.Linq;

namespace SubSpec
{
    /// <remarks>
    /// We declare our own delegate instead of using Func 
    /// because we can't use implicit covariance on the generic type parameter in .net 3.5"/>
    /// </remarks>
    public delegate IDisposable ContextDelegate();

    public class DisposableAction : IDisposable
    {
        public static readonly DisposableAction None = new DisposableAction( () => { } );

        private readonly Action _action;

        public DisposableAction( Action action )
        {
            if (action == null)
                throw new ArgumentNullException( "action" );

            _action = action;
        }

        public void Dispose()
        {
            _action();
        }
    }

    public interface ISpecificationPrimitive
    {
        /// <summary>
        /// Indicate that execution of this delegate should be canceled after a specified timeout.
        /// </summary>
        /// <param name="timeoutMs">The timeout in milliseconds.</param>
        ISpecificationPrimitive WithTimeout( int timeoutMs );
    }

    internal static class Core
    {
        private class SpecificationPrimitive<T> : ISpecificationPrimitive
        {
            private readonly string _message;
            private readonly T _action;
            private int _timeoutMs;

            /// <summary>
            /// Initializes a new instance of the Context class.
            /// </summary>
            /// <param name="message"></param>
            /// <param name="action"></param>
            public SpecificationPrimitive( string message, T action )
            {
                if (message == null)
                    throw new ArgumentNullException( "message" );
                if (action == null)
                    throw new ArgumentNullException( "action" );

                _message = message;
                _action = action;
            }

            public string Message
            {
                get { return _message; }
            }
            public T ActionDelegate
            {
                get { return _action; }
            }
            public int TimeoutMs
            {
                get { return _timeoutMs; }
            }

            public ISpecificationPrimitive WithTimeout( int timeoutMs )
            {
                _timeoutMs = timeoutMs;
                return this;
            }
        }

        private static class SpecificationPrimitiveExecutor
        {
            public static void Execute( SpecificationPrimitive<Action> primitive )
            {
                Debug.Assert( primitive.ActionDelegate != null );

                if (primitive.TimeoutMs > 0)
                {
#if SILVERLIGHT
                IAsyncResult asyncResult = AsyncDelegatesCompatibility.WorkingBeginInvoke( primitive.ActionDelegate, null, null );
#else
                    IAsyncResult asyncResult = primitive.ActionDelegate.BeginInvoke( null, null );
#endif

                    if (!asyncResult.AsyncWaitHandle.WaitOne( primitive.TimeoutMs ))
                        throw new Xunit.Sdk.TimeoutException( primitive.TimeoutMs );
                    else
                    {
#if SILVERLIGHT
                    primitive.ActionDelegate.WorkingEndInvoke( asyncResult );
#else
                        primitive.ActionDelegate.EndInvoke( asyncResult );
#endif

                    }
                }
                else
                    primitive.ActionDelegate();
            }

            public static IDisposable Execute( SpecificationPrimitive<ContextDelegate> primitive )
            {
                Debug.Assert( primitive.ActionDelegate != null );

                if (primitive.TimeoutMs > 0)
                {
#if SILVERLIGHT
                IAsyncResult asyncResult = AsyncDelegatesCompatibility.WorkingBeginInvoke( primitive.ActionDelegate, null, null );
#else
                    IAsyncResult asyncResult = primitive.ActionDelegate.BeginInvoke( null, null );
#endif

                    if (!asyncResult.AsyncWaitHandle.WaitOne( primitive.TimeoutMs ))
                        throw new Xunit.Sdk.TimeoutException( primitive.TimeoutMs );
                    else
                    {
#if SILVERLIGHT
                    return (IDisposable)primitive.ActionDelegate.WorkingEndInvoke( asyncResult );
#else
                        return primitive.ActionDelegate.EndInvoke( asyncResult );
#endif

                    }
                }
                else
                    return primitive.ActionDelegate();
            }
        }

        private class ActionTestCommand : TestCommand, ITestCommand
        {
            private readonly Action _action;

            public ActionTestCommand( IMethodInfo method, string name, int timeout, Action action )
                : base( method, name, timeout )
            {
                _action = action;
            }

            public override MethodResult Execute( object testClass )
            {
                try
                {
                    _action();
                    return new PassedResult( testMethod, DisplayName );
                }
                catch (Exception ex)
                {
                    return new FailedResult( testMethod, ex, DisplayName );
                }
            }
        }

        private class ExceptionTestCommand : ActionTestCommand
        {
            public ExceptionTestCommand( IMethodInfo method, Xunit.Assert.ThrowsDelegate action )
                : base( method, null, 0, () => action() )
            {
            }

            public override bool ShouldCreateInstance
            {
                get { return false; }
            }
        }

        private class AssertExecutor
        {
            private readonly List<SpecificationPrimitive<Action>> _asserts;
            private readonly SpecificationPrimitive<ContextDelegate> _context;
            private readonly SpecificationPrimitive<Action> _do;

            public AssertExecutor( SpecificationPrimitive<ContextDelegate> context, SpecificationPrimitive<Action> @do, List<SpecificationPrimitive<Action>> asserts )
            {
                _asserts = asserts;
                _context = context;
                _do = @do;
            }

            public IEnumerable<ITestCommand> AssertCommands( string name, IMethodInfo method )
            {
                foreach (var assertion in _asserts)
                {
                    // do not capture the iteration variable because 
                    // all tests would point to the same assertion
                    var capturableAssertion = assertion;
                    Action test =
                        () =>
                        {
                            using (SpecificationPrimitiveExecutor.Execute( _context ))
                            {
                                if (_do != null)
                                    SpecificationPrimitiveExecutor.Execute( _do );

                                SpecificationPrimitiveExecutor.Execute( capturableAssertion );
                            }
                        };

                    string testDescription = String.Format( "{0}, {1}", name, assertion.Message );

                    yield return new ActionTestCommand( method, testDescription, MethodUtility.GetTimeoutParameter( method ), test );
                }
            }
        }

        private class ObservationExecutor
        {
            private readonly IEnumerable<SpecificationPrimitive<Action>> _observations;
            private readonly SpecificationPrimitive<ContextDelegate> _context;
            private readonly SpecificationPrimitive<Action> _do;

            public ObservationExecutor( SpecificationPrimitive<ContextDelegate> context, SpecificationPrimitive<Action> @do, IEnumerable<SpecificationPrimitive<Action>> observations )
            {
                _observations = observations;
                _context = context;
                _do = @do;
            }

            public IEnumerable<ITestCommand> ObservationCommands( string name, IMethodInfo method )
            {
                if (_observations.Count() == 0)
                    yield break;

                bool setupExceptionOccurred = false;
                IDisposable systemUnderTest = default( IDisposable );

                Action setupAction = () =>
                {
                    try
                    {
                        systemUnderTest = SpecificationPrimitiveExecutor.Execute( _context );

                        if (_do != null)
                            SpecificationPrimitiveExecutor.Execute( _do );
                    }
                    catch (Exception)
                    {
                        setupExceptionOccurred = true;
                        throw;
                    }
                };

                yield return new ActionTestCommand( method, "{ " + name, 0, setupAction );

                foreach (var observation in _observations)
                {
                    // do not capture the iteration variable because 
                    // all tests would point to the same observation
                    var capturableObservation = observation;
                    Action perform = () =>
                    {
                        if (setupExceptionOccurred)
                            throw new ContextSetupFailedException( "Setting up Context failed" );

                        SpecificationPrimitiveExecutor.Execute( capturableObservation );
                    };

                    yield return new ActionTestCommand( method, "\t- " + capturableObservation.Message, 0, perform );
                }

                Action tearDownAction = () =>
                {
                    if (systemUnderTest != null)
                        systemUnderTest.Dispose();

                    if (setupExceptionOccurred)
                        throw new ContextSetupFailedException( "Setting up Context failed, but Fixtures were disposed." );
                };

                yield return new ActionTestCommand( method, "} " + name, 0, tearDownAction );
            }
        }

        /// <summary>
        /// An exception that is thrown from Observations or their teardown whenever the corresponding setup failed.
        /// </summary>
        private class ContextSetupFailedException : Exception
        {
            public ContextSetupFailedException( string message ) : base( message ) { }
        }

        internal static class SpecificationContext
        {
            [ThreadStatic]
            private static bool _threadStaticInitialized;
            [ThreadStatic]
            private static SpecificationPrimitive<ContextDelegate> _context;
            [ThreadStatic]
            private static SpecificationPrimitive<Action> _do;
            [ThreadStatic]
            private static List<SpecificationPrimitive<Action>> _asserts;
            [ThreadStatic]
            private static List<SpecificationPrimitive<Action>> _observations;
            [ThreadStatic]
            private static List<SpecificationPrimitive<Action>> _skips;
            [ThreadStatic]
            private static List<Action> _exceptions;

            private static void Reset()
            {
                _exceptions = new List<Action>();
                _context = null;
                _do = null;
                _asserts = new List<SpecificationPrimitive<Action>>();
                _observations = new List<SpecificationPrimitive<Action>>();
                _skips = new List<SpecificationPrimitive<Action>>();
            }

            private static void EnsureThreadStaticInitialized()
            {
                if (_threadStaticInitialized)
                    return;

                Reset();
                _threadStaticInitialized = true;
            }

            public static ISpecificationPrimitive Context( string message, ContextDelegate arrange )
            {
                EnsureThreadStaticInitialized();

                if (_context == null)
                    _context = new SpecificationPrimitive<ContextDelegate>( message, arrange );
                else
                    _exceptions.Add( () => { throw new InvalidOperationException( "Cannot have more than one Context statement in a specification" ); } );

                return _context;
            }

            public static ISpecificationPrimitive Do( string message, Action doAction )
            {
                EnsureThreadStaticInitialized();

                if (_do == null)
                    _do = new SpecificationPrimitive<Action>( message, doAction );
                else
                    _exceptions.Add( () => { throw new InvalidOperationException( "Cannot have more than one Do statement in a specification" ); } );

                return _do;
            }

            public static ISpecificationPrimitive Assert( string message, Action assertAction )
            {
                EnsureThreadStaticInitialized();

                SpecificationPrimitive<Action> assert = new SpecificationPrimitive<Action>( message, assertAction );
                _asserts.Add( assert );

                return assert;
            }

            public static ISpecificationPrimitive Observation( string message, Action observationAction )
            {
                EnsureThreadStaticInitialized();

                var observation = new SpecificationPrimitive<Action>( message, observationAction );
                _observations.Add( observation );

                return observation;
            }

            public static ISpecificationPrimitive Todo( string message, Action skippedAction )
            {
                EnsureThreadStaticInitialized();

                SpecificationPrimitive<Action> skip = new SpecificationPrimitive<Action>( message, skippedAction );
                _skips.Add( skip );

                return skip;
            }

            private static string PrepareSetupDescription()
            {
                string name = _context.Message;

                if (_do != null)
                    name += " " + _do.Message;
                return name;
            }

            public static IEnumerable<ITestCommand> SafelyEnumerateTestCommands( IMethodInfo method, Action<IMethodInfo> registerPrimitives )
            {
                try
                {
                    registerPrimitives( method );

                    IEnumerable<ITestCommand> testCommands = SpecificationContext.BuildCommandsFromRegisteredPrimitives( method );

                    return testCommands;
                }
                catch (Exception ex)
                {
                    return new ITestCommand[] {
                        new SubSpec.Core.ExceptionTestCommand(method, () =>
                          {
                                              		throw new InvalidOperationException(string.Format("An exception was thrown while building tests from Specification {0}.{1}:\r\n" + ex.ToString(), 
                                                                                            method.TypeName, 
                                                                                            method.Name));
                                              })};
                }
            }

            private static IEnumerable<ITestCommand> BuildCommandsFromRegisteredPrimitives( IMethodInfo method )
            {
                EnsureThreadStaticInitialized();

                try
                {
                    var validationException = ValidateSpecification( method );
                    if (validationException != null)
                    {
                        yield return validationException;
                        yield break;
                    }

                    int testsReturned = 0;
                    string name = PrepareSetupDescription();

                    var ax = new AssertExecutor( _context, _do, _asserts );
                    foreach (var item in ax.AssertCommands( name, method ))
                    {
                        yield return item;
                        testsReturned++;
                    }

                    var ox = new ObservationExecutor( _context, _do, _observations );
                    foreach (var item in ox.ObservationCommands( name, method ))
                    {
                        yield return item;
                        testsReturned++;
                    }
                                                                                                                                     
                    foreach (var item in SkipCommands( name, method ))
                    {
                        yield return item;
                        testsReturned++;
                    }

                    if (testsReturned == 0)
                        yield return new ExceptionTestCommand( method, () => { throw new InvalidOperationException( "Must have at least one Assert or Observation in each specification" ); } );
                }
                finally
                {
                    Reset();
                }
            }

            private static ExceptionTestCommand ValidateSpecification( IMethodInfo method )
            {
                if (_context == null)
                    _exceptions.Add( () => { throw new InvalidOperationException( "Must have a Context in each specification" ); } );

                // check if we have any recorded exceptions
                if (_exceptions.Count > 0)
                {
                    // throw the first recorded exception, preserves stacktraces nicely.
                    return new ExceptionTestCommand( method, () => _exceptions[0]() );
                }

                return null;
            }

            private static IEnumerable<ITestCommand> SkipCommands( string name, IMethodInfo method )
            {
                foreach (var kvp in _skips)
                    yield return new SkipCommand( method, name + ", " + kvp.Message, "Action is Todo (instead of Observation or Assert)" );
            }
        }
    }

    [AttributeUsage( AttributeTargets.Method, AllowMultiple = false, Inherited = true )]
    public class SpecificationAttribute : FactAttribute
    {
        protected override IEnumerable<ITestCommand> EnumerateTestCommands( IMethodInfo method )
        {
            return SubSpec.Core.SpecificationContext.SafelyEnumerateTestCommands( method, RegisterSpecificationPrimitives);
        }

        public static IEnumerable<ITestCommand> FtoEnumerateTestCommands( IMethodInfo method )
        {
            return SubSpec.Core.SpecificationContext.SafelyEnumerateTestCommands( method, RegisterSpecificationPrimitives );
        }

        private static void RegisterSpecificationPrimitives( IMethodInfo method )
        {
            if (method.IsStatic)
                method.Invoke( null, null );
            else
            {
                ConstructorInfo defaultConstructor = method.MethodInfo.ReflectedType.GetConstructor( Type.EmptyTypes );

                if (defaultConstructor == null)
                    throw new InvalidOperationException( "Specification class does not have a default constructor" );

                object instance = defaultConstructor.Invoke( null );
                method.Invoke( instance, null );
            }
        }
    }

    /// <summary>
    /// Provides extensions for a fluent specification syntax
    /// </summary>
    public static class SpecificationExtensions
    {
        private const string IDisposableHintMessaage = "Your context implements IDisposable. Use ContextFixture() to have its lifecycle managed by SubSpec.";

        /// <summary>
        /// Records a context setup for this specification.
        /// </summary>
        /// <param name="message">A message describing the established context.</param>
        /// <param name="arrange">The action that will establish the context.</param>
        public static ISpecificationPrimitive Context( this string message, Action arrange )
        {
            return SubSpec.Core.SpecificationContext.Context( message,
                                          () =>
                                          {
                                              arrange();
                                              return DisposableAction.None;
                                          } );
        }

        /// <summary>
        /// Trap for using contexts implementing IDisposable with the wrong overload.
        /// </summary>
        /// <param name="message">A message describing the established context.</param>
        /// <param name="arrange">The action that will establish and return the context for this test.</param>
        [Obsolete( IDisposableHintMessaage )]
        public static void Context( this string message, ContextDelegate arrange )
        {
            throw new InvalidOperationException( IDisposableHintMessaage );
        }

        /// <summary>
        /// Records a disposable context for this specification. The context lifecycle will be managed by SubSpec.
        /// </summary>
        /// <param name="message">A message describing the established context.</param>
        /// <param name="arrange">The action that will establish and return the context for this test.</param>
        public static ISpecificationPrimitive ContextFixture( this string message, ContextDelegate arrange )
        {
            return SubSpec.Core.SpecificationContext.Context( message, arrange );
        }

        /// <summary>
        /// Records an action to be performed on the context for this specification.
        /// </summary>
        /// <param name="message">A message describing the action.</param>
        /// <param name="arrange">The action to perform.</param>
        public static ISpecificationPrimitive Do( this string message, Action act )
        {
            return SubSpec.Core.SpecificationContext.Do( message, act );
        }

        /// <summary>
        /// Records an assertion for this specification.
        /// Each assertion is executed on an isolated context.
        /// </summary>
        /// <param name="message">A message describing the expected result.</param>
        /// <param name="assert">The action that will verify the expectation.</param>
        public static ISpecificationPrimitive Assert( this string message, Action assert )
        {
            return SubSpec.Core.SpecificationContext.Assert( message, assert );
        }

        /// <summary>
        /// Records an observation for this specification.
        /// All observations are executed on the same context.
        /// </summary>
        /// <param name="message">A message describing the expected result.</param>
        /// <param name="observation">The action that will verify the expectation.</param>
        public static ISpecificationPrimitive Observation( this string message, Action observation )
        {
            return SubSpec.Core.SpecificationContext.Observation( message, observation );
        }

        /// <summary>
        /// Records a skipped assertion for this specification.
        /// </summary>
        /// <param name="message">A message describing the expected result.</param>
        /// <param name="skippedAction">The action that will verify the expectation.</param>
        public static ISpecificationPrimitive Todo( this string message, Action skippedAction )
        {
            return SubSpec.Core.SpecificationContext.Todo( message, skippedAction );
        }
    }
}