/// <summary>
        /// Verifies that the resulting stream buffer is in the expected state.
        /// </summary>
        /// <param name="assert">The assertion handler.</param>
        /// <param name="streamBuffer">The stream buffer whose state to verify.</param>
        /// <param name="testCaseDebugDescription">A textual description of the test case to make debugging easier.</param>
        public virtual void VerifyResult(AssertionHandler assert, BatchReaderStreamBufferWrapper streamBuffer, string testCaseDebugDescription)
        {
            Debug.Assert(assert != null, "assert != null");
            Debug.Assert(streamBuffer != null, "streamBuffer != null");

            if (this.ReadPositionInBuffer.HasValue)
            {
                assert.AreEqual(
                    this.ReadPositionInBuffer.Value, streamBuffer.CurrentReadPosition,
                    string.Format("\r\n{0}:\r\nCurrent read position in the buffer '{1}' does not match expected read position '{2}'", testCaseDebugDescription, streamBuffer.CurrentReadPosition, this.ReadPositionInBuffer.Value));
            }

            if (this.NumberOfBytesInBuffer.HasValue)
            {
                assert.AreEqual(
                    this.NumberOfBytesInBuffer.Value, streamBuffer.NumberOfBytesInBuffer,
                    string.Format("\r\n{0}:\r\nNumber of bytes in the buffer '{1}' does not match expected number '{2}'", testCaseDebugDescription, streamBuffer.NumberOfBytesInBuffer, this.NumberOfBytesInBuffer.Value));
            }

            if (this.ExpectedBytesInBuffer != null)
            {
                foreach (KeyValuePair <int, byte> kvp in this.ExpectedBytesInBuffer)
                {
                    assert.AreEqual(
                        kvp.Value, streamBuffer.Bytes[kvp.Key],
                        string.Format("\r\n{0}:\r\nExpected value '{1}' at position '{2}' in the buffer but found '{3}'", testCaseDebugDescription, kvp.Value, kvp.Key, streamBuffer.Bytes[kvp.Key]));
                }
            }
        }
        /// <summary>
        /// Asserts that the given action throws the specified exception type.
        /// </summary>
        /// <typeparam name="TException">Exception type.</typeparam>
        /// <param name="action">Action to try.</param>
        /// <param name="expectedExceptionMessage">The expected exception message.</param>
        /// <param name="desciption">String to attach to all errors so that it's easier to locate what went wrong.</param>
        public static void ExpectedException <TException>(this AssertionHandler assert, Action action, string expectedExceptionMessage, string description = null)
        {
            Exception exception = RunCatching(action);

            exception = TestExceptionUtils.UnwrapAggregateException(exception, assert);
            IsExpectedException <TException>(assert, exception, expectedExceptionMessage, description);
        }
        /// <summary>
        /// Runs a single JsonReaderTestCaseDescriptor test.
        /// </summary>
        /// <param name="testCase">The test case descriptor to run.</param>
        /// <param name="testConfiguration">The test configuration to use.</param>
        /// <param name="jsonValueComparer">The comparer to use to compare JSON OMs.</param>
        /// <param name="assert">The assertion handler.</param>
        public static void ReadAndVerifyJson(
            JsonReaderTestCaseDescriptor testCase, 
            JsonReaderTestConfiguration testConfiguration, 
            IJsonValueComparer jsonValueComparer, 
            AssertionHandler assert,
            IExceptionVerifier exceptionVerifier)
        {
            TextReader testReader = new TestTextReader(new StringReader(testCase.JsonText))
            {
                FailOnPeek = true,
                FailOnSingleCharacterRead = true,
                ReadSizesEnumerator = testConfiguration.ReadSizes.EndLessLoop()
            };

            JsonValue actualJsonResult = null;
            assert.ExpectedException(() =>
                {
                    JsonReader jsonReader = testConfiguration.JsonReaderCreatorFunc(testReader, assert);
                    actualJsonResult = ReadJson(jsonReader, assert);
                },
                testCase.ExpectedException,
                exceptionVerifier);

            if (testCase.ExpectedException == null)
            {
                if (testCase.FragmentExtractor != null)
                {
                    actualJsonResult = testCase.FragmentExtractor(actualJsonResult);
                }

                jsonValueComparer = new JsonValueComparer();
                jsonValueComparer.Compare(testCase.ExpectedJson, actualJsonResult);
            }
        }
        internal static void CompareValue(IEdmValue edmValue, object odataValue, AssertionHandler assert)
        {
            if (odataValue == null)
            {
                ValidateNullValue(edmValue, assert);
                return;
            }

            ODataEntry entry = odataValue as ODataEntry;
            if (entry != null)
            {
                CompareStructuralValue(edmValue, entry, assert);
                return;
            }

            ODataComplexValue complexValue = odataValue as ODataComplexValue;
            if (complexValue != null)
            {
                CompareStructuralValue(edmValue, complexValue, assert);
                return;
            }

            ODataCollectionValue collectionValue = odataValue as ODataCollectionValue;
            if (collectionValue != null)
            {
                CompareCollectionValue(edmValue, collectionValue, assert);
                return;
            }

            ComparePrimitiveValue(edmValue, odataValue, assert);
        }
Exemple #5
0
        /// <summary>
        /// Runs a single JsonReaderTestCaseDescriptor test.
        /// </summary>
        /// <param name="testCase">The test case descriptor to run.</param>
        /// <param name="testConfiguration">The test configuration to use.</param>
        /// <param name="jsonValueComparer">The comparer to use to compare JSON OMs.</param>
        /// <param name="assert">The assertion handler.</param>
        public static void ReadAndVerifyJson(
            JsonReaderTestCaseDescriptor testCase,
            JsonReaderTestConfiguration testConfiguration,
            IJsonValueComparer jsonValueComparer,
            AssertionHandler assert,
            IExceptionVerifier exceptionVerifier)
        {
            TextReader testReader = new TestTextReader(new StringReader(testCase.JsonText))
            {
                FailOnPeek = true,
                FailOnSingleCharacterRead = true,
                ReadSizesEnumerator       = testConfiguration.ReadSizes.EndLessLoop()
            };

            JsonValue actualJsonResult = null;

            assert.ExpectedException(() =>
            {
                JsonReader jsonReader = testConfiguration.JsonReaderCreatorFunc(testReader, assert);
                actualJsonResult      = ReadJson(jsonReader, assert);
            },
                                     testCase.ExpectedException,
                                     exceptionVerifier);

            if (testCase.ExpectedException == null)
            {
                if (testCase.FragmentExtractor != null)
                {
                    actualJsonResult = testCase.FragmentExtractor(actualJsonResult);
                }

                jsonValueComparer = new JsonValueComparer();
                jsonValueComparer.Compare(testCase.ExpectedJson, actualJsonResult);
            }
        }
        /// <summary>
        /// Verifies that the resulting stream buffer is in the expected state.
        /// </summary>
        /// <param name="assert">The assertion handler.</param>
        /// <param name="streamBuffer">The stream buffer whose state to verify.</param>
        /// <param name="testCaseDebugDescription">A textual description of the test case to make debugging easier.</param>
        public virtual void VerifyResult(AssertionHandler assert, BatchReaderStreamBufferWrapper streamBuffer, string testCaseDebugDescription)
        {
            Debug.Assert(assert != null, "assert != null");
            Debug.Assert(streamBuffer != null, "streamBuffer != null");

            if (this.ReadPositionInBuffer.HasValue)
            {
                assert.AreEqual(
                    this.ReadPositionInBuffer.Value, streamBuffer.CurrentReadPosition,
                    string.Format("\r\n{0}:\r\nCurrent read position in the buffer '{1}' does not match expected read position '{2}'", testCaseDebugDescription, streamBuffer.CurrentReadPosition, this.ReadPositionInBuffer.Value));
            }

            if (this.NumberOfBytesInBuffer.HasValue)
            {
                assert.AreEqual(
                    this.NumberOfBytesInBuffer.Value, streamBuffer.NumberOfBytesInBuffer,
                    string.Format("\r\n{0}:\r\nNumber of bytes in the buffer '{1}' does not match expected number '{2}'", testCaseDebugDescription, streamBuffer.NumberOfBytesInBuffer, this.NumberOfBytesInBuffer.Value));
            }

            if (this.ExpectedBytesInBuffer != null)
            {
                foreach (KeyValuePair<int, byte> kvp in this.ExpectedBytesInBuffer)
                {
                    assert.AreEqual(
                        kvp.Value, streamBuffer.Bytes[kvp.Key],
                        string.Format("\r\n{0}:\r\nExpected value '{1}' at position '{2}' in the buffer but found '{3}'", testCaseDebugDescription, kvp.Value, kvp.Key, streamBuffer.Bytes[kvp.Key]));
                }
            }
        }
        /// <summary>
        /// Asserts that the given action throws the specified exception type.
        /// </summary>
        /// <param name="action">Action to try.</param>
        /// <param name="expectedException">The expected exception.</param>
        /// <param name="exceptionVerifier">The exception verifier.</param>
        public static void ExpectedException(this AssertionHandler assert, Action action, ExpectedException expectedException, IExceptionVerifier exceptionVerifier)
        {
            ExceptionUtilities.CheckArgumentNotNull(assert, "assert");
            ExceptionUtilities.CheckArgumentNotNull(action, "action");
            ExceptionUtilities.CheckArgumentNotNull(exceptionVerifier, "exceptionVerifier");

            Exception exception = RunCatching(action);

            if (exception == null && expectedException == null)
            {
                return;
            }
            else if (exception == null)
            {
                assert.IsNotNull(exception,
                                 "Expected exception of type '{0}' with message resource ID '{1}' but none was thrown.",
                                 expectedException.ExpectedExceptionType.ToString(),
                                 expectedException.ExpectedMessage == null ? "<null>" : expectedException.ExpectedMessage.ResourceIdentifier);
            }
            else if (expectedException == null)
            {
                assert.IsNotNull(expectedException,
                                 "Did not expect an exception but an exception of type '{0}' with message '{1}' was thrown.",
                                 exception.GetType().ToString(),
                                 exception.Message);
            }

            exception = TestExceptionUtils.UnwrapAggregateException(exception, assert);
            exceptionVerifier.VerifyExceptionResult(expectedException, exception);
        }
Exemple #8
0
        internal static void CompareValue(IEdmValue edmValue, object odataValue, AssertionHandler assert)
        {
            if (odataValue == null)
            {
                ValidateNullValue(edmValue, assert);
                return;
            }

            ODataEntry entry = odataValue as ODataEntry;

            if (entry != null)
            {
                CompareStructuralValue(edmValue, entry, assert);
                return;
            }

            ODataComplexValue complexValue = odataValue as ODataComplexValue;

            if (complexValue != null)
            {
                CompareStructuralValue(edmValue, complexValue, assert);
                return;
            }

            ODataCollectionValue collectionValue = odataValue as ODataCollectionValue;

            if (collectionValue != null)
            {
                CompareCollectionValue(edmValue, collectionValue, assert);
                return;
            }

            ComparePrimitiveValue(edmValue, odataValue, assert);
        }
Exemple #9
0
 private static bool VerifyNullnessMatches(object expected, object actual, AssertionHandler assert, string description)
 {
     if (expected == null)
     {
         assert.IsNull(actual, string.Format("The actual {0} should have been null.", description));
         return(false);
     }
     assert.IsNotNull(actual, string.Format("The actual {0} should have been not-null.", description));
     return(true);
 }
            /// <summary>
            /// Compares the given clr value value to the given query scalar value, and throws a DataComparisonException if they dont match
            /// </summary>
            /// <param name="expected">expected CLR value</param>
            /// <param name="actual">actual query primitive value to compare</param>
            /// <param name="assert">The assertion handler to use</param>
            public void Compare(object expected, QueryScalarValue actual, AssertionHandler assert)
            {
                if (actual.IsDynamicPropertyValue())
                {
                    expected = this.converter.SerializePrimitive(expected);
                    actual   = new QueryClrPrimitiveType(typeof(string), actual.Type.EvaluationStrategy).CreateValue(this.converter.SerializePrimitive(actual.Value));
                }

                this.UnderlyingComparer.Compare(expected, actual, assert);
            }
Exemple #11
0
 /// <summary>
 /// Calls the specified action and if it throws it unwraps the aggregate exception (is any) and continues throwing the exception.
 /// </summary>
 /// <param name="action">The action to execute.</param>
 /// <param name="assert">The assertion handler.</param>
 public static void UnwrapAggregateException(Action action, AssertionHandler assert)
 {
     try
     {
         action();
     }
     catch (AggregateException aggregateException)
     {
         throw UnwrapAggregateException(aggregateException, assert);
     }
 }
Exemple #12
0
        /// <summary>
        /// Creates a new JsonReader wrapper with a given Microsoft.OData.Core.Json.JsonReader instance.
        /// </summary>
        /// <param name="instance">The JsonReader instance to use.</param>
        /// <param name="assert">Optional assertion handler to use to verify the behavior of the reader.</param>
        protected JsonReader(object instance, AssertionHandler assert)
        {
            this.instance = instance;
            this.assert = assert;

            if (this.assert != null)
            {
                this.assert.IsNull(this.Value, "The Value should return null on newly created JsonReader.");
                this.assert.AreEqual(JsonNodeType.None, this.NodeType, "The initial NodeType of the JsonReader should be None.");
            }
        }
Exemple #13
0
        /// <summary>
        /// Creates a new JsonReader wrapper with a given Microsoft.OData.Json.JsonReader instance.
        /// </summary>
        /// <param name="instance">The JsonReader instance to use.</param>
        /// <param name="assert">Optional assertion handler to use to verify the behavior of the reader.</param>
        protected JsonReader(object instance, AssertionHandler assert)
        {
            this.instance = instance;
            this.assert   = assert;

            if (this.assert != null)
            {
                this.assert.IsNull(this.Value, "The Value should return null on newly created JsonReader.");
                this.assert.AreEqual(JsonNodeType.None, this.NodeType, "The initial NodeType of the JsonReader should be None.");
            }
        }
Exemple #14
0
            /// <summary>
            /// Initializes a new instance of the Tracker class
            /// </summary>
            /// <param name="context">The context</param>
            /// <param name="assert">The assertion handler to use</param>
            /// <param name="httpTracker">The http tracker to use</param>
            /// <param name="callback">The callback to call on the event args</param>
            /// <param name="model">The test model</param>
            public Tracker(DataServiceContext context, AssertionHandler assert, IDataServiceContextHttpTracker httpTracker, Action <SendingRequest2EventArgs, IDictionary <string, string> > callback, EntityModelSchema model)
            {
                ExceptionUtilities.CheckArgumentNotNull(context, "context");
                ExceptionUtilities.CheckArgumentNotNull(assert, "assert");
                ExceptionUtilities.CheckArgumentNotNull(httpTracker, "httpTracker");

                this.expectedContext = context;
                this.assert          = assert;
                this.httpTracker     = httpTracker;
                this.callback        = callback;
                this.model           = model;
            }
Exemple #15
0
 /// <summary>
 /// Verifies that the specified XPath (or more) return at least one result.
 /// </summary>
 /// <param name="navigable">Document to look in.</param>
 /// <param name="xpaths">The xpaths to verify.</param>
 public static void VerifyXPathExists(AssertionHandler assert, IXPathNavigable navigable, params string[] xpaths)
 {
     foreach (string xpath in xpaths)
     {
         int count = navigable.CreateNavigator().Select(xpath, NamespaceManager).Count;
         if (count == 0)
         {
             Trace.WriteLine(navigable.CreateNavigator().OuterXml);
             assert.Fail("Failed to find specified xpath in the document: " + xpath);
         }
     }
 }
Exemple #16
0
        public static void VerifyQueryNodesAreEqual(QueryNode expected, QueryNode actual, AssertionHandler assert)
        {
            try
            {
                if (expected == null)
                {
                    assert.IsNull(actual, "The node should be null.");
                    return;
                }
                else
                {
                    assert.IsNotNull(actual, "The node should not be null.");
                }

                assert.AreEqual(expected.InternalKind, actual.InternalKind, "The node kind differs from expected one.");
                switch (expected.InternalKind)
                {
                    case InternalQueryNodeKind.Constant:
                        VerifyConstantQueryNodesAreEqual((ConstantNode)expected, (ConstantNode)actual, assert);
                        break;
                    case InternalQueryNodeKind.Convert:
                        VerifyConvertQueryNodesAreEqual((ConvertNode)expected, (ConvertNode)actual, assert);
                        break;
                    case InternalQueryNodeKind.NonentityRangeVariableReference:
                        VerifyNonentityRangeVariableReferenceNodesAreEqual((NonentityRangeVariableReferenceNode) expected, (NonentityRangeVariableReferenceNode) actual,assert);
                        break;
                    case InternalQueryNodeKind.EntityRangeVariableReference:
                        VerifyEntityRangeVariableReferenceNodesAreEqual((EntityRangeVariableReferenceNode)expected, (EntityRangeVariableReferenceNode)actual, assert);
                        break;
                    case InternalQueryNodeKind.BinaryOperator:
                        VerifyBinaryOperatorQueryNodesAreEqual((BinaryOperatorNode)expected, (BinaryOperatorNode)actual, assert);
                        break;
                    case InternalQueryNodeKind.UnaryOperator:
                        VerifyUnaryOperatorQueryNodesAreEqual((UnaryOperatorNode)expected, (UnaryOperatorNode)actual, assert);
                        break;
                    case InternalQueryNodeKind.SingleValuePropertyAccess:
                        VerifyPropertyAccessQueryNodesAreEqual((SingleValuePropertyAccessNode)expected, (SingleValuePropertyAccessNode)actual, assert);
                        break;
                    case InternalQueryNodeKind.SingleValueFunctionCall:
                        VerifySingleValueFunctionCallQueryNodesAreEqual((SingleValueFunctionCallNode)expected, (SingleValueFunctionCallNode)actual, assert);
                        break;
                    default:
                        throw new Exception("Query node of kind '" + expected.InternalKind.ToString() + "' not yet supported by VerifyQueryNodesAreEqual.");
                }
            }
            catch (Exception)
            {
                assert.Warn("Expected query node: " + expected.ToDebugString());
                assert.Warn("Actual query node: " + actual.ToDebugString());
                throw;
            }
        }
        /// <summary>
        /// Compares the given clr value to the given query scalar value, and throws a DataComparisonException if they dont match
        /// </summary>
        /// <param name="expected">expected CLR value</param>
        /// <param name="actual">actual query primitive value to compare</param>
        /// <param name="assert">The assertion handler to use</param>
        public override void Compare(object expected, QueryScalarValue actual, AssertionHandler assert)
        {
            ExceptionUtilities.CheckArgumentNotNull(actual, "actual");

            if (actual.IsDynamicPropertyValue() && !(actual.Type is QueryClrSpatialType))
            {
                this.CompareDynamicValues(actual.Type, expected, actual.Value, assert);
            }
            else
            {
                base.Compare(expected, actual, assert);
            }
        }
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="reader">The XML reader to wrap.</param>
 /// <param name="parentXmlBaseUri">The parent xml:base URI to start with.</param>
 /// <param name="documentBaseUri">The base URI for the document.</param>
 /// <param name="disableXmlBase">Flag controling if xml:base attributes should be processed when reading.</param>
 /// <param name="maxInnerErrorDepth">The maximumum number of recursive internalexception elements to allow when reading in-stream errors.</param>
 /// <param name="assert">The assertion handler to use.</param>
 public BufferingXmlReader(XmlReader reader, Uri parentXmlBaseUri, Uri documentBaseUri, bool disableXmlBase, int maxInnerErrorDepth, AssertionHandler assert)
 {
     ExceptionUtilities.CheckArgumentNotNull(reader, "reader");
     this.instance = (XmlReader)ReflectionUtils.CreateInstance(
         BufferingXmlReaderType, 
         new Type[] { typeof(XmlReader), typeof(Uri), typeof(Uri), typeof(bool), typeof(int)}, 
         reader, 
         parentXmlBaseUri,
         documentBaseUri, 
         disableXmlBase, 
         maxInnerErrorDepth);
     this.assert = assert;
 }
 /// <summary>
 /// Asserts that the given exception is the specified exception type.
 /// </summary>
 /// <typeparam name="TException">Exception type.</typeparam>
 /// <param name="exception">The exception instance to verify.</param>
 /// <param name="expectedExceptionMessage">The expected exception message. If this is null, the check will verify that no exception was thrown.</param>
 /// <param name="desciption">String to attach to all errors so that it's easier to locate what went wrong.</param>
 public static void IsExpectedException <TException>(this AssertionHandler assert, Exception exception, string expectedExceptionMessage, string description = null)
 {
     if (expectedExceptionMessage == null)
     {
         assert.IsNull(exception, "No exception was expected, but it occured. " + (description ?? string.Empty) + "\r\n" + (exception == null ? string.Empty : exception.ToString()));
     }
     else
     {
         assert.IsNotNull(exception, "Expected " + typeof(TException).FullName + " but it was not thrown. " + (description ?? string.Empty));
         assert.IsTrue(exception is TException, "Exception had unexpected type " + exception.GetType().FullName + ", expected type is " + typeof(TException).FullName + ". " + description);
         assert.AreEqual(expectedExceptionMessage, exception.Message, "Unexpected exception message. " + (description ?? string.Empty));
     }
 }
Exemple #20
0
        /// <summary>
        /// If an <see cref="AggregateException"/> is passed as <paramref name="exception"/> this method will check whether
        /// more than one inner exceptions exist and throw if that is the case. Otherwise it returns the single inner exception.
        /// </summary>
        /// <param name="exception">The <see cref="Exception"/> instance to check.</param>
        /// <param name="assert">The assertion handler.</param>
        /// <returns>
        /// If the <paramref name="exception"/> is an <see cref="AggregateException"/> a single inner exception is expected and returned;
        /// otherwise returns the <paramref name="exception"/> itself.
        /// </returns>
        public static Exception UnwrapAggregateException(Exception exception, AssertionHandler assert)
        {
            AggregateException ae = exception as AggregateException;

            if (ae == null)
            {
                return(exception);
            }

            ae = ae.Flatten();
            assert.AreEqual(1, ae.InnerExceptions.Count, "Expected exception count does not match.");
            return(ae.InnerExceptions[0]);
        }
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="reader">The XML reader to wrap.</param>
 /// <param name="parentXmlBaseUri">The parent xml:base URI to start with.</param>
 /// <param name="documentBaseUri">The base URI for the document.</param>
 /// <param name="disableXmlBase">Flag controling if xml:base attributes should be processed when reading.</param>
 /// <param name="maxInnerErrorDepth">The maximumum number of recursive internalexception elements to allow when reading in-stream errors.</param>
 /// <param name="assert">The assertion handler to use.</param>
 public BufferingXmlReader(XmlReader reader, Uri parentXmlBaseUri, Uri documentBaseUri, bool disableXmlBase, int maxInnerErrorDepth, AssertionHandler assert)
 {
     ExceptionUtilities.CheckArgumentNotNull(reader, "reader");
     this.instance = (XmlReader)ReflectionUtils.CreateInstance(
         BufferingXmlReaderType,
         new Type[] { typeof(XmlReader), typeof(Uri), typeof(Uri), typeof(bool), typeof(int) },
         reader,
         parentXmlBaseUri,
         documentBaseUri,
         disableXmlBase,
         maxInnerErrorDepth);
     this.assert = assert;
 }
        /// <summary>
        /// Compares the given clr value to the given query scalar value, and throws a DataComparisonException if they dont match
        /// </summary>
        /// <param name="expected">expected CLR value</param>
        /// <param name="actual">actual query primitive value to compare</param>
        /// <param name="assert">The assertion handler to use</param>
        public override void Compare(object expected, QueryScalarValue actual, AssertionHandler assert)
        {
            ExceptionUtilities.CheckArgumentNotNull(actual, "actual");

            if (actual.IsDynamicPropertyValue() && !(actual.Type is QueryClrSpatialType))
            {
                this.CompareDynamicValues(actual.Type, expected, actual.Value, assert);
            }
            else
            {
                base.Compare(expected, actual, assert);
            }
        }
 /// <summary>
 /// Calls constructor and verifies expected exception.
 /// </summary>
 /// <param name="type">The type to construct.</param>
 /// <param name="errorMessage">The expected error message.</param>
 /// <param name="parameters">The parameters for the constructor.</param>
 public static void CheckInvalidConstructorParameters(AssertionHandler assert, Type type, string errorMessage, params object[] parameters)
 {
     try
     {
         ConstructorInfo c = type.GetConstructors(BindingFlags.Public | BindingFlags.Instance).Single();
         c.Invoke(parameters);
         assert.Fail(errorMessage);
     }
     catch (TargetInvocationException e)
     {
         assert.IsTrue(e.InnerException is ArgumentException, "Expecting argument exception");
         assert.IsTrue(e.InnerException.Message.Contains(errorMessage), "The exception message doesn't contain the expected string '" + errorMessage + "'.");
     }
 }
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="messageWriter">The message writer to wrap.</param>
        /// <param name="testConfiguration">The test configuration to use.</param>
        /// <param name="messageStream">the stream of the message.</param>
        /// <param name="message">The message to write to.</param>
        /// <param name="assert">The assertion handler for the test.</param>
        public ODataMessageWriterTestWrapper(ODataMessageWriter messageWriter, WriterTestConfiguration testConfiguration, TestMessage message, AssertionHandler assert)
        {
            ExceptionUtilities.CheckArgumentNotNull(messageWriter, "messageWriter");
            ExceptionUtilities.CheckArgumentNotNull(testConfiguration, "testConfiguration");

            this.messageWriter = messageWriter;
            this.testConfiguration = testConfiguration;
            this.message = message;
            this.assert = assert;

            if (message != null && message.TestStream != null && assert != null)
            {
                this.assert.AreEqual(0, message.TestStream.DisposeCount, "If the underlying message stream is a TestStream, its dispose count must be 0.");
                this.assert.AreEqual(false, message.StreamRetrieved, "GetMessage and GetMessageAsync must not be called privously on the given message.");
            }
        }
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="messageWriter">The message writer to wrap.</param>
        /// <param name="testConfiguration">The test configuration to use.</param>
        /// <param name="messageStream">the stream of the message.</param>
        /// <param name="message">The message to write to.</param>
        /// <param name="assert">The assertion handler for the test.</param>
        public ODataMessageWriterTestWrapper(ODataMessageWriter messageWriter, WriterTestConfiguration testConfiguration, TestMessage message, AssertionHandler assert)
        {
            ExceptionUtilities.CheckArgumentNotNull(messageWriter, "messageWriter");
            ExceptionUtilities.CheckArgumentNotNull(testConfiguration, "testConfiguration");

            this.messageWriter     = messageWriter;
            this.testConfiguration = testConfiguration;
            this.message           = message;
            this.assert            = assert;

            if (message != null && message.TestStream != null && assert != null)
            {
                this.assert.AreEqual(0, message.TestStream.DisposeCount, "If the underlying message stream is a TestStream, its dispose count must be 0.");
                this.assert.AreEqual(false, message.StreamRetrieved, "GetMessage and GetMessageAsync must not be called privously on the given message.");
            }
        }
        /// <summary>
        /// Calls the specified action and if it throws it unwraps the aggregate exception (is any) and continues throwing the exception.
        /// </summary>
        /// <param name="action">The action to execute.</param>
        /// <param name="assert">The assertion handler.</param>
        public static void UnwrapAggregateException(Action action, AssertionHandler assert)
        {
            try
            {
                action();
            }
#if SILVERLIGHT
            catch (Exception aggregateException)
            {
                throw UnwrapAggregateException(aggregateException, assert);
            }
#else
            catch (AggregateException aggregateException)
            {
                throw UnwrapAggregateException(aggregateException, assert);
            }
#endif
        }
Exemple #27
0
        public static void VerifyEnumerationsAreEqual <T>(
            IEnumerable <T> expectedEnumeration,
            IEnumerable <T> actualEnumeration,
            Action <T, T, AssertionHandler> verifyItem,
            Func <T, string> itemToDebugString,
            AssertionHandler assert)
        {
            if (expectedEnumeration == null)
            {
                assert.IsNull(actualEnumeration, "The enumeration of items should have been null.");
                return;
            }
            else
            {
                assert.IsNotNull(actualEnumeration, "The enumeration of items should not have been null.");
            }

            try
            {
                var expectedEnumerator = expectedEnumeration.GetEnumerator();
                var actualEnumerator   = actualEnumeration.GetEnumerator();
                while (expectedEnumerator.MoveNext())
                {
                    assert.IsTrue(
                        actualEnumerator.MoveNext(),
                        "The actual enumeration has less items than the expected enumeration.\r\n" +
                        "Expected items: " + string.Join(", ", expectedEnumeration.Select(t => "<" + itemToDebugString(t) + ">")) + "\r\n" +
                        "Actual items: " + string.Join(", ", actualEnumeration.Select(t => "<" + itemToDebugString(t) + ">")));
                    verifyItem(expectedEnumerator.Current, actualEnumerator.Current, assert);
                }

                assert.IsFalse(
                    actualEnumerator.MoveNext(),
                    "The expected enumeration has less items than the actual enumeration.\r\n" +
                    "Expected items: " + string.Join(", ", expectedEnumeration.Select(t => "<" + itemToDebugString(t) + ">")) + "\r\n" +
                    "Actual items: " + string.Join(", ", actualEnumeration.Select(t => "<" + itemToDebugString(t) + ">")));
            }
            catch (Exception)
            {
                assert.Warn("Expected items: " + string.Join(", ", expectedEnumeration.Select(t => "<" + itemToDebugString(t) + ">")));
                assert.Warn("Actual items: " + string.Join(", ", actualEnumeration.Select(t => "<" + itemToDebugString(t) + ">")));
                throw;
            }
        }
        /// <summary>
        /// Compares the given values of the given type, and throws a DataComparisonException or AssertionFailedException if values don't match
        /// </summary>
        /// <param name="type">The expected type</param>
        /// <param name="expected">The expected value</param>
        /// <param name="actual">The actual value</param>
        /// <param name="assert">The assertion handler to use</param>
        protected virtual void Compare(QueryScalarType type, object expected, object actual, AssertionHandler assert)
        {
            ExceptionUtilities.CheckArgumentNotNull(type, "type");
            ExceptionUtilities.CheckArgumentNotNull(assert, "assert");

            if (expected == type.NullValue.Value)
            {
                assert.IsNull(actual, "Primitive value unexpectedly non-null");
            }
            else
            {
                assert.IsNotNull(actual, "Primitive value unexpectedly null");

                assert.AreEqual(expected.GetType(), actual.GetType(), EqualityComparer<Type>.Default, "Types did not match");

                var comparer = new DelegateBasedEqualityComparer<QueryScalarValue>((v1, v2) => v1.Type.EvaluationStrategy.Compare(v1, v2) == 0);
                assert.AreEqual(type.CreateValue(expected), type.CreateValue(actual), comparer, "Primitive value did not match");
            }
        }
Exemple #29
0
        public static void VerifyOrderByClauseAreEqual(OrderByClause expected, OrderByClause actual, AssertionHandler assert)
        {
            if (expected == null)
            {
                if (actual != null)
                {
                    throw new Exception("Expected no ThenBy, but found one.");
                }
                return;
            }
            
            if (actual == null)
            {
                throw new Exception("Expected a ThenBy, but found none.");
            }

            VeryfyRangeVariablesAreEqual(expected.RangeVariable, actual.RangeVariable, assert);
            VerifyQueryNodesAreEqual(expected.Expression, actual.Expression, assert);
            VerifyOrderByClauseAreEqual(expected.ThenBy, actual.ThenBy, assert);
        }
        internal void CompareDynamicValues(QueryType queryType, object expected, object actual, AssertionHandler assert)
        {
            var expectedValue = expected;
            var actualValue = actual;

            if (expected is DateTime && actual is DateTime)
            {
                expectedValue = this.Converter.Normalize(expectedValue);
                actualValue = this.Converter.Normalize(actualValue);
            }

            var expectedString = this.Converter.SerializePrimitive(expectedValue);
            var actualString = this.Converter.SerializePrimitive(actualValue);

            base.Compare(
                new QueryClrPrimitiveType(typeof(string), queryType.EvaluationStrategy),
                expectedString,
                actualString,
                assert);
        }
Exemple #31
0
        static void Main(string[] args)
        {
            AssertionHandler.CatchAssertions();
            PrivateLock.OnDeadLock += () => Console.WriteLine("!!!!!!!!!!!!! DEADLOCK !!!!!!!!!!!!");

            var services = new ServiceManager();
            var node     = new BlockchainNode(services);
            var explorer = new BlockchainExplorer(services);

            Console.WriteLine("Initializing...");
            services.Initialize();
            Console.WriteLine("Starting...");
            services.Start();
            Console.WriteLine("Running...");

            var console = new ConsoleCommandProcessor(typeof(Program).Assembly);

            console.Initialize();

            console.Run();
        }
Exemple #32
0
        private static void Main(string[] args)
        {
            AssertionHandler.CatchAssertions();
            PrivateLock.OnDeadLock += () => Console.WriteLine("!!!!!!!!!!!!! DEADLOCK !!!!!!!!!!!!");

            var services = new ServiceManager();
            var node     = new BlockchainNode(services);
            var wallet   = (IWalletService) new WalletService();

            services.Add(wallet);

            wallet.AddressListener.RegisterWalletUpdated(input =>
            {
                var verb     = input.IsInput ? "Sent" : "Received";
                var amount   = Amount.ToWholeDecimal(input.Amount);
                var currency = Currency.ToSymbol(input.Currency);
                Console.WriteLine($"{verb} {input.Address.Encoded} {amount} {currency}");
            });

            wallet.TransactionSubmissionListener.OnSuccess += (transaction, elapsed) => { Console.WriteLine($"Transaction Included ! Elapsed Time {elapsed.TotalSeconds}s"); };

            Console.WriteLine("Initializing...");
            services.Initialize();
            Console.WriteLine("Starting...");
            services.Start();
            Console.WriteLine("Running...");

            var console = new ConsoleCommandProcessor(typeof(SetActiveKeyCommand).Assembly);

            console.Initialize();
            console.RunCommand("loadinstructions", new [] { Configuration.InstructionsFile });

            if (!wallet.GetPrivateKeys().Any())
            {
                console.RunCommand("initializewallet", new string[0]);
            }

            console.Run();
        }
Exemple #33
0
 /// <summary>
 /// Verifies that the specified XPath (or more) return at least one result.
 /// </summary>
 /// <param name="node">Node to look in.</param>
 /// <param name="xpaths">The xpaths to verify.</param>
 public static void VerifyXPathExists(AssertionHandler assert, XNode node, params string[] xpaths)
 {
     VerifyXPathExists(assert, node.CreateNavigator(NameTable), xpaths);
 }
 /// <summary>
 /// Constructor.
 /// </summary>
 public ReorderingJsonReaderTestCaseDescriptor(AssertionHandler assert)
 {
     this.assert = assert;
 }
Exemple #35
0
 private static void VerifyCustomQueryOptionQueryTokensAreEqual(CustomQueryOptionToken expected, CustomQueryOptionToken actual, AssertionHandler assert)
 {
     assert.AreEqual(expected.Name, actual.Name, "The Name of the query option token doesn't match the expected one.");
     assert.AreEqual(expected.Value, actual.Value, "The Value of the query option token doesn't match the expected one.");
 }
            /// <summary>
            /// Initializes a new instance of the Tracker class
            /// </summary>
            /// <param name="context">The context</param>
            /// <param name="assert">The assertion handler to use</param>
            /// <param name="httpTracker">The http tracker to use</param>
            /// <param name="callback">The callback to call on the event args</param>
            /// <param name="model">The test model</param>
            public Tracker(DataServiceContext context, AssertionHandler assert, IDataServiceContextHttpTracker httpTracker, Action<SendingRequest2EventArgs, IDictionary<string, string>> callback, EntityModelSchema model)
            {
                ExceptionUtilities.CheckArgumentNotNull(context, "context");
                ExceptionUtilities.CheckArgumentNotNull(assert, "assert");
                ExceptionUtilities.CheckArgumentNotNull(httpTracker, "httpTracker");

                this.expectedContext = context;
                this.assert = assert;
                this.httpTracker = httpTracker;
                this.callback = callback;
                this.model = model;
            }
 private static void VerifyStarQueryTokensAreEqual(StarToken expected, StarToken actual, AssertionHandler assert)
 {
     VerifyQueryTokensAreEqual(expected.NextToken, actual.NextToken, assert);
 }
 /// <summary>
 /// Verifies that two queries are equal.
 /// </summary>
 /// <param name="expected">The expected query.</param>
 /// <param name="actual">The actual query.</param>
 /// <param name="assert">Assertion handler to use.</param>
 internal static void VerifySyntaxTreesAreEqual(SyntacticTree expected, SyntacticTree actual, AssertionHandler assert)
 {
     try
     {
         if (!VerifyNullnessMatches(expected, actual, assert, "query")) return;
         VerifySyntaxTreesAreEqualImpl(expected, actual, assert);
     }
     catch (Exception)
     {
         assert.Warn("Expected query: " + expected.ToDebugString());
         assert.Warn("Actual query: " + actual.ToDebugString());
         throw;
     }
 }
 internal static void VerifyPathSegmentTokensAreEqual(IEnumerable<PathSegmentToken> expectedTokens, IEnumerable<PathSegmentToken> actualTokens, AssertionHandler assert)
 {
     VerificationUtils.VerifyEnumerationsAreEqual(
         expectedTokens,
         actualTokens,
         VerifyPathSegmentTokensAreEqual,
         ToDebugString,
         assert);
 }
        private static void VerifyPathSegmentTokensAreEqual(PathSegmentToken expected, PathSegmentToken actual, AssertionHandler assert)
        {
            try
            {
                if (!VerifyNullnessMatches(expected, actual, assert, "token")) return;

                assert.AreEqual(expected.GetType(), actual.GetType(), "The token kinds are different.");

                assert.AreEqual(expected.Identifier, actual.Identifier, "The token identifiers are different.");

                VerifyPathSegmentTokensAreEqual(expected.NextToken, actual.NextToken, assert);
            }
            catch (Exception)
            {
                assert.Warn("Expected query token: " + expected.ToDebugString());
                assert.Warn("Actual query token: " + actual.ToDebugString());
                throw;
            }
        }
 private static void VerifySelectQueryTokensAreEqual(SelectToken expected, SelectToken actual, AssertionHandler assert)
 {
     VerifyPathSegmentTokensAreEqual(expected.Properties, actual.Properties, assert);
 }
 private static void VerifySyntaxTreesAreEqualImpl(SyntacticTree expected, SyntacticTree actual, AssertionHandler assert)
 {
     VerifyStringsAreEqual(expected.Path, actual.Path, assert);
     VerifyQueryTokensAreEqual(expected.Filter, actual.Filter, assert);
     if (expected.OrderByTokens != null && actual.OrderByTokens != null)
         VerifyQueryTokensAreEqual(expected.OrderByTokens.Cast<QueryToken>(), actual.OrderByTokens.Cast<QueryToken>(), assert);
     else if ((expected.OrderByTokens != null && actual.OrderByTokens == null) || (expected.OrderByTokens == null && actual.OrderByTokens != null))
         assert.Fail("Query tokens are different");
     assert.AreEqual(expected.Skip, actual.Skip, "Skip values are different.");
     VerificationUtils.VerifyEnumerationsAreEqual(
         expected.QueryOptions,
         actual.QueryOptions,
         VerifyCustomQueryOptionQueryTokensAreEqual,
         (item) => item.ToDebugString(),
         assert);
 }
 private static void VerifyCustomQueryOptionQueryTokensAreEqual(CustomQueryOptionToken expected, CustomQueryOptionToken actual, AssertionHandler assert)
 {
     assert.AreEqual(expected.Name, actual.Name, "The Name of the query option token doesn't match the expected one.");
     assert.AreEqual(expected.Value, actual.Value, "The Value of the query option token doesn't match the expected one.");
 }
Exemple #44
0
 private static void VerifyNonRootSegmentQueryTokensAreEqual(InnerPathToken expected, InnerPathToken actual, AssertionHandler assert)
 {
     assert.AreEqual(expected.Identifier, actual.Identifier, "The Name of the navigation property token doesn't match the expected one.");
     VerifyQueryTokensAreEqual(expected.NextToken, actual.NextToken, assert);
 }
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="assert">The assertion handler to use.</param>
 public ObjectModelVisitor(AssertionHandler assert)
 {
     this.assert = assert;
 }
Exemple #46
0
 private static void VerifyFunctionParameterTokensAreEqual(FunctionParameterToken expected, FunctionParameterToken actual, AssertionHandler assert)
 {
     assert.AreEqual(expected.ParameterName, actual.ParameterName, "The Name of the function call token doesn't match the expected one.");
     VerifyQueryTokensAreEqual(expected.ValueToken, actual.ValueToken, assert);
 }
 private static void VerifyLiteralQueryTokensAreEqual(LiteralToken expected, LiteralToken actual, AssertionHandler assert)
 {
     assert.AreEqual(expected.Value, actual.Value, "Literal values are different.");
 }
Exemple #48
0
 private static void VerifySelectQueryTokensAreEqual(SelectToken expected, SelectToken actual, AssertionHandler assert)
 {
     VerifyPathSegmentTokensAreEqual(expected.Properties, actual.Properties, assert);
 }
Exemple #49
0
 private static void VerifyFunctionCallQueryTokensAreEqual(FunctionCallToken expected, FunctionCallToken actual, AssertionHandler assert)
 {
     assert.AreEqual(expected.Name, actual.Name, "The Name of the function call token doesn't match the expected one.");
     VerifyQueryTokensAreEqual(expected.Arguments, actual.Arguments, assert);
 }
 private static void VerifyUnaryOperatorQueryTokensAreEqual(UnaryOperatorToken expected, UnaryOperatorToken actual, AssertionHandler assert)
 {
     assert.AreEqual(expected.OperatorKind, actual.OperatorKind, "The unary operator kind doesn't match the expected one.");
     VerifyQueryTokensAreEqual(expected.Operand, actual.Operand, assert);
 }
Exemple #51
0
 private static void VerifyOrderByQueryTokensAreEqual(OrderByToken expected, OrderByToken actual, AssertionHandler assert)
 {
     assert.AreEqual(expected.Direction, actual.Direction, "The Direction of the order by doesn't match the expected one.");
     VerifyQueryTokensAreEqual(expected.Expression, actual.Expression, assert);
 }
 private static void VerifyPropertyAccessQueryTokensAreEqual(EndPathToken expected, EndPathToken actual, AssertionHandler assert)
 {
     assert.AreEqual(expected.Identifier, actual.Identifier, "The Name of the property access token doesn't match the expected one.");
     VerifyQueryTokensAreEqual(expected.NextToken, actual.NextToken, assert);
 }
Exemple #53
0
 private static void VerifyStarQueryTokensAreEqual(StarToken expected, StarToken actual, AssertionHandler assert)
 {
     VerifyQueryTokensAreEqual(expected.NextToken, actual.NextToken, assert);
 }
 private static void VerifyNonRootSegmentQueryTokensAreEqual(InnerPathToken expected, InnerPathToken actual, AssertionHandler assert)
 {
     assert.AreEqual(expected.Identifier, actual.Identifier, "The Name of the navigation property token doesn't match the expected one.");
     VerifyQueryTokensAreEqual(expected.NextToken, actual.NextToken, assert);
 }
Exemple #55
0
        private static void RunHeaderTest(
            Func <IEnumerable <KeyValuePair <string, string> > > getHeadersFunc,
            bool writing,
            Func <string, string> getHeaderFunc,
            Action <string, string> setHeaderAction,
            AssertionHandler assert,
            IExceptionVerifier exceptionVerifier)
        {
            assert.IsNotNull(getHeadersFunc(), "Non-null headers expected.");
            assert.AreEqual(0, getHeadersFunc().Count(), "Empty header collection expected.");
            assert.IsNull(getHeaderFunc("a"), "Unexpectedly found header.");

            ExpectedException expectedException = writing ? null : ODataExpectedExceptions.ODataException("ODataMessage_MustNotModifyMessage");

            TestExceptionUtils.ExpectedException(
                assert,
                () =>
            {
                setHeaderAction("a", "b");

                assert.AreEqual(1, getHeadersFunc().Count(), "One header expected.");
                assert.AreEqual("b", getHeaderFunc("a"), "Header not found or invalid header value.");
                List <KeyValuePair <string, string> > expectedHeaders = new List <KeyValuePair <string, string> >
                {
                    new KeyValuePair <string, string>("a", "b")
                };
                VerificationUtils.VerifyEnumerationsAreEqual(
                    expectedHeaders,
                    getHeadersFunc(),
                    (first, second, assert2) => assert2.AreEqual(first, second, "Items differ."),
                    (item) => item.Key + " = " + item.Value,
                    assert);

                setHeaderAction("a", "c");

                assert.AreEqual(1, getHeadersFunc().Count(), "One header expected.");
                assert.AreEqual("c", getHeaderFunc("a"), "Header not found or invalid header value.");
                expectedHeaders[0] = new KeyValuePair <string, string>("a", "c");
                VerificationUtils.VerifyEnumerationsAreEqual(
                    expectedHeaders,
                    getHeadersFunc(),
                    (first, second, assert2) => assert2.AreEqual(first, second, "Items differ."),
                    (item) => item.Key + " = " + item.Value,
                    assert);

                setHeaderAction("d", "e");

                assert.AreEqual(2, getHeadersFunc().Count(), "Two headers expected.");
                assert.AreEqual("c", getHeaderFunc("a"), "Header not found or invalid header value.");
                assert.AreEqual("e", getHeaderFunc("d"), "Header not found or invalid header value.");
                expectedHeaders.Add(new KeyValuePair <string, string>("d", "e"));
                VerificationUtils.VerifyEnumerationsAreEqual(
                    expectedHeaders,
                    getHeadersFunc(),
                    (first, second, assert2) => assert2.AreEqual(first, second, "Items differ."),
                    (item) => item.Key + " = " + item.Value,
                    assert);

                setHeaderAction("d", null);
                setHeaderAction("a", null);

                assert.AreEqual(0, getHeadersFunc().Count(), "Empty header collection expected.");
                assert.IsNull(getHeaderFunc("a"), "Unexpectedly found header.");
            },
                expectedException,
                exceptionVerifier);
        }
 private static void VerifyFunctionCallQueryTokensAreEqual(FunctionCallToken expected, FunctionCallToken actual, AssertionHandler assert)
 {
     assert.AreEqual(expected.Name, actual.Name, "The Name of the function call token doesn't match the expected one.");
     VerifyQueryTokensAreEqual(expected.Arguments, actual.Arguments, assert);
 }
 /// <summary>
 /// Copy constructor.
 /// </summary>
 /// <param name="other">The <see cref="BufferingJsonReaderTestDescriptor"/> instance to clone.</param>
 public ReorderingJsonReaderTestCaseDescriptor(ReorderingJsonReaderTestCaseDescriptor other)
 {
     this.assert = other.assert;
     this.JsonText = other.JsonText;
     this.ExpectedJsonText = other.ExpectedJsonText;
 }
 private static void VerifyFunctionParameterTokensAreEqual(FunctionParameterToken expected, FunctionParameterToken actual, AssertionHandler assert)
 {
     assert.AreEqual(expected.ParameterName, actual.ParameterName, "The Name of the function call token doesn't match the expected one.");
     VerifyQueryTokensAreEqual(expected.ValueToken, actual.ValueToken, assert);
 }
 private static bool VerifyNullnessMatches(object expected, object actual, AssertionHandler assert, string description)
 {
     if (expected == null)
     {
         assert.IsNull(actual, string.Format("The actual {0} should have been null.", description));
         return false;
     }
     assert.IsNotNull(actual, string.Format("The actual {0} should have been not-null.", description));
     return true;
 }
 private static void VerifyOrderByQueryTokensAreEqual(OrderByToken expected, OrderByToken actual, AssertionHandler assert)
 {
     assert.AreEqual(expected.Direction, actual.Direction, "The Direction of the order by doesn't match the expected one.");
     VerifyQueryTokensAreEqual(expected.Expression, actual.Expression, assert);
 }