Beispiel #1
0
        private static void CtorSetTests()
        {
            QUnit.Module("CtorSetTests");

            QUnit.Test("Simple string property CtorSet initialisation", assert =>
            {
                var x = new SomethingWithStringId("abc");
                assert.Equal(x.Id, "abc");
            });

            QUnit.Test("Simple string property CtorSet initialisation on 'Plain' autoProperty", assert =>
            {
                var x = new SomethingWithPlainAutoPropertyStringId("abc");
                assert.Equal(x.Id, "abc");
            });

            QUnit.Test("CtorSet may not be called outside of the constructor (only works if CtorSet is set consistently within the constructor)", assert =>
            {
                var x = new SomethingWithStringId("abc");
                assert.Throws(
                    () => x.CtorSet(_ => _.Id, "abc"),
                    "CtorSet should throw if called outside of the constructor (since it should only be called once per property and the constructor should call it for all properties)"
                    );
            });
        }
Beispiel #2
0
        public static void RunTests()
        {
            QUnit.Module(nameof(InteractiveTranslationSessionTests));

            QUnit.Test(nameof(CurrentSuggestion_EmptyPrefix), CurrentSuggestion_EmptyPrefix);
            QUnit.Test(nameof(UpdatePrefix_AddOneCompleteWord), UpdatePrefix_AddOneCompleteWord);
            QUnit.Test(nameof(UpdatePrefix_AddOnePartialWord), UpdatePrefix_AddOnePartialWord);
            QUnit.Test(nameof(UpdatePrefix_RemoveOneWord), UpdatePrefix_RemoveOneWord);
            QUnit.Test(nameof(UpdatePrefix_RemoveEntirePrefix), UpdatePrefix_RemoveEntirePrefix);
            QUnit.Test(nameof(Approve_Success), Approve_Success);
            QUnit.Test(nameof(Approve_Error), Approve_Error);
            QUnit.Test(nameof(Approve_SegmentInvalid), Approve_SegmentInvalid);
            QUnit.Test(nameof(GetSuggestionText_LastWordComplete), GetSuggestionText_LastWordComplete);
            QUnit.Test(nameof(GetSuggestionText_LastWordCompleteSuggestionIndexZero),
                       GetSuggestionText_LastWordCompleteSuggestionIndexZero);
            QUnit.Test(nameof(GetSuggestionText_LastWordCompleteSuggestionIndexOne),
                       GetSuggestionText_LastWordCompleteSuggestionIndexOne);
            QUnit.Test(nameof(GetSuggestionText_LastWordIncomplete), GetSuggestionText_LastWordIncomplete);
            QUnit.Test(nameof(GetSuggestionText_LastWordIncompleteSuggestionIndexZero),
                       GetSuggestionText_LastWordIncompleteSuggestionIndexZero);
            QUnit.Test(nameof(GetSuggestionText_LastWordIncompleteSuggestionIndexOne),
                       GetSuggestionText_LastWordIncompleteSuggestionIndexOne);
            QUnit.Test(nameof(IsSourceSegmentValid_SegmentValid), IsSourceSegmentValid_SegmentValid);
            QUnit.Test(nameof(IsSourceSegmentValid_SegmentInvalid), IsSourceSegmentValid_SegmentInvalid);
        }
Beispiel #3
0
        private static void CtorSetTests()
        {
            QUnit.Module("CtorSetTests");

            QUnit.Test("Simple string property CtorSet initialisation", assert =>
            {
                var x = new SomethingWithStringId("abc");
                assert.Equal(x.Id, "abc");
            });

            QUnit.Test("Simple string property CtorSet initialisation on 'Plain' autoProperty", assert =>
            {
                var x = new SomethingWithPlainAutoPropertyStringId("abc");
                assert.Equal(x.Id, "abc");
            });

            QUnit.Test("CtorSet may not be called outside of the constructor (only works if CtorSet is set consistently within the constructor)", assert =>
            {
#pragma warning disable CtorSet // CtorSet should only be used in specific circumstances - suppress this, we're testing the runtime error handling
                var x = new SomethingWithStringId("abc");
                assert.Throws(
                    () => x.CtorSet(_ => _.Id, "abc"),
                    "CtorSet should throw if called outside of the constructor (since it should only be called once per property and the constructor should call it for all properties)"
                    );
            });
#pragma warning restore CtorSet // CtorSet should only be used in specific circumstances
        }
 public static void Go()
 {
     QUnit.Module("Navigator");
     QUnit.Test("Single level: Static root plus dynamic 'item' id routes [static navigation methods]", TestHotelRouterWithStaticNavigationCalls);
     QUnit.Test("Single level: Static root plus dynamic 'item' id routes [via historyHandler NavigateTo changes]", TestHotelRouterWithDynamicNavigationCalls);
     QUnit.Test("Nested Navigators: Root plus static-root-plus-dynamic-'item'-id-routes for 'hotel' and 'restaurant' [static navigation methods]", TestNestedRouterWithStaticNavigationCalls);
     QUnit.Test("Nested Navigators: Root plus static-root-plus-dynamic-'item'-id-routes for 'hotel' and 'restaurant' [via historyHandler NavigateTo changes]", TestNestedRouterWithDynamiccNavigationCalls);
 }
Beispiel #5
0
        public static void Run()
        {
            QUnit.Module("Property");

            var time = new DateTime(2016, 12, 10, 20, 30, 0, 100);

            var instance = new PropDataExample
            {
                Time    = time,
                Long    = 10,
                Decimal = 10m,
                Double  = 2.5,
                Int32   = 20
            };

            var propData = Converters.ExtactExistingProps(instance);

            var timeProp    = propData.FirstOrDefault(prop => prop.Name == "Time");
            var longProp    = propData.FirstOrDefault(prop => prop.Name == "Long");
            var decimalProp = propData.FirstOrDefault(prop => prop.Name == "Decimal");
            var doubleProp  = propData.FirstOrDefault(prop => prop.Name == "Double");
            var intProp     = propData.FirstOrDefault(prop => prop.Name == "Int32");


            QUnit.Test("Number of properties extracted is correct", assert =>
            {
                assert.Equal(propData.Length, 5);
            });

            QUnit.Test("Properties extracted are not null", assert =>
            {
                assert.Equal(timeProp == null, false);
                assert.Equal(longProp == null, false);
                assert.Equal(decimalProp == null, false);
                assert.Equal(doubleProp == null, false);
                assert.Equal(intProp == null, false);
            });

            QUnit.Test("Property types are extracted correctly", assert =>
            {
                assert.Equal(timeProp.Type, typeof(DateTime));
                assert.Equal(longProp.Type, typeof(long));
                assert.Equal(decimalProp.Type, typeof(decimal));
                assert.Equal(doubleProp.Type, typeof(double));
                assert.Equal(intProp.Type, typeof(int));
            });


            QUnit.Test("Property values are extracted correctly", assert =>
            {
                assert.Equal(timeProp.Value, time);
                assert.Equal((long)longProp.Value == (long)10, true);
                assert.Equal((decimal)decimalProp.Value == 10m, true);
                assert.Equal(doubleProp.Value, 2.5);
                assert.Equal(intProp.Value, 20);
            });
        }
Beispiel #6
0
        public static void Run()
        {
            ModuleInfo module = new ModuleInfo();

            module.BeforeEach = SetUp;
            module.AfterEach  = Teardown;
            QUnit.Module("Unit Tests", module);
            QUnit.Test("Test1", Test1);
        }
Beispiel #7
0
        public static void Run()
        {
            ModuleInfo module = new ModuleInfo();

            module.BeforeEach = SetUp;
            module.AfterEach  = Teardown;
            QUnit.Module("Contact View Model Tests", module);
            QUnit.Test("Test Create Contact", TestCreateContact);
        }
Beispiel #8
0
        public static void Run()
        {
            QUnit.Module("Inheritance Tests");

            QUnit.Test("Inherited class from abstract class is converted correctly", assert =>
            {
                var sample = new Derived
                {
                    Id       = 5,
                    Long     = 10L,
                    Decimal  = 10m,
                    DateTime = DateTime.Now
                };

                var serialized = Json.Serialize(sample);

                var deserialized = Json.Deserialize <Derived>(serialized);

                assert.Equal(deserialized.Id, sample.Id);
                assert.Equal(deserialized.DateTime == sample.DateTime, true);
                assert.Equal(deserialized.Decimal == sample.Decimal, true);
                assert.Equal(deserialized.Long == sample.Long, true);
            });

            QUnit.Test("Inherited class from generic abstract class is converted correctly", assert =>
            {
                var sample = new DerivedFromGeneric
                {
                    Value = 20
                };

                var serialized = Json.Serialize(sample);

                var deserialized = Json.Deserialize <DerivedFromGeneric>(serialized);

                assert.Equal(deserialized.Value, 20);
            });

            QUnit.Test("Inherited generic class from generic abstract class is converted correctly", assert =>
            {
                var sample = new GenericDerived <int, string>
                {
                    Value      = "MyValue",
                    OtherValue = 10
                };

                var serialized = Json.Serialize(sample);

                var deserialized = Json.Deserialize <GenericDerived <int, string> >(serialized);

                assert.Equal(deserialized.Value, sample.Value);

                assert.Equal(deserialized.OtherValue, sample.OtherValue);
            });
        }
        public static void Run()
        {
            ModuleInfo module = new ModuleInfo();

            module.BeforeEach = SetUp;
            module.AfterEach  = Teardown;
            QUnit.Module("Connection View Model Tests", module);
            QUnit.Test("Test Create Connection", TestCreateConnection);
            QUnit.Test("Test Create Connection Validation", TestCreateConnectionValidation);
            QUnit.Test("Check Connections Collection", CheckConnectionsCollection);
        }
        public static void RunTests()
        {
            QUnit.Module(nameof(TranslationEngineTests));

            QUnit.Test(nameof(TranslateInteractively_Success), TranslateInteractively_Success);
            QUnit.Test(nameof(TranslateInteractively_Error), TranslateInteractively_Error);
            QUnit.Test(nameof(TranslateInteractively_NoRuleResult), TranslateInteractively_NoRuleResult);
            QUnit.Test(nameof(Train_NoErrors), Train_NoErrors);
            QUnit.Test(nameof(Train_ErrorCreatingBuild), Train_ErrorCreatingBuild);
            QUnit.Test(nameof(ListenForTrainingStatus_NoErrors), ListenForTrainingStatus_NoErrors);
            QUnit.Test(nameof(ListenForTrainingStatus_Close), ListenForTrainingStatus_Close);
        }
        public static void RunTests()
        {
            QUnit.Module(nameof(LatinWordTokenizerTests));

            QUnit.Test(nameof(Tokenize_Empty_ReturnsEmpty), Tokenize_Empty_ReturnsEmpty);
            QUnit.Test(nameof(Tokenize_Whitespace_ReturnsEmpty), Tokenize_Whitespace_ReturnsEmpty);
            QUnit.Test(nameof(Tokenize_PunctuationAtEndOfWord_ReturnsTokens), Tokenize_PunctuationAtEndOfWord_ReturnsTokens);
            QUnit.Test(nameof(Tokenize_PunctuationAtStartOfWord_ReturnsTokens), Tokenize_PunctuationAtStartOfWord_ReturnsTokens);
            QUnit.Test(nameof(Tokenize_PunctuationInsideWord_ReturnsTokens), Tokenize_PunctuationInsideWord_ReturnsTokens);
            QUnit.Test(nameof(Tokenize_Abbreviation_ReturnsTokens), Tokenize_Abbreviation_ReturnsTokens);
            QUnit.Test(nameof(Tokenize_NonAsciiCharacter_DoesNotThrow), Tokenize_NonAsciiCharacter_DoesNotThrow);
        }
Beispiel #12
0
        private static void DictionaryTests()
        {
            QUnit.Module("Dictionary lookups");

            QUnit.Test("Two instances of NonBlankTrimmedString with the same value are found to be equal when used as a Dictionary key", assert =>
            {
                // This will test both the bridge.getHashCode AND the bridge.equals hacks
                var d = new Dictionary <NonBlankTrimmedString, int>
                {
                    { new NonBlankTrimmedString("xyz"), 123 }
                };
                assert.Ok(d.ContainsKey(new NonBlankTrimmedString("xyz")));
            });
        }
Beispiel #13
0
        private static void ToStringTests()
        {
            QUnit.Module("ToString()");

            QUnit.Test("NonBlankTrimmedString ToString() call works as expected", assert => assert.Equal(new NonBlankTrimmedString("xyz").ToString(), "xyz"));
            QUnit.Test("NonBlankTrimmedString in string interpolation works as expected", assert => assert.Equal($"{new NonBlankTrimmedString("xyz")}", "xyz"));
            QUnit.Test("NonBlankTrimmedString in string concatenation works as expected", assert => assert.Equal("" + new NonBlankTrimmedString("xyz"), "xyz"));
            QUnit.Test("[ObjectLiteral]-as-generic-type-param's ToString() call works as expected", assert =>
            {
                // This is part of the second reproduce case in https://forums.bridge.net/forum/community/help/6001
                var x = new MultiLanguageTextBoxModel(new LangKey(1));
                assert.Equal(x.TestValue, "1");
            });
        }
Beispiel #14
0
        public static void Run()
        {
            QUnit.Module("TimeSpan Tests");

            QUnit.Test("TimeSpan is converted correctly", assert =>
            {
                var timeSpan = TimeSpan.FromHours(5);

                var serialized = Json.Serialize(timeSpan);

                var deserialized = Json.Deserialize(serialized, typeof(TimeSpan)).As <TimeSpan>();

                assert.Equal(true, timeSpan.Ticks == deserialized.Ticks);
            });
        }
Beispiel #15
0
        public static void Run()
        {
            QUnit.Module("String tests");

            var sample = "my string";

            QUnit.Test("Strings is serialized and deserialized correctly", assert =>
            {
                var serialized = Json.Serialize(sample);

                var deserialized = Json.Deserialize(serialized, typeof(string)).As <string>();

                assert.Equal(deserialized, sample);
            });
        }
Beispiel #16
0
        public static void RunTests()
        {
            QUnit.Module(nameof(LineSegmentTokenizerTests));

            QUnit.Test(nameof(Tokenize_Empty_ReturnsEmpty), Tokenize_Empty_ReturnsEmpty);
            QUnit.Test(nameof(Tokenize_SingleLine_ReturnsTokens), Tokenize_SingleLine_ReturnsTokens);
            QUnit.Test(nameof(Tokenize_MultipleLines_ReturnsTokens), Tokenize_MultipleLines_ReturnsTokens);
            QUnit.Test(nameof(Tokenize_EndsWithNewLine_ReturnsTokens), Tokenize_EndsWithNewLine_ReturnsTokens);
            QUnit.Test(nameof(Tokenize_EndsWithNewLineAndSpace_ReturnsTokens),
                       Tokenize_EndsWithNewLineAndSpace_ReturnsTokens);
            QUnit.Test(nameof(Tokenize_EndsWithTextAndSpace_ReturnsTokens),
                       Tokenize_EndsWithTextAndSpace_ReturnsTokens);
            QUnit.Test(nameof(Tokenize_EmptyLine_ReturnsTokens), Tokenize_EmptyLine_ReturnsTokens);
            QUnit.Test(nameof(Tokenize_LineEndsWithSpace_ReturnsTokens), Tokenize_LineEndsWithSpace_ReturnsTokens);
        }
Beispiel #17
0
        public static void Run()
        {
            QUnit.Module("Service Registration Tests");

            //QUnit.Test("Cable.Resolve throws exception if interface not reflectable", assert =>
            //{
            //    try
            //    {
            //        var service = Client.Resolve<INonReflectable>();
            //    }
            //    catch (ArgumentException ex)
            //    {
            //        assert.Equal(ex.Message, "The interface does not have any methods, if there are any methods then annotate the interface with the [Reflectable] attribute");
            //    }
            //});

            //QUnit.Test("Cable.Resolve throws an exception if type is not an interface", assert =>
            //{
            //    try
            //    {
            //        var service = Client.Resolve<int>();
            //    }
            //    catch (ArgumentException ex)
            //    {
            //        var msg = ex.Message;
            //        assert.Equal(msg, "Type Int32 must be an interface");
            //    }
            //});

            //QUnit.Test("Cable.Resolve throws exception if reflectable interface does not have methods", assert =>
            //{
            //    try
            //    {
            //        var service = Client.Resolve<IReflectable>();
            //    }
            //    catch (ArgumentException ex)
            //    {
            //        var msg = ex.Message;
            //        assert.Equal(msg, "The interface does not have any methods, if there are any methods then annotate the interface with the [Reflectable] attribute");
            //    }
            //});

            QUnit.Test("Cable.Resolve doesn't throw exception on reflectable interface where all methods have return type of Task", assert =>
            {
                var service = BridgeClient.Resolve <IService>();
                assert.Equal(true, Script.IsDefined(service));
            });
        }
        public static void RunTests()
        {
            QUnit.Module(nameof(LatinSentenceTokenizerTests));

            QUnit.Test(nameof(Tokenize_Empty_ReturnsEmpty), Tokenize_Empty_ReturnsEmpty);
            QUnit.Test(nameof(Tokenize_SingleLine_ReturnsTokens), Tokenize_SingleLine_ReturnsTokens);
            QUnit.Test(nameof(Tokenize_MultipleLines_ReturnsTokens), Tokenize_MultipleLines_ReturnsTokens);
            QUnit.Test(nameof(Tokenize_TwoSentences_ReturnsTokens), Tokenize_TwoSentences_ReturnsTokens);
            QUnit.Test(nameof(Tokenize_Quotes_ReturnsTokens), Tokenize_Quotes_ReturnsTokens);
            QUnit.Test(nameof(Tokenize_QuotationInSentence_ReturnsTokens), Tokenize_QuotationInSentence_ReturnsTokens);
            QUnit.Test(nameof(Tokenize_Parens_ReturnsTokens), Tokenize_Parens_ReturnsTokens);
            QUnit.Test(nameof(Tokenize_Abbreviation_ReturnsTokens), Tokenize_Abbreviation_ReturnsTokens);
            QUnit.Test(nameof(Tokenize_IncompleteSentence_ReturnsTokens), Tokenize_IncompleteSentence_ReturnsTokens);
            QUnit.Test(nameof(Tokenize_CompleteSentenceWithSpaceAtEnd_ReturnsTokens),
                       Tokenize_CompleteSentenceWithSpaceAtEnd_ReturnsTokens);
        }
Beispiel #19
0
        private static void OptionalTests()
        {
            QUnit.Module("OptionalTests");

            QUnit.Test("Optional.Map from one string to another", assert =>
            {
                var x = Optional.For("abc");
                x     = x.Map(_ => _ + _);
                assert.Equal(x.IsDefined, true);
                assert.Equal(x.Value, "abcabc");
            });

            // I don't expect this to be a common thing to do but it makes more sense to allow a null result from a mapper to result in a Missing
            // response than for it to throw its toys out the pram
            QUnit.Test("Optional.Map from one string to null (should return Missing)", assert =>
            {
                var x = Optional.For("abc");
                x     = x.Map <string>(_ => null);
                assert.Equal(x.IsDefined, false);
            });

            QUnit.Test("Optional.Map from one string to itself (should return same instance back)", assert =>
            {
                var x        = Optional.For("abc");
                var updatedX = x.Map(_ => _);
                assert.StrictEqual(updatedX, x);
            });

            QUnit.Test("Optional Equality works with type that has with custom Equality override", assert =>
            {
                var x0 = Optional.For(new StandardObjectWithCustomEquality("abc"));
                var x1 = Optional.For(new StandardObjectWithCustomEquality("abc"));
                assert.Ok(x0.Equals(x1));
            });

            QUnit.Test("Optional Equality works with type that is [ObjectLiteral] with custom Equality override", assert =>
            {
                // Use NonBlankTrimmedString from ProductiveRage.Immutable.Extensions because that is an [ObjectLiteral] with a custom Equals method and referencing
                // that assembly pulls through the [ObjectLiteral] hacks that are required until the Bridge Team (hopefully) improve the support for them
                var x0 = Optional.For(new NonBlankTrimmedString("abc"));
                var x1 = Optional.For(new NonBlankTrimmedString("abc"));
                assert.Ok(x0.Equals(x1));
            });
        }
Beispiel #20
0
        public static void Run()
        {
            QUnit.Module("List Tests");


            QUnit.Test("List is encoded correctly", assert =>
            {
                var list = new List <int>();
                list.Add(1);
                list.Add(2);
                list.Add(3);

                var encoded = Converters.EncodeObject(list);

                assert.Equal(encoded["Type"], "List");
                assert.Equal(encoded["Value"]["length"], list.Count);
            });


            QUnit.Test("Serilization and deserialization of List<int> works", assert =>
            {
                var sample = new List <int>();
                sample.Add(10);
                sample.Add(20);

                var serialized   = Json.Serialize(sample);
                var deserialized = Json.Deserialize <List <int> >(serialized);

                assert.Equal(deserialized == null, false);
                assert.Equal(sample.Count, deserialized.Count);

                for (int i = 0; i < sample.Count; i++)
                {
                    assert.Equal(sample[i], deserialized[i]);
                }


                deserialized.Add(30);
                assert.Equal(deserialized.Sum(), 60);
            });
        }
        private static void ClassKeyMapTests()
        {
            QUnit.Module("Class-Key Map Tests");

            QUnit.Test("Get returns {Missing} for key not found", assert =>
            {
                var map = Map <MyCompositeId, string> .Empty;
                assert.Equal(map.GetIfPresent(new MyCompositeId(123, "test")), Optional <string> .Missing);
            });

            QUnit.Test("Get returns value for key just added", assert =>
            {
                var map = Map <MyCompositeId, string> .Empty
                          .AddOrUpdate(new MyCompositeId(123, "test"), "abc");
                assert.Equal(map.GetIfPresent(new MyCompositeId(123, "test")), "abc");
            });

            QUnit.Test("Get returns {Missing} for key added and then removed", assert =>
            {
                var map = Map <MyCompositeId, string> .Empty
                          .AddOrUpdate(new MyCompositeId(123, "test"), "abc")
                          .RemoveIfPresent(new MyCompositeId(123, "test"));
                assert.Equal(map.GetIfPresent(new MyCompositeId(123, "test")), Optional <string> .Missing);
            });

            QUnit.Test("Nothing happens if key removed that does not exist", assert =>
            {
                var map = Map <MyCompositeId, string> .Empty
                          .RemoveIfPresent(new MyCompositeId(123, "test"));
                assert.Ok(true);
            });

            QUnit.Test("Setting key that already exists overwrites existing data", assert =>
            {
                var map = Map <MyCompositeId, string> .Empty
                          .AddOrUpdate(new MyCompositeId(123, "test"), "abc")
                          .AddOrUpdate(new MyCompositeId(123, "test"), "xyz");
                assert.Equal(map.GetIfPresent(new MyCompositeId(123, "test")), "xyz");
                assert.Equal(map.Count, 1);
            });
        }
        private static void IntKeyMapSerialisationTests()
        {
            QUnit.Module("Int-Key Map Serialisation Tests");

            QUnit.Test("Single item serialised", assert =>
            {
                var map = Map <int, string> .Empty.AddOrUpdate(123, "abc");
                assert.Equal(
                    JsonConvert.SerializeObject(map),
                    "[{\"Key\":123,\"Value\":\"abc\"}]"
                    );
            });

            QUnit.Test("Single item deserialised", assert =>
            {
                var json = "[{\"Key\":123,\"Value\":\"abc\"}]";
                var map  = JsonConvert.DeserializeObject <Map <int, string> >(json);
                assert.Equal(map.Count, 1);
                assert.Equal(map.GetIfPresent(123), "abc");
            });
        }
Beispiel #23
0
        public static void Go()
        {
            QUnit.Module("Static Matches");

            QUnit.Test("Match '/'", assert =>
            {
                var routeInfo = RouteBuilder.Empty;
                var url       = UrlDetailsCreator.New();
                assert.RouteMatched(routeInfo, url);
            });

            QUnit.Test("Match '/home'", assert =>
            {
                var routeInfo = RouteBuilder.Empty.Fixed("home");
                var url       = UrlDetailsCreator.New("home");
                assert.RouteMatched(routeInfo, url);
            });

            QUnit.Test("Match '/home/info'", assert =>
            {
                var routeInfo = RouteBuilder.Empty.Fixed("home", "info");
                var url       = UrlDetailsCreator.New("home", "info");
                assert.RouteMatched(routeInfo, url);
            });

            QUnit.Test("NotFound '/home' if only '/other' route specified", assert =>
            {
                var routeInfo = RouteBuilder.Empty.Fixed("other");
                var url       = UrlDetailsCreator.New("home");
                assert.RouteNotMatched(routeInfo, url);
            });

            QUnit.Test("NotFound '/home' if only '/home/info' route specified", assert =>
            {
                var routeInfo = RouteBuilder.Empty.Fixed("home", "info");
                var url       = UrlDetailsCreator.New("home");
                assert.RouteNotMatched(routeInfo, url);
            });
        }
Beispiel #24
0
        public static void RunTests()
        {
            QUnit.Module("PersonService");

            QUnit.Test("Method GetPerson()", (assert) =>
            {
                var service = Test.GetService();
                var person  = service.GetPerson(55);

                assert.Expect(3);

                assert.Ok(person != null, "Person created");
                assert.DeepEqual(person.Id, 55, "person.Id = 55");
                assert.DeepEqual(person.Name, "Frank", "person.Name = 'Frank'");
            });

            QUnit.Module("PersonView");
            QUnit.Test("Method CreateLabelElement", Test.TestCreateLabel);

            QUnit.Module("PersonApplication");
            QUnit.Test("RenderPerson", Test.TestCreatePersonUIElements);
        }
Beispiel #25
0
 public static void Run()
 {
     QUnit.Module("DateTime Tests");
     DateTimeIsEncodedCorrectly();
 }
Beispiel #26
0
        public static void Run()
        {
            QUnit.Module("Array Tests");
            ArrayIsEncodedCorrectly();

            QUnit.Test("Serialization and deserialization of int array works", assert =>
            {
                var ints         = new int[] { 1, 2, 3 };
                var serialized   = Json.Serialize(ints);
                var deserialized = Json.Deserialize <int[]>(serialized);
                assert.DeepEqual(deserialized, ints);
            });


            QUnit.Test("Serialization and deserialization of string array works", assert =>
            {
                var strings      = new string[] { "one", "two" };
                var serialized   = Json.Serialize(strings);
                var deserialized = Json.Deserialize <string[]>(serialized);
                assert.DeepEqual(deserialized, strings);
            });

            QUnit.Test("Serialization and deserialization of long array works", assert =>
            {
                var longs        = new long[] { 10L, 20L, 30L };
                var serialized   = Json.Serialize(longs);
                var deserialized = Json.Deserialize <long[]>(serialized);

                assert.Equal(longs[0] == deserialized[0], true);
                assert.Equal(longs[1] == deserialized[1], true);
                assert.Equal(longs[2] == deserialized[2], true);
            });

            QUnit.Test("Serialization and deserialization of double[] works", assert =>
            {
                var doubles      = new double[] { 2.5, 2.56, 2.567 };
                var serialized   = Json.Serialize(doubles);
                var deserialized = Json.Deserialize <double[]>(serialized);

                assert.Equal(doubles[0] == deserialized[0], true);
                assert.Equal(doubles[1] == deserialized[1], true);
                assert.Equal(doubles[2] == deserialized[2], true);
            });

            QUnit.Test("Serialization and deserialization of decimal[] works", assert =>
            {
                var decimals     = new decimal[] { 2.5m, 2.56m, 2.567m };
                var serialized   = Json.Serialize(decimals);
                var deserialized = Json.Deserialize <decimal[]>(serialized);

                assert.Equal(decimals[0] == deserialized[0], true);
                assert.Equal(decimals[1] == deserialized[1], true);
                assert.Equal(decimals[2] == deserialized[2], true);
            });

            QUnit.Test("Serialization and deserialization of DateTime array works", assert =>
            {
                var dates        = new DateTime[] { DateTime.Now, new DateTime(2016, 12, 10, 20, 30, 0, 15) };
                var serialized   = Json.Serialize(dates);
                var deserialized = Json.Deserialize <DateTime[]>(serialized);
                assert.DeepEqual(deserialized, dates);
            });
        }
Beispiel #27
0
        public static void Run()
        {
            QUnit.Module("Nested object tests");

            var sample = new WrappedInt
            {
                Id       = 5,
                Name     = "Zaid",
                HasValue = true,
                Large    = 238472746327434243L
            };

            QUnit.Test("Nested object is encoded correctly", assert =>
            {
                var encoded = Converters.EncodeObject(sample);
                assert.Equal(encoded["Type"], "Cable.Bridge.Tests.NestedObjectTests+WrappedInt");
                assert.Equal(encoded["Value"]["Id"] == null, false);
                assert.Equal(encoded["Value"]["Id"]["Type"], "Int32");
                assert.Equal(encoded["Value"]["Id"]["Value"], "5");
                assert.Equal(encoded["Value"]["Name"] == null, false);
                assert.Equal(encoded["Value"]["Name"]["Type"], "String");
                assert.Equal(encoded["Value"]["Name"]["Value"], "Zaid");
                assert.Equal(encoded["Value"]["HasValue"] == null, false);
                assert.Equal(encoded["Value"]["HasValue"]["Type"], "Boolean");
                assert.Equal(encoded["Value"]["HasValue"]["Value"], true);
                assert.Equal(encoded["Value"]["Large"] == null, false);
                assert.Equal(encoded["Value"]["Large"]["Type"], "Int64");
                assert.Equal(encoded["Value"]["Large"]["Value"], "238472746327434243");
            });

            QUnit.Test("Serialization and deserialization of nested object works", assert =>
            {
                var serialized = Json.Serialize(sample);

                var deserialized = Json.Deserialize(serialized, typeof(WrappedInt)).As <WrappedInt>();

                assert.Equal(sample.Id, deserialized.Id);
                assert.Equal(sample.Name, deserialized.Name);
                assert.Equal(sample.HasValue, deserialized.HasValue);
                assert.Equal(sample.Large == deserialized.Large, true);
            });

            var generic = new WeirdGenericClass <WeirdGenericClass <int> >
            {
                Inner = new WeirdGenericClass <int>
                {
                    Inner  = 20,
                    Nested = new Nested <int>
                    {
                        InnerInner = 5
                    }
                },
                Nested = new Nested <WeirdGenericClass <int> >
                {
                    InnerInner = new WeirdGenericClass <int>
                    {
                        Inner  = 30,
                        Nested = new Nested <int>
                        {
                            InnerInner = 40
                        }
                    }
                }
            };



            QUnit.Test("Weird generic class is converted correctly", assert =>
            {
                var serialized = Json.Serialize(generic);

                var deserialized = Json.Deserialize <WeirdGenericClass <WeirdGenericClass <int> > >(serialized);


                assert.Equal(generic.Inner.Inner, deserialized.Inner.Inner);
                assert.Equal(generic.Inner.Nested.InnerInner, deserialized.Inner.Nested.InnerInner);
                assert.Equal(generic.Nested.InnerInner.Inner, deserialized.Nested.InnerInner.Inner);
                assert.Equal(generic.Nested.InnerInner.Nested.InnerInner, deserialized.Nested.InnerInner.Nested.InnerInner);
            });
        }
Beispiel #28
0
        private static void EqualsTests()
        {
            QUnit.Module("Equals(..)");

            QUnit.Test("An instance of NonBlankTrimmedString is found to be equal to itself", assert =>
            {
                var x = new NonBlankTrimmedString("xyz");
                AssertEqualsViaNonBlankTrimmedStringEqualsCall(assert, x, x, shouldBeEqual: true);
            });

            QUnit.Test("Two instances of NonBlankTrimmedString with the same value are found to be equal when compared as NonBlankTrimmedString", assert =>
            {
                var x = new NonBlankTrimmedString("xyz");
                var y = new NonBlankTrimmedString("xyz");
                AssertEqualsViaNonBlankTrimmedStringEqualsCall(assert, x, y, shouldBeEqual: true);
            });
            QUnit.Test("Two instances of NonBlankTrimmedString with the same value are found to be equal when compared as generic type param of NonBlankTrimmedString", assert =>
            {
                var x = new NonBlankTrimmedString("xyz");
                var y = new NonBlankTrimmedString("xyz");
                AssertEqualsViaSharedGenericTypeEqualsCall(assert, x, y, shouldBeEqual: true);
            });
            QUnit.Test("Two instances of NonBlankTrimmedString with the same value are found to be equal when compared as Object", assert =>
            {
                var x = new NonBlankTrimmedString("xyz");
                var y = new NonBlankTrimmedString("xyz");
                AssertEqualsViaObjectEqualsCall(assert, x, y, shouldBeEqual: true);
            });

            // There was a hack in ProductiveRage.Immutable to help Optional<T>'s Equals implementation work when T is an [ObjectLiteral] but that isn't required with the hacks in this library
            // (so, once I'm happy with this all, I'll remove them from ProductiveRage.Immutable, so 3.2.0 will have the hacks removed that were introduced in 3.1.0 - for now, the tests here
            // are referencing the 3.0.0 NuGet package, which doesn't have the hacks in it)
            QUnit.Test("Two instances of Optional<NonBlankTrimmedString> with the same value are found to be equal when compared as NonBlankTrimmedString", assert =>
            {
                var x = Optional.For(new NonBlankTrimmedString("xyz"));
                var y = Optional.For(new NonBlankTrimmedString("xyz"));
                AssertEqualsViaOptionalNonBlankTrimmedStringEqualsCall(assert, x, y, shouldBeEqual: true);
            });
            QUnit.Test("Two instances of Optional<NonBlankTrimmedString> with the same value are found to be equal when compared as generic type param of NonBlankTrimmedString", assert =>
            {
                var x = Optional.For(new NonBlankTrimmedString("xyz"));
                var y = Optional.For(new NonBlankTrimmedString("xyz"));
                AssertEqualsViaSharedGenericTypeEqualsCall(assert, x, y, shouldBeEqual: true);
            });
            QUnit.Test("Two instances of Optional<NonBlankTrimmedString> with the same value are found to be equal when compared as Object", assert =>
            {
                var x = Optional.For(new NonBlankTrimmedString("xyz"));
                var y = Optional.For(new NonBlankTrimmedString("xyz"));
                AssertEqualsViaObjectEqualsCall(assert, x, y, shouldBeEqual: true);
            });

            QUnit.Test("Two instances of NonBlankTrimmedString with the same value are NOT equal if they are of different types when compared as NonBlankTrimmedString", assert =>
            {
                var x = new NonBlankTrimmedString("xyz");
                var y = new ClassName("xyz");
                AssertEqualsViaNonBlankTrimmedStringEqualsCall(assert, x, y, shouldBeEqual: false);
            });
            QUnit.Test("Two instances of NonBlankTrimmedString with the same value are NOT equal if they are of different types when compared as generic type param of NonBlankTrimmedString", assert =>
            {
                var x = new NonBlankTrimmedString("xyz");
                var y = new ClassName("xyz");
                AssertEqualsViaSharedGenericTypeEqualsCall(assert, x, y, shouldBeEqual: false);
            });
            QUnit.Test("Two instances of NonBlankTrimmedString with the same value are NOT equal if they are of different types when compared as Object", assert =>
            {
                var x = new NonBlankTrimmedString("xyz");
                var y = new ClassName("xyz");
                AssertEqualsViaObjectEqualsCall(assert, x, y, shouldBeEqual: false);
            });

            // This tests a few issues that have been encountered after using [ObjectLiteral] in more places - the FixObjectLiteralEqualsHack approach means that the implicit operator will
            // not reliably be called when comparing an Optional<T> to T (the fix for that is in 4.1.0 of ProductiveRage.Immutable) and FixObjectLiteralEqualsHack now supports "falling
            // through" equality checks if false is returned (so is comparing a NonBlankTrimmedString, which is an [ObjectLiteral], to an Optional<NonBlankTrimmedString> then the Equals
            // check made against the NonBlankTrimmedString's Equals method will return false as it is unaware of Optional's implicit casting support and so other Equals methods need to
            // be give opportunity to run) and it tests a bug with FixObjectLiteralEqualsHack relating to different generic types where the cached Equals lookup for an [ObjectLiteral]
            // generic class would result in type checks against the generic type parameters being incorrect.
            QUnit.Test("Integration tests around NonBlankTrimmedString / Optional / another [ObjectLiteral]", assert =>
            {
                var stringValue           = new NonBlankTrimmedString("test");
                var optionalOfString      = Optional.For(stringValue);
                var resultOrErrorOfString = ResultOrErrorDetails.FromResult(stringValue);

                assert.NotOk(Equals(optionalOfString, resultOrErrorOfString));
                assert.Ok(Equals(optionalOfString, stringValue));
                assert.Ok(Equals(stringValue, optionalOfString));
                assert.Ok(Equals(ResultOrErrorDetails.FromResult("abc"), ResultOrErrorDetails.FromResult("abc")));
                assert.Ok(Equals(ResultOrErrorDetails.FromResult(new NonBlankTrimmedString("abc")), ResultOrErrorDetails.FromResult(new NonBlankTrimmedString("abc"))));
                assert.NotOk(Equals(ResultOrErrorDetails.FromResult(new NonBlankTrimmedString("abc")), ResultOrErrorDetails.FromResult("abc")));
            });
        }
Beispiel #29
0
        private static void NonNullListTests()
        {
            QUnit.Module("NonNullListTests");

            QUnit.Test("NonNullList.OrderBy - numeric sequence permutations", assert =>
            {
                for (var numberOfItems = 0; numberOfItems <= 4; numberOfItems++)
                {
                    var data = Enumerable.Range(0, numberOfItems);
                    var expectedResultAsString = string.Join(", ", data);
                    foreach (var permutation in GetPermutations(data.ToArray()).Select(permutation => NonNullList.Of(permutation).OrderBy(value => value)))
                    {
                        var actualResultAsString = string.Join(", ", permutation);
                        assert.Equal(actualResultAsString, expectedResultAsString);
                    }
                }
            });

            QUnit.Test("NonNullList.Map - items change (no index passed to lambda)", assert =>
            {
                var actual = NonNullList.Of(1, 2, 3, 4).Map(value => value + 1);
                assert.Equal(
                    actual: string.Join(",", actual),
                    expected: "2,3,4,5"
                    );
            });

            QUnit.Test("NonNullList.Map - items change (index passed to lambda)", assert =>
            {
                var actual = NonNullList.Of(1, 2, 3, 4).Map((value, index) => value + index);
                assert.Equal(
                    actual: string.Join(",", actual),
                    expected: "1,3,5,7"
                    );
            });

            QUnit.Test("NonNullList.Map - items don't change and so list returning unaltered", assert =>
            {
                var items = NonNullList.Of(1, 2, 3, 4);
                assert.Equal(
                    actual: items.Map(value => value),
                    expected: items
                    );
            });

            QUnit.Test("NonNullList.Map - items don't change (according to Equals override) and so list returning unaltered", assert =>
            {
                var items = NonNullList.Of(new StandardObjectWithCustomEquality("abc"));
                assert.Equal(
                    actual: items.Map(value => new StandardObjectWithCustomEquality("abc")),
                    expected: items
                    );
            });

            QUnit.Test("NonNullList.Map - items [ObjectLiteral] don't change (according to Equals override) and so list returning unaltered", assert =>
            {
                // Use NonBlankTrimmedString from ProductiveRage.Immutable.Extensions because that is an [ObjectLiteral] with a custom Equals method and referencing
                // that assembly pulls through the [ObjectLiteral] hacks that are required until the Bridge Team (hopefully) improve the support for them
                var items = NonNullList.Of(new NonBlankTrimmedString("abc"));
                assert.Equal(
                    actual: items.Map(value => new NonBlankTrimmedString("abc")),
                    expected: items
                    );
            });
        }
Beispiel #30
0
        private static void WithTests()
        {
            QUnit.Module("WithTests");

            QUnit.Test("Simple string property update using With directly", assert =>
            {
                var x = new SomethingWithStringId("abc");
                x     = x.With(_ => _.Id, "def");
                assert.Equal(x.Id, "def");
            });

            QUnit.Test("With does not affect original instance", assert =>
            {
                var x0 = new SomethingWithStringId("abc");
                var x1 = x0.With(_ => _.Id, "def");
                assert.Equal(x0.Id, "abc");
                assert.Equal(x1.Id, "def");
            });

            QUnit.Test("Simple string property update of property on a base class using With directly", assert =>
            {
                // This test is just to ensure that there's no monkey business involved when targeting properties on a base class (as there are
                // with interface properties - see above)
                var x = new SecurityPersonDetails(1, "test", 10);
                x     = x.With(_ => _.Name, "test2");
                assert.Equal(x.Name, "test2");
            });

            QUnit.Test("Simple string property update using With indirectly", assert =>
            {
                var x         = new SomethingWithStringId("abc");
                var idUpdater = x.With(_ => _.Id);
                x             = idUpdater("def");
                assert.Equal(x.Id, "def");
            });

            QUnit.Test("Simple string property update using GetProperty and With", assert =>
            {
                var x = new SomethingWithStringId("abc");
                var propertyToUpdate = x.GetProperty(_ => _.Id);
                x = x.With(propertyToUpdate, "def");
                assert.Equal(x.Id, "def");
            });

            QUnit.Test("Single-element NonNullList<string> property update using With directly", assert =>
            {
                var x = new SomethingWithNonNullListStringValues(NonNullList.Of("abc", "def"));
                x     = x.With(_ => _.Values, 1, "xyz");
                assert.Equal(x.Values[1], "xyz");
            });

            QUnit.Test("Single-element NonNullList<string> property update using GetProperty and With", assert =>
            {
                var x = new SomethingWithNonNullListStringValues(NonNullList.Of("abc", "def"));
                var propertyToUpdate = x.GetProperty(_ => _.Values);
                x = x.With <SomethingWithNonNullListStringValues, string>(propertyToUpdate, 1, "xyz");
                assert.Equal(x.Values[1], "xyz");
            });

            QUnit.Test("Single-element Set<string> (legacy compatibility alias for NonNullList) property update using GetProperty and With", assert =>
            {
#pragma warning disable CS0618 // Ignore the fact that Set is obsolete
                var x = new SomethingWithNonNullListStringValues(Set.Of("abc", "def"));
#pragma warning restore CS0618
                var propertyToUpdate = x.GetProperty(_ => _.Values);
                x = x.With <SomethingWithNonNullListStringValues, string>(propertyToUpdate, 1, "xyz");
                assert.Equal(x.Values[1], "xyz");
            });

            QUnit.Test("The Validate method (if there is one defined with zero parameters) should be called after With", assert =>
            {
                var x = new SomethingWithNonZeroKey(123);
                assert.Throws(
                    () => x.With(_ => _.Key, (uint)0),
                    "The Validate method should be called after With"
                    );
            });

            // When first changing the Clone behaviour within ImmutabilityHelpers to work with Bridge 16 (which changes how properties are defined on objects), there was a
            // bug introduced where the updating properties on the clone would update the values on the original value too! These tests confirm that that bug is no more.
            QUnit.Test("Simple string property update against an interface using With directly", assert =>
            {
                // Inspired by issue https://github.com/ProductiveRage/Bridge.Immutable/issues/4
                IAmImmutableAndHaveName viaInterfacePerson = new PersonDetails(1, "test");
                viaInterfacePerson = viaInterfacePerson.With(_ => _.Name, "test2");
                assert.Equal(viaInterfacePerson.Name, "test2");
            });
            QUnit.Test("Double-check must-not-affect-original-instance when targeting property on base class", assert =>
            {
                var x0 = new SecurityPersonDetails(1, "test", 10);
                var x1 = x0.With(_ => _.Name, "test2");
                assert.Equal(x0.Name, "test");
                assert.Equal(x1.Name, "test2");
            });
        }