Ejemplo n.º 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 =>
            {
#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
        }
Ejemplo n.º 2
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)"
                    );
            });
        }
Ejemplo n.º 3
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);
        }
 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);
 }
Ejemplo n.º 5
0
        public static void Run()
        {
            ModuleInfo module = new ModuleInfo();

            module.BeforeEach = SetUp;
            module.AfterEach  = Teardown;
            QUnit.Module("Unit Tests", module);
            QUnit.Test("Test1", Test1);
        }
 public NeuralNetworkTest()
 {
     QUnit.Test("inputTest", InputTest);
     QUnit.Test("hiddenLayerTest", HiddenLayerTest);
     QUnit.Test("OutputTest", OutputTest);
     QUnit.Test("WeightTest", WeightTest);
     QUnit.Test("NeuroEvolutionTest", NeuroEvolution);
     QUnit.Test("EvolutionTest", EvolutionTest);
 }
Ejemplo n.º 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);
        }
Ejemplo n.º 8
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);
            });
        }
Ejemplo n.º 9
0
        public static void Register()
        {
            QUnit.Test(nameof(RandomValueTest) + "->" + nameof(If_Property_Has_Already_Value_Do_Not_Change_It), If_Property_Has_Already_Value_Do_Not_Change_It);

            QUnit.Test(nameof(RandomValueTest) + "->" + nameof(Must_Support_Circular_Referenced_Types), Must_Support_Circular_Referenced_Types);

            QUnit.Test(nameof(RandomValueTest) + "->" + nameof(Must_Support_Primitive_Types), Must_Support_Primitive_Types);

            QUnit.Test(nameof(RandomValueTest) + "->" + nameof(String_With_Length_Parameter), String_With_Length_Parameter);
        }
Ejemplo n.º 10
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);
        }
Ejemplo n.º 12
0
        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);
        }
Ejemplo n.º 13
0
        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);
        }
Ejemplo n.º 14
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");
            });
        }
Ejemplo n.º 15
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")));
            });
        }
Ejemplo n.º 16
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);
            });
        }
Ejemplo n.º 17
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);
            });
        }
Ejemplo n.º 18
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);
        }
Ejemplo n.º 19
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);
        }
Ejemplo n.º 21
0
        static void EnumerableIsConvertedCorrectly()
        {
            var sample = GetNumber(10);

            var encoded = Converters.EncodeObject(sample);

            QUnit.Test("IEnumerable with yield return is converted corretly to array", assert =>
            {
                assert.Equal(encoded == null, false);
                assert.Equal(encoded["Type"], "Array");
                assert.Equal(encoded["Value"]["length"], 1);

                var number = Script.Write <object>("encoded.Value[0]");
                assert.Equal(number["Type"], "Int32");
                assert.Equal(number["Value"], 10);
            });

            QUnit.Test("IEnumerable from range is converted correctly", assert =>
            {
                var range     = System.Linq.Enumerable.Range(1, 1);
                var converted = Converters.EncodeObject(range);
                assert.Equal(converted == null, false);
                assert.Equal(converted["Type"], "Array");
                assert.Equal(converted["Value"]["length"], 1);

                var number = Script.Write <object>("converted.Value[0]");
                assert.Equal(number["Type"], "Int32");
                assert.Equal(number["Value"], 1);
            });

            QUnit.Test("IEnumerable of int is serialized and deserialized correctly", assert =>
            {
                IEnumerable <int> enu = Enumerable.Range(1, 10);
                var serialized        = Json.Serialize(enu);
                var deserialized      = Json.Deserialize <IEnumerable <int> >(serialized);
                assert.Equal(deserialized.Count(), enu.Count());

                var enuArr          = enu.ToArray();
                var deserializedArr = deserialized.ToArray();

                for (int i = 0; i < enuArr.Length; i++)
                {
                    assert.Equal(enuArr[i], deserializedArr[i]);
                }
            });
        }
Ejemplo n.º 22
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));
            });
        }
Ejemplo n.º 23
0
        public override void Execute()
        {
            base.Execute();

            MockGoogleTracerView mockView = new MockGoogleTracerView();

            Container.RegisterInstance(typeof(IGoogleTracerView), mockView);

            GoogleTracerController controller = new GoogleTracerController();

            QUnit.Test("Test get View", delegate
            {
                QUnit.Equals(mockView, controller.View);
            });

            QUnit.Test("Test Execute() & ShowMoreResults()", delegate
            {
                GoogleSearchResponse data = new GoogleSearchResponse();

                Mock mockAddShowMoreResults = new Mock(mockView, "add_showMoreResults");
                mockAddShowMoreResults.Modify().Args(Is.Anything).ReturnValue();
                Mock mockRenderSearchResult = new Mock(mockView, "renderSearchResult");
                mockRenderSearchResult.Modify().Args(data).ReturnValue();
                mockRenderSearchResult.Modify().Args(data).ReturnValue();
                Mock mockGetScript = new Mock(Script.Eval("jQuery"), "getScript");
                mockGetScript.Modify().Args(Is.Anything, Is.Anything).Callback(1, null).ReturnValue();
                mockGetScript.Modify().Args(Is.Anything, Is.Anything).Callback(1, null).ReturnValue();

                QUnit.Equals(0, mockView.SearchStart);
                ((Dictionary)(object)Window.Self)["_googlewebsearchresults"] = data;
                controller.Execute();
                ((Dictionary)(object)Window.Self)["_googlewebsearchresults"] = data;
                controller.ShowMoreResults();
                QUnit.Equals(4, mockView.SearchStart);

                mockAddShowMoreResults.Verify();
                mockAddShowMoreResults.Restore();
                mockRenderSearchResult.Verify();
                mockRenderSearchResult.Restore();
                mockGetScript.Verify();
                mockGetScript.Restore();
            });
        }
Ejemplo n.º 24
0
        static void ArrayIsEncodedCorrectly()
        {
            var arr     = new int[] { 1, 2, 3 };
            var encoded = Converters.EncodeObject(arr);

            QUnit.Test("Array of ints is encoded correctly", assert =>
            {
                assert.Equal(encoded["Type"], "Array");
                assert.Equal(encoded["Value"]["length"], arr.Length);

                var values = encoded["Value"].As <object[]>();

                for (int i = 0; i < values.Length; i++)
                {
                    var intJson = values[i];
                    assert.Equal(intJson["Type"], "Int32");
                    assert.Equal(intJson["Value"], i + 1);
                }
            });
        }
        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);
            });
        }
Ejemplo n.º 26
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 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");
            });
        }
Ejemplo n.º 28
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);
        }
Ejemplo n.º 29
0
        static void DateTimeIsEncodedCorrectly()
        {
            var time = new DateTime(2016, 12, 10, 20, 30, 0, 235);

            var encoded = Converters.EncodeDateTime(time);


            QUnit.Test("Encoding DateTime works", assert =>
            {
                assert.Equal(encoded["Type"], "DateTime");
                assert.Equal(encoded["Value"], time.ToString("dd/MM/yyyy HH:mm:ss.fff"));
            });

            QUnit.Test("Encoding boxed DateTime works", assert =>
            {
                object boxed = time;

                var boxedEncoded = Converters.EncodeDateTime(boxed.As <DateTime>());

                assert.DeepEqual(encoded, boxedEncoded);
            });

            QUnit.Test("Encode -> Decode DateTime works", assert =>
            {
                var now = DateTime.Now;

                var serialized = Json.Serialize(now);

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

                assert.Equal(now.Year, deserialized.Year);
                assert.Equal(now.Month, deserialized.Month);
                assert.Equal(now.Day, deserialized.Day);
                assert.Equal(now.Hour, deserialized.Hour);
                assert.Equal(now.Minute, deserialized.Minute);
                assert.Equal(now.Second, deserialized.Second);
                assert.Equal(now.Millisecond, deserialized.Millisecond);
            });
        }
Ejemplo n.º 30
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);
            });
        }