Example #1
0
    public static void StringAsserts()
    {
        StringAssert.Clear();

        String a = "Primeira contem Segunda";
        String b = "Segunda";
        String c = "segunda";
        String d = "Primeira";

        // Define a regular expression for repeated words.
        Regex  rx  = new Regex(@"\b(?<word>\w+)\s+(\k<word>)\b", RegexOptions.Compiled | RegexOptions.IgnoreCase);
        String reg = "The dog dog lazy fog";

        StringAssert.Contains(a, b);
        StringAssert.Contains(a, c);

        StringAssert.EndsWith(a, b);
        StringAssert.EndsWith(a, c);

        StringAssert.StartsWith(a, d);
        StringAssert.StartsWith(a, c);

        StringAssert.DoesNotMatch(a, rx);
        StringAssert.DoesNotMatch(reg, rx);

        StringAssert.Matches(reg, rx);
        StringAssert.Matches(a, rx);
    }
Example #2
0
        private void VerifyRoundTrips(SrmDocument document)
        {
            var compactFormatOptionOld = Settings.Default.CompactFormatOption;
            var regexpTransitionData   = new Regex(".*transition_data.*");

            try
            {
                foreach (var compactFormatOption in new[] { CompactFormatOption.NEVER, CompactFormatOption.ONLY_FOR_LARGE_FILES, CompactFormatOption.ALWAYS })
                {
                    Settings.Default.CompactFormatOption = compactFormatOption.Name;
                    var stringWriter  = new StringWriter();
                    var xmlSerializer = new XmlSerializer(typeof(SrmDocument));
                    xmlSerializer.Serialize(stringWriter, document);
                    var documentText = stringWriter.ToString();
                    if (compactFormatOption.UseCompactFormat(document))
                    {
                        if (document.MoleculeTransitions.Any())
                        {
                            StringAssert.Matches(documentText, regexpTransitionData);
                        }
                    }
                    else
                    {
                        StringAssert.DoesNotMatch(documentText, regexpTransitionData);
                    }
                    var document2 = (SrmDocument)xmlSerializer.Deserialize(new StringReader(stringWriter.ToString()));
                    Assert.AreEqual(document, document2);
                }
            }
            finally
            {
                Settings.Default.CompactFormatOption = compactFormatOptionOld;
            }
        }
        public void SerializesWithAmountAndClientData()
        {
            var clientData = @"{
                ""authorizationFingerprint"": ""auth-fingerprint"",
                ""braintreeLibraryVersion"": ""braintree/web/3.44.0"",
                ""dfReferenceId"": ""ABC-123"",
                ""nonce"": ""FAKE-NONCE"",
                ""clientMetadata"": {
                     ""cardinalDeviceDataCollectionTimeElapsed"": 40,
                     ""issuerDeviceDataCollectionResult"": true,
                     ""issuerDeviceDataCollectionTimeElapsed"": 413,
                     ""requestedThreeDSecureVersion"": ""2"",
                     ""sdkVersion"": ""web/3.42.0""
                }
            }";

            ThreeDSecureLookupRequest request = new ThreeDSecureLookupRequest
            {
                Amount     = "10.00",
                ClientData = clientData
            };

            Assert.AreEqual("10.00", request.Amount);

            var outputJSON = request.ToJSON();

            StringAssert.Contains(@"""amount"":""" + request.Amount, outputJSON);
            StringAssert.Contains(@"""df_reference_id"":""ABC-123""", outputJSON);
            StringAssert.Contains(@"""authorizationFingerprint"":""auth-fingerprint""", outputJSON);
            StringAssert.Contains(@"""braintreeLibraryVersion"":""braintree/web/3.44.0""", outputJSON);
            StringAssert.DoesNotMatch(@"challengeRequested", outputJSON);
            StringAssert.DoesNotMatch(@"exemptionRequested", outputJSON);
        }
        public void SigningDataUnregisterTest()
        {
            /// Check success Fail
            _signingData.UnRegister();

            /// Check return value from remote call
            StringAssert.IsMatch("CSK file deleted.\n", _signingData.Messages, "Return value from command is not as expected. " + _signingData.Messages);

            /// Check return value for errors
            StringAssert.DoesNotMatch("", _signingData.Errors, "Errors have been regturned from remote call. " + _signingData.Errors);

            /// Check to see that the cert file was removed
            Assert.False(File.Exists(_signingData.CertPath + @"/author.p12"), "Certificate File is still present");

            /// Check to see that the csk file was removed
            Assert.False(File.Exists(_signingData.CertPath + @"/bbidtoken.csk"), "CSK File is still present.");

            /// Get CSK Password
            RegistryKey rkHKCU    = Registry.CurrentUser;
            RegistryKey rkCDKPass = null;

            rkCDKPass = rkHKCU.CreateSubKey("Software\\BlackBerry\\BlackBerryVSPlugin");
            StringAssert.IsMatch("", GlobalFunctions.Decrypt(rkCDKPass.GetValue("CSKPass").ToString()), "Password is not set to blank");
            rkCDKPass.Close();
            rkHKCU.Close();
        }
        public void GetPageModel_XpmMarkup_Success()
        {
            string testPageUrlPath = TestFixture.ArticlePageUrlPath;

            PageModel pageModel = SiteConfiguration.ContentProvider.GetPageModel(testPageUrlPath, TestFixture.ParentLocalization, addIncludes: false);

            Assert.IsNotNull(pageModel, "pageModel");

            Article testArticle = pageModel.Regions["Main"].Entities[0] as Article;

            Assert.IsNotNull(testArticle, "Test Article not found on Page.");

            Assert.IsNotNull(testArticle.XpmMetadata, "entityModel.XpmMetadata");
            object isQueryBased;

            Assert.IsFalse(testArticle.XpmMetadata.TryGetValue("IsQueryBased", out isQueryBased), "XpmMetadata contains 'IsQueryBased'");
            object isRepositoryPublished;

            Assert.IsTrue(testArticle.XpmMetadata.TryGetValue("IsRepositoryPublished", out isRepositoryPublished), "XpmMetadata contains 'IsRepositoryPublished'");
            Assert.AreEqual(false, isRepositoryPublished, "IsRepositoryPublished value");

            // NOTE: boolean value must not have quotes in XPM markup (TSI-1251)
            string xpmMarkup = testArticle.GetXpmMarkup(TestFixture.ParentLocalization);

            StringAssert.DoesNotMatch(xpmMarkup, new Regex("IsQueryBased"), "XPM markup");
            StringAssert.Contains(xpmMarkup, "\"IsRepositoryPublished\":false", "XPM markup");
        }
Example #6
0
    public async Task UseWireCrypt(FbWireCrypt wireCrypt)
    {
        if (!EnsureServerVersion(new Version(3, 0, 0, 0)))
        {
            return;
        }
        if (!EnsureServerType(FbServerType.Default))
        {
            return;
        }

        var csb = BuildConnectionStringBuilder(ServerType, Compression, WireCrypt);

        csb.WireCrypt = wireCrypt;
        await using (var conn = new FbConnection(csb.ToString()))
        {
            await conn.OpenAsync();

            const string Pattern = ":[^:]*C[^:]*$";
            if (wireCrypt == FbWireCrypt.Enabled || wireCrypt == FbWireCrypt.Required)
            {
                StringAssert.IsMatch(Pattern, conn.ServerVersion);
            }
            else
            {
                StringAssert.DoesNotMatch(Pattern, conn.ServerVersion);
            }
        }
    }
Example #7
0
        /// <summary>
        /// Validate if the overall test count and results are matching.
        /// </summary>
        /// <param name="passedTestsCount">Passed test count</param>
        /// <param name="failedTestsCount">Failed test count</param>
        /// <param name="skippedTestsCount">Skipped test count</param>
        public void ValidateSummaryStatus(int passedTestsCount, int failedTestsCount, int skippedTestsCount)
        {
            var totalTestCount = passedTestsCount + failedTestsCount + skippedTestsCount;

            if (totalTestCount == 0)
            {
                // No test should be found/run
                var summaryStatus = string.Format(TestSummaryStatusMessageFormat, @"\d+", @"\d+", @"\d+", @"\d+");
                StringAssert.DoesNotMatch(
                    this.standardTestOutput,
                    new Regex(summaryStatus),
                    "Excepted: There should not be test summary{2}Actual: {0}{2}Standard Error: {1}{2}Arguments: {3}{2}",
                    this.standardTestOutput,
                    this.standardTestError,
                    Environment.NewLine,
                    this.arguments);
            }
            else
            {
                var summaryStatus = string.Format(TestSummaryStatusMessageFormat, totalTestCount, passedTestsCount, failedTestsCount, skippedTestsCount);

                Assert.IsTrue(
                    this.standardTestOutput.Contains(summaryStatus),
                    "The Test summary does not match.{3}Expected summary: {1}{3}Test Output: {0}{3}Standard Error: {2}{3}Arguments: {4}{3}",
                    this.standardTestOutput,
                    summaryStatus,
                    this.standardTestError,
                    Environment.NewLine,
                    this.arguments);
            }
        }
Example #8
0
        public void NoArgs()
        {
            rgbFusionTool.Main(new string[] {});

            Assert.IsFalse(mock.IsInitialized, "Expect uninitialized");
            StringAssert.DoesNotMatch(stdout.ToString(), ANY, "Expect stdout is empty");
        }
        public void DumpsTypedConfigUsedIntoLog()
        {
            // the log should be empty
            Assert.AreEqual(0, memoryAppender.GetEvents().Length);

            // read the config file
            ConfigFile.Deserialize <AcousticIndices.AcousticIndicesConfig>(knownConfigFile);

            // the log should contain the serialized config
            var actualEvents = memoryAppender.GetEvents();

            // acoustic indices config loads another config, hence we expect two log messages
            Assert.AreEqual(2, actualEvents.Length);
            var expectedMessage = new Regex(@"Config file `.*Towsey\.Acoustic\.yml` loaded:\r?\n{"".*");

            StringAssert.Matches(actualEvents[0].RenderedMessage, expectedMessage);

            string expectedContent = "\"IndexCalculationDuration\":60.0";

            StringAssert.Contains(actualEvents[0].RenderedMessage, expectedContent);
            Assert.AreEqual(1, Regex.Matches(actualEvents[0].RenderedMessage, expectedContent).Count);
            StringAssert.DoesNotMatch(actualEvents[0].RenderedMessage, new Regex("\"RankOrder\""));

            var expectedMessage2 = new Regex(@"Config file `.*IndexPropertiesConfig\.yml` loaded:\r?\n{""RankOrder"":{.*");

            StringAssert.Matches(actualEvents[1].RenderedMessage, expectedMessage2);
        }
        public void StringChecks()
        {
            var valueToTest = "Abc Def Xyz Bin";

            // Constraint-style asserts:
            Assert.That("", Is.Empty);
            Assert.That(valueToTest, Is.Not.Empty);
            Assert.That(valueToTest, Does.Contain("Def"));
            Assert.That(valueToTest, Does.Not.Contain("Bang"));
            Assert.That(valueToTest, Does.StartWith("Abc"));
            Assert.That(valueToTest, Does.Not.StartWith("Def"));
            Assert.That(valueToTest, Does.EndWith("Bin"));
            Assert.That(valueToTest, Does.Not.EndWith("Xyz"));
            Assert.That(valueToTest, Is.EqualTo("abc def xyz bin").IgnoreCase);
            Assert.That(valueToTest, Is.Not.EqualTo("something else").IgnoreCase);
            Assert.That(valueToTest, Does.Match("^Abc.*Bin$"));
            Assert.That(valueToTest, Does.Not.Match("^Abc.*Def$"));


            // Classic-style asserts:
            StringAssert.Contains("Def", valueToTest);
            StringAssert.DoesNotContain("Bang", valueToTest);
            StringAssert.StartsWith("Abc", valueToTest);
            StringAssert.DoesNotStartWith("Def", valueToTest);
            StringAssert.EndsWith("Bin", valueToTest);
            StringAssert.DoesNotEndWith("Xyz", valueToTest);
            StringAssert.AreEqualIgnoringCase("abc def xyz bin", valueToTest);
            StringAssert.AreNotEqualIgnoringCase("something else", valueToTest);
            StringAssert.IsMatch("^Abc.*Bin$", valueToTest);      //first param is a regex pattern
            StringAssert.DoesNotMatch("^Abc.*Def$", valueToTest); //first param is a regex pattern
        }
Example #11
0
    public async Task UseCompression(bool compression)
    {
        if (!EnsureServerVersion(new Version(3, 0, 0, 0)))
        {
            return;
        }
        if (!EnsureServerType(FbServerType.Default))
        {
            return;
        }

        var csb = BuildConnectionStringBuilder(ServerType, Compression, WireCrypt);

        csb.Compression = compression;
        await using (var conn = new FbConnection(csb.ToString()))
        {
            await conn.OpenAsync();

            const string Pattern = ":[^:]*Z[^:]*$";
            if (compression)
            {
                StringAssert.IsMatch(Pattern, conn.ServerVersion);
            }
            else
            {
                StringAssert.DoesNotMatch(Pattern, conn.ServerVersion);
            }
        }
    }
Example #12
0
        private static void AssertUriNotContainerString(string uri, string containingString)
        {
            var result = GetUri(uri);

            StringAssert.DoesNotMatch(result, new Regex(containingString), $"Result still contains {containingString}");
            //StringAssert.Contains(result, containingString, $"Result does not container {containingString}");
        }
Example #13
0
        public void SeqHandlesStructuredDictionary()
        {
            var mockRequestFactory = new MockHttpWebRequestFactory();

            mockRequestFactory.ResponseQueue.Enqueue(
                new MockHttpWebResponse(HttpStatusCode.OK, null)
                );

            var listener = new SeqTraceListener("http://testuri");

            listener.BatchSize = 0;
            listener.BatchSender.HttpWebRequestFactory = mockRequestFactory;

            var dictionaryData = new Dictionary <string, object>()
            {
                { "MessageTemplate", "{a}" },
                { "a", 1 }
            };

            listener.TraceData(null, "TestSource", TraceEventType.Warning, 1, dictionaryData);

            Assert.AreEqual(1, mockRequestFactory.RequestsCreated.Count);

            var request     = mockRequestFactory.RequestsCreated[0];
            var requestBody = request.RequestBody;

            Console.WriteLine(requestBody);
            StringAssert.Contains(requestBody, "\"MessageTemplate\":\"{a}\"");
            StringAssert.Contains(requestBody, "\"a\":1");
            //var regexTemplateData = new Regex("\"MessageTemplate\":\"{Data}\"");
            //StringAssert.DoesNotMatch(requestBody, regexTemplateData);
            var regexData = new Regex("\"Data\":");

            StringAssert.DoesNotMatch(requestBody, regexData);
        }
Example #14
0
        public void EncryptUsing_WherePassPhraseIsSet_Succeeds()
        {
            var cipherText = plainText.EncryptUsing(passPhrase);

            Assert.IsNotNull(cipherText, "Encrypted text is null");
            StringAssert.DoesNotMatch(cipherText, new Regex($".*{plainText}.*"), "Encrypted text contains plain text");
        }
        public void DumpsUntypedConfigUsedIntoLog()
        {
            // the log should be empty
            Assert.AreEqual(0, memoryAppender.GetEvents().Length);

            // read the config file
            ConfigFile.Deserialize(knownConfigFile);

            // the log should contain the serialized config
            var actualEvents = memoryAppender.GetEvents();

            // acoustic indices config normally loads another config, but since we're not using the "static"
            // config, the extra on-loaded behaviour does not happen!
            Assert.AreEqual(1, actualEvents.Length);
            var expectedMessage = new Regex(@"Config file `.*Towsey\.Acoustic\.yml` loaded:\r?\n{"".*");

            StringAssert.Matches(actualEvents[0].RenderedMessage, expectedMessage);

            // all values are strings in generic configs
            string expectedContent = "\"IndexCalculationDuration\":\"60.0\"";

            StringAssert.Contains(actualEvents[0].RenderedMessage, expectedContent);
            Assert.AreEqual(1, Regex.Matches(actualEvents[0].RenderedMessage, expectedContent).Count);
            StringAssert.DoesNotMatch(actualEvents[0].RenderedMessage, new Regex("\"RankOrder\""));
        }
Example #16
0
        public void WhenActivityId()
        {
            var consoleOutputInterceptor = new MockConsoleOutputInterceptor();
            var formatter = new EventTextFormatter(EventTextFormatter.DashSeparator);
            var logger    = MockConsoleListenerEventSource.Logger;

            var activityId         = Guid.NewGuid();
            var previousActivityId = Guid.Empty;

            EventSource.SetCurrentThreadActivityId(activityId, out previousActivityId);
            TestScenario.With1Listener(
                logger,
                listener =>
            {
                listener.LogToConsole();
                listener.EnableEvents(logger, EventLevel.Critical);
                logger.Critical("This is to log critical in Console");
            });

            EventSource.SetCurrentThreadActivityId(previousActivityId);

            var entry = Regex.Split(consoleOutputInterceptor.Ouput, formatter.Header).Where(c => !string.IsNullOrWhiteSpace(c)).SingleOrDefault();

            Assert.IsNotNull(entry);
            StringAssert.Contains(entry, "200");
            StringAssert.Contains(entry, "Keywords : None");
            Assert.AreEqual(DefaultConsoleColorMapper.Critical, consoleOutputInterceptor.OutputForegroundColor);
            StringAssert.Contains(entry, "ActivityId : " + activityId.ToString());
            StringAssert.DoesNotMatch(entry, new Regex("RelatedActivityId"));
        }
        public void OnlyDumpsEachConfigFileOnce()
        {
            // the log should be empty
            Assert.AreEqual(0, memoryAppender.GetEvents().Length);

            // read the config file
            ConfigFile.Deserialize <AcousticIndices.AcousticIndicesConfig>(knownConfigFile);
            ConfigFile.Deserialize(knownConfigFile);
            ConfigFile.Deserialize <AcousticIndices.AcousticIndicesConfig>(knownConfigFile);

            var actualEvents = memoryAppender.GetEvents();

            // acoustic indices config loads another config, hence we expect two log messages
            // despite how many times this config is "loaded" it's info should have only been dumped once
            Assert.AreEqual(2, actualEvents.Length);
            var expectedMessage = new Regex(@"Config file `.*Towsey\.Acoustic\.yml` loaded:\r?\n{"".*");

            StringAssert.Matches(actualEvents[0].RenderedMessage, expectedMessage);

            string expectedContent = "\"IndexCalculationDuration\":60.0";

            StringAssert.Contains(actualEvents[0].RenderedMessage, expectedContent);
            Assert.AreEqual(1, Regex.Matches(actualEvents[0].RenderedMessage, expectedContent).Count);
            StringAssert.DoesNotMatch(actualEvents[0].RenderedMessage, new Regex("\"RankOrder\""));

            var expectedMessage2 = new Regex(@"Config file `.*IndexPropertiesConfig\.yml` loaded:\r?\n{""RankOrder"":{.*");

            StringAssert.Matches(actualEvents[1].RenderedMessage, expectedMessage2);
        }
        public void CodedUITestMethod1()
        {
            var testPage = Path.Combine(TestContext.DeploymentDirectory, "HTMLPage1.html");
            var window   = BrowserWindow.Launch(testPage);

            // run script before Coded UI interaction to show document.all.item(...) returns a single object
            window.ExecuteScript("foo();");

            window.CaptureImage().Save(Path.Combine(TestContext.DeploymentDirectory, "00-before.png"), ImageFormat.Png);
            TestContext.AddResultFile("00-before.png");

            // Use Coded UI to Find a control but not interact with it
            var radioButton = new HtmlRadioButton(window);

            radioButton.SearchProperties.Add(HtmlControl.PropertyNames.Id, "a");
            radioButton.Find();

            // run script after Coded UI interaction to show document.all.item(...) now returns an array of length 1
            window.ExecuteScript("foo();");

            window.CaptureImage().Save(Path.Combine(TestContext.DeploymentDirectory, "01-after.png"), ImageFormat.Png);
            TestContext.AddResultFile("01-after.png");

            var p = new HtmlCustom(window);

            p.SearchProperties.Add(HtmlControl.PropertyNames.Id, "p");
            StringAssert.DoesNotMatch(p.InnerText, new Regex(@"\.checked : undefined"));
        }
Example #19
0
        public void StringChecks()
        {
            var valueToTest = "Foo Bar Baz Bin";

            // Constraint-style asserts:
            Assert.That("", Is.Empty);
            Assert.That(valueToTest, Is.Not.Empty);
            Assert.That(valueToTest, Does.Contain("Bar"));
            Assert.That(valueToTest, Does.Not.Contain("Bang"));
            Assert.That(valueToTest, Does.StartWith("Foo"));
            Assert.That(valueToTest, Does.Not.StartWith("Bar"));
            Assert.That(valueToTest, Does.EndWith("Bin"));
            Assert.That(valueToTest, Does.Not.EndWith("Baz"));
            Assert.That(valueToTest, Is.EqualTo("foo bar baz bin").IgnoreCase);
            Assert.That(valueToTest, Is.Not.EqualTo("something else").IgnoreCase);
            Assert.That(valueToTest, Does.Match("^Foo.*Bin$"));     // param is a regex pattern
            Assert.That(valueToTest, Does.Not.Match("^Foo.*Bar$")); // param is a regex pattern


            // Classic-style asserts:
            StringAssert.Contains("Bar", valueToTest);
            StringAssert.DoesNotContain("Bang", valueToTest);
            StringAssert.StartsWith("Foo", valueToTest);
            StringAssert.DoesNotStartWith("Bar", valueToTest);
            StringAssert.EndsWith("Bin", valueToTest);
            StringAssert.DoesNotEndWith("Baz", valueToTest);
            StringAssert.AreEqualIgnoringCase("foo bar baz bin", valueToTest);
            StringAssert.AreNotEqualIgnoringCase("something else", valueToTest);
            StringAssert.IsMatch("^Foo.*Bin$", valueToTest);      //first param is a regex pattern
            StringAssert.DoesNotMatch("^Foo.*Bar$", valueToTest); //first param is a regex pattern
        }
Example #20
0
        public void Leaves_ChangeDateFilter_FilterTable(string date, string filter)
        {
            LoginPageObject   loginPage   = new LoginPageObject();
            MySchedPageObject mySchedPage = loginPage.Login("*****@*****.**", "admin");
            MenuLayoutObject  menu        = new MenuLayoutObject();
            LeavePageObject   leavesPage  = menu.EnterLeavesage();

            leavesPage.SetDate(date);
            leavesPage.AddLeave(date, date, "test");
            leavesPage.AddLeave(filter, filter, "test");
            SeleniumUtilityMethods.WaitForJavascript();

            string Id1 = leavesPage.tabLeaves.GetTableCell(0, 0);
            string Id2 = leavesPage.tabLeaves.GetTableCell(1, 0);

            leavesPage.SetDate(filter);
            string Id3 = leavesPage.tabLeaves.GetTableCell(0, 0);
            string Id4 = "";

            try
            {
                Id4 = leavesPage.tabLeaves.GetTableCell(1, 0);
            }
            catch { }

            StringAssert.IsMatch(Id1, Id3);
            StringAssert.DoesNotMatch(Id3, Id4);
        }
Example #21
0
        public void Person_ChangeDataToAnotherInCorrectValue_DataChanged(string name, string surname, string email, string password, string hours)
        {
            String            personValues = "test";
            LoginPageObject   loginPage    = new LoginPageObject();
            MySchedPageObject mySchedPage  = loginPage.Login("*****@*****.**", "admin");
            MenuLayoutObject  menu         = new MenuLayoutObject();
            PeoplePageObject  peoplePage   = menu.EnterPeople();
            PersonPageObject  personPage;

            string id = "0";

            try
            {
                id = peoplePage.GetCellContent(0, 0);
            }
            catch { }
            peoplePage.AddPerson(personValues, personValues, personValues + id + "@" + personValues + id + ".pl", "1qazxsw2", "1");
            SeleniumUtilityMethods.WaitForJavascript();
            personPage = peoplePage.EneterPerson(0);

            personPage.setData(name, surname, email, hours, false, password);
            personPage.Save();
            peoplePage = menu.EnterPeople();
            personPage = peoplePage.EneterPerson(0);

            string nname    = personPage.getName();
            string nsurname = personPage.getSurname();
            string nemail   = personPage.getEmail();
            string nhours   = personPage.getHours();

            StringAssert.DoesNotMatch(name, nname);
            StringAssert.DoesNotMatch(surname, nsurname);
            StringAssert.DoesNotMatch(email, nemail);
            StringAssert.DoesNotMatch(hours, nhours);
        }
Example #22
0
        public void Help(string[] args)
        {
            rgbFusionTool.Main(args);

            Assert.IsFalse(mock.IsInitialized, "Expect uninitialized");
            StringAssert.DoesNotMatch(stderr.ToString(), ANY, "Expect stderr is empty");
            StringAssert.Matches(stdout.ToString(), USAGE, "Expect stdout shows usage");

            // Ensure each supported option appears in help
            string[] supportedOptions =
            {
                "zone",

                "static",
                "colorcycle",
                "pulse",
                "flash",
                "off",

                "verbose",
                "list",
                "help",
                "version"
            };
            foreach (string option in supportedOptions)
            {
                Regex regex = new Regex(string.Format("--{0}\\b", option));
                StringAssert.Matches(stdout.ToString(), regex, "Expect stdout shows usage");
            }
        }
        public void UseCompression(bool compression)
        {
            if (!EnsureVersion(new Version("3.0.0.0")))
            {
                return;
            }
            if (!EnsureServerType(FbServerType.Default))
            {
                return;
            }

            var csb = BuildConnectionStringBuilder(FbServerType, Compression);

            csb.Compression = compression;
            using (var conn = new FbConnection(csb.ToString()))
            {
                conn.Open();
                TestContext.WriteLine(conn.ServerVersion);
                const string Pattern = ":[^:]*Z[^:]*$";
                if (compression)
                {
                    StringAssert.IsMatch(Pattern, conn.ServerVersion);
                }
                else
                {
                    StringAssert.DoesNotMatch(Pattern, conn.ServerVersion);
                }
            }
        }
        public void Json_serialize_should_be_consider_security()
        {
            //Security Considerations
            //front-end interactive: system variable needs avoid(eg, window)
            var obj = new Root {
                window = new Window {
                    onclick = "alert(123)"
                }
            };
            var json = JsonSerializer.ToJson(obj);

            Assert.IsTrue(JsonValidator.IsValid(json));
            Assert.AreEqual("{\"window\":{\"onclick\":\"alert(123)\"}}", json);
            var json1 = json;

            Assert.ThrowsException <AssertFailedException>(() =>
            {
                StringAssert.DoesNotMatch(json1, new Regex("\"window\":"));
            });
            //directly generates executable code
            var str = "alert('hello world')";

            json = JsonSerializer.ToJson(str);
            Assert.IsTrue(JsonValidator.IsValid(json));
            Assert.AreEqual("\"alert('hello world')\"", json);
            Assert.ThrowsException <AssertFailedException>(() =>
            {
                StringAssert.DoesNotMatch(json, new Regex("alert[(](.*?)[)]"));
            });
        }
 public void StringAssertTests()
 {
     StringAssert.Contains("Hello World", "World");
     StringAssert.DoesNotMatch("Hello World", new System.Text.RegularExpressions.Regex(".*Earth"));
     StringAssert.EndsWith("Hello World", "World");
     StringAssert.Matches("Hello World", new System.Text.RegularExpressions.Regex(".*"));
     StringAssert.StartsWith("Hello World", "Hello");
 }
Example #26
0
        public void CanProvisionTokenizedTermsTwiceNameMatch()
        {
            var          template      = new ProvisioningTemplate();
            const string termGroupName = "TestProvisioningGroup";
            var          termGroup     = new TermGroup(_termGroupGuid, termGroupName, null);

            const string termSiteName = "TestProvisioningTermSet - {sitename}";
            var          termSet1     = new TermSet(_termSetGuid, termSiteName, null, true, false, null, null);

            var          term1Id   = Guid.NewGuid();
            const string term1Name = "TestProvisioningTerm - {siteid}";
            var          term1     = new Term(term1Id, term1Name, null, null, null, null, null);

            termSet1.Terms.Add(term1);
            termGroup.TermSets.Add(termSet1);
            template.TermGroups.Add(termGroup);

            for (int index = 0; index < 2; index++)
            {
                if (index == 1)
                {
                    // Assign a new ID to the Term to test the name matching logic.
                    term1.Id = Guid.NewGuid();
                }

                using (ClientContext ctx = TestCommon.CreateClientContext())
                {
                    var parser = new TokenParser(ctx.Web, template);
                    new ObjectTermGroups().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation());
                }

                using (ClientContext ctx = TestCommon.CreateClientContext())
                {
                    TaxonomySession session = TaxonomySession.GetTaxonomySession(ctx);

                    var store = session.GetDefaultKeywordsTermStore();
                    var group = store.GetGroup(_termGroupGuid);
                    var set   = store.GetTermSet(_termSetGuid);

                    ctx.Load(group);
                    ctx.Load(set, s => s.Id, s => s.Name, s => s.Terms);
                    ctx.ExecuteQueryRetry();

                    Assert.IsInstanceOfType(group, typeof(Microsoft.SharePoint.Client.Taxonomy.TermGroup));
                    StringAssert.Matches(group.Name, new Regex(Regex.Escape(termGroupName)));
                    Assert.AreEqual(_termGroupGuid, group.Id);

                    Assert.IsInstanceOfType(set, typeof(Microsoft.SharePoint.Client.Taxonomy.TermSet));
                    Assert.AreEqual(1, set.Terms.Count);
                    Assert.AreEqual(_termSetGuid, set.Id);
                    StringAssert.DoesNotMatch(set.Name, new Regex(Regex.Escape(termSiteName)));

                    var remoteTerm1 = set.Terms[0];
                    Assert.AreEqual(term1Id, remoteTerm1.Id);
                    StringAssert.DoesNotMatch(remoteTerm1.Name, new Regex(Regex.Escape(term1Name)));
                }
            }
        }
        public void IsNotAllLowerCaseTest()
        {
            //Arrange
            var    regex = new Regex(@"^([^A-Z])+$");
            string str1  = "ALL LOWER CASE";

            //Assert
            StringAssert.DoesNotMatch(str1, regex);
        }
Example #28
0
        public void StringAssertTestWithRegex()
        {
            var reg = new Regex(@"^j\S*e$");

            StringAssert.Matches("joyce", reg);
            StringAssert.Matches("joydce", reg);
            StringAssert.DoesNotMatch("joyce1", reg);
            StringAssert.DoesNotMatch("joy ce", reg);
        }
Example #29
0
        public void Match_Test()
        {
            string actual   = "adc";
            string expected = "adc";

            StringAssert.IsMatch(expected, actual);
            expected = "g";
            StringAssert.DoesNotMatch(expected, actual);
        }
Example #30
0
        public void List(string[] args)
        {
            rgbFusionTool.Main(args);

            StringAssert.DoesNotMatch(stderr.ToString(), ANY, "Expect stderr is empty");
            StringAssert.Matches(stdout.ToString(), new Regex("zone \\d+", RegexOptions.IgnoreCase), "Expect stdout lists zones");

            Assert.IsTrue(mock.IsInitialized, "Expect initialized");
        }