Пример #1
0
        public void SimpleEqualityConstraint()
        {
            Constraint constrainedEqualTo999 = new EqualConstraint(expected: 999);
            int        actual = 999;

            Assert.That(actual, constrainedEqualTo999);
        }
Пример #2
0
 protected override void SetUp()
 {
     Matcher     = new EqualConstraint(4);
     GoodValues  = new object[] { 4, 4.0f, 4.0d, 4.0000m };
     BadValues   = new object[] { 5, null, "Hello" };
     Description = "4";
 }
        public void ChangeEventIsFiredAppropriatelyWhenFocusIsLost()
        {
            driver.Url = javascriptPage;

            IWebElement input = driver.FindElement(By.Id("changeable"));

            input.SendKeys("test");
            driver.FindElement(By.Id("clickField")).Click(); // move focus
            EqualConstraint firstConstraint  = new EqualConstraint("focus change blur");
            EqualConstraint secondConstraint = new EqualConstraint("focus change blur");


            Assert.That(driver.FindElement(By.Id("result")).Text.Trim(), firstConstraint | secondConstraint);

            input.SendKeys(Keys.Backspace + "t");
            driver.FindElement(By.Id("clickField")).Click();  // move focus

            firstConstraint  = new EqualConstraint("focus change blur focus blur");
            secondConstraint = new EqualConstraint("focus blur change focus blur");
            EqualConstraint thirdConstraint  = new EqualConstraint("focus blur change focus blur change");
            EqualConstraint fourthConstraint = new EqualConstraint("focus change blur focus change blur"); //What Chrome does

            // I weep.
            Assert.That(driver.FindElement(By.Id("result")).Text.Trim(),
                        firstConstraint | secondConstraint | thirdConstraint | fourthConstraint);
        }
Пример #4
0
 protected override void SetUp()
 {
     Matcher = new EqualConstraint( 4 );
     GoodValues = new object[] { 4, 4.0f, 4.0d, 4.0000m };
     BadValues = new object[] { 5, null, "Hello" };
     Description = "4";
 }
Пример #5
0
 public SpecificationConstraint(T value, bool satisfied)
 {
     _values = new List <T> {
         value
     };
     Delegate = new EqualConstraint(satisfied);
 }
Пример #6
0
            /// <summary>
            ///
            /// </summary>
            /// <param name="expected_"></param>
            /// <returns></returns>
            public XmlDeserializerConstraint <T> To(T expected_)
            {
                var deserializedConstraint = new EqualConstraint(expected_);
                var deserializerConstraint = Factory.Create(Serializer, deserializedConstraint);

                return(deserializerConstraint);
            }
Пример #7
0
 public void SetUp()
 {
     Matcher = new EqualConstraint("Hello World!").IgnoreCase;
     GoodValues = new object[] { "hello world!", "Hello World!", "HELLO world!" };
     BadValues = new object[] { "goodbye", "Hello Friends!", string.Empty, null };
     Description = "\"Hello World!\", ignoring case";
 }
Пример #8
0
 public void SetUp()
 {
     Matcher     = new EqualConstraint("Hello World!").IgnoreCase;
     GoodValues  = new object[] { "hello world!", "Hello World!", "HELLO world!" };
     BadValues   = new object[] { "goodbye", "Hello Friends!", string.Empty, null };
     Description = "\"Hello World!\", ignoring case";
 }
        public void ReusingConstraints()
        {
            var isEqualTo4 = new EqualConstraint(4);

            Assert.That(2 + 2, isEqualTo4);
            Assert.That(1 + 3, isEqualTo4);
            Assert.That(10 - 6, isEqualTo4);
        }
Пример #10
0
            public override bool Equals(object actual)
            {
                if (actual == null)
                {
                    return(true);
                }

                Assert.AreEqual(_expected.GetType(), actual.GetType());

                PropertyInfo[] properties = _expected.GetType().GetProperties();
                foreach (PropertyInfo property in properties)
                {
                    if (_ignores.Contains(property.Name))
                    {
                        continue;
                    }

                    if (property.GetIndexParameters().Length > 0)
                    {
                        continue;
                    }

                    if (property.PropertyType.IsAssignableFrom(typeof(ICollection)))
                    {
                        continue;
                    }

                    if (!property.CanRead)
                    {
                        continue;
                    }

                    Debug.WriteLine("Comparing Property " + property.Name);

                    object expectedValue = property.GetValue(_expected, null);
                    object actualValue   = property.GetValue(actual, null);


                    if (expectedValue != null)
                    {
                        if (expectedValue.GetType().IsValueType)
                        {
                            Assert.AreEqual(expectedValue, actualValue, property.Name);
                        }
                        else
                        {
                            var childConstraint = new EqualConstraint(expectedValue);
                            childConstraint._ignores = _ignores;

                            childConstraint.Equals(actualValue);
                        }
                    }
                }

                return(true);
            }
        public void WriteMessageTo_DifferentJson_DelegateToEquals()
        {
            string expected = "{'prop'='value'}",
               actual = "{\"abcd\"=\"12345\"}";
            var subject = new JsonEqualConstraint(expected);
            var equals = new EqualConstraint(expected.Jsonify());

            Assert.That(getMessage(subject, actual),
                Is.EqualTo(getMessage(equals, actual)));
        }
Пример #12
0
            public static void AssertEquals(object expected, object actual, params string[] ignores)
            {
                var constraint = new EqualConstraint(expected);

                foreach (string property in ignores)
                {
                    constraint.IgnoreProperty(property);
                }
                constraint.AssertEquals(actual);
            }
        public void WriteMessageTo_DifferentJson_DelegateToEquals()
        {
            string expected = "{'prop'='value'}",
                   actual   = "{\"abcd\"=\"12345\"}";
            var subject     = new JsonEqualConstraint(expected);
            var equals      = new EqualConstraint(expected.Jsonify());

            Assert.That(getMessage(subject, actual),
                        Is.EqualTo(getMessage(equals, actual)));
        }
Пример #14
0
        public override ConstraintResult ApplyTo <TActual>(TActual actual)
        {
            var eq = new EqualConstraint(Expected);

            Description = Prefix + eq.Description;
            var success = eq.ApplyTo(actual).IsSuccess;

            if (AppliedOp == Op.Not)
            {
                success = !success;
            }
            return(new ErrConstraintResult(this, actual, success));
        }
Пример #15
0
        public override ConstraintResult ApplyTo <TActual>(TActual actual)
        {
            // null checks mimic how nunit equals work
            if (expected == null && actual == null)
            {
                return(new ConstraintResult(this, actual, true));
            }
            if (expected == null)
            {
                return(new MessageConstraintResult(this, actual, "Expected is null"));
            }
            if (actual == null)
            {
                return(new MessageConstraintResult(this, actual, "Actual is null"));
            }

            // actual should contain all of the properties which expected has
            // though actual may have extra properties which expected does not
            var expectedProperties = new List <PropertyInfo>(expected.GetType().GetProperties().Where(p => propertiesToIgnore.Contains(p.Name) == false));
            var actualProperties   = new List <PropertyInfo>(actual.GetType().GetProperties());

            var missingProperties = expectedProperties.Select(p => p.Name).Except(actualProperties.Select(p => p.Name)).ToList();

            if (missingProperties.Any())
            {
                return(new MessageConstraintResult(this, actual, $"Expected contains the following properties which actual is missing: {string.Join(", ", missingProperties)}"));
            }

            // loop though expected objects properties, and use nunit equal constraint to see if properties are equal
            var result = new MultiEqualsConstraintResult(this, actual);

            foreach (var expectedProperty in expectedProperties)
            {
                var expectedPropertyValue = expectedProperty.GetValue(expected, null);
                var actualPropertyValue   = actualProperties.Single(p => p.Name == expectedProperty.Name).GetValue(actual, null);

                var equalConstraint = new EqualConstraint(expectedPropertyValue);
                result.AddResult(expectedProperty.Name, equalConstraint.ApplyTo(actualPropertyValue));
            }

            return(result);
        }
Пример #16
0
        /// <summary>
        /// Test whether the constraint is satisfied by a given value
        /// </summary>
        /// <param name="actual">The value to be tested</param>
        /// <returns>True for success, false for failure</returns>
        protected override ConstraintResult ApplyConstraint <TActual>(TActual actual)
        {
            if (actual is string && ExpectedValue is string)
            {
                StringConstraint constraint = new SubstringConstraint(ExpectedValue as string);
                if (_ignoreCase)
                {
                    constraint = constraint.IgnoreCase;
                }
                _realConstraint = constraint;
            }
            else
            {
                var itemConstraint = new EqualConstraint <TExpected>(ExpectedValue);
                if (_ignoreCase)
                {
                    itemConstraint = itemConstraint.IgnoreCase;
                }
                _realConstraint = new SomeItemsConstraint(itemConstraint);
            }

            return(_realConstraint.ApplyTo(actual));
        }
        public void ChangeEventIsFiredAppropriatelyWhenFocusIsLost()
        {
            driver.Url = javascriptPage;

            IWebElement input = driver.FindElement(By.Id("changeable"));
            input.SendKeys("test");
            driver.FindElement(By.Id("clickField")).Click(); // move focus
            EqualConstraint firstConstraint = new EqualConstraint("focus change blur");
            EqualConstraint secondConstraint = new EqualConstraint("focus change blur");

            Assert.That(driver.FindElement(By.Id("result")).Text.Trim(), firstConstraint | secondConstraint);

            input.SendKeys(Keys.Backspace + "t");
            driver.FindElement(By.Id("clickField")).Click();  // move focus

            firstConstraint = new EqualConstraint("focus change blur focus blur");
            secondConstraint = new EqualConstraint("focus blur change focus blur");
            EqualConstraint thirdConstraint = new EqualConstraint("focus blur change focus blur change");
            EqualConstraint fourthConstraint = new EqualConstraint("focus change blur focus change blur"); //What Chrome does
            // I weep.
            Assert.That(driver.FindElement(By.Id("result")).Text.Trim(),
                       firstConstraint | secondConstraint | thirdConstraint | fourthConstraint);
        }
Пример #18
0
        /// <summary>
        /// Test whether the constraint is satisfied by a given value
        /// </summary>
        /// <param name="actual">The value to be tested</param>
        /// <returns>True for success, false for failure</returns>
        public override ConstraintResult ApplyTo <TActual>(TActual actual)
        {
            if (actual is string)
            {
                StringConstraint constraint = new SubstringConstraint((string)_expected);
                if (_ignoreCase)
                {
                    constraint = constraint.IgnoreCase;
                }
                _realConstraint = constraint;
            }
            else
            {
                var itemConstraint = new EqualConstraint(_expected);
                if (_ignoreCase)
                {
                    itemConstraint = itemConstraint.IgnoreCase;
                }
                _realConstraint = new SomeItemsConstraint(itemConstraint);
            }

            return(_realConstraint.ApplyTo(actual));
        }
Пример #19
0
 public static Constraint UsingItemComparer(this EqualConstraint constraint)
 => constraint.Using(ItemComparerInstance.Value);
Пример #20
0
		/// <summary>
		/// Verifies that two doubles are equal considering a delta. If the
		/// expected value is infinity then the delta value is ignored. If 
		/// they are not equals then an <see cref="AssertionException"/> is
		/// thrown.
		/// </summary>
		/// <param name="expected">The expected value</param>
		/// <param name="actual">The actual value</param>
		/// <param name="delta">The maximum acceptable difference between the
		/// the expected and the actual</param>
		/// <param name="message">The message that will be displayed on failure</param>
		/// <param name="args">Arguments to be used in formatting the message</param>
		static public void AreEqual(double expected, 
			double actual, double delta, string message, params object[] args) 
		{
			Constraint constraint = new EqualConstraint( expected );
			if ( double.IsNaN(expected) || double.IsInfinity(expected) )
				Assert.That(actual, Is.EqualTo( expected ), message, args);
			else
				Assert.That(actual, Is.EqualTo(expected).Within(delta), message, args);
        }
Пример #21
0
 public void SetUp()
 {
     theConstraint        = new EqualConstraint(4);
     expectedDescription  = "4";
     stringRepresentation = "<equal 4>";
 }
Пример #22
0
 /// <summary>
 /// Flags the constraint to use the supplied compact JSON string when performing equality.
 /// </summary>
 /// <param name="constraint">The constraint to modify.</param>
 /// <returns>The modified constraint.</returns>
 /// <example><code>Assert.That("{\"prop\"=\"value\"}", Is.EqualTo("{'prop'='value'}").AsJson())</code></example>
 public static EqualConstraint AsJson(this EqualConstraint constraint)
 {
     return(constraint.Using(JsonString.Comparer));
 }
 public static EqualConstraint UsingItemComparer(this EqualConstraint constraint) =>
 constraint.Using(ItemComparer.LazyComparer);
Пример #24
0
        public void PropertyEqualToValueWithTolerance()
        {
            Constraint c = new EqualConstraint(105m).Within(0.1m);
            TextMessageWriter w = new TextMessageWriter();
            c.WriteDescriptionTo(w);
            Assert.That(w.ToString(), Is.EqualTo("105m +/- 0.1m"));

            c = new PropertyConstraint("D", new EqualConstraint(105m).Within(0.1m));
            w = new TextMessageWriter();
            c.WriteDescriptionTo(w);
            Assert.That(w.ToString(), Is.EqualTo("property D equal to 105m +/- 0.1m"));
        }
 public ComplexEqualConstraint(EqualConstraint that)
     : base(that)
 {
 }
 public static EqualConstraint UsingItemEqualityComparer(this EqualConstraint constraint)
 => constraint.Using(new ItemEqualityComparer());
Пример #27
0
        protected void Test(Delegate d, object knownResult = null, bool knownResultNull = false)
        {
            var mi = d.Method;
            //var stackTrace = new StackTrace();
            //var testMethod = stackTrace.GetFrame(1).GetMethod().Name;
            //Console.WriteLine("Test++ {0}", testMethod);
            var method = CecilHelper.GetMethod(d);
            var js     = Js.CreateFrom(method, this.Verbose, true).Js;

            if (this.Verbose)
            {
                Console.WriteLine(js);
            }
            var testDefaultParamGen = mi.GetCustomAttribute <ParamAttribute>()
                                      ?? mi.DeclaringType.GetCustomAttribute <ParamAttribute>()
                                      ?? defaultParamGen;
            var withinAttr        = mi.GetCustomAttribute <WithinAttribute>();
            var withinUlpsAttr    = mi.GetCustomAttribute <WithinUlpsAttribute>();
            var withinPercentAttr = mi.GetCustomAttribute <WithinPercentAttribute>();
            var icAttr            = mi.GetCustomAttribute <IterationCountAttribute>();
            var minIterations     = mi.GetParameters().Max(x =>
                                                           (x.GetCustomAttribute <ParamAttribute>() ?? testDefaultParamGen).MinIterations);
            int iterationCount;

            if (icAttr != null)
            {
                iterationCount = icAttr.IterationCount;
            }
            else
            {
                iterationCount = method.Parameters.Any() ? defaultTestIterations : 1;
            }
            if (iterationCount < minIterations)
            {
                iterationCount = minIterations.Value;
            }
            var range = Enumerable.Range(0, iterationCount);
            var args  = range.Select(i => this.CreateArgs(mi, i, testDefaultParamGen)).ToArray();

            var runResults = range.Select(i => {
                object r    = null;
                Exception e = null;
                try {
                    r = d.DynamicInvoke(args[i]);
                } catch (TargetInvocationException ex) {
                    e = ex.InnerException;
                }
                if (knownResult != null || knownResultNull)
                {
                    Assert.That(r, Is.EqualTo(knownResult));
                }
                return(Tuple.Create(r, e));
            }).ToArray();

            var usingNamespace = NamespaceSetup.Chrome != null;
            var chrome         = usingNamespace ? NamespaceSetup.Chrome : new ChromeDriver();

            try {
                for (int i = 0; i < args.Length; i++)
                {
                    var arg = args[i];
                    if (!mi.IsStatic)
                    {
                        arg = arg.Prepend(null).ToArray();
                    }
                    var jsArgs = string.Join(", ", arg.Select(x => this.ConvertArgToJavascript(x)));
                    //Console.WriteLine("JS args: '{0}'", jsArgs);
                    var jsCall   = @"
var r;
try {
    r = main(" + jsArgs + @");
    console.log(r);
} catch (e) {
    return {exception:[e._.$$TypeNamespace, e._.$$TypeName, e.$$_message]};
}
if (typeof r === 'number') {
    if (isNaN(r)) {
        return 'NaN';
    }
    if (r === Number.POSITIVE_INFINITY) {
        return '+Infinity';
    }
    if (r === Number.NEGATIVE_INFINITY) {
        return '-Infinity';
    }
    return r.toString();
}
return r;
";
                    var jsResult = chrome.ExecuteScript(js + jsCall);
                    if (jsResult != null && jsResult is Dictionary <string, object> )
                    {
                        // Exception
                        Assert.That(runResults[i].Item1, Is.Null, "JS threw exception, but exception not expected");
                        var jsExInfo       = ((ICollection <object>)((Dictionary <string, object>)jsResult)["exception"]).Cast <string>().ToArray();
                        var jsExType       = jsExInfo[0] + "." + jsExInfo[1];
                        var expectedExType = runResults[i].Item2.GetType().FullName;
                        Assert.That(jsExType, Is.EqualTo(expectedExType));
                    }
                    else
                    {
                        var returnTypeCode = Type.GetTypeCode(d.Method.ReturnType);
                        if (jsResult != null && jsResult.GetType() != d.Method.ReturnType)
                        {
                            switch (returnTypeCode)
                            {
                            case TypeCode.Int64: {
                                var array = (IList <object>)jsResult;
                                var hi    = Convert.ToUInt64(array[0]);
                                var lo    = Convert.ToUInt64(array[1]);
                                jsResult = (long)(((ulong)hi) << 32 | (ulong)lo);
                            }
                            break;

                            case TypeCode.UInt64: {
                                var array = (IList <object>)jsResult;
                                var hi    = Convert.ToUInt64(array[0]);
                                var lo    = Convert.ToUInt64(array[1]);
                                jsResult = ((ulong)hi) << 32 | (ulong)lo;
                            }
                            break;

                            case TypeCode.Single:
                                switch (jsResult as string)
                                {
                                case "NaN": jsResult = Single.NaN; break;

                                case "+Infinity": jsResult = Single.PositiveInfinity; break;

                                case "-Infinity": jsResult = Single.NegativeInfinity; break;

                                default: jsResult = Single.Parse(jsResult as string); break;
                                }
                                break;

                            case TypeCode.Double:
                                switch (jsResult as string)
                                {
                                case "NaN": jsResult = Double.NaN; break;

                                case "+Infinity": jsResult = Double.PositiveInfinity; break;

                                case "-Infinity": jsResult = Double.NegativeInfinity; break;

                                default: jsResult = Double.Parse(jsResult as string); break;
                                }
                                break;

                            case TypeCode.Char:
                                jsResult = (char)int.Parse(jsResult as string);
                                break;

                            default:
                                jsResult = Convert.ChangeType(jsResult, d.Method.ReturnType);
                                break;
                            }
                        }
                        Assert.That(runResults[i].Item2, Is.Null, "Exception expected in JS, but not thrown");
                        EqualConstraint    equalTo  = Is.EqualTo(runResults[i].Item1);
                        IResolveConstraint expected = equalTo;
                        if (withinAttr != null)
                        {
                            expected = equalTo.Within(withinAttr.Delta);
                        }
                        else if (withinUlpsAttr != null)
                        {
                            expected = equalTo.Within(withinUlpsAttr.Ulps).Ulps;
                        }
                        else if (withinPercentAttr != null)
                        {
                            expected = equalTo.Within(withinPercentAttr.Percent).Percent;
                        }
                        else
                        {
                            switch (returnTypeCode)
                            {
                            case TypeCode.Single:
                                // Always allow a little inaccuracy with Singles
                                expected = equalTo.Within(0.0001).Percent;
                                break;

                            case TypeCode.Double:
                                expected = equalTo.Within(0.0001).Percent;
                                break;
                            }
                        }
                        Assert.That(jsResult, expected);
                    }
                }
            } finally {
                if (!usingNamespace)
                {
                    chrome.Quit();
                    chrome.Dispose();
                }
            }

            //Console.WriteLine("Test-- {0}", testMethod);
        }
Пример #28
0
            public static void AssertEquals(object expected, object actual)
            {
                var constraint = new EqualConstraint(expected);

                constraint.AssertEquals(actual);
            }
 private void HasLogMessageException(EqualConstraint s)
 {
     // NSubstitute 
     // log.Received().Log(LogLevel.Error, Arg.Is<Func<string>>(x => Verify(x, s)), exception);
     log.Verify(y => y.Log(LogLevel.Error, It.Is<Func<string>>(x => Verify(x, s)), It.IsAny<Exception>()));
 }
 private void HasLogMessage(EqualConstraint s)
 {
     // NSubstitute 
     //log.Received().Log(LogLevel.Error, Arg.Is<Func<string>>(x => Verify(x, s)));
     log.Verify(y=>y.Log(LogLevel.Error, It.Is<Func<string>>(x => Verify(x, s)), null));
 }
 public static EqualConstraint UsingCodeFileComparer(this EqualConstraint constraint) =>
 constraint.Using(Comparer);
 public StringRepresentationConstraint(string representation)
 {
     _representation = representation;
     _inner          = new EqualConstraint(representation);
 }
Пример #33
0
 public void ErrorWithUlpsAndPercentToleranceModes()
 {
     EqualConstraint shouldFail = new EqualConstraint(100.0f).Within(10.0f).Ulps.Percent;
 }
Пример #34
0
 public static void That(DateTime?result, EqualConstraint constraint) => Assert.That(result, constraint.Within(1).Seconds);
Пример #35
0
 public void ErrorWithPercentAndUlpsToleranceModes()
 {
     EqualConstraint shouldFail = new EqualConstraint(100.0f).Within(10.0f).Percent.Ulps;
 }
Пример #36
0
 public void NamedAndUnnamedColorsCompareAsEqual()
 {
     EqualConstraint.SetConstraintForType(typeof(Color), typeof(SameColorAs));
     Assert.That(System.Drawing.Color.Red,
                 Is.EqualTo(System.Drawing.Color.FromArgb(255, 0, 0)));
 }
Пример #37
0
 public static EqualConstraint UsingNoteComparer(this EqualConstraint equalConstraint)
 => equalConstraint.Using(NoteEqualityComparer.Instance);
        public void ConstructableConstraints()
        {
            Constraint isEqualTo4 = new EqualConstraint(4);

            Assert.That(2 + 2, isEqualTo4);
        }