public void WriteTo_FailingAssertionForOneMeasureGroup_TextContainsFewKeyInfo() { var exp = "Expected measure"; var description = new CommandDescription(Target.Hierarchies, new CaptionFilter[] { new CaptionFilter(Target.Perspectives, "perspective-name") , new CaptionFilter(Target.MeasureGroups, "measure-group-caption") }); var actuals = new string[] { "Actual hierarchy 1" }; var commandStub = new Mock <IStructureDiscoveryCommand>(); commandStub.Setup(cmd => cmd.Execute()).Returns(actuals); commandStub.Setup(cmd => cmd.Description).Returns(description); var containsConstraint = new ContainConstraint(exp) { }; //Method under test string assertionText = null; try { Assert.That(commandStub.Object, containsConstraint); } catch (AssertionException ex) { assertionText = ex.Message; } //Test conclusion Assert.That(assertionText, Does.Contain("perspective-name").And .StringContaining("measure-group-caption").And .StringContaining("Expected measure")); }
public void TwoRowsHaveOutput() { var package1 = PackageVersionRange.Parse("foo.bar", "1.2.3"); var package2 = PackageVersionRange.Parse("fish", "2.3.4"); var rows = new List <PackageUpdateSet> { PackageUpdates.UpdateSetFor(package1, PackageUpdates.MakePackageForV110(package1)), PackageUpdates.UpdateSetFor(package2, PackageUpdates.MakePackageForV110(package2)) }; var output = ReportToString(rows); Assert.That(output, Is.Not.Null); Assert.That(output, Is.Not.Empty); var lines = output.Split(Environment.NewLine); Assert.That(lines.Length, Is.EqualTo(3)); Assert.That(lines[1], Does.Contain("foo.bar,")); Assert.That(lines[2], Does.Contain("fish,")); }
public void Request_for_dir_index_page_using_supported_conventions() { var htmlOrig = Config.ListeningOn.CombineWith("dir/index.html") .GetStringFromUrl(accept: MimeTypes.Html); Assert.That(htmlOrig, Does.StartWith("<html><head><title>no prefix @ /dir</title>")); Assert.That(htmlOrig, Does.Contain("id='dir-alt-layout'")); Assert.That(htmlOrig, Does.Contain("<h1>/dir/noprefix page!</h1>")); var html = Config.ListeningOn.CombineWith("dir/index") .GetStringFromUrl(accept: MimeTypes.Html); Assert.That(html, Is.EqualTo(htmlOrig)); html = Config.ListeningOn.CombineWith("dir/") .GetStringFromUrl(accept: MimeTypes.Html); Assert.That(html, Is.EqualTo(htmlOrig)); html = Config.ListeningOn.CombineWith("dir") .GetStringFromUrl(accept: MimeTypes.Html); Assert.That(html, Is.EqualTo(htmlOrig)); }
public void Can_capture_command_CreateTable_APIs() { using (var db = OpenDbConnection()) { db.DropTable <Person>(); } using (var captured = new CaptureSqlFilter()) using (var db = OpenDbConnection()) { int i = 0; i++; db.CreateTable <Person>(); Assert.That(captured.SqlCommandHistory.Last().Sql.NormalizeSql(), Does.Contain("create table person")); Assert.That(captured.SqlCommandHistory.Count, Is.EqualTo(i) .Or.EqualTo(i + 1)); //Check table if exists captured.SqlCommandHistory.PrintDump(); } }
public void SuggestCorrectNamedArgumentType() { const string source = @" public class Test { private int _intField = 0; private string _stringField = ""; private bool _boolField = false; public void Method() { MultiMethod(boolVar: } public void MultiMethod(int intVar, string strVar, bool boolVar){ } }"; var completions = GetCompletions(Provider, source, "MultiMethod(boolVar: "); var completionsNames = completions.Select(completion => completion.DisplayText); Assert.That(completionsNames, Does.Not.Contain("_intField")); Assert.That(completionsNames, Does.Not.Contain("_stringField")); Assert.That(completionsNames, Does.Contain("_boolField")); }
public void Can_write_ValidateRequestAttribute() { var gen = appHost.AssertPlugin <NativeTypesFeature>().DefaultGenerator; var attr = new ValidateRequestAttribute("HasRole('Accounts')") { ErrorCode = "ExCode", Message = "'Id' Is Required", }; var metaAttr = gen.ToAttribute(attr); string argValue(string name) => metaAttr.Args.First(x => x.Name == name).Value; Assert.That(metaAttr.Name, Is.EqualTo("ValidateRequest")); Assert.That(metaAttr.Args.Count, Is.EqualTo(3)); Assert.That(argValue(nameof(ValidateRequestAttribute.Validator)), Is.EqualTo("HasRole('Accounts')")); Assert.That(argValue(nameof(ValidateRequestAttribute.ErrorCode)), Is.EqualTo("ExCode")); Assert.That(argValue(nameof(ValidateRequestAttribute.Message)), Is.EqualTo("'Id' Is Required")); var csharp = new CSharpGenerator(new MetadataTypesConfig { DefaultNamespaces = new List <string> { "ServiceStack" } }); var src = csharp.GetCode(new MetadataTypes { Types = new List <MetadataType> { new MetadataType { Name = "TheType", Attributes = new List <MetadataAttribute> { metaAttr, } } } }, new BasicRequest()); src.Print(); Assert.That(src, Does.Contain( "[ValidateRequest(\"HasRole('Accounts')\", ErrorCode=\"ExCode\", Message=\"'Id' Is Required\")]")); }
public void Can_access_Secured_Pages_with_BasicAuth() { Assert.That(ListeningOn.CombineWith("/secured").GetStringFromUrl( requestFilter: req => req.AddBasicAuth(Username, Password)), Does.Contain("<!--view:Secured.cshtml-->")); Assert.That(ListeningOn.CombineWith("/SecuredPage").GetStringFromUrl( requestFilter: req => req.AddBasicAuth(Username, Password)), Does.Contain("<!--page:SecuredPage.cshtml-->")); Assert.That(ListeningOn.CombineWith("/test/session").GetJsonFromUrl( requestFilter: req => req.AddBasicAuth(Username, Password)), Does.Contain("\"IsAuthenticated\":true")); Assert.That(ListeningOn.CombineWith("/TestSessionPage").GetStringFromUrl( requestFilter: req => req.AddBasicAuth(Username, Password)), Does.Contain("IsAuthenticated:True")); Assert.That(ListeningOn.CombineWith("/test/session/view").GetStringFromUrl( requestFilter: req => req.AddBasicAuth(Username, Password)), Does.Contain("IsAuthenticated:True")); }
public void SetIp_WhenSpecified_IsAddedToRequest(bool setValue) { // Arrange var expectedIp = "l30.54.2.1"; //Act if (setValue) { _sut.SetIp(expectedIp); } // Assert var actual = _sut.GetRequest(SiteId); if (setValue) { Assert.That(actual, Does.Contain("&cip=" + HttpUtility.UrlEncode(expectedIp))); } else { Assert.That(actual, Does.Not.Contain("&cip")); } }
public void SetUserId_WhenSpecified_IsAddedToRequest(bool setValue) { // Arrange var expectedId = "l30%&Ö"; //Act if (setValue) { _sut.SetUserId(expectedId); } // Assert var actual = _sut.GetRequest(SiteId); if (setValue) { Assert.That(actual, Does.Contain("&uid=" + HttpUtility.UrlEncode(expectedId))); } else { Assert.That(actual, Does.Not.Contain("&uid")); } }
public void ExpressionAliasFluent([IncludeDataSources(TestProvName.AllSQLite)] string context, [Values] bool finalAliases) { var ms = new MappingSchema(); ms.GetFluentMappingBuilder() .Entity <PersonCustom>() .Property(p => p.Money).IsExpression(p => Sql.AsSql(p.Age * Sql.AsSql(1000) + p.Name.Length * 10), true, "MONEY"); using (new GenerateFinalAliases(finalAliases)) using (var db = GetDataContext(context, ms)) { Query.ClearCaches(); var query = db.GetTable <PersonCustom>().Where(p => p.Name != ""); var sql1 = query.ToString(); TestContext.WriteLine(sql1); if (finalAliases) { Assert.That(sql1, Does.Contain("[MONEY]")); } else { Assert.That(sql1, Does.Not.Contain("[MONEY]")); } var sql2 = query.Select(q => new { q.Name, q.Money }).ToString(); TestContext.WriteLine(sql2); if (finalAliases) { Assert.That(sql2, Does.Contain("[Money]")); } else { Assert.That(sql2, Does.Not.Contain("[Money]")); } } }
public void AddEcommerceItem_Test(string sku, string name, string categories, double price, ulong quantity) { List <string> categoryList = null; if (!string.IsNullOrEmpty(categories)) { categoryList = categories.Split(',').ToList(); } var actual = _sut.GetUrlTrackEcommerce(0); Assert.That(actual, Does.Not.Contain("ec_items")); _sut.AddEcommerceItem(sku, name, categoryList, price, quantity); actual = _sut.GetUrlTrackEcommerce(0); var expected = new Dictionary <string, object[]> { { "", new object[] { sku, name, categoryList, price.ToString("0.##", CultureInfo.InvariantCulture), quantity } } }; var expectedAsJson = JsonConvert.SerializeObject(expected.Values); Console.WriteLine(expectedAsJson); Assert.That(actual, Does.Contain("&ec_items=" + HttpUtility.UrlEncode(expectedAsJson))); }
public void Console_executable_runs_and_outputs_info_about_surviving_mutants() { var baseDir = TestContext.CurrentContext.TestDirectory; var configFilePath = Path.Combine(baseDir, "Console", "fettle.config.yml"); ModifyConfigFile(configFilePath); var fettleProcess = new Process { StartInfo = new ProcessStartInfo { CreateNoWindow = true, WindowStyle = ProcessWindowStyle.Hidden, FileName = Path.Combine(baseDir, "Fettle.Console.exe"), Arguments = $"--quiet --config {configFilePath}", UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true } }; var stopwatch = Stopwatch.StartNew(); fettleProcess.Start(); fettleProcess.WaitForExit((int)TimeSpan.FromMinutes(1).TotalMilliseconds); stopwatch.Stop(); var stdOut = fettleProcess.StandardOutput.ReadToEnd(); var stdErr = fettleProcess.StandardError.ReadToEnd(); Assert.Multiple(() => { Assert.That(fettleProcess.ExitCode, Is.EqualTo(1)); Assert.That(stdErr, Is.Empty); Assert.That(stdOut, Does.Contain("mutant(s) survived!")); Assert.That(stdOut, Does.Contain("PartiallyTestedNumberComparison.cs:7")); }); }
public void Does_deserialize_LicenseKey() { var key = new LicenseKey { Name = "The Name", Ref = "1000", Type = LicenseType.Business, Expiry = new DateTime(2001, 01, 01), Meta = (long)(LicenseMeta.Subscription | LicenseMeta.Cores), }; var jsv = key.ToJsv(); Assert.That(jsv, Does.Contain($"eta:" + (int)key.Meta)); jsv.Print(); var fromKey = jsv.FromJsv <LicenseKey>(); Assert.That(fromKey.Name, Is.EqualTo(key.Name)); Assert.That(fromKey.Ref, Is.EqualTo(key.Ref)); Assert.That(fromKey.Type, Is.EqualTo(key.Type)); Assert.That(fromKey.Expiry, Is.EqualTo(key.Expiry)); Assert.That(fromKey.Meta, Is.EqualTo(key.Meta)); var oldKey = jsv.FromJsv <OldLicenseKey>(); Assert.That(oldKey.Name, Is.EqualTo(key.Name)); Assert.That(oldKey.Ref, Is.EqualTo(key.Ref)); Assert.That(oldKey.Type, Is.EqualTo(key.Type)); Assert.That(oldKey.Expiry, Is.EqualTo(key.Expiry)); var oldJsv = oldKey.ToJsv(); fromKey = oldJsv.FromJsv <LicenseKey>(); Assert.That(fromKey.Name, Is.EqualTo(key.Name)); Assert.That(fromKey.Ref, Is.EqualTo(key.Ref)); Assert.That(fromKey.Type, Is.EqualTo(key.Type)); Assert.That(fromKey.Expiry, Is.EqualTo(key.Expiry)); Assert.That(fromKey.Meta, Is.EqualTo(0)); }
public async Task IncludeErrorDetails() { var builder = new NpgsqlConnectionStringBuilder(ConnectionString) { IncludeErrorDetails = true }; using var _ = CreateTempPool(builder, out var connectionStringWithDetails); await using var conn = await OpenConnectionAsync(connectionStringWithDetails); await using var __ = GetTempFunctionName(conn, out var raiseExceptionFunc); await using var ___ = GetTempFunctionName(conn, out var raiseNoticeFunc); await conn.ExecuteNonQueryAsync($@" CREATE OR REPLACE FUNCTION {raiseExceptionFunc}() RETURNS VOID AS $$ BEGIN RAISE EXCEPTION 'testexception' USING DETAIL = 'secret'; END; $$ LANGUAGE 'plpgsql'; CREATE OR REPLACE FUNCTION {raiseNoticeFunc}() RETURNS VOID AS $$ BEGIN RAISE NOTICE 'testexception' USING DETAIL = 'secret'; END; $$ LANGUAGE 'plpgsql';"); var ex = Assert.ThrowsAsync <PostgresException>(() => conn.ExecuteNonQueryAsync($"SELECT * FROM {raiseExceptionFunc}()")); Assert.That(ex.Detail, Does.Contain("secret")); Assert.That(ex.Data[nameof(PostgresException.Detail)], Does.Contain("secret")); Assert.That(ex.ToString(), Does.Contain("secret")); PostgresNotice?notice = null; conn.Notice += (____, a) => notice = a.Notice; await conn.ExecuteNonQueryAsync($"SELECT * FROM {raiseNoticeFunc}()"); Assert.That(notice !.Detail, Does.Contain("secret")); }
public void Can_include_filter_into_new_eval_context() { var context = new ScriptContext { ScriptBlocks = { new EvalScriptBlock() }, ScriptMethods = { new InfoScripts() }, Args = { ["evalContent"] = "{{envServerUserAgent}}", } }.Init(); Assert.That(context.EvaluateScript("{{#eval}}{{evalContent}}{{/eval}}"), Does.Not.Contain("ServiceStack")); Assert.That(context.EvaluateScript("{{ evalContent | evalTemplate}}"), Does.Not.Contain("ServiceStack")); Assert.That(context.EvaluateScript("{{#eval {use:{filters:'InfoScripts'}}{{evalContent}}{{/eval}}"), Does.Contain("ServiceStack")); Assert.That(context.EvaluateScript("{{ evalContent | evalTemplate({use:{filters:'InfoScripts'}}) }}"), Does.Contain("ServiceStack")); }
public void Export() { File.Delete("test.xls"); var order = CreateOrder(); session.Save(order); var report = new OrderDetails(); report.ReportCaption = "тест"; report.ClientId = order.Client.Id; report.Connection = (MySqlConnection)session.Connection; report.Session = session; report.Interval = true; report.From = DateTime.Today.AddDays(-1); report.To = DateTime.Today; this.report = report; var sheet = ReadReport(); Assert.That(ToText(sheet), Does.Contain(order.Id.ToString())); sheet = sheet.Workbook.GetSheetAt(1); Assert.That(ToText(sheet), Does.Contain(order.Id.ToString()), "на второй странице должна быть детализация"); }
public void Parser_Error_Action_MaintainTokens(string invalidTemplate, bool lastItemIsPlaceholder) { var parser = GetRegularParser(); parser.Settings.ParseErrorAction = ErrorAction.MaintainTokens; var parsed = parser.ParseFormat(invalidTemplate, new[] { Guid.NewGuid().ToString("N") }); Assert.That(parsed.Items.Count, Is.EqualTo(4), "Number of parsed items"); Assert.That(parsed.Items[0].RawText, Is.EqualTo("Hello, I'm ")); Assert.That(parsed.Items[1].RawText, Is.EqualTo("{Name from {City}")); Assert.That(parsed.Items[2].RawText, Is.EqualTo(" ")); if (lastItemIsPlaceholder) { Assert.That(parsed.Items[3], Is.TypeOf(typeof(Placeholder)), "Last item should be Placeholder"); Assert.That(parsed.Items[3].RawText, Does.Contain("{Street}")); } else { Assert.That(parsed.Items[3], Is.TypeOf(typeof(LiteralText)), "Last item should be LiteralText"); Assert.That(parsed.Items[3].RawText, Does.Contain("{Street")); } }
public async Task ShouldUpdateConditionOnTaskImport() { var workDirectory = Path.Combine(TestContext.CurrentContext.WorkDirectory, nameof(ShouldUpdateConditionOnTaskImport)); Directory.CreateDirectory(workDirectory); var projectName = nameof(ShouldUpdateConditionOnTaskImport) + ".csproj"; var projectPath = Path.Combine(workDirectory, projectName); await File.WriteAllTextAsync(projectPath, _testWebApiProject); var subject = new UpdateProjectImportsCommand(); var package = new PackageInProject("acme", "1.0.0", new PackagePath(workDirectory, projectName, PackageReferenceType.ProjectFileOldStyle)); await subject.Invoke(package, null, null, NuGetSources.GlobalFeed); var updatedContents = await File.ReadAllTextAsync(projectPath); Assert.That(updatedContents, Does.Not.Contain(_unpatchedImport)); Assert.That(updatedContents, Does.Contain(_patchedImport)); }
public async Task Can_access_Secured_Pages_with_ApiKeyAuth_BearerToken_Async() { Assert.That(await ListeningOn.CombineWith("/secured").GetStringFromUrlAsync( requestFilter: req => req.AddBearerToken(ApiKey)), Does.Contain("<!--view:Secured.cshtml-->")); Assert.That(await ListeningOn.CombineWith("/SecuredPage").GetStringFromUrlAsync( requestFilter: req => req.AddBearerToken(ApiKey)), Does.Contain("<!--page:SecuredPage.cshtml-->")); Assert.That(await ListeningOn.CombineWith("/test/session").GetJsonFromUrlAsync( requestFilter: req => req.AddBearerToken(ApiKey)), Does.Contain("\"IsAuthenticated\":true")); Assert.That(await ListeningOn.CombineWith("/TestSessionPage").GetStringFromUrlAsync( requestFilter: req => req.AddBearerToken(ApiKey)), Does.Contain("IsAuthenticated:True")); Assert.That(await ListeningOn.CombineWith("/test/session/view").GetStringFromUrlAsync( requestFilter: req => req.AddBearerToken(ApiKey)), Does.Contain("IsAuthenticated:True")); }
public void Can_create_field_with_custom_sql() { OrmLiteConfig.BeforeExecFilter = cmd => cmd.GetDebugString().Print(); using var db = OpenDbConnection(); db.DropAndCreateTable <PocoTable>(); var createTableSql = db.GetLastSql().NormalizeSql(); createTableSql.Print(); if (Dialect != Dialect.Firebird) { Assert.That(createTableSql, Does.Contain("charcolumn char(20) null")); Assert.That(createTableSql, Does.Contain("decimalcolumn decimal(18,4) null")); } else { Assert.That(createTableSql, Does.Contain("charcolumn char(20)")); Assert.That(createTableSql, Does.Contain("decimalcolumn decimal(18,4)")); } }
public void Can_Render_Text_Template_Without_Some_Sections() { var renderer = new TemplateRenderer(new ReportModel { Error = new Error { Exception = new TestException() }, App = new App { Name = TestApp, Version = Version } }); var result = renderer.RenderPreset(); Assert.That(result, Does.Contain(string.Format("Application: {0}", TestApp))); Assert.That(result, Does.Contain(string.Format("Version: {0}", Version))); Assert.That(result, Does.Not.Contain("User Explanation:")); // whole section not shown Assert.That(result, Does.Not.Contain("User:")); // whole section not shown }
public async Task Get_NonJsonContentFromGoogle_GetsContentCorrectly() { var nonJsonContent = new HttpResponseMessage { Content = new StringContent(("<html><body>Top Stories</body></html>")) }; dynamic google = new RestClient ( BaseUri, new Dictionary <string, string> { { "Accept", "text/html" } }, new Config(new UnitTestHandler(request => nonJsonContent)) ); var result = await google.news.Get(); var content = result.ToString(); Assert.That(result.HttpResponseMessage.StatusCode, Is.EqualTo(HttpStatusCode.OK)); Assert.That(content, Does.Contain("Top Stories")); }
protected void WaitWindow(string title, string body = null) { var found = false; dispatcher.Invoke(() => { found = activeWindow.Title == title; }); if (found) { return; } var opened = manager.WindowOpened.Timeout(30.Second()).First(); opened.Dispatcher.Invoke(() => { var text = opened.AsText(); Assert.AreEqual(title, opened.Title, text); if (!String.IsNullOrEmpty(body)) { Assert.That(text, Does.Contain(body), text); } }); }
public void Compare_Mix_CorrectDisplay() { var res = new ListComparer.Result( new List <string> { "x" }, new List <string> { "a", "b", "c" } ); var formatter = new ListComparisonFormatter(); var display = formatter.Format(res).ToString(); Assert.That(display, Does.Not.Contain("Missing items")); Assert.That(display, Does.Contain("Missing item")); Assert.That(display, Does.Contain("Unexpected items")); Assert.That(display, Does.Contain("<x>")); Assert.That(display, Does.Contain("<a>")); Assert.That(display, Does.Contain("<b>")); Assert.That(display, Does.Contain("<c>")); }
public void SuggestUsingVariable() { const string source = @" using System.IO; public class Test { public void Method() { using (var v = new StreamReader("")) { SrMethod( } } public void SrMethod(StreamReader var){ } }"; var completions = GetCompletions(Provider, source, "SrMethod("); var completionsNames = completions.Select(completion => completion.DisplayText); Assert.That(completionsNames, Does.Contain("v")); }
public void FailedTransaction() { var client = InstrumentClient( new ConfidentialLedgerClient( new("https://client.name"), new MockCredential(), new ConfidentialLedgerClientOptions { Retry = { Delay = TimeSpan.Zero, MaxRetries = 0 }, Transport = new MockTransport( req => { if (req.Uri.Host == "identity.accledger.azure.com") { var cert = new MockResponse(200); cert.SetContent( @" { ""ledgerTlsCertificate"": ""-----BEGIN CERTIFICATE-----\nMIIBejCCASGgAwIBAgIRANPpW17pcDYr1KnqsJH5yC8wCgYIKoZIzj0EAwIwFjEU\nMBIGA1UEAwwLQ0NGIE5ldHdvcmswHhcNMjEwMzExMDAwMDAwWhcNMjMwNjExMjM1\nOTU5WjAWMRQwEgYDVQQDDAtDQ0YgTmV0d29yazBZMBMGByqGSM49AgEGCCqGSM49\nAwEHA0IABOCPGnfcmfm5Vyax3bvg5Xqg6RUZtda0U5qpmxqGgLfL3LYJd3heTPd\u002B\n51o29pMtKJGG4cWeZ3\u002BYbhZzHnetf8WjUDBOMAwGA1UdEwQFMAMBAf8wHQYDVR0O\nBBYEFFxq\u002BImyEVh4u4BfynwnEAsbvRJBMB8GA1UdIwQYMBaAFFxq\u002BImyEVh4u4Bf\nynwnEAsbvRJBMAoGCCqGSM49BAMCA0cAMEQCIC597R3C89/IzfqjkO31XKy4Rnfy\nXauWszBChtH1v2CoAiAS0tmFNjD3fweHH8O2ySXK/tPCBTq877pIjFGwvuj2uw==\n-----END CERTIFICATE-----\n\u0000"", ""ledgerId"": ""chrissconfidentialledger""}"); return(cert); } if (req.Uri.Path.Contains($"transactions/{transactionId}/status")) { var success = new MockResponse(500); success.SetContent("success"); return(success); } var failed = new MockResponse(200); failed.AddHeader("x-ms-ccf-transaction-id", transactionId); failed.SetContent("failed"); return(failed); }) })); var ex = Assert.ThrowsAsync <InvalidOperationException>( async() => await client.PostLedgerEntryAsync(RequestContent.Create(new { contents = "test" }), null, true, default)); Assert.That(ex.Message, Does.Contain(transactionId)); }
public async Task UpdateDetachedObjectAsync() { // When the update is used directly as method to reattach a entity the OldState is null // that mean that NH should not retrieve info from DB ((DebugSessionFactory)Sfi).EventListeners.PostUpdateEventListeners = new IPostUpdateEventListener[] { new AssertOldStatePostListener( eArgs => Assert.That(eArgs.OldState, Is.Null)) }; await(FillDbAsync()); SimpleEntity toModify; using (ISession s = OpenSession()) { using (ITransaction tx = s.BeginTransaction()) { IList <SimpleEntity> l = await(s.CreateCriteria <SimpleEntity>().ListAsync <SimpleEntity>()); toModify = l[0]; await(tx.CommitAsync()); } } toModify.Description = "Modified"; using (var ls = new LogSpy(typeof(AssertOldStatePostListener))) { using (ISession s = OpenSession()) { using (ITransaction tx = s.BeginTransaction()) { await(s.UpdateAsync(toModify)); await(tx.CommitAsync()); } } Assert.That(ls.GetWholeLog(), Does.Contain(AssertOldStatePostListener.LogMessage)); } await(DbCleanupAsync()); ((DebugSessionFactory)Sfi).EventListeners.PostUpdateEventListeners = Array.Empty <IPostUpdateEventListener>(); }
public void Serialize_WithCategorieAndTrait_CategorieAndTraitNotSerialized() { var test = new TestXml() { InstanceSettling = new InstanceSettlingXml() { Variable = new InstanceVariableXml() { Name = "firstOfMonth" }, Categories = new List <string>() { "~{@firstOfMonth:MMM}", "~{@firstOfMonth:MM}" }, Traits = new List <TraitXml>() { new TraitXml() { Name = "Year", Value = "~{@firstOfMonth:YYYY}" } } } }; var serializer = new XmlSerializer(test.GetType()); using (var stream = new MemoryStream()) using (var writer = new StreamWriter(stream, Encoding.UTF8)) { serializer.Serialize(writer, test); var content = Encoding.UTF8.GetString(stream.ToArray()); Debug.WriteLine(content); Assert.That(content, Does.Contain("<instance-settling")); Assert.That(content, Does.Contain("<category")); Assert.That(content, Does.Contain("<trait")); } }
public void WriteTo_FailingAssertionForTwoPerspectives_TextContainsFewKeyInfo() { var exp = new string[] { "Expected perspective 1", "Expected perspective 2" }; var description = new CommandDescription(Target.Perspectives, new CaptionFilter[] { }); var actuals = new string[] { "Actual perspective 1", "Actual perspective 2" }; var commandStub = new Mock <IStructureDiscoveryCommand>(); commandStub.Setup(cmd => cmd.Execute()).Returns(actuals); commandStub.Setup(cmd => cmd.Description).Returns(description); var containsConstraint = new ContainConstraint(exp) { }; //Method under test string assertionText = null; try { Assert.That(commandStub.Object, containsConstraint); } catch (AssertionException ex) { assertionText = ex.Message; } //Test conclusion Assert.That(assertionText, Does.Contain("find the perspectives named").And .StringContaining("Expected perspective 1").And .StringContaining("Expected perspective 2").And .StringContaining(".").And .StringContaining("Actual perspective 1").And .StringContaining("Actual perspective 2").And .Not.StringContaining("contain")); }
public void ThrowDumpTest() { // Create a unique test number to store with the exception var rnd = new Random(); var unique = rnd.NextDouble().ToString(); this.Navigate("/"); this.Click("EnterButton"); this.Write("Operand", unique); this.Click("EnterButton"); Assert.That(this.Stack, Does.Contain(unique)); // Deliberately throw an exception this.Click("EnterButton"); this.Write("Operand", "except"); this.Click("EnterButton", expectedStatusCode: 200); // UseDeveloperExceptionPage yields no 500 Assert.That(this.Html(), Does.Contain("Deliberate Exception")); // Navigate to the Code dump on the (again blue) bsod Page string coredumpPath = null; var reUrl = new Regex(@"_CORE_DUMP.*?http:\/\/[^\/]+([^<]+)<", RegexOptions.Singleline); var match = reUrl.Match(this.Html()); if (match != null) { coredumpPath = match.Groups[1].Value; } Assert.That(coredumpPath, Does.StartWith("/Calculator?session=")); this.Navigate(coredumpPath); Assert.Multiple(() => { // The non-initial State and the random number must come from the database with Storage.ViewState Assert.That(StorageImplementation.SessionStorage, Is.EqualTo(Storage.ViewState)); Assert.That(this.State, Is.EqualTo(CalculatorContext.Map1.Enter)); Assert.That(this.Stack, Does.Contain(unique)); }); }