The Assert class contains a collection of static methods that implement the most common assertions used in NUnit.
 public BooleanQueryTst(
     string queryText,
     int[] expectedDocNrs,
     SingleFieldTestDb dBase,
     string fieldName,
     Assert testCase,
     BasicQueryFactory qf)
 {
     this.queryText = queryText;
     this.expectedDocNrs = expectedDocNrs;
     this.dBase = dBase;
     this.fieldName = fieldName;
     this.testCase = testCase;
     this.qf = qf;
 }
示例#2
0
    private IEnumerator TryToLoadUrl(string url)
    {
        yield return(new WaitForEndOfFrame());

        var request = (HttpWebRequest)WebRequest.Create(url);
        var result  = request.BeginGetResponse(null, null);

        yield return(new WaitForIAsyncResult(result));

        NAssert.DoesNotThrow(() =>
        {
            using (var response = (HttpWebResponse)request.EndGetResponse(result))
            {
                Assert.AreEqual(response.StatusCode, HttpStatusCode.OK, "Unexpected HTTP response code");
            }
        });
        yield return(new WaitForEndOfFrame());
    }
示例#3
0
    private IEnumerator VerifyCompressionSupport(string url)
    {
        yield return(new WaitForEndOfFrame());

        var request = (HttpWebRequest)WebRequest.Create(url);

        request.AutomaticDecompression = DecompressionMethods.GZip;
        var result = request.BeginGetResponse(null, null);

        yield return(new WaitForIAsyncResult(result));

        NAssert.DoesNotThrow(() =>
        {
            using (var response = (HttpWebResponse)request.EndGetResponse(result))
            {
                Assert.AreEqual(response.StatusCode, HttpStatusCode.OK, "Unexpected HTTP response code");
                var encoding = response.ContentEncoding.ToLower();
                Assert.IsTrue(encoding.Contains("gzip"), string.Format("Expected: {0}, Actual: {1}", "gzip", encoding));
            }
        });
        yield return(new WaitForEndOfFrame());
    }
        public void TestToString_String_AsNullIFormatProvider()
        {
            var originalCurrentCulture = CultureInfo.CurrentCulture;

            try
            {
#if (!NET35 && !SILVERLIGHT) || WINDOWS_UWP
                CultureInfo.CurrentCulture =
#else // ( !NET35 && !SILVERLIGHT ) || WINDOWS_UWP
                Thread.CurrentThread.CurrentCulture =
#endif // ( !NET35 && !SILVERLIGHT ) || WINDOWS_UWP
                    new LegacyJapaneseCultureInfo();

                if (!(CultureInfo.CurrentCulture is LegacyJapaneseCultureInfo) || CultureInfo.CurrentCulture.NumberFormat.NegativeSign != "\uFF0D")
                {
                    Assert.Ignore("This platform does not support custom culture correctly.");
                }

                Assert.That(
                    new Timestamp(
                        -62193657600,
                        0
                        ).ToString("s"),
                    Is.EqualTo("�|0001-03-01T00:00:00Z")
                    );
            }
            finally
            {
#if (!NET35 && !SILVERLIGHT) || WINDOWS_UWP
                CultureInfo.CurrentCulture =
#else // ( !NET35 && !SILVERLIGHT ) || WINDOWS_UWP
                Thread.CurrentThread.CurrentCulture =
#endif // ( !NET35 && !SILVERLIGHT ) || WINDOWS_UWP
                    originalCurrentCulture;
            }
        }
        public void TestToString_String_IFormatProvider_Distinguishable_s_null_CurrentCultureIsUsed()
        {
            var originalCurrentCulture = CultureInfo.CurrentCulture;

            try
            {
#if (!NET35 && !SILVERLIGHT) || WINDOWS_UWP
                CultureInfo.CurrentCulture =
#else // ( !NET35 && !SILVERLIGHT ) || WINDOWS_UWP
                Thread.CurrentThread.CurrentCulture =
#endif // ( !NET35 && !SILVERLIGHT ) || WINDOWS_UWP
                    new LegacyJapaneseCultureInfo();

                if (!(CultureInfo.CurrentCulture is LegacyJapaneseCultureInfo) || CultureInfo.CurrentCulture.NumberFormat.NegativeSign != "\uFF0D")
                {
                    Assert.Ignore("This platform does not support custom culture correctly.");
                }

                Assert.That(
                    new Timestamp(
                        -23215049511,
                        123456789
                        ).ToString("s", null),
                    Is.EqualTo("1234-05-06T07:08:09Z")
                    );
            }
            finally
            {
#if (!NET35 && !SILVERLIGHT) || WINDOWS_UWP
                CultureInfo.CurrentCulture =
#else // ( !NET35 && !SILVERLIGHT ) || WINDOWS_UWP
                Thread.CurrentThread.CurrentCulture =
#endif // ( !NET35 && !SILVERLIGHT ) || WINDOWS_UWP
                    originalCurrentCulture;
            }
        }
        public IEnumerator ItCanSubscribeToAChannelAndReceiveAMessage()
        {
            CreateClient(ChannelParameterOne);
            yield return(WaitForClientToSettle());

            Assert.IsEmpty(client.receivedMessages);

            yield return(OnFacet <BroadcastingFacet> .Call(
                             nameof(BroadcastingFacet.SendMyMessage),
                             ChannelParameterOne,
                             "Hello world!"
                             ).AsCoroutine());

            yield return(WaitForMessages(1));

            Assert.AreEqual(1, client.receivedMessages.Count);
            Assert.IsInstanceOf <MyMessage>(client.receivedMessages[0]);
            Assert.AreEqual(
                "Hello world!",
                ((MyMessage)client.receivedMessages[0]).foo
                );

            yield return(null);
        }
        public void TestEqualsPartialTrust()
        {
            var appDomainSetUp = new AppDomainSetup()
            {
                ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase
            };
            var evidence = new Evidence();

#if MONO || NET35
#pragma warning disable 0612
            // TODO: patching
            // currently, Mono does not declare AddHostEvidence
            evidence.AddHost(new Zone(SecurityZone.Internet));
#pragma warning restore 0612
            var permisions = GetDefaultInternetZoneSandbox();
#else
            evidence.AddHostEvidence(new Zone(SecurityZone.Internet));
            var permisions = SecurityManager.GetStandardSandbox(evidence);
#endif // if MONO || NET35
            AppDomain workerDomain = AppDomain.CreateDomain("PartialTrust", evidence, appDomainSetUp, permisions, GetStrongName(this.GetType()), GetStrongName(typeof(Assert)));
            try
            {
                workerDomain.DoCallBack(TestEqualsWorker);

#if !MONO
                // P/Invoke is not disabled on Mono even if in the InternetZone.
                Assert.That(( bool )workerDomain.GetData("MessagePackString.IsFastEqualsDisabled"), Is.True);
#endif // if !MONO
                Console.WriteLine("TestEqualsPartialTrust");
                ShowResult(workerDomain.GetData("TestEqualsWorker.Performance") as Tuple <double, double, double, double>);
            }
            finally
            {
                AppDomain.Unload(workerDomain);
            }
        }
示例#8
0
        public void BorrarReservaTest()
        {
            var           logicaHospedajeMock = new Mock <IHospedaje>(MockBehavior.Strict);
            var           repoMock            = new Mock <IRepository <Reserva> >(MockBehavior.Strict);
            Reserva_Logic logica  = new Reserva_Logic(repoMock.Object, logicaHospedajeMock.Object);
            Reserva       reserva = new Reserva()
            {
                Id          = 0,
                Descripcion = "Test",
                Estado      = EstadoReserva.Creada,
            };

            repoMock.Setup(x => x.Create(reserva));
            repoMock.Setup(x => x.Save());
            repoMock.Setup(x => x.Get(reserva.Id)).Throws(new EntidadNoExisteExcepcion());
            logica.AgregarReserva(reserva);
            repoMock.Setup(x => x.Get(reserva.Id)).Returns(reserva);
            repoMock.Setup(x => x.Delete(reserva));
            logica.BorrarReserva(reserva.Id);
            repoMock.Setup(x => x.GetAll()).Returns(new List <Reserva>());
            List <Reserva> resultado = logica.ObtenerTodos();

            Assert.AreEqual(0, resultado.Count);
        }
示例#9
0
        public void TestIssue99_HoGyuLee_AotForEnumKeyDictionary()
        {
            MessagePackSerializer.PrepareType <FileMode>();
            using (var buffer = new MemoryStream(new byte[] { 0x81, 0x01, 0x00 }))
            {
                var serializer =
                    MessagePackSerializer.Get <Dictionary <FileMode, int> >(
                        PreGeneratedSerializerActivator.CreateContext(
                            SerializationMethod.Array,
                            PackerCompatibilityOptions.None
                            )
                        );
                var result = serializer.Unpack(buffer);
                Assert.That(result.Count, Is.EqualTo(1));
                var singleResult = default(KeyValuePair <FileMode, int>);
                foreach (var kv in result)
                {
                    singleResult = kv;
                }

                Assert.That(singleResult.Key, Is.EqualTo(( FileMode )1));
                Assert.That(singleResult.Value, Is.EqualTo(0));
            }
        }
示例#10
0
        public virtual void multiThreadAppAccessTest()
        {
            LexThread runner1 = new LexThread(this, "lie");
            LexThread runner2 = new LexThread(this, "bark");

            Thread thread1 = new Thread(runner1.Run);
            Thread thread2 = new Thread(runner2.Run);

            thread1.Start();
            thread2.Start();

            try
            {
                Thread.Sleep(500);
            }
            catch (Exception)
            {
                ; // do nothing
            }


            Assert.AreEqual("lie", runner1.word.BaseForm);
            Assert.AreEqual("bark", runner2.word.BaseForm);
        }
        private static void TestDataContractAndNonSerializableAreMixedCore(SerializationMethod method)
        {
            var context = new SerializationContext {
                SerializationMethod = method
            };

            using (var buffer = new MemoryStream())
            {
                var target = new DataContractAndNonSerializedMixedTarget();
                target.ShouldSerialized = 111;
                var serializer = MessagePackSerializer.CreateInternal <DataContractAndNonSerializedMixedTarget>(context);
                serializer.Pack(buffer, target);

                buffer.Position = 0;
                var intermediate = Unpacking.UnpackObject(buffer);

                if (method == SerializationMethod.Array)
                {
                    var asArray = intermediate.AsList();
                    Assert.That(asArray.Count, Is.EqualTo(1));
                    Assert.That(asArray[0] == target.ShouldSerialized);
                }
                else
                {
                    var asMap = intermediate.AsDictionary();
                    Assert.That(asMap.Count, Is.EqualTo(1));
                    Assert.That(asMap["ShouldSerialized"] == target.ShouldSerialized);
                }

                buffer.Position = 0;

                var result = serializer.Unpack(buffer);

                Assert.That(result.ShouldSerialized, Is.EqualTo(target.ShouldSerialized));
            }
        }
示例#12
0
        public void Client_ImageSetUrlCallBackAmazon_IsTrue()
        {
            var client    = HelperFunctions.CreateWorkingClient();
            var dataStore = new DataStore(
                Settings.AmazonKey,
                Settings.AmazonSecret,
                Settings.AmazonBucket,
                string.Empty
                );

            var request = new OptimizeSetRequest(new Uri(TestData.ImageOne), _callbackUri, dataStore)
            {
                Lossy = true,
            };

            request.AddSet(new ResizeImageSet {
                Name = "test1", Height = 10, Width = 10, StoragePath = "test1/test1.png"
            });
            request.AddSet(new ResizeImageSet {
                Name = "test2", Height = 15, Width = 15, StoragePath = "test2/test2.png"
            });
            request.AddSet(new ResizeImageSet {
                Name = "test3", Height = 20, Width = 20, StoragePath = "test3/test3.png"
            });

            var response = client.Optimize(
                request
                );

            var result = response.Result;

            Assert.IsTrue(result.StatusCode == HttpStatusCode.OK);
            Assert.IsTrue(result.Success);
            Assert.IsTrue(result.Body != null);
            Assert.IsTrue(!string.IsNullOrEmpty(result.Body.Id));
        }
示例#13
0
        public void Client_OptimizeWaitAmazonWithPath_IsTrue()
        {
            var client = HelperFunctions.CreateWorkingClient();

            var response = client.OptimizeWait(
                new OptimizeWaitRequest(
                    new Uri(TestData.ImageOne),
                    new DataStore(
                        Settings.AmazonKey,
                        Settings.AmazonSecret,
                        Settings.AmazonBucket,
                        string.Empty)
            {
                Path = "test/"
            }
                    ));

            var result = response.Result;

            Assert.IsTrue(result.StatusCode == HttpStatusCode.OK);
            Assert.IsTrue(result.Success);
            Assert.IsTrue(!string.IsNullOrEmpty(result.Body.KrakedUrl));
            Assert.IsTrue(result.Body.KrakedUrl.Contains(".amazonaws.com"));
        }
示例#14
0
        public void Client_UploadOptimizeCallbackAmazonDataStore_IsTrue()
        {
            var client = HelperFunctions.CreateWorkingClient();
            var image  = File.ReadAllBytes(GetPathResources(TestData.LocalTestImage));

            var response = client.Optimize(
                image,
                TestData.TestImageName,
                new OptimizeUploadRequest(
                    _callbackUri, new DataStore(
                        Settings.AmazonKey,
                        Settings.AmazonSecret,
                        Settings.AmazonBucket,
                        string.Empty)
                    )
                );

            var result = response.Result;

            Assert.IsTrue(result.StatusCode == HttpStatusCode.OK);
            Assert.IsTrue(result.Success);
            Assert.IsTrue(result.Body != null);
            Assert.IsTrue(!string.IsNullOrEmpty(result.Body.Id));
        }
示例#15
0
        public void Option()
        {
            var dom = TestDom("jquery-unit-index");
            var res = dom["#select4"];

            var el = (IHTMLOptionElement)res.Find("#option4a")[0];

            Assert.AreEqual("", el.Value);
            Assert.IsFalse(el.Selected);
            Assert.IsTrue(el.Disabled);

            el = (IHTMLOptionElement)el.NextElementSibling;

            Assert.AreEqual("1", el.Value);
            Assert.IsTrue(el.Selected);
            Assert.IsTrue(el.Disabled);

            // this one inherits disabled from the opt group
            el = (IHTMLOptionElement)el.NextElementSibling;

            Assert.AreEqual("2", el.Value);
            Assert.IsTrue(el.Selected);
            Assert.IsTrue(el.Disabled);
        }
示例#16
0
        public void GetAllSuccess_pageNumber_second()
        {
            Setup();

            AlbumsRequest request = new AlbumsRequest();

            request.PageSize   = 1;
            request.PageNumber = 2;


            getAllAlbumsByFilterResponse.ListAlbums = getAllAlbumsByFilterResponse.ListAlbums
                                                      .Skip((request.PageNumber - 1) * request.PageSize)
                                                      .Take(request.PageSize)
                                                      .ToList();


            albumAppServiceMock.Setup(p => p.GetAllAlbumsByFilter(It.IsAny <GetAllAlbumsByFilterRequest>())).Returns(getAllAlbumsByFilterResponse);


            var result = controller.Get(request);

            Assert.AreEqual(result.ListAlbums.Count, 1);
            Assert.AreEqual(result.ListAlbums[0].Id, 2);
        }
示例#17
0
        public void Issue143()
        {
            var array =
                new object[]
            {
                "111",
                32432,
                new int[] { 9, 8 },
                909
            };
            var serializer   = MessagePackSerializer.Get <object>(new SerializationContext());
            var packedBinary = serializer.PackSingleObject(array);
            var unpacked     = serializer.UnpackSingleObject(packedBinary);
            var unpackedList = (( MessagePackObject )unpacked).AsList();

            Assert.That(unpackedList.Count, Is.EqualTo(4));
            Assert.That(unpackedList[0] == "111");
            Assert.That(unpackedList[1] == 32432);
            Assert.That(unpackedList[2].IsList);
            Assert.That(unpackedList[2].AsList().Count, Is.EqualTo(2));
            Assert.That(unpackedList[2].AsList()[0] == 9);
            Assert.That(unpackedList[2].AsList()[1] == 8);
            Assert.That(unpackedList[3] == 909);
        }
示例#18
0
        public void Post_ValidLectorIsSavedInRepository()
        {
            //Arange
            var lector = new LectorBuilder().Build();

            _controller.LectorRepositoryMock.Setup(repo => repo.Post(It.IsAny <Lector>())).Returns(() =>
            {
                lector.Id = new Random().Next();
                return(lector);
            });

            //Act
            var actionResult = _controller.Post(lector) as CreatedAtRouteNegotiatedContentResult <Lector>;

            //Assert
            Assert.That(actionResult, Is.Not.Null);
            _controller.LectorRepositoryMock.Verify(repo => repo.Post(lector), Times.Once);
            Assert.That(actionResult.Content, Is.EqualTo(lector)); //---
            Assert.That(actionResult.Content.Id, Is.GreaterThan(0));
            Assert.That(actionResult.RouteName, Is.EqualTo("DefaultApi"));
            Assert.That(actionResult.RouteValues.Count, Is.EqualTo(2));
            Assert.That(actionResult.RouteValues["controller"], Is.EqualTo("Lector"));
            Assert.That(actionResult.RouteValues["id"], Is.EqualTo(actionResult.Content.Id));
        }
示例#19
0
        private static void TestFieldSwappedCore(EmitterFlavor flavor)
        {
            var serializer = CreateSerializer <VersioningTestTarget>(flavor);

            using (var stream = new MemoryStream())
            {
                var packer = Packer.Create(stream, false);
                packer.PackMapHeader(3);
                packer.PackString("Field1");
                packer.Pack(1);
                packer.PackString("Field2");
                packer.Pack(-1);
                packer.PackString("Extra");
                packer.Pack(2);                   // Issue6

                stream.Position = 0;

                var result = serializer.Unpack(stream);

                Assert.That(result.Field1, Is.EqualTo(1));
                Assert.That(result.Field2, Is.EqualTo(-1));
                Assert.That(result.Field3, Is.Null);
            }
        }
        public void TestReadExtendedTypeObject_FixExt2_AndBinaryLengthIs2_Extra()
        {
            var typeCode = ( byte )(Math.Abs(Environment.TickCount) % 128);
            var data     =
                new byte[] { 0xD5, typeCode }
            .Concat(Enumerable.Repeat(( byte )0xFF, 2)).ToArray();

            using (var unpacker = this.CreateUnpacker(PrependAppendExtra(data), 1))
            {
                // Verify initial offset (prepended bytes length)
                Assert.That(unpacker.Offset, Is.EqualTo(1));

                MessagePackExtendedTypeObject result;

                Assert.IsTrue(unpacker.ReadMessagePackExtendedTypeObject(out result));

                Assert.That(result.TypeCode, Is.EqualTo(typeCode));
                Assert.That(result.Body, Is.Not.Null);
                Assert.That(result.Body.Length, Is.EqualTo(2));

                // -1 is prepended extra bytes length
                Assert.That(unpacker.Offset - 1, Is.EqualTo(data.Length));
            }
        }
示例#21
0
 public void TestExts_Splitted()
 {
     foreach (
         var count in
         new[]
     {
         0,                                 // empty
         1,                                 // fixext1
         2,                                 // fixext2
         4,                                 // fixext4
         8,                                 // fixext8
         16,                                // fixext16
         17,                                // min ext8 size
         0xff,                              // max ext8 size
         0x100,                             // min ext16 size
         0xffff,                            // max ext16 size
         0x10000,                           // min ext32 size
     }
         )
     {
         using (var output = new MemoryStream())
         {
             var value = new MessagePackExtendedTypeObject(
                 1, Enumerable.Range(0, count).Select(i => ( byte )(i % 0x100)).ToArray());
             Packer.Create(output, PackerCompatibilityOptions.None).PackExtendedTypeValue(value);
             output.Position = 0;
             using (var splitted = new SplittingStream(output))
             {
                 Assert.AreEqual(
                     value,
                     Unpacking.UnpackObject(splitted).AsMessagePackExtendedTypeObject()
                     );
             }
         }
     }
 }
        public IEnumerator ItDoesntReceiveMessagesAfterUnsubscribing()
        {
            CreateClient(ChannelParameterOne);
            yield return(WaitForClientToSettle());

            Assert.IsEmpty(client.receivedMessages);

            yield return(OnFacet <BroadcastingFacet> .Call(
                             nameof(BroadcastingFacet.SendMyMessage),
                             ChannelParameterOne,
                             "Hello world!"
                             ).AsCoroutine());

            yield return(WaitForMessages(1));

            // disable --> unsubscribes
            client.gameObject.SetActive(false);

            // clear log
            client.receivedMessages.Clear();

            // send a message
            yield return(OnFacet <BroadcastingFacet> .Call(
                             nameof(BroadcastingFacet.SendMyMessage),
                             ChannelParameterOne,
                             "Hello world!"
                             ).AsCoroutine());

            // wait a sec.
            yield return(new WaitForSeconds(1f));

            // nothing
            Assert.IsEmpty(client.receivedMessages);

            yield return(null);
        }
        public void Post_ValidStagevoorstelIsSavedInRepository()
        {
            //Arange
            var stagevoorstel = new StagevoorstelBuilder().Build();

            _controller.StagevoorstelRepositoryMock.Setup(repo => repo.Post(It.IsAny <Stagevoorstel>())).Returns(() =>
            {
                stagevoorstel.Id = new Random().Next();
                return(stagevoorstel);
            });

            //Act
            var actionResult = _controller.Post(stagevoorstel) as CreatedAtRouteNegotiatedContentResult <Stagevoorstel>;

            //Assert
            Assert.That(actionResult, Is.Not.Null);
            _controller.StagevoorstelRepositoryMock.Verify(repo => repo.Post(stagevoorstel), Times.Once);
            Assert.That(actionResult.Content, Is.EqualTo(stagevoorstel)); //---
            Assert.That(actionResult.Content.Id, Is.GreaterThan(0));
            Assert.That(actionResult.RouteName, Is.EqualTo("DefaultApi"));
            Assert.That(actionResult.RouteValues.Count, Is.EqualTo(2));
            Assert.That(actionResult.RouteValues["controller"], Is.EqualTo("Stagevoorstellen"));
            Assert.That(actionResult.RouteValues["id"], Is.EqualTo(actionResult.Content.Id));
        }
示例#24
0
        public void TestExts()
        {
            var sw = new Stopwatch();

            foreach (
                var count in
                new[]
            {
                0,                         // empty
                1,                         // fixext1
                2,                         // fixext2
                4,                         // fixext4
                8,                         // fixext8
                16,                        // fixext16
                17,                        // min ext8 size
                0xff,                      // max ext8 size
                0x100,                     // min ext16 size
                0xffff,                    // max ext16 size
                0x10000,                   // min ext32 size
            }
                )
            {
                sw.Restart();
                var output = new MemoryStream();
                var value  = new MessagePackExtendedTypeObject(
                    1, Enumerable.Range(0, count).Select(i => ( byte )(i % 0x100)).ToArray());
                Packer.Create(output, PackerCompatibilityOptions.None).Pack(value);
                Assert.AreEqual(
                    value,
                    UnpackOne(output).AsMessagePackExtendedTypeObject()
                    );
                sw.Stop();
            }

            Console.WriteLine("Ext: {0:0.###} msec/byte", sw.Elapsed.TotalMilliseconds / 0x10000);
        }
 public void TestToLowerCamel(string input, string expected)
 {
     Assert.That(KeyNameTransformers.ToLowerCamel(input), Is.EqualTo(expected));
 }
 public void TestToUpperSnake(string input, string expected)
 {
     Assert.That(KeyNameTransformers.ToUpperSnake(input), Is.EqualTo(expected));
 }
示例#27
0
        public void selectDayTest()
        {
            IWebElement day = ToDoListUtilites.selectDate("25");

            Assert.IsTrue(day.Selected);
        }
示例#28
0
 public void markCompleteTest()
 {
     ToDoListUtilites.createTask("Second Task");
     ToDoListModels.markCompletedBtn.Click();
     Assert.IsTrue(ToDoListModels.markCompletedBtn.Selected);
 }
        private static void TestSerializationCore(SerializationContext context, DateTimeConversionMethod expected)
        {
            Assert.That(context.DefaultDateTimeConversionMethod, Is.EqualTo(expected));

            var now         = Timestamp.UtcNow;
            var dateTimeNow = now.ToDateTimeOffset();
            var source      =
                new ClassHasTimestamp
            {
                Timestamp      = now,
                DateTime       = dateTimeNow.AddSeconds(1).UtcDateTime,
                DateTimeOffset = dateTimeNow.AddSeconds(2),
#if (!SILVERLIGHT || WINDOWS_PHONE) && !XAMARIN && !UNITY && !UNITY
                FileTime = now.Add(TimeSpan.FromSeconds(3)).ToDateTime().ToWin32FileTimeUtc()
#endif // ( !SILVERLIGHT || WINDOWS_PHONE ) && !XAMARIN && !UNITY && !UNITY
            };

            using (var buffer = new MemoryStream())
            {
                var serializer = context.GetSerializer <ClassHasTimestamp>();
                serializer.Pack(
                    buffer,
                    source
                    );

                // Test representation
                buffer.Position = 0;
                var native = MessagePackSerializer.UnpackMessagePackObject(buffer);
                Assert.That(native.IsArray, Is.True);
                var nativeMembers = native.AsList();
                Assert.That(nativeMembers.Count, Is.EqualTo(ClassHasTimestamp.MemberCount));

                for (var i = 0; i < ClassHasTimestamp.MemberCount; i++)
                {
                    switch (expected)
                    {
                    case DateTimeConversionMethod.Native:
                    {
                        if (i == 2)
                        {
                            // DateTimeOffset -> [long, shourt]
                            Assert.That(nativeMembers[i].IsArray, Is.True);
                            var dtoComponents = nativeMembers[i].AsList();
                            Assert.That(dtoComponents.Count, Is.EqualTo(2));
                            Assert.That(dtoComponents[0].IsTypeOf <long>(), Is.True);
                            Assert.That(dtoComponents[1].IsTypeOf <short>(), Is.True);
                        }
                        else
                        {
                            Assert.That(nativeMembers[i].IsTypeOf <long>(), Is.True);
                        }
                        break;
                    }

                    case DateTimeConversionMethod.UnixEpoc:
                    {
                        Assert.That(nativeMembers[i].IsTypeOf <long>(), Is.True);
                        break;
                    }

                    case DateTimeConversionMethod.Timestamp:
                    {
                        Assert.That(nativeMembers[i].IsTypeOf <MessagePackExtendedTypeObject>(), Is.True);
                        var asExt = nativeMembers[i].AsMessagePackExtendedTypeObject();
                        Assert.That(asExt.TypeCode, Is.EqualTo(0xFF));
                        // Actual encoding should be tested in Timestamp tests.
                        break;
                    }
                    }
                }

                // Test round trip
                buffer.Position = 0;

                var result = serializer.Unpack(buffer);
                switch (expected)
                {
                case DateTimeConversionMethod.Native:
                {
                    Assert.That(result.Timestamp, Is.EqualTo(new Timestamp(now.UnixEpochSecondsPart, now.NanosecondsPart / 100 * 100)));
                    Assert.That(result.DateTime, Is.EqualTo(now.ToDateTime().AddSeconds(1)));
                    Assert.That(result.DateTimeOffset, Is.EqualTo(now.ToDateTimeOffset().AddSeconds(2)));
#if (!SILVERLIGHT || WINDOWS_PHONE) && !XAMARIN && !UNITY && !UNITY
                    Assert.That(result.FileTime, Is.EqualTo(now.Add(TimeSpan.FromSeconds(3).Subtract(TimeSpan.FromTicks(now.NanosecondsPart % 100))).ToDateTime().ToWin32FileTimeUtc()));
#endif // ( !SILVERLIGHT || WINDOWS_PHONE ) && !XAMARIN && !UNITY && !UNITY
                    break;
                }

                case DateTimeConversionMethod.UnixEpoc:
                {
                    Assert.That(result.Timestamp, Is.EqualTo(new Timestamp(now.UnixEpochSecondsPart, now.NanosecondsPart / 1000000 * 1000000)));
                    Assert.That(result.DateTime, Is.EqualTo(now.ToDateTime().AddSeconds(1).Subtract(TimeSpan.FromTicks(now.NanosecondsPart / 100 % 10000))));
                    Assert.That(result.DateTimeOffset, Is.EqualTo(now.ToDateTimeOffset().AddSeconds(2).Subtract(TimeSpan.FromTicks(now.NanosecondsPart / 100 % 10000))));
#if (!SILVERLIGHT || WINDOWS_PHONE) && !XAMARIN && !UNITY && !UNITY
                    Assert.That(result.FileTime, Is.EqualTo(now.Add(TimeSpan.FromSeconds(3).Subtract(TimeSpan.FromTicks(now.NanosecondsPart / 100 % 10000))).ToDateTime().ToWin32FileTimeUtc()));
#endif // ( !SILVERLIGHT || WINDOWS_PHONE ) && !XAMARIN && !UNITY && !UNITY
                    break;
                }

                case DateTimeConversionMethod.Timestamp:
                {
                    Assert.That(result.Timestamp, Is.EqualTo(now));
                    Assert.That(result.DateTime, Is.EqualTo(now.ToDateTime().AddSeconds(1)));
                    Assert.That(result.DateTimeOffset, Is.EqualTo(now.ToDateTimeOffset().AddSeconds(2)));
#if (!SILVERLIGHT || WINDOWS_PHONE) && !XAMARIN && !UNITY && !UNITY
                    Assert.That(result.FileTime, Is.EqualTo(now.Add(TimeSpan.FromSeconds(3)).ToDateTime().ToWin32FileTimeUtc()));
#endif // ( !SILVERLIGHT || WINDOWS_PHONE ) && !XAMARIN && !UNITY && !UNITY
                    break;
                }
                }
            }
        }
        private static void TestDeserializationCore(DateTimeConversionMethod kind)
        {
            var now         = Timestamp.UtcNow;
            var dateTimeNow = now.ToDateTimeOffset();

            using (var buffer = new MemoryStream())
                using (var packer = Packer.Create(buffer, PackerCompatibilityOptions.None))
                {
                    packer.PackArrayHeader(ClassHasTimestamp.MemberCount);
                    for (var i = 0; i < ClassHasTimestamp.MemberCount; i++)
                    {
                        switch (kind)
                        {
                        case DateTimeConversionMethod.Native:
                        {
                            if (i == 2)
                            {
                                // DateTimeOffset -> [long, shourt]
                                packer.PackArrayHeader(2);
                                packer.Pack(dateTimeNow.AddSeconds(i).Ticks);
                                packer.Pack(( short )0);
                            }
                            else
                            {
                                packer.Pack(dateTimeNow.AddSeconds(i).Ticks);
                            }

                            break;
                        }

                        case DateTimeConversionMethod.UnixEpoc:
                        {
                            packer.Pack(MessagePackConvert.FromDateTimeOffset(dateTimeNow.AddSeconds(i)));
                            break;
                        }

                        case DateTimeConversionMethod.Timestamp:
                        {
                            packer.PackExtendedTypeValue((now.Add(TimeSpan.FromSeconds(i)).Encode()));
                            break;
                        }

                        default:
                        {
                            Assert.Fail("Unexpected Kind");
                            break;
                        }
                        }
                    }

                    var context = new SerializationContext();
                    context.DefaultDateTimeConversionMethod = kind;

                    var serializer = context.GetSerializer <ClassHasTimestamp>();
                    buffer.Position = 0;

                    var result = serializer.Unpack(buffer);
                    switch (kind)
                    {
                    case DateTimeConversionMethod.Native:
                    {
                        Assert.That(result.Timestamp, Is.EqualTo(new Timestamp(now.UnixEpochSecondsPart, now.NanosecondsPart / 100 * 100)));
                        Assert.That(result.DateTime, Is.EqualTo(now.ToDateTime().AddSeconds(1)));
                        Assert.That(result.DateTimeOffset, Is.EqualTo(now.ToDateTimeOffset().AddSeconds(2)));
#if (!SILVERLIGHT || WINDOWS_PHONE) && !XAMARIN && !UNITY && !UNITY
                        Assert.That(result.FileTime, Is.EqualTo(now.Add(TimeSpan.FromSeconds(3).Subtract(TimeSpan.FromTicks(now.NanosecondsPart % 100))).ToDateTime().ToWin32FileTimeUtc()));
#endif // ( !SILVERLIGHT || WINDOWS_PHONE ) && !XAMARIN && !UNITY && !UNITY
                        break;
                    }

                    case DateTimeConversionMethod.UnixEpoc:
                    {
                        Assert.That(result.Timestamp, Is.EqualTo(new Timestamp(now.UnixEpochSecondsPart, now.NanosecondsPart / 1000000 * 1000000)));
                        Assert.That(result.DateTime, Is.EqualTo(now.ToDateTime().AddSeconds(1).Subtract(TimeSpan.FromTicks(now.NanosecondsPart / 100 % 10000))));
                        Assert.That(result.DateTimeOffset, Is.EqualTo(now.ToDateTimeOffset().AddSeconds(2).Subtract(TimeSpan.FromTicks(now.NanosecondsPart / 100 % 10000))));
#if (!SILVERLIGHT || WINDOWS_PHONE) && !XAMARIN && !UNITY && !UNITY
                        Assert.That(result.FileTime, Is.EqualTo(now.Add(TimeSpan.FromSeconds(3).Subtract(TimeSpan.FromTicks(now.NanosecondsPart / 100 % 10000))).ToDateTime().ToWin32FileTimeUtc()));
#endif // ( !SILVERLIGHT || WINDOWS_PHONE ) && !XAMARIN && !UNITY && !UNITY
                        break;
                    }

                    case DateTimeConversionMethod.Timestamp:
                    {
                        Assert.That(result.Timestamp, Is.EqualTo(now));
                        Assert.That(result.DateTime, Is.EqualTo(now.ToDateTime().AddSeconds(1)));
                        Assert.That(result.DateTimeOffset, Is.EqualTo(now.ToDateTimeOffset().AddSeconds(2)));
#if (!SILVERLIGHT || WINDOWS_PHONE) && !XAMARIN && !UNITY && !UNITY
                        Assert.That(result.FileTime, Is.EqualTo(now.Add(TimeSpan.FromSeconds(3)).ToDateTime().ToWin32FileTimeUtc()));
#endif // ( !SILVERLIGHT || WINDOWS_PHONE ) && !XAMARIN && !UNITY && !UNITY
                        break;
                    }
                    }
                }
        }
示例#31
0
        //[Test]
        //public void Given_searchKey_When_SearchPosts_Then_returns_single_needed_post()
        //{
        //    //Given
        //    var searchkey = "MockPost2";

        //    //When
        //    Post result = _blogRepository.SearchPosts(searchkey).Single();

        //    //Then
        //    Assert.NotNull(result);
        //    Assert.AreEqual(post2.Id, result.Id);
        //}
        //[Test]
        //public void Given_searchKey_When_SearchPosts_Then_returns_multiple_needed_post()
        //{
        //    //Given

        //    var searchkey = "MockPost";

        //    //When
        //    List<Post> result = _blogRepository.SearchPosts(searchkey);

        //    //Then
        //    Assert.NotNull(result);
        //    Assert.AreEqual(true, result.Contains(post1));
        //    Assert.AreEqual(true, result.Contains(post2));
        //}

        public void sdf(int t)
        {
            Assert.AreEqual("{t}", t.ToString());
        }