#region CPL License
/*
Nuclex Framework
Copyright (C) 2002-2010 Nuclex Development Labs
This library is free software; you can redistribute it and/or
modify it under the terms of the IBM Common Public License as
published by the IBM Corporation; either version 1.0 of the
License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
IBM Common Public License for more details.
You should have received a copy of the IBM Common Public
License along with this library
*/
#endregion
#if UNITTEST
using System;
using System.Collections.Generic;
using System.IO;
using NUnit.Framework;
using NMock2;
using Nuclex.Support.Tracking;
namespace Nuclex.Support.Scheduling {
  /// Unit Test for the operation queue class
  [TestFixture]
  public class OperationQueueTest {
    #region interface IOperationQueueSubscriber
    /// Interface used to test the operation queue
    public interface IOperationQueueSubscriber {
      /// Called when the operations queue's progress changes
      /// Operation queue whose progress has changed
      /// Contains the new progress achieved
      void ProgressChanged(object sender, ProgressReportEventArgs arguments);
      /// Called when the operation queue has ended
      /// Operation queue that as ended
      /// Not used
      void Ended(object sender, EventArgs arguments);
    }
    #endregion // interface IOperationQueueSubscriber
    #region class ProgressUpdateEventArgsMatcher
    /// Compares two ProgressUpdateEventArgsInstances for NMock validation
    private class ProgressUpdateEventArgsMatcher : Matcher {
      /// Initializes a new ProgressUpdateEventArgsMatcher 
      /// Expected progress update event arguments
      public ProgressUpdateEventArgsMatcher(ProgressReportEventArgs expected) {
        this.expected = expected;
      }
      /// 
      ///   Called by NMock to verfiy the ProgressUpdateEventArgs match the expected value
      /// 
      /// Actual value to compare to the expected value
      /// 
      ///   True if the actual value matches the expected value; otherwise false
      /// 
      public override bool Matches(object actualAsObject) {
        ProgressReportEventArgs actual = (actualAsObject as ProgressReportEventArgs);
        if(actual == null)
          return false;
        return (actual.Progress == this.expected.Progress);
      }
      /// Creates a string representation of the expected value
      /// Writer to write the string representation into
      public override void DescribeTo(TextWriter writer) {
        writer.Write(this.expected.Progress.ToString());
      }
      /// Expected progress update event args value
      private ProgressReportEventArgs expected;
    }
    #endregion // class ProgressUpdateEventArgsMatcher
    #region class TestOperation
    /// Operation used for testing in this unit test
    private class TestOperation : Operation, IProgressReporter {
      /// will be triggered to report when progress has been achieved
      public event EventHandler AsyncProgressChanged;
      /// Begins executing the operation. Yeah, sure :)
      public override void Start() { }
      /// Moves the operation into the ended state
      public void SetEnded() {
        SetEnded(null);
      }
      /// Moves the operation into the ended state with an exception
      /// Exception
      public void SetEnded(Exception exception) {
        this.exception = exception;
        OnAsyncEnded();
      }
      /// Changes the testing operation's indicated progress
      /// 
      ///   New progress to be reported by the testing operation
      /// 
      public void ChangeProgress(float progress) {
        OnAsyncProgressChanged(progress);
      }
      /// 
      ///   Allows the specific request implementation to re-throw an exception if
      ///   the background process finished unsuccessfully
      /// 
      protected override void ReraiseExceptions() {
        if(this.exception != null)
          throw this.exception;
      }
      /// Fires the progress update event
      /// Progress to report (ranging from 0.0 to 1.0)
      /// 
      ///   Informs the observers of this operation about the achieved progress.
      /// 
      protected virtual void OnAsyncProgressChanged(float progress) {
        OnAsyncProgressChanged(new ProgressReportEventArgs(progress));
      }
      /// Fires the progress update event
      /// Progress to report (ranging from 0.0 to 1.0)
      /// 
      ///   Informs the observers of this operation about the achieved progress.
      ///   Allows for classes derived from the Operation class to easily provide
      ///   a custom event arguments class that has been derived from the
      ///   operation's ProgressUpdateEventArgs class.
      /// 
      protected virtual void OnAsyncProgressChanged(ProgressReportEventArgs eventArguments) {
        EventHandler copy = AsyncProgressChanged;
        if(copy != null)
          copy(this, eventArguments);
      }
      /// Exception that has occured in the background process
      private volatile Exception exception;
    }
    #endregion // class TestOperation
    /// Initialization routine executed before each test is run
    [SetUp]
    public void Setup() {
      this.mockery = new Mockery();
    }
    /// Validates that the queue executes operations sequentially
    [Test]
    public void TestSequentialExecution() {
      TestOperation operation1 = new TestOperation();
      TestOperation operation2 = new TestOperation();
      OperationQueue testQueueOperation =
        new OperationQueue(
          new TestOperation[] { operation1, operation2 }
        );
      IOperationQueueSubscriber mockedSubscriber = mockSubscriber(testQueueOperation);
      testQueueOperation.Start();
      Expect.Once.On(mockedSubscriber).
        Method("ProgressChanged").
        With(
          new Matcher[] {
            new NMock2.Matchers.TypeMatcher(typeof(OperationQueue)),
            new ProgressUpdateEventArgsMatcher(new ProgressReportEventArgs(0.25f))
          }
        );
      operation1.ChangeProgress(0.5f);
      Expect.Once.On(mockedSubscriber).
        Method("ProgressChanged").
        With(
          new Matcher[] {
            new NMock2.Matchers.TypeMatcher(typeof(OperationQueue)),
            new ProgressUpdateEventArgsMatcher(new ProgressReportEventArgs(0.5f))
          }
        );
      operation1.SetEnded();
      this.mockery.VerifyAllExpectationsHaveBeenMet();
    }
    /// 
    ///   Validates that the queue executes operations sequentially and honors the weights
    ///   assigned to the individual operations
    /// 
    [Test]
    public void TestWeightedSequentialExecution() {
      TestOperation operation1 = new TestOperation();
      TestOperation operation2 = new TestOperation();
      OperationQueue testQueueOperation =
        new OperationQueue(
          new WeightedTransaction[] {
            new WeightedTransaction(operation1, 0.5f),
            new WeightedTransaction(operation2, 2.0f)
          }
        );
      IOperationQueueSubscriber mockedSubscriber = mockSubscriber(testQueueOperation);
      testQueueOperation.Start();
      Expect.Once.On(mockedSubscriber).
        Method("ProgressChanged").
        With(
          new Matcher[] {
            new NMock2.Matchers.TypeMatcher(typeof(OperationQueue)),
            new ProgressUpdateEventArgsMatcher(new ProgressReportEventArgs(0.1f))
          }
        );
      operation1.ChangeProgress(0.5f);
      Expect.Once.On(mockedSubscriber).
        Method("ProgressChanged").
        With(
          new Matcher[] {
            new NMock2.Matchers.TypeMatcher(typeof(OperationQueue)),
            new ProgressUpdateEventArgsMatcher(new ProgressReportEventArgs(0.2f))
          }
        );
      operation1.SetEnded();
      this.mockery.VerifyAllExpectationsHaveBeenMet();
    }
    /// 
    ///   Validates that the operation queue propagates the ended event once all contained
    ///   operations have completed
    /// 
    [Test]
    public void TestEndPropagation() {
      TestOperation operation1 = new TestOperation();
      TestOperation operation2 = new TestOperation();
      OperationQueue testQueueOperation =
        new OperationQueue(
          new TestOperation[] {
            operation1,
            operation2
          }
        );
      testQueueOperation.Start();
      Assert.IsFalse(testQueueOperation.Ended);
      operation1.SetEnded();
      Assert.IsFalse(testQueueOperation.Ended);
      operation2.SetEnded();
      Assert.IsTrue(testQueueOperation.Ended);
      testQueueOperation.Join();
    }
    /// 
    ///   Validates that the operation queue delivers an exception occuring in one of the
    ///   contained operations to the operation queue joiner
    /// 
    [Test]
    public void TestExceptionPropagation() {
      TestOperation operation1 = new TestOperation();
      TestOperation operation2 = new TestOperation();
      OperationQueue testQueueOperation =
        new OperationQueue(
          new TestOperation[] {
            operation1,
            operation2
          }
        );
      testQueueOperation.Start();
      Assert.IsFalse(testQueueOperation.Ended);
      operation1.SetEnded();
      Assert.IsFalse(testQueueOperation.Ended);
      operation2.SetEnded(new AbortedException("Hello World"));
      Assert.Throws(
        delegate() { testQueueOperation.Join(); }
      );
    }
    /// 
    ///   Ensures that the operation queue transparently wraps the child operations in
    ///   an observation wrapper that is not visible to an outside user
    /// 
    [Test]
    public void TestTransparentWrapping() {
      WeightedTransaction operation1 = new WeightedTransaction(
        new TestOperation()
      );
      WeightedTransaction operation2 = new WeightedTransaction(
        new TestOperation()
      );
      OperationQueue testQueueOperation =
        new OperationQueue(
          new WeightedTransaction[] {
            operation1,
            operation2
          }
        );
      // Order is important due to sequential execution!
      Assert.AreSame(operation1, testQueueOperation.Children[0]);
      Assert.AreSame(operation2, testQueueOperation.Children[1]);
    }
    /// Mocks a subscriber for the events of an operation
    /// Operation to mock an event subscriber for
    /// The mocked event subscriber
    private IOperationQueueSubscriber mockSubscriber(Operation operation) {
      IOperationQueueSubscriber mockedSubscriber =
        this.mockery.NewMock();
      operation.AsyncEnded += new EventHandler(mockedSubscriber.Ended);
      (operation as IProgressReporter).AsyncProgressChanged +=
        new EventHandler(mockedSubscriber.ProgressChanged);
      return mockedSubscriber;
    }
    /// Mock object factory
    private Mockery mockery;
  }
} // namespace Nuclex.Support.Tracking
#endif // UNITTEST