Ejemplo n.º 1
0
        public void b_deck_after_Shuffle_has_52_card_unordered()
        {
            _deck.Shuffle();
            _cards = _deck.Cards;

            _cards.FirstOrDefault().Value.Should().Not.Be.EqualTo( new Value(SuitEnum.Hearts, RankEnum.Ace));
            _cards.LastOrDefault().Value.Should().Not.Be.EqualTo(new Value(SuitEnum.Clubs, RankEnum.King));
        }
Ejemplo n.º 2
0
        public void WindowIdentityComputesCorrectly()
        {
            var indicator = new WindowIdentity(4);
            var data = new[] {1m, 10m, 100m, 1000m, 10000m, 1234m, 56789m};

            var seen = new List<decimal>();
            for (int i = 0; i < data.Length; i++)
            {
                var datum = data[i];
                seen.Add(datum);
                indicator.Update(new IndicatorDataPoint(DateTime.Now.AddSeconds(i), datum));
                Assert.AreEqual(seen.LastOrDefault(), indicator.Current.Value);
            }
        }
Ejemplo n.º 3
0
        public void InterpolatePerformance3(LineSeries.SearchType search_type)
        {
            var randNumbers = new Random(0);

            var interPoints = new List<double>();
            var valuePoints = new List<Point>();

            for (int i = 0; i < 100000; i++)
            {
                interPoints.Add(interPoints.LastOrDefault() + 100 * randNumbers.NextDouble());
            }

            for (int i = 0; i < 10000000; i++)
            {
                valuePoints.Add(new Point(valuePoints.LastOrDefault().X + randNumbers.NextDouble(), randNumbers.NextDouble()));
            }

            var series = new LineSeries(valuePoints);
            var result = series.Interpolate(interPoints, search_type).ToList();
        }
        public void Download_Error_PlaintextResponse()
        {
            var downloadUri = "http://www.sample.com";
            var chunkSize = 100;
            var responseText = "Not Found";

            var handler = new MultipleChunksMessageHandler { ErrorResponse = responseText };
            handler.StatusCode = HttpStatusCode.NotFound;
            handler.ChunkSize = chunkSize;
            // The media downloader adds the parameter...
            handler.DownloadUri = new Uri(downloadUri + "?alt=media");

            using (var service = CreateMockClientService(handler))
            {
                var downloader = new MediaDownloader(service);
                downloader.ChunkSize = chunkSize;
                IList<IDownloadProgress> progressList = new List<IDownloadProgress>();
                downloader.ProgressChanged += (p) =>
                {
                    progressList.Add(p);
                };

                var outputStream = new MemoryStream();
                downloader.Download(downloadUri, outputStream);

                var lastProgress = progressList.LastOrDefault();
                Assert.That(lastProgress.Status, Is.EqualTo(DownloadStatus.Failed));
                GoogleApiException exception = (GoogleApiException) lastProgress.Exception;
                Assert.That(exception.HttpStatusCode, Is.EqualTo(handler.StatusCode));
                Assert.That(exception.Message, Is.EqualTo(responseText));
                Assert.IsNull(exception.Error);
            }
        }
        public void Download_Error_JsonResponse()
        {
            var downloadUri = "http://www.sample.com";
            var chunkSize = 100;
            var error = new RequestError { Code = 12345, Message = "Text", Errors = new[] { new SingleError { Message = "Nested error" } } };
            var response = new StandardResponse<object> { Error = error };
            var responseText = new NewtonsoftJsonSerializer().Serialize(response);

            var handler = new MultipleChunksMessageHandler { ErrorResponse = responseText };
            handler.StatusCode = HttpStatusCode.BadRequest;
            handler.ChunkSize = chunkSize;
            // The media downloader adds the parameter...
            handler.DownloadUri = new Uri(downloadUri + "?alt=media");

            using (var service = CreateMockClientService(handler))
            {
                var downloader = new MediaDownloader(service);
                downloader.ChunkSize = chunkSize;
                IList<IDownloadProgress> progressList = new List<IDownloadProgress>();
                downloader.ProgressChanged += (p) =>
                    {
                        progressList.Add(p);
                    };

                var outputStream = new MemoryStream();
                downloader.Download(downloadUri, outputStream);

                var lastProgress = progressList.LastOrDefault();
                Assert.That(lastProgress.Status, Is.EqualTo(DownloadStatus.Failed));
                GoogleApiException exception = (GoogleApiException) lastProgress.Exception;
                Assert.That(exception.HttpStatusCode, Is.EqualTo(handler.StatusCode));
                // Just a smattering of checks - if these two pass, it's surely okay.
                Assert.That(exception.Error.Code, Is.EqualTo(error.Code));
                Assert.That(exception.Error.Errors[0].Message, Is.EqualTo(error.Errors[0].Message));
            }
        }
        /// <summary>A helper test to test sync and async downloads.</summary>
        /// <param name="chunkSize">The chunk size for each part.</param>
        /// <param name="sync">Indicates if this download should be synchronously or asynchronously.</param>
        /// <param name="cancelRequest">Defines the request index to cancel the download request.</param>
        /// <param name="downloadUri">The URI which contains the media to download.</param>
        private void Subtest_Download_Chunks(int chunkSize, bool sync = true, int cancelRequest = 0,
            string downloadUri = "http://www.sample.com")
        {
            var handler = new MultipleChunksMessageHandler(MediaContent);
            handler.StatusCode = HttpStatusCode.OK;
            handler.ChunkSize = chunkSize;
            handler.DownloadUri = new Uri(downloadUri +
                (downloadUri.Contains("?") ? "&" : "?") + "alt=media");

            // support cancellation
            if (cancelRequest > 0)
            {
                handler.CancelRequestNum = cancelRequest;
            }
            handler.CancellationTokenSource = new CancellationTokenSource();

            int expectedCalls = (int)Math.Ceiling((double) MediaContent.Length / chunkSize);
            using (var service = CreateMockClientService(handler))
            {
                var downloader = new MediaDownloader(service);
                downloader.ChunkSize = chunkSize;
                IList<IDownloadProgress> progressList = new List<IDownloadProgress>();
                downloader.ProgressChanged += (p) =>
                {
                    progressList.Add(p);
                };

                var outputStream = new MemoryStream();
                if (sync)
                {
                    downloader.Download(downloadUri, outputStream);
                }
                else
                {
                    try
                    {
                        var result = downloader.DownloadAsync(downloadUri, outputStream,
                            handler.CancellationTokenSource.Token).Result;
                        Assert.AreEqual(0, handler.CancelRequestNum);
                    }
                    catch (AggregateException ex)
                    {
                        Assert.IsInstanceOf<TaskCanceledException>(ex.InnerException);
                    }
                }

                var lastProgress = progressList.LastOrDefault();
                if (cancelRequest > 0)
                {
                    // the download was interrupted in the middle
                    Assert.That(handler.Calls, Is.EqualTo(cancelRequest));
                    // last request should fail
                    Assert.NotNull(lastProgress);
                    Assert.NotNull(lastProgress.Exception);
                    Assert.That(lastProgress.Status, Is.EqualTo(DownloadStatus.Failed));
                    Assert.That(lastProgress.BytesDownloaded, Is.EqualTo(chunkSize * cancelRequest));
                }
                else
                {
                    // the download succeeded
                    Assert.That(handler.Calls, Is.EqualTo(expectedCalls));
                    Assert.NotNull(lastProgress);
                    Assert.Null(lastProgress.Exception);
                    Assert.That(lastProgress.Status, Is.EqualTo(DownloadStatus.Completed));
                    Assert.That(lastProgress.BytesDownloaded, Is.EqualTo(MediaContent.Length));

                    byte[] actual = outputStream.ToArray();
                    CollectionAssert.AreEqual(MediaContent, actual);
                }
            }
        }
        public void Download_Error_PlaintextResponse()
        {
            using (var service = new MockClientService())
            {
                var downloader = new MediaDownloader(service);
                IList<IDownloadProgress> progressList = new List<IDownloadProgress>();
                downloader.ProgressChanged += (p) =>
                {
                    progressList.Add(p);
                };

                var outputStream = new MemoryStream();
                downloader.Download(_httpPrefix + "NotFoundPlainText", outputStream);

                var lastProgress = progressList.LastOrDefault();
                Assert.That(lastProgress.Status, Is.EqualTo(DownloadStatus.Failed));
                GoogleApiException exception = (GoogleApiException) lastProgress.Exception;
                Assert.That(exception.HttpStatusCode, Is.EqualTo(HttpStatusCode.NotFound));
                Assert.That(exception.Message, Is.EqualTo(NotFoundError));
                Assert.IsNull(exception.Error);
            }
        }
        public void Download_Error_JsonResponse()
        {
            using (var service = new MockClientService())
            {
                var downloader = new MediaDownloader(service);
                IList<IDownloadProgress> progressList = new List<IDownloadProgress>();
                downloader.ProgressChanged += (p) =>
                    {
                        progressList.Add(p);
                    };

                var outputStream = new MemoryStream();
                downloader.Download(_httpPrefix + "BadRequestJson", outputStream);

                var lastProgress = progressList.LastOrDefault();
                Assert.That(lastProgress.Status, Is.EqualTo(DownloadStatus.Failed));
                GoogleApiException exception = (GoogleApiException) lastProgress.Exception;
                Assert.That(exception.HttpStatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
                // Just a smattering of checks - if these two pass, it's surely okay.
                Assert.That(exception.Error.Code, Is.EqualTo(BadRequestError.Code));
                Assert.That(exception.Error.Errors[0].Message, Is.EqualTo(BadRequestError.Errors[0].Message));
            }
        }
        /// <summary>A helper test to test sync and async downloads.</summary>
        /// <param name="chunkSize">The chunk size for each part.</param>
        /// <param name="sync">Indicates if this download should be synchronously or asynchronously.</param>
        /// <param name="cancelChunk">Defines the chunk at which to cancel the download request.</param>
        /// <param name="target">Last component of the Uri to download</param>
        private void Subtest_Download_Chunks(int chunkSize, bool sync = true, int cancelChunk = 0, string target = "content")
        {
            string downloadUri = _httpPrefix + target;
            var cts = new CancellationTokenSource();

            using (var service = new MockClientService())
            {
                var downloader = new MediaDownloader(service);
                downloader.ChunkSize = chunkSize;
                IList<IDownloadProgress> progressList = new List<IDownloadProgress>();
                int progressUpdates = 0;
                long lastBytesDownloaded = 0;
                downloader.ProgressChanged += (p) =>
                {
                    if (p.Status != DownloadStatus.Failed)
                    {
                        // We shouldn't receive duplicate notifications for the same range.
                        Assert.That(p.BytesDownloaded, Is.GreaterThan(lastBytesDownloaded));
                    }
                    lastBytesDownloaded = p.BytesDownloaded;

                    progressList.Add(p);
                    if (++progressUpdates == cancelChunk)
                    {
                        cts.Cancel();
                    }
                };

                var outputStream = new MemoryStream();
                if (sync)
                {
                    downloader.Download(downloadUri, outputStream);
                }
                else
                {
                    try
                    {
                        var result = downloader.DownloadAsync(downloadUri, outputStream, cts.Token).Result;
                        if (result.Exception == null)
                        {
                            Assert.AreEqual(0, cancelChunk);
                        }
                        else
                        {
                            Assert.IsInstanceOf<OperationCanceledException>(result.Exception);
                        }
                    }
                    catch (AggregateException ex)
                    {
                        Assert.IsInstanceOf<TaskCanceledException>(ex.InnerException);
                    }
                }

                var lastProgress = progressList.LastOrDefault();
                if (cancelChunk > 0)
                {
                    // last request should fail
                    Assert.NotNull(lastProgress);
                    Assert.NotNull(lastProgress.Exception);
                    Assert.That(lastProgress.Status, Is.EqualTo(DownloadStatus.Failed));
                    Assert.That(lastProgress.BytesDownloaded, Is.EqualTo(chunkSize * cancelChunk));
                }
                else
                {
                    Assert.NotNull(lastProgress);
                    Assert.Null(lastProgress.Exception);
                    Assert.That(lastProgress.Status, Is.EqualTo(DownloadStatus.Completed));
                    Assert.That(lastProgress.BytesDownloaded, Is.EqualTo(MediaContent.Length));

                    byte[] actual = outputStream.ToArray();
                    CollectionAssert.AreEqual(MediaContent, actual);
                }
            }
        }
Ejemplo n.º 10
0
        private static List<string> GenerateTooltipMessages(IWebDriver driver, List<Point> graph,
            HighchartsPage page)
        {
            Actions action = new Actions(driver);

            action.MoveToElement(page.RootElement, 0, 0)
                .MoveByOffset(graph[0].X, graph[0].Y)
                .Build()
                .Perform();
            List<string> tooltip = new List<string>();
            for (int point = 1; point < graph.Count; point++)
            {
                for (int i = 0; i <= graph[point].X - graph[point - 1].X; i+=Step)
                {
                    action.MoveByOffset(Step, 0).Build().Perform();
                    if (tooltip.LastOrDefault() != page.TooltipElement.Text &&
                        page.TooltipElement.Text.Contains(HighchartsPage.EmployeeKeyword))
                    {
                        tooltip.Add(page.TooltipElement.Text);
                    }
                }
                action.MoveByOffset(0, graph[point].Y - graph[point - 1].Y)
                    .Build()
                    .Perform();
            }
            return tooltip;
        }
Ejemplo n.º 11
0
        public void Can_ChainTask_ExecuteDataSetTask() {
            var dsTasks = new List<Task<DataSet>>();

            // 테이블 정보를 로딩하는 작업 자체는 비동기로 이루어지지만, 테이블별로 순서대로 로드되도록 합니다.
            // Loading Task의 순차 실행이라 보시면 됩니다. (단 이런 작업이 설정된대로 자동으로 수행되므로, 최족 Task의 실행여부만 판단하면 됩니다.)
            //
            foreach(var section in Sections2) {
                var query = NorthwindAdoRepository.QueryProvider.GetQuery(section, QueryKey);
                Assert.IsNotEmpty(query);

                var prevTask = dsTasks.LastOrDefault();

                // ExecuteDataSet() 실행을 순서대로 수행하도록 한다.
                if(prevTask != null) {
                    var task =
                        prevTask
                            .ContinueWith(_ => NorthwindAdoRepository.ExecuteDataSetAsync(query),
                                          TaskContinuationOptions.ExecuteSynchronously)
                            .Unwrap();
                    dsTasks.Add(task);
                }
                else {
                    var task = NorthwindAdoRepository.ExecuteDataSetAsync(query);
                    dsTasks.Add(task);
                }
            }

            foreach(var task in dsTasks) {
                var dataset = task.Result;

                dataset.Tables.Count.Should().Be(1);
                dataset.Tables[0].HasErrors.Should().Be.False();

                if(IsDebugEnabled)
                    log.Debug("Table[{0}] has [{1}] rows", dataset.Tables[0].TableName, dataset.Tables[0].Rows.Count);

                dataset.Dispose();
            }
        }