コード例 #1
0
ファイル: PwipReposTests.cs プロジェクト: royra/pwipper
        public void GetFrom_Max()
        {
            savedIds = savedIds.OrderByDescending(i => i).ToList();

            Assert.That(repos.GetNewFrom(1).Select(p => p.Id), Is.EquivalentTo(savedIds.Take(1)));
            Assert.That(repos.GetNewFrom(2).Select(p => p.Id), Is.EquivalentTo(savedIds.Take(2)));
        }
コード例 #2
0
        public void MeasureUpdatePerformance()
        {
            var subscriptions = new List<Subscription>();
            for (var typeIdIndex = 0; typeIdIndex < 20; ++typeIdIndex)
            {
                var typeId = new MessageTypeId("Abc.Foo.Events.FakeEvent" + typeIdIndex);
                for (var routingIndex = 0; routingIndex < 500; ++routingIndex)
                {
                    subscriptions.Add(new Subscription(typeId, new BindingKey(routingIndex.ToString())));
                }
            }

            var subscriptionsByTypeId = subscriptions.GroupBy(x => x.MessageTypeId).ToDictionary(x => x.Key, x => x.Select(s=>s.BindingKey).ToArray());

            _directory = new PeerDirectoryClient(_configurationMock.Object);
            _directory.Handle(new PeerStarted(_otherPeer.ToPeerDescriptor(false)));

            Console.WriteLine("Snapshot updates (add)");
            using (Measure.Throughput(subscriptions.Count))
            {
                for (var subscriptionCount = 1; subscriptionCount <= subscriptions.Count; ++subscriptionCount)
                {
                    _directory.Handle(new PeerSubscriptionsUpdated(_otherPeer.ToPeerDescriptor(false, subscriptions.Take(subscriptionCount))));
                }
            }
            Console.WriteLine("Snapshot updates (remove)");
            using (Measure.Throughput(subscriptions.Count))
            {
                for (var subscriptionCount = subscriptions.Count; subscriptionCount >= 1; --subscriptionCount)
                {
                    _directory.Handle(new PeerSubscriptionsUpdated(_otherPeer.ToPeerDescriptor(false, subscriptions.Take(subscriptionCount))));
                }
            }

            _directory = new PeerDirectoryClient(_configurationMock.Object);
            _directory.Handle(new PeerStarted(_otherPeer.ToPeerDescriptor(false)));

            Console.WriteLine("Snapshot updates per message type id (add)");
            using (Measure.Throughput(subscriptions.Count))
            {
                foreach (var subscriptionGroup in subscriptionsByTypeId)
                {
                    _directory.Handle(new PeerSubscriptionsForTypesUpdated(_otherPeer.Id, DateTime.UtcNow, subscriptionGroup.Key, subscriptionGroup.Value));
                }
            }
            Console.WriteLine("Snapshot updates per message type id (remove)");
            using (Measure.Throughput(subscriptions.Count))
            {
                foreach (var subscriptionGroup in subscriptionsByTypeId)
                {
                    _directory.Handle(new PeerSubscriptionsForTypesUpdated(_otherPeer.Id, DateTime.UtcNow, subscriptionGroup.Key));
                }
            }
        }
コード例 #3
0
ファイル: getting.cs プロジェクト: czcz1024/EventStore
        protected override void Given()
        {
            Events = new List<object>
            {
                new {EventId = Guid.NewGuid(), EventType = "event-type", Data = new {A = "1"}},
                new {EventId = Guid.NewGuid(), EventType = "event-type", Data = new {B = "2"}},
                new {EventId = Guid.NewGuid(), EventType = "event-type", Data = new {C = "3"}},
                new {EventId = Guid.NewGuid(), EventType = "event-type", Data = new {D = "4"}}
            };

            var response = MakeArrayEventsPost(
                         TestStream,
                         Events.Take(NumberOfEventsToCreate ?? Events.Count),
                         _admin);
            Assert.AreEqual(HttpStatusCode.Created, response.StatusCode);

            GroupName = Guid.NewGuid().ToString();
            SubscriptionPath = string.Format("/subscriptions/{0}/{1}", TestStream.Substring(9), GroupName);
            response = MakeJsonPut(SubscriptionPath,
                new
                {
                    ResolveLinkTos = true,
                    MessageTimeoutMilliseconds = 10000,
                },
                _admin);
            Assert.AreEqual(HttpStatusCode.Created, response.StatusCode);
        }
コード例 #4
0
ファイル: Fixture.cs プロジェクト: marchlud/nhibernate-core
		public void UsingFiltersIsThreadSafe()
		{
			var errors = new List<Exception>();
			var threads = new List<Thread>();
			for (int i = 0; i < 50; i++)
			{
				var thread = new Thread(() =>
				{
					try
					{
						ScenarioRunningWithMultiThreading();
					}
					catch (Exception ex)
					{
						lock (errors)
							errors.Add(ex);
					}
				});
				thread.Start();
				threads.Add(thread);
			}

			foreach (var thread in threads)
			{
				thread.Join();
			}

			Console.WriteLine("Detected {0} errors in threads. Displaying the first three (if any):", errors.Count);
			foreach (var exception in errors.Take(3))
				Console.WriteLine(exception);

			Assert.AreEqual(0, errors.Count, "number of threads with exceptions");
		}
コード例 #5
0
        public void be_able_to_read_all_one_by_one_and_return_empty_slice_at_last()
        {
            const string stream = "read_all_events_backward_should_be_able_to_read_all_one_by_one_and_return_empty_slice_at_last";
            using (var store = EventStoreConnection.Create())
            {
                store.Connect(Node.TcpEndPoint);
                var create = store.CreateStreamAsync(stream, false, new byte[0]);
                Assert.DoesNotThrow(create.Wait);

                var testEvents = Enumerable.Range(0, 5).Select(x => new TestEvent((x + 1).ToString())).ToArray();

                var write = store.AppendToStreamAsync(stream, ExpectedVersion.EmptyStream, testEvents);
                Assert.DoesNotThrow(write.Wait);

                var all = new List<RecordedEvent>();
                var position = Position.End;
                AllEventsSlice slice;

                while ((slice = store.ReadAllEventsBackward(position, 1)).Events.Any())
                {
                    all.Add(slice.Events.Single());
                    position = slice.Position;
                }

                Assert.That(TestEventsComparer.Equal(testEvents.Reverse().ToArray(), all.Take(testEvents.Length).ToArray()));
            }
        }
コード例 #6
0
        public void IsValidHandShouldThrowAnExceptionIfCountOfTheCardsInTheHandIsNotExactly5(int count)
        {
            var cards = new List<ICard>() { new Card(CardFace.King, CardSuit.Spades), new Card(CardFace.Three, CardSuit.Clubs), new Card(CardFace.Two, CardSuit.Clubs), new Card(CardFace.Queen, CardSuit.Spades), new Card(CardFace.King, CardSuit.Diamonds), new Card(CardFace.King, CardSuit.Spades), new Card(CardFace.Three, CardSuit.Clubs), new Card(CardFace.Two, CardSuit.Clubs), new Card(CardFace.Queen, CardSuit.Spades), new Card(CardFace.King, CardSuit.Diamonds) };
            var hand = new Hand(cards.Take(count).ToList());
            var checker = new PokerHandsChecker();

            checker.IsValidHand(hand);
        }
コード例 #7
0
ファイル: PwipReposTests.cs プロジェクト: royra/pwipper
        public void GetFrom_StartId()
        {
            savedIds = savedIds.OrderByDescending(i => i).ToList();

            var firstTwo = repos.GetNewFrom(2).Select(p => p.Id);
            Assert.That(firstTwo, Is.EquivalentTo(savedIds.Take(2)));
            var nextTwo = repos.GetNewFrom(2, firstTwo.Min()).Select(p => p.Id);
            Assert.That(nextTwo, Is.EquivalentTo(savedIds.Skip(2).Take(2)));
        }
コード例 #8
0
ファイル: ControlTests.cs プロジェクト: KiraTanaka/VK
 public void FindTop10VideoFriends_EmptyFieldVideo()
 {
     List<Video> listVideo = new List<Video>();
     listVideo = FillingListVideo(listVideo);
     listVideo.Add(new Video { Vid = 0, OwnerId = 0, Views = 0 });
     List<Video> listVideoResult = new List<Video>();
     listVideoResult = listVideo.Take(10).ToList();
     Assert.AreEqual(listVideoResult, control.FindTop10Video(listVideo));
 }
コード例 #9
0
ファイル: ControlTests.cs プロジェクト: KiraTanaka/VK
 public void FindTop10VideoFriends_VideoIsNull()
 {
     List<Video> listVideo = new List<Video>();
     listVideo = FillingListVideo(listVideo);
     listVideo.Add(null);
     listVideo.Add(new Video { Vid = 82474, OwnerId = 924898, Views = 987654 });
     List<Video> listVideoResult = new List<Video>();
     listVideoResult.Add(listVideo[11]);
     listVideoResult.AddRange(listVideo.Take(9).ToList());
     Assert.AreEqual(listVideoResult, control.FindTop10Video(listVideo));
 }
		public void TestFixtureSetUp()
		{
			var jsonPages = File.ReadAllText("~/AppData/Pages.json".MapProjectPath());
	
			Pages = JsonSerializer.DeserializeFromString<List<Page>>(jsonPages);

			SearchResponse = new SearchResponse {
				Query = "OrmLite",
				Results = Pages.Take(5).ToList(),
			};
		}
コード例 #11
0
ファイル: TestEvolution.cs プロジェクト: stefc/evogate
        public void TestXorEvolution()
        {
            Func<BitArray,double> fitness = (chromosome) =>
            {
                Wiring wiring = new Wiring(2,1,4, chromosome);

                FPGA xorGate = new FPGA(wiring);

                double total = 0.0;
                if(!xorGate.Output(CreateInput(false,false))[0]) total += 1.0;
                if(!xorGate.Output(CreateInput(true,true))[0])	total += 1.0;
                if(xorGate.Output(CreateInput(true,false))[0]) total += 1.0;
                if(xorGate.Output(CreateInput(false,true))[0]) total += 1.0;
                if(total == 0.0) return 0.0;

                return 4.0 / total;
            };

            Random rnd = new Random();

            Func<BitArray> init = () =>
            {
                BitArray result = new BitArray(Wiring.CalcLength(2,1,4));
                for(int i=0; i<result.Length; i++)
                {
                    if(rnd.NextDouble()<0.5)
                        result[i]=true;
                }
                return result;
            };

            Evolution evo = new Evolution(fitness,0.001, new int[]{
                0,2,4,6,8,10,12,14,
                16,19,22,25,
                28,30,32, 34,36, 38});

            int n = 100;
            IList<BitArray> population = new List<BitArray>(n);
            for(int i=0; i<n; i++)
                population.Add(init());

            population = evo.Run(population, (generation,error) => {
                return
                    (generation > 1000); // || (error > 0.99);
            });

            foreach(BitArray wiring in population.Take(10))
            {
                Wiring temp = new Wiring(2,1,4,wiring);
                Console.WriteLine (temp.ToString());
                Console.WriteLine (fitness(wiring));
            }
        }
コード例 #12
0
        public void TestSkip()
        {
            var s = new List<string> { "one", "two", "three" };

            var list = s.Take(3).Take(5).ToList();

            var query = _collection.AsQueryable<C>().Skip(5);

            var selectQuery = (SelectQuery)MongoQueryTranslator.Translate(query);
            Assert.AreEqual(5, selectQuery.Skip);
            Assert.IsNull(selectQuery.Take);
        }
コード例 #13
0
        public void be_able_to_read_all_one_by_one_until_end_of_stream()
        {
            var all = new List<RecordedEvent>();
            var position = Position.End;
            AllEventsSlice slice;

            while (!(slice = _conn.ReadAllEventsBackwardAsync(position, 1, false).Result).IsEndOfStream)
            {
                all.Add(slice.Events.Single().Event);
                position = slice.NextPosition;
            }

            Assert.That(EventDataComparer.Equal(_testEvents.Reverse().ToArray(), all.Take(_testEvents.Length).ToArray()));
        }
コード例 #14
0
        public void be_able_to_read_events_slice_at_time()
        {
            var all = new List<RecordedEvent>();
            var position = Position.End;
            AllEventsSlice slice;

            while (!(slice = _conn.ReadAllEventsBackwardAsync(position, 5, false).Result).IsEndOfStream)
            {
                all.AddRange(slice.Events.Select(x => x.Event));
                position = slice.NextPosition;
            }

            Assert.That(EventDataComparer.Equal(_testEvents.Reverse().ToArray(), all.Take(_testEvents.Length).ToArray()));
        }
コード例 #15
0
        public void Delete_Should_Remove_Multiple_Items(ICompoundKeyRepository<User, string, int> repository)
        {
            IList<User> users = new List<User>
                                        {
                                            new User { Username = "******", Age = 11, FullName = "Test User - 11" },
                                            new User { Username = "******", Age = 21, FullName = "Test User - 21" },
                                            new User { Username = "******", Age = 11, FullName = "Test User  2- 11" },
                                        };

            repository.Add(users);
            var items = repository.GetAll().ToList();
            items.Count().ShouldEqual(3);

            repository.Delete(users.Take(2));
            items = repository.GetAll().ToList();
            items.Count().ShouldEqual(1);
            items.First().Username.ShouldEqual("Test User 2");
        }
コード例 #16
0
        public void Delete_Should_Remove_Multiple_Items(IRepository<Contact, string> repository)
        {
            IList<Contact> contacts = new List<Contact>
                                        {
                                            new Contact {Name = "Contact 1"},
                                            new Contact {Name = "Contact 2"},
                                            new Contact {Name = "Contact 3"},
                                        };

            repository.Add(contacts);
            var items = repository.GetAll().ToList();
            items.Count().ShouldEqual(3);

            repository.Delete(contacts.Take(2));
            items = repository.GetAll().ToList();
            items.Count().ShouldEqual(1);
            items.First().Name.ShouldEqual("Contact 3");
        }
コード例 #17
0
        public void Update_Should_Update_Multiple_Items(ICompoundKeyRepository<User, string, int> repository)
        {
            var users = new List<User>
                                        {
                                            new User { Username = "******", Age = 11, FullName = "Test User - 11" },
                                            new User { Username = "******", Age = 21, FullName = "Test User - 21" },
                                            new User { Username = "******", Age = 11, FullName = "Test User  2- 11" },
                                        };

            repository.Add(users);
            var items = repository.GetAll().ToList();
            items.Count().ShouldEqual(3);

            foreach (var user in users.Take(2))
            {
                user.FullName += "UPDATED";
            }

            repository.Update(users);
            items = repository.GetAll().ToList();
            items.Count(x => x.FullName.EndsWith("UPDATED")).ShouldEqual(2);
        }
コード例 #18
0
        public void Update_Should_Update_Multiple_Items(IRepository<Contact, string> repository)
        {
            IList<Contact> contacts = new List<Contact>
                                        {
                                            new Contact {Name = "Contact 1"},
                                            new Contact {Name = "Contact 2"},
                                            new Contact {Name = "Contact 3"},
                                        };

            repository.Add(contacts);
            var items = repository.GetAll().ToList();
            items.Count().ShouldEqual(3);

            foreach (var contact in contacts.Take(2))
            {
                contact.Name += "UPDATED";
            }

            repository.Update(contacts);
            items = repository.GetAll().ToList();
            items.Count(x => x.Name.EndsWith("UPDATED")).ShouldEqual(2);
        }
コード例 #19
0
ファイル: TakeTests.cs プロジェクト: barisertekin/LINQlone
        public void TakeQueryReuse()
        {
            List<int> data = new List<int> { 1, 2, 3 };
            IEnumerable<int> enumerable = data.Take(2);

            enumerable.AssertEqual(1, 2);

            data.Insert(0, 0);
            enumerable.AssertEqual(0, 1);
        }
コード例 #20
0
        public void Split_DefersExecution()
        {
            // ReSharper disable PossibleMultipleEnumeration
            var source = new List<int>();

            var query = source.Split(3);

            source.AddRange(new[] { 1, 2, 3, 4, 5, 6, 7 });

            var result = query.ToList();

            Assert.That(result.Count, Is.EqualTo(3));
            CollectionAssert.AreEqual(result[0], source.Take(3));
            CollectionAssert.AreEqual(result[1], source.Skip(3).Take(3));
            CollectionAssert.AreEqual(result[2], source.Skip(6).Take(3));
            CollectionAssert.AreEqual(result.SelectMany(group => group.ToList()), source);

            source.AddRange(new[] { 8, 9, 10 });

            result = query.ToList();

            Assert.That(result.Count, Is.EqualTo(4));
            CollectionAssert.AreEqual(result[0], source.Take(3));
            CollectionAssert.AreEqual(result[1], source.Skip(3).Take(3));
            CollectionAssert.AreEqual(result[2], source.Skip(6).Take(3));
            CollectionAssert.AreEqual(result[3], source.Skip(9).Take(3));
            CollectionAssert.AreEqual(result.SelectMany(group => group.ToList()), source);
            // ReSharper restore PossibleMultipleEnumeration
        }
コード例 #21
0
        public void SuccessfulProcessTest1()
        {
            // Arrange
            var container = new UnityContainer();

            var appender = new log4net.Appender.ConsoleAppender { Layout = new log4net.Layout.SimpleLayout() };
            log4net.Config.BasicConfigurator.Configure(appender);

            var logger = LogManager.GetLogger(typeof(IncomingTransactionProcessorTests));

            container.RegisterInstance(logger);

            var sessionId = Guid.NewGuid();

            var mockService = new Mock<IClientService>(MockBehavior.Strict);
            mockService.Setup(s => s.GetLastProcessedTransactionId(sessionId)).Returns(default(string));
            container.RegisterInstance(mockService.Object);

            var mockRpcClient = new Mock<IRpcClient>(MockBehavior.Strict);

            var transactions = new List<Transaction>
                {
                    new Transaction
                        {
                            Account = "100",
                            Address = "address",
                            Amount = 50m,
                            Category = "receive",
                            Confirmations = 1,
                            Time = DateTime.UtcNow.AddMinutes(-11),
                            TransactionId = "1000"
                        },
                    new Transaction
                        {
                            Account = "101",
                            Address = "address",
                            Amount = 75m,
                            Category = "receive",
                            Confirmations = 1,
                            Time = DateTime.UtcNow.AddMinutes(-10),
                            TransactionId = "1001"
                        },
                };

            mockRpcClient.Setup(r => r.GetTransactions(null, 1000, 0)).Returns(transactions.Take(1).ToList());
            ////mockRpcClient.Setup(r => r.GetTransactions(null, 12, 0)).Returns(transactions.Take(2).ToList());
            ////mockRpcClient.Setup(r => r.GetTransactions(null, 14, 0)).Returns(transactions.Take(2).ToList());
            container.RegisterInstance(mockRpcClient.Object);

            var processor = new Mock<IncomingTransactionProcessor>() { CallBase = true };
            processor.Setup(p => p.Process(sessionId, It.IsAny<Transaction>()));
            container.BuildUp(processor.Object);

            // Act
            processor.Object.Process(sessionId);

            // Assert
            mockService.Verify(s => s.GetLastProcessedTransactionId(sessionId), Times.Once());
            mockRpcClient.Verify(r => r.GetTransactions(null, 1000, 0), Times.Once());
            ////mockRpcClient.Verify(r => r.GetTransactions(null, 12, 0), Times.Once());
            ////mockRpcClient.Verify(r => r.GetTransactions(null, 14, 0), Times.Once());
            processor.Verify(p => p.Process(sessionId, It.IsAny<Transaction>()), Times.Exactly(1));
        }
        public void be_able_to_read_events_slice_at_time()
        {
            const string stream = "read_all_events_backward_should_be_able_to_read_events_slice_at_time";
            using (var store = EventStoreConnection.Create())
            {
                store.Connect(_node.TcpEndPoint);
                var create = store.CreateStreamAsync(stream, Guid.NewGuid(), false, new byte[0]);
                Assert.DoesNotThrow(create.Wait);

                var testEvents = Enumerable.Range(0, 10).Select(x => TestEvent.NewTestEvent((x + 1).ToString())).ToArray();

                var write = store.AppendToStreamAsync(stream, ExpectedVersion.EmptyStream, testEvents);
                Assert.DoesNotThrow(write.Wait);

                var all = new List<RecordedEvent>();
                var position = Position.End;
                AllEventsSlice slice;

                while ((slice = store.ReadAllEventsBackward(position, 5, false)).Events.Any())
                {
                    all.AddRange(slice.Events.Select(x => x.Event));
                    position = slice.NextPosition;
                }

                Assert.That(EventDataComparer.Equal(testEvents.Reverse().ToArray(), all.Take(testEvents.Length).ToArray()));
            }
        }
コード例 #23
0
 public void InputSizeIncorrect(List<object> samples, List<double> labels)
 {
     new FakeAlgorithm(samples, labels.Take(2));
 }
コード例 #24
0
        public void DCAwareRoundRobinPolicyTestInParallel()
        {
            byte hostLength = 6;
            var hostList = new List<Host>();
            hostList.AddRange(GetHostList(1, 1, "remote1"));
            hostList.AddRange(GetHostList(1, 1, "remote2"));
            hostList.AddRange(GetHostList((byte)(hostLength - 3)));
            hostList.AddRange(GetHostList(1, 2, "remote1"));

            var clusterMock = new Mock<ICluster>();
            clusterMock
                .Setup(c => c.AllHosts())
                .Returns(hostList);

            //Initialize the balancing policy
            var policy = new DCAwareRoundRobinPolicy("local", 1);
            policy.Initialize(clusterMock.Object);

            Action action = () =>
            {
                var resultingHosts = new List<Host>();
                var hostEnumerator = policy.NewQueryPlan(new SimpleStatement());
                foreach (var h in hostEnumerator)
                {
                    //Slow down to try to execute it at the same time
                    Thread.Sleep(50);
                    resultingHosts.Add(h);
                }
                //The first hosts should be local
                Assert.True(resultingHosts.Take(hostLength-3).All(h => h.Datacenter == "local"));
                //It should return the local hosts first and then 1 per each dc
                Assert.AreEqual(hostLength - 1, resultingHosts.Count);
                Assert.AreEqual(hostLength - 1, resultingHosts.Distinct().Count());
            };

            var actions = new List<Action>();
            for (var i = 0; i < 100; i++)
            {
                actions.Add(action);
            }

            var parallelOptions = new ParallelOptions();
            parallelOptions.TaskScheduler = new ThreadPerTaskScheduler();
            parallelOptions.MaxDegreeOfParallelism = 1000;

            Parallel.Invoke(parallelOptions, actions.ToArray());
            clusterMock.Verify();
        }
コード例 #25
0
        public void Trim_GivenTrimValue_WhenTrimValueSmallerThanBufferedAmount_ShouldTrimOldest()
        {
            //---------------Set up test pack-------------------
            var sut = Create();
            var howMany = RandomValueGen.GetRandomInt(4, 8);
            var ids = new List<long>();
            for (var i = 0; i < howMany; i++)
                ids.Add(sut.Buffer(RandomValueGen.GetRandomString(10, 10)));
            ids.Reverse();
            var expected = ids.Take(2).ToArray();
            //---------------Assert Precondition----------------
            Assert.AreEqual(howMany, GetCurrentlyBufferedItemsIn(sut.ConnectionString).Count);

            //---------------Execute Test ----------------------
            sut.Trim(2);

            //---------------Test Result -----------------------
            var remaining = GetCurrentlyBufferedItemsIn(sut.ConnectionString);
            Assert.AreEqual(2, remaining.Count);
            var reaminingIds = remaining.Select(r => r.Id).ToArray();
            CollectionAssert.AreEquivalent(expected, reaminingIds);
        }
コード例 #26
0
        public void TestPullerChangedEvent()
        {
            if (!Boolean.Parse((string)Runtime.Properties["replicationTestsEnabled"]))
            {
                Assert.Inconclusive("Replication tests disabled.");
                return;
            }
            var docIdTimestamp = Convert.ToString(Runtime.CurrentTimeMillis());
            var doc1Id = string.Format("doc1-{0}", docIdTimestamp);
            var doc2Id = string.Format("doc2-{0}", docIdTimestamp);           
            AddDocWithId(doc1Id, "attachment.png");
            AddDocWithId(doc2Id, "attachment2.png");

            var pull = database.CreatePullReplication(GetReplicationURL());
            List<ReplicationStatus> statusHistory = new List<ReplicationStatus>();

            pull.Changed += (sender, e) => 
            {
                statusHistory.Add(e.Source.Status);
                if(e.Source.ChangesCount > 0 && e.Source.CompletedChangesCount != e.Source.ChangesCount) {
                    Assert.AreEqual(ReplicationStatus.Active, e.Source.Status);
                }

                if(e.Source.Status == ReplicationStatus.Stopped) {
                    Assert.AreNotEqual(0, e.Source.CompletedChangesCount);
                    Assert.AreEqual(e.Source.ChangesCount, e.Source.CompletedChangesCount);
                }
            };

            RunReplication(pull);

            foreach (var status in statusHistory.Take(statusHistory.Count - 1)) {
                Assert.AreEqual(ReplicationStatus.Active, status);
            }
                
            Assert.AreEqual(ReplicationStatus.Stopped, statusHistory[statusHistory.Count - 1]);

            doc1Id = string.Format("doc3-{0}", docIdTimestamp);
            doc2Id = string.Format("doc4-{0}", docIdTimestamp);           
            AddDocWithId(doc1Id, "attachment.png");
            AddDocWithId(doc2Id, "attachment2.png");
            pull = database.CreatePullReplication(GetReplicationURL());
            pull.Continuous = true;
            statusHistory.Clear();
            var doneEvent = new ManualResetEventSlim();

            pull.Changed += (sender, e) => 
            {
                statusHistory.Add(e.Source.Status);
                if(e.Source.ChangesCount > 0 && e.Source.CompletedChangesCount != e.Source.ChangesCount) {
                    Assert.AreEqual(ReplicationStatus.Active, e.Source.Status);
                }

                if(e.Source.Status == ReplicationStatus.Idle) {
                    Assert.AreNotEqual(0, e.Source.CompletedChangesCount);
                    Assert.AreEqual(e.Source.ChangesCount, e.Source.CompletedChangesCount);
                    doneEvent.Set();
                } else if(e.Source.Status == ReplicationStatus.Stopped) {
                    doneEvent.Set();
                }
            };

            pull.Start();
            Assert.IsTrue(doneEvent.Wait(TimeSpan.FromSeconds(60)));
            Assert.IsNull(pull.LastError);
            foreach (var status in statusHistory.Take(statusHistory.Count - 1)) {
                Assert.AreEqual(ReplicationStatus.Active, status);
            }

            Assert.AreEqual(ReplicationStatus.Idle, statusHistory[statusHistory.Count - 1]);
            doneEvent.Reset();

            statusHistory.Clear();
            doc1Id = string.Format("doc5-{0}", docIdTimestamp);         
            AddDocWithId(doc1Id, "attachment.png");

            Assert.IsTrue(doneEvent.Wait(TimeSpan.FromSeconds(60)));
            Assert.IsNull(pull.LastError);
            foreach (var status in statusHistory.Take(statusHistory.Count - 1)) {
                Assert.AreEqual(ReplicationStatus.Active, status);
            }

            Assert.AreEqual(ReplicationStatus.Idle, statusHistory[statusHistory.Count - 1]);
            doneEvent.Reset();
            statusHistory.Clear();
            pull.Stop();
            Assert.IsTrue(doneEvent.Wait(TimeSpan.FromSeconds(60)));
            Assert.IsNull(pull.LastError);

            Assert.AreEqual(2, statusHistory.Count);
            Assert.AreEqual(ReplicationStatus.Active, statusHistory.First());
            Assert.AreEqual(ReplicationStatus.Stopped, statusHistory[1]);
        }
コード例 #27
0
        public void CacheStore_MultipleUris_StoresAll()
        {
            // Arrange

            var servers = new List<Uri>
            {
                Uri1,
                Uri2
            };

            var provider = new DefaultVersionProvider();

            // Act

            provider.CacheStore(servers, Version45);

            // Assert

            var result = provider.CacheLookup(servers.Take(1));
            Assert.AreEqual(Version45, result);

            result = provider.CacheLookup(servers.Skip(1));
            Assert.AreEqual(Version45, result);
        }
コード例 #28
0
    public async Task Test_CRUD ()
    {
      foreach (var evt in await _calDavDataAccess.GetEvents (null))
        await _calDavDataAccess.DeleteEntity (evt.Id);

      var entitiesWithVersion = new List<EntityIdWithVersion<Uri, string>>();

      var uids = new List<string>();

      for (int i = 1; i <= 5; i++)
      {
        var iCalendar = CreateEntity (i);
        uids.Add (iCalendar.Events[0].UID);
        entitiesWithVersion.Add (
            await _calDavDataAccess.CreateEntity (
                SerializeCalendar (
                    iCalendar)));
      }

      var queriedEntitesWithVersion = await _calDavDataAccess.GetEvents (new DateTimeRange (DateTime.Now.AddDays (150), DateTime.Now.AddDays (450)));

      Assert.That (queriedEntitesWithVersion.Count, Is.EqualTo (3));

      CollectionAssert.IsSubsetOf (
          queriedEntitesWithVersion.Select (e => e.Id),
          entitiesWithVersion.Select (e => e.Id));

      var updatedCalendar = CreateEntity (600);
      updatedCalendar.Events[0].UID = uids[1];
      var updated = await _calDavDataAccess.UpdateEntity (entitiesWithVersion[1].Id, SerializeCalendar (updatedCalendar));

      Assert.That (
          (await _calDavDataAccess.GetEvents (new DateTimeRange (DateTime.Now.AddDays (150), DateTime.Now.AddDays (450)))).Count,
          Is.EqualTo (2));

      var updatedRevertedCalendar = CreateEntity (2);
      updatedRevertedCalendar.Events[0].UID = uids[1];
      var updateReverted = await _calDavDataAccess.UpdateEntity (updated.Id, SerializeCalendar (updatedRevertedCalendar));

      Assert.That (
          (await _calDavDataAccess.GetEvents (new DateTimeRange (DateTime.Now.AddDays (150), DateTime.Now.AddDays (450)))).Count,
          Is.EqualTo (3));

      await _calDavDataAccess.DeleteEntity (updateReverted.Id);

      Assert.That (
          (await _calDavDataAccess.GetEvents (new DateTimeRange (DateTime.Now.AddDays (150), DateTime.Now.AddDays (450)))).Count,
          Is.EqualTo (2));

      var entites = await _calDavDataAccess.GetEntities (entitiesWithVersion.Take (4).Select (e => e.Id));

      if (!DeletedEntitesAreJustMarkedAsDeletedAndStillAvailableViaCalendarMultigetReport)
      {
        Assert.That (entites.Count, Is.EqualTo (3)); // Only 3, the second was deleted

        CollectionAssert.AreEquivalent (
            entites.Select (e => DeserializeCalendar (e.Entity).Events[0].Summary),
            new[] { "Event1", "Event3", "Event4" });
      }
      else
      {
        CollectionAssert.AreEquivalent (
            entites.Select (e => DeserializeCalendar (e.Entity).Events[0].Summary),
            new[] { "Event1", "Event2", "Event3", "Event4" });
      }
    }
コード例 #29
0
        public void TestPusherChangedEvent()
        {
            if (!Boolean.Parse((string)GetProperty("replicationTestsEnabled")))
            {
                Assert.Inconclusive("Replication tests disabled.");
                return;
            }
                
            using (var remoteDb = _sg.CreateDatabase(TempDbName())) {
                CreateDocuments(database, 2);
                var push = database.CreatePushReplication(remoteDb.RemoteUri);
                List<ReplicationStatus> statusHistory = new List<ReplicationStatus>();

                push.Changed += (sender, e) =>
                {
                    statusHistory.Add(e.Status);
                    if (e.ChangesCount > 0 && e.CompletedChangesCount != e.ChangesCount) {
                        Assert.AreEqual(ReplicationStatus.Active, e.Status);
                    }

                    if (e.Status == ReplicationStatus.Stopped) {
                        Assert.AreNotEqual(0, e.CompletedChangesCount);
                        Assert.AreEqual(e.ChangesCount, e.CompletedChangesCount);
                    }
                };

                RunReplication(push);
                Sleep(1000);

                Assert.IsNull(push.LastError);
                foreach (var status in statusHistory.Take(statusHistory.Count - 1)) {
                    Assert.AreEqual(ReplicationStatus.Active, status);
                }

                Assert.AreEqual(ReplicationStatus.Stopped, statusHistory[statusHistory.Count - 1]);

                CreateDocuments(database, 2);
                push = database.CreatePushReplication(remoteDb.RemoteUri);
                push.Continuous = true;
                statusHistory.Clear();
                var doneEvent = new ManualResetEventSlim();

                push.Changed += (sender, e) =>
                {
                    statusHistory.Add(e.Status);
                    if(e.Status == ReplicationStatus.Idle && e.ChangesCount == e.CompletedChangesCount) {
                        doneEvent.Set();
                    }
                };

                push.Start();
                Assert.IsTrue(doneEvent.Wait(TimeSpan.FromSeconds(60)));
                Assert.IsNull(push.LastError);
                foreach (var status in statusHistory.Take(statusHistory.Count - 1)) {
                    Assert.AreEqual(ReplicationStatus.Active, status);
                }

                Assert.AreEqual(ReplicationStatus.Idle, statusHistory[statusHistory.Count - 1]);
                doneEvent.Reset();

                statusHistory.Clear();
                CreateDocuments(database, 1);

                Assert.IsTrue(doneEvent.Wait(TimeSpan.FromSeconds(60)));
                Assert.IsNull(push.LastError);
                foreach (var status in statusHistory.Take(statusHistory.Count - 1)) {
                    Assert.IsTrue(status == ReplicationStatus.Active || status == ReplicationStatus.Idle);
                }

                Assert.AreEqual(ReplicationStatus.Idle, statusHistory[statusHistory.Count - 1]);

                doneEvent.Reset();
                statusHistory.Clear();
                StopReplication(push);

                Assert.AreEqual(2, statusHistory.Count);
                Assert.AreEqual(ReplicationStatus.Active, statusHistory.First());
                Assert.AreEqual(ReplicationStatus.Stopped, statusHistory[1]);
            }
        }
コード例 #30
0
        public void TestSimpleFieldRemoval(
			[Values(VersionToleranceLevel.Exact, VersionToleranceLevel.FieldRemoval, VersionToleranceLevel.FieldAdditionAndRemoval)] VersionToleranceLevel versionToleranceLevel)
        {
            var fields = new List<Tuple<string, Type>>();
            fields.Add(Tuple.Create(Field1Name, typeof(int)));
            fields.Add(Tuple.Create(Field2Name, typeof(int)));
            testsOnDomain1.BuildTypeOnAppDomain(TypeName, fields, false);
            var field1Check = new FieldCheck(Field1Name, 667);
            testsOnDomain1.SetValueOnAppDomain(field1Check);
            testsOnDomain1.SetValueOnAppDomain(new FieldCheck(Field2Name, 668));
            var data = testsOnDomain1.SerializeOnAppDomain();

            testsOnDomain2.BuildTypeOnAppDomain(TypeName, fields.Take(1).ToArray(), true);

            TestDelegate deserialization = () => testsOnDomain2.DeserializeOnAppDomain(data, new [] { field1Check }, GetSettings(versionToleranceLevel));
            if(versionToleranceLevel == VersionToleranceLevel.Exact)
            {
                Assert.Throws<InvalidOperationException>(deserialization);
            }
            else
            {
                deserialization();
            }
        }