Beispiel #1
0
        public void TestSynSets()
        {
            var synSets = WordNetEngine.GetSynSets("Fish").ToList();

            synSets.Should().HaveCountGreaterThan(2);

            foreach (var synSet in synSets)
            {
                TestOutputHelper.WriteLine(synSet.Gloss);
            }
        }
        private void UpdateConfigForGoogleCloudBuild()
        {
            if (Directory.GetCurrentDirectory().Contains("/workspace/"))
            {
                TestConfigValues["Postgres:ConnectionString"] =
                    "host=roadkill-postgres;port=5432;database=roadkilltests;username=roadkill;password=roadkill;";
            }

            TestOutputHelper.WriteLine($"Directory: {Directory.GetCurrentDirectory()}");
            TestOutputHelper.WriteLine($"Connection: {IntegrationTestsWebFactory.TestConfigValues["Postgres:ConnectionString"]}");
        }
Beispiel #3
0
        public override void Initialize(MethodInfo methodInfo, object[] testMethodArguments, ITestOutputHelper testOutputHelper)
        {
            base.Initialize(methodInfo, testMethodArguments, testOutputHelper);

            try
            {
                TestOutputHelper.WriteLine("Test");
                ITestOutputHelperIsInitialized = true;
            } catch { }
            SetupInvoked = true;
        }
        private void AssertOutput()
        {
            FileSystemTasks.EnsureExistingDirectory(ApprovalDirectory);
            var oldFiles = Directory.GetFiles(ApprovalDirectory, "*.tmp");

            foreach (var oldFile in oldFiles)
            {
                File.Delete(oldFile);
            }

            var fixFiles = new List <string>();
            var builder  = new StringBuilder();

            var enumerable = Directory.GetFiles(TestOutputDirectory, "*", SearchOption.AllDirectories);

            foreach (var file in enumerable)
            {
                var fileName     = Path.GetFileName(file);
                var approvalFile = ApprovalDirectory / (fileName + ".gold");
                var tempFile     = Path.ChangeExtension(approvalFile, "tmp").NotNull();
                File.Move(file, tempFile);

                string fixFile = null;
                if (!File.Exists(approvalFile))
                {
                    fixFile = CreateMoveScript(approvalFile, tempFile);
                    builder.AppendLine($"{fileName} COPY {fixFile}");
                }
                else if (!File.ReadAllText(approvalFile).Equals(File.ReadAllText(tempFile)))
                {
                    fixFile = CreateMoveScript(approvalFile, tempFile);
                    builder.AppendLine($"{fileName} COPY {fixFile}");
                    builder.AppendLine($"{fileName} COMPARE {CreateRiderComparisonScript(approvalFile, tempFile)}");
                }
                else
                {
                    File.Delete(tempFile);
                }

                if (fixFile != null)
                {
                    fixFiles.Add(fixFile);
                }
            }

            if (fixFiles.Count > 0)
            {
                TestOutputHelper.WriteLine($"COPY ALL {CreateCompositeScript(fixFiles)}");
            }

            TestOutputHelper.WriteLine(builder.ToString());

            Assert.True(fixFiles.Count == 0);
        }
Beispiel #5
0
        /// <summary>
        /// Pings the reply event handler.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="args">The <see cref="PingReplyEventArgs"/> instance containing the event data.</param>
        /// <autogeneratedoc />
        private void PingReplyEventHandler(object sender, PingReplyEventArgs args)
        {
            sender.Should().BeAssignableTo <IPingService>();

            if (args != null)
            {
                args.CancellationToken.Should().NotBeNull();
                TestOutputHelper.WriteLine(
                    $"Job: {args.PingJob.JobGuid}, TaskId: {args.PingJob.TaskId}, IPAddressSubnet: {args.PingJob.IPAddressSubnet}, Status: {args.PingReply.Status}");
            }
        }
        public async Task TestWebhook()
        {
            string requestData = File.ReadAllText(TestsConstants.Assets.AliceRequestFilePath);

            using var requestContent = new StringContent(requestData, Encoding.UTF8, "application/json");
            var response = await _httpClient.PostAsync(new Uri("alice", UriKind.Relative), requestContent).ConfigureAwait(false);

            Assert.True(response.IsSuccessStatusCode, response.ToString());
            string responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

            TestOutputHelper.WriteLine(responseContent);
        }
        protected override async Task <RunSummary> RunTestAsync()
        {
            var output = new TestOutputHelper();

            output.Initialize(this.MessageBus, new XunitTest(this.TestCase, this.DisplayName));
            var exportProvider = await TestUtilities.CreateContainerAsync(this.configuration, output);

            var containerWrapper = new TestUtilities.V3ContainerWrapper(exportProvider, this.configuration);

            this.TestMethodArguments = new object[] { containerWrapper };
            return(await base.RunTestAsync());
        }
        public void MandatoryEnding()
        {
            var fireEmoji = char.ConvertFromUtf32(0x1F525);
            var cardItem  = new AliceGalleryCardItem
            {
                Title = AliceHelper.PrepareGalleryCardItemTitle("IamShort", fireEmoji, AliceHelper.DefaultReducedStringEnding)
            };

            Assert.True(cardItem.Title.Length < AliceGalleryCardItem.MaxTitleLength);
            Assert.EndsWith(fireEmoji, cardItem.Title, StringComparison.OrdinalIgnoreCase);
            TestOutputHelper.WriteLine(cardItem.Title);
        }
        public void DhcpMessage_FormatPropertyList()
        {
            DhcpMessage dhcpRequestMessage = new DhcpMessage(_bcDenDiscoverDhcpMsgBytes, TestLoggerFactory);

            var logLevel = LogLevel.Trace;
            var sb       = new StringBuilder();

            PureLogPropertyLevel.FormatPropertyList(sb, LoggableFormat.ToLogWithParents,
                                                    dhcpRequestMessage.GetLogPropertyListLevel(logLevel, LoggableFormat.ToStringWithParents), logLevel);

            TestOutputHelper.WriteLine(sb.ToString());
        }
        public async Task <string> QuerySomethingAsync(QuerySomethingWithDelay query, CancellationToken cancellationToken)
        {
            base.HandleAsync <QuerySomethingWithDelay, string>(query);

            TestOutputHelper.WriteLine($"Query result: {query.Data}.");

            TestOutputHelper.WriteLine($"Instance #{_instanceCounter}.");

            await Task.Delay(query.DelayInMilliseconds, cancellationToken);

            return(query.Data);
        }
        public async void TestLargeNumberOfVersionsPerformance()
        {
            // Test the performance of writing and reading a single document with a large number of versions.
            //
            // CosmosDb emulator setup
            // - 2000 RU/s collection
            // - Rate limiting.
            //
            // Current performance
            // - 2nd write: 0.04 sec
            // - 1000th write: 0.04 sec
            // - Read: 0.04 sec
            //
            // The current implementation does not work when thrashed with lower RU/s due to the RU cost of
            // the read and write operations. There is a timeout waiting for retries. An improved
            // implementation should be considered to lower the cost of versioned read and write against
            // latest documents. E.g., a @latest flag would solve this issue.

            const int collectionRuLimit = 2000;
            const int numberOfVersions  = 1000;

            var configManager = new ServiceDbConfigManager("TestService");
            var dbAccess      = await CreateDbAccess(configManager, collectionRuLimit);

            var dbAccessProvider = new TestDocumentDbAccessProvider(dbAccess);

            var store = new LargeDocumentStore(dbAccessProvider);

            var attachment = JsonConvert.DeserializeObject <LargeDocument>(File.ReadAllText("TestData/LargeDocument.json"));

            var document = new SmallDocumentWithLargeAttachment();

            document.Id = Guid.NewGuid();

            Stopwatch sw = new Stopwatch();

            sw.Start();

            for (var i = 0; i < numberOfVersions; i++)
            {
                sw.Restart();

                await store.UpsertDocument(document, attachment);

                TestOutputHelper.WriteLine("Write={0}", sw.Elapsed);
            }

            var result = await store.GetSmallDocument(document.Id);

            TestOutputHelper.WriteLine("Read={0}", sw.Elapsed);

            Assert.NotNull(result);
        }
        internal void Trace(IGraphReplicaSetLowLevel replicaSet)
        {
            TestOutputHelper.WriteLine("replicaSet:");
            TestOutputHelper.WriteLine($"  InstanceCount={replicaSet.InstanceCount}, EnabledInstanceCount={replicaSet.EnabledInstanceCount}");
            for (int instance = 0; instance < replicaSet.InstanceCount; ++instance)
            {
                var graph = replicaSet.GraphInstances[instance];

                TestOutputHelper.WriteLine($"    Graph #{instance}: {graph.GraphName}");
                TestOutputHelper.WriteLine($"      IsEnabled()={replicaSet.IsEnabled(instance)}");
            }
        }
Beispiel #13
0
        public void Archive_GetArchive_Uncompressed_FromZipFile()
        {
            var archive = GetMemoryBackedArchiveFromFile("Files\\KDTree.zip");

            archive.Should().NotBeNull();

            foreach (var archiveFile in archive.Files)
            {
                archiveFile.Should().NotBeNull();
                TestOutputHelper.WriteLine(archiveFile.FullPath);
            }
        }
Beispiel #14
0
        public async Task TabControl_TabPage_IsHoveredWithMouse_IsFalse_WhenMouseIs_OutsideMainScreenAsync()
        {
            await RunTestAsync(async (form, tabControl) =>
            {
                TestOutputHelper.WriteLine($"Primary screen: {Screen.PrimaryScreen?.WorkingArea}");

                // We can't physically move the mouse outside the desktop area,
                // so the mouse cursor will be stuck at the bottom right corner of the desktop.
                bool result = await IsHoveredWithMouseAsync(form, tabControl, new(1000, 1000), assertCorrectLocation: false);

                Assert.False(result);
            });
        }
 public async Task ServiceSendsRequestWithPutVerb()
 {
     using (new MockServer(MockApiClientOptions.TestPort, string.Empty, (req, rsp, prm) =>
     {
         TestOutputHelper.WriteLine($"HttpMethod: {req.HttpMethod}");
         Assert.Equal("PUT", req.HttpMethod);
     }))
     {
         var client  = CreateClient();
         var service = new MockApiService(client);
         await service.MockPut();
     }
 }
 public void GatewayIPAddressExtensions_IPv4OrDefault()
 {
     foreach (var networkInterface in _networkingSystem.GetAllNetworkInterfaces())
     {
         if (networkInterface.GetIPProperties().GatewayAddresses.IPv4OrDefault() != null)
         {
             foreach (var unicastIpAddress in networkInterface.GetIPProperties().UnicastAddresses)
             {
                 TestOutputHelper.WriteLine($"Found IPAddress: {unicastIpAddress.Address}");
             }
         }
     }
 }
Beispiel #17
0
        public async Task Time_to_take_to_read_1000_read_head_positions()
        {
            await Store.AppendToStream("stream-1", ExpectedVersion.NoStream, CreateNewStreamMessages(1, 2, 3));

            var stopwatch = Stopwatch.StartNew();

            for (int i = 0; i < 1000; i++)
            {
                await Store.ReadHeadPosition();
            }

            TestOutputHelper.WriteLine(stopwatch.ElapsedMilliseconds.ToString());
        }
Beispiel #18
0
        public void FileExtensions_PrefixExt(string prefix, string ext)
        {
            var randomFile = FileExtensions.GetRandomFileName(prefix, ext);

            TestOutputHelper.WriteLine(randomFile);
            randomFile.Should().EndWith(ext);
            randomFile.Should().StartWith(prefix);

            var randomFile2 = FileExtensions.GetRandomFileName(prefix, ext);

            randomFile2.Should().NotBe(randomFile);
            TestOutputHelper.WriteLine(randomFile2);
        }
 protected override async Task <Tuple <decimal, string> > InvokeTestAsync(ExceptionAggregator aggregator)
 {
     using (var testLifetimeScope = _testClassLifetimeScope.BeginLifetimeScope(AutofacTestScopes.Test, builder => builder.RegisterModules(TestClass)))
     {
         TestOutputHelper testOutputHelper = testLifetimeScope.Resolve <TestOutputHelper>();
         testOutputHelper.Initialize(MessageBus, Test);
         decimal seconds = await new AutofacTestInvoker(testLifetimeScope, Test, MessageBus, TestClass, ConstructorArguments, TestMethod, TestMethodArguments,
                                                        BeforeAfterAttributes, aggregator, CancellationTokenSource).RunAsync();
         string output = testOutputHelper.Output;
         testOutputHelper.Uninitialize();
         return(Tuple.Create(seconds, output));
     }
 }
        public void Test1_JustGettingStarted_ReadingCSVfile()
        {
            // this is not a UnitTest! (we use a file)

            // Arrange
            ITestOutputHelper logger = new TestOutputHelper();
            bool firstLine           = true;

            IMappingListUuidTestData target = new MappingListUuidTestData();

            string filename = @"C:\jad\source\Pluralsight\NationalCookies-WithCache\BridgeUuid\TestData\mapnigsliste-uuid-jad.csv";
            var    result   = target.GetMappingList(filename);

            IDictionary <string, Guid> cacheDictionary = new Dictionary <string, Guid>();

            // List<UuidCacheKey>


            foreach (string line in result)
            {
                _testOutputHelper.WriteLine(line);

                // skift first line
                if (firstLine)
                {
                    firstLine = false;
                    continue;
                }

                if (!String.IsNullOrEmpty(line) || line != ";;;;")
                {
                    // lineStrings
                    string[] lineStrings = line.Split(";", StringSplitOptions.None);

                    string key   = string.Format($"{lineStrings[0]}{lineStrings[1]}{lineStrings[2]}{lineStrings[3]}");
                    string value = lineStrings[4];

                    try
                    {
                        KeyValuePair <string, Guid> sssKeyValuePair = new KeyValuePair <string, Guid>(key, new Guid(value));
                        cacheDictionary.Add(sssKeyValuePair);
                    }
                    catch (FormatException e)
                    {
                        Console.WriteLine(e);
                        _testOutputHelper.WriteLine("Skipping ... {line}");
                        // throw;
                    }
                }
            }
        }
Beispiel #21
0
        public void IsCertificateAllowedForServerAuth_RejectsCertificatesMissingServerEku(string testCertName)
        {
            var certPath = TestResources.GetCertPath(testCertName);

            TestOutputHelper.WriteLine("Loading " + certPath);
            var cert = new X509Certificate2(certPath, "testPassword");

            Assert.NotEmpty(cert.Extensions);
            var eku = Assert.Single(cert.Extensions.OfType <X509EnhancedKeyUsageExtension>());

            Assert.NotEmpty(eku.EnhancedKeyUsages);

            Assert.False(CertificateLoader.IsCertificateAllowedForServerAuth(cert));
        }
Beispiel #22
0
        private async Task <string> DownloadPackageFromFeed(string packageId, string version, string operation = "Install")
        {
            string filename;
            var    client     = new HttpClient();
            var    requestUri = UrlHelper.V2FeedRootUrl + @"Package/" + packageId + @"/" + version;

            TestOutputHelper.WriteLine("GET " + requestUri);

            var request = new HttpRequestMessage(HttpMethod.Get, requestUri);

            request.Headers.Add("user-agent", "TestAgent");
            request.Headers.Add("NuGet-Operation", operation);

            var responseMessage = await client.SendAsync(request);

            if (responseMessage.StatusCode == HttpStatusCode.OK)
            {
                try
                {
                    var contentDisposition = responseMessage.Content.Headers.ContentDisposition;
                    if (contentDisposition != null)
                    {
                        filename = contentDisposition.FileName;
                    }
                    else
                    {
                        // if file name not present set the package Id for the file name
                        filename = packageId;
                    }

                    using (var fileStream = File.Create(filename))
                    {
                        await responseMessage.Content.CopyToAsync(fileStream);
                    }
                }
                catch (Exception e)
                {
                    TestOutputHelper.WriteLine("EXCEPTION: " + e);
                    throw;
                }
            }
            else
            {
                var message = string.Format("Http StatusCode: {0}", responseMessage.StatusCode);
                TestOutputHelper.WriteLine(message);
                throw new ApplicationException(message);
            }

            return(filename);
        }
        public void DhcpMessage_With()
        {
            DhcpMessage dhcpRequestMessage = new DhcpMessage(_iPhoneRequestDhcpMsgBytes, TestLoggerFactory);

            var logLevel = LogLevel.Debug;

            using (Logger?.PushLogProperties(
                       dhcpRequestMessage.GetLogPropertyListLevel(logLevel, LoggableFormat.ToLogWithParents), logLevel))
            {
                Logger?.LogDebug("DhcpRequest_With by {LogLevel}", logLevel);
            }

            TestOutputHelper.WriteLine(Environment.NewLine + dhcpRequestMessage);
        }
Beispiel #24
0
        public async Task Can_subscribe_to_a_stream_from_end()
        {
            using (var fixture = GetFixture())
            {
                using (var store = await fixture.GetStreamStore())
                {
                    string streamId1 = "stream-1";
                    await AppendMessages(store, streamId1, 10);

                    string streamId2 = "stream-2";
                    await AppendMessages(store, streamId2, 10);

                    var receiveMessage = new TaskCompletionSource <StreamMessage>();
                    int receivedCount  = 0;
                    using (var subscription = store.SubscribeToStream(
                               streamId1,
                               StreamVersion.End,
                               (_, message, ct) =>
                    {
                        TestOutputHelper.WriteLine($"Received message {message.StreamId} {message.StreamVersion} "
                                                   + $"{message.Position}");
                        receivedCount++;
                        if (message.StreamVersion >= 11)
                        {
                            receiveMessage.SetResult(message);
                        }
                        return(Task.CompletedTask);
                    }))
                    {
                        await subscription.Started;
                        await AppendMessages(store, streamId1, 2);

                        var allMessagesPage = await store.ReadAllForwards(0, 30);

                        foreach (var streamMessage in allMessagesPage.Messages)
                        {
                            TestOutputHelper.WriteLine(streamMessage.ToString());
                        }

                        var receivedMessage = await receiveMessage.Task.WithTimeout();

                        receivedCount.ShouldBe(2);
                        subscription.StreamId.ShouldBe(streamId1);
                        receivedMessage.StreamId.ShouldBe(streamId1);
                        receivedMessage.StreamVersion.ShouldBe(11);
                        subscription.LastVersion.Value.ShouldBeGreaterThan(0);
                    }
                }
            }
        }
        private async Task <TestResponse> GetTestResponseAsync(string relativePath, HttpRequestMessage request)
        {
            TestOutputHelper.WriteLine($"Request:  {request.Method} {request.RequestUri.AbsoluteUri}");
            var stopwatch = Stopwatch.StartNew();

            using (var httpResponseMessage = await _httpClient.SendAsync(request))
            {
                var response = await TestResponse.FromHttpResponseMessageAsync(relativePath, httpResponseMessage);

                TestOutputHelper.WriteLine($"Duration: {stopwatch.ElapsedMilliseconds}ms");
                TestOutputHelper.WriteLine(response.ToString());
                return(response);
            }
        }
        public void TryGet_Malformed()
        {
            var testOutputHelper = new TestOutputHelper();

            var prov = new SpringBootEnvProvider(new XunitLoggerFactory(testOutputHelper))
            {
                SpringApplicationJson =
                    @"{""test\"":}"
            };

            prov.Load();

            Assert.Contains("SPRING_APPLICATION_JSON", testOutputHelper.Output);
        }
Beispiel #27
0
        public void AcceptsCertificateWithoutExtensions(string testCertName)
        {
            var certPath = TestResources.GetCertPath(testCertName);

            TestOutputHelper.WriteLine("Loading " + certPath);
            var cert = new X509Certificate2(certPath, "testPassword");

            Assert.Empty(cert.Extensions.OfType <X509EnhancedKeyUsageExtension>());

            new HttpsConnectionAdapter(new HttpsConnectionAdapterOptions
            {
                ServerCertificate = cert,
            });
        }
Beispiel #28
0
        public void FileExtensions_NullPrefix()
        {
            string ext = ".ext";

            var randomFile = FileExtensions.GetRandomFileName(null, ext);

            TestOutputHelper.WriteLine(randomFile);
            randomFile.Should().EndWith(ext);

            var randomFile2 = FileExtensions.GetRandomFileName(null, ext);

            TestOutputHelper.WriteLine(randomFile2);
            randomFile2.Should().NotBe(randomFile);
        }
        public void TestDhcpOptionTypeMap(byte[] dhcpMessageBytes)
        {
            DhcpMessage dhcpRequestMessage = new DhcpMessage(dhcpMessageBytes, TestLoggerFactory);

            var maxLength = dhcpRequestMessage.DhcpOptionKeys().MaxStringLength() + 2;

            foreach (var dhcpOption in dhcpRequestMessage.DhcpOptionKeys())
            {
                var dhcpOptionString = DhcpOptionTypeMap.GetDhcpOptionString(dhcpOption,
                                                                             dhcpRequestMessage.GetOptionData(dhcpOption),
                                                                             DhcpOptionTypeMap.DhcpRequestListFormat.StringCommaSeparated, Logger);

                TestOutputHelper.WriteLine($"{dhcpOption.ToString().PadWithDelim(": ", maxLength)}{dhcpOptionString}");
            }
        }
Beispiel #30
0
 public AspNetTestInvoker(
     ITest test,
     IMessageBus messageBus,
     Type testClass,
     object[] constructorArguments,
     MethodInfo testMethod,
     object[] testMethodArguments,
     IReadOnlyList <BeforeAfterTestAttribute> beforeAfterAttributes,
     ExceptionAggregator aggregator,
     CancellationTokenSource cancellationTokenSource,
     TestOutputHelper testOutputHelper)
     : base(test, messageBus, testClass, constructorArguments, testMethod, testMethodArguments, beforeAfterAttributes, aggregator, cancellationTokenSource)
 {
     _testOutputHelper = testOutputHelper;
 }