public void SetMetadata(string value) { var src = GetExamplesWith("Sample.pdf"); var dest = Path(Args(value)); var cmp = new Metadata { Title = value, Author = value, Subject = value, Keywords = value, Creator = value, Producer = value, Version = new Version(1, 5), Viewer = ViewerPreferences.TwoColumnLeft, }; using (var w = new DocumentWriter(IO)) { w.Set(cmp); w.Add(new DocumentReader(src, "", false, IO)); w.Save(dest); } using (var r = new DocumentReader(dest, "", false, IO)) { var m = r.Metadata; Assert.That(m.Title, Is.EqualTo(cmp.Title), nameof(m.Title)); Assert.That(m.Author, Is.EqualTo(cmp.Author), nameof(m.Author)); Assert.That(m.Subject, Is.EqualTo(cmp.Subject), nameof(m.Subject)); Assert.That(m.Keywords, Is.EqualTo(cmp.Keywords), nameof(m.Keywords)); Assert.That(m.Creator, Is.EqualTo(cmp.Creator), nameof(m.Creator)); Assert.That(m.Producer, Does.StartWith("iTextSharp")); Assert.That(m.Version.Major, Is.EqualTo(cmp.Version.Major)); Assert.That(m.Version.Minor, Is.EqualTo(cmp.Version.Minor)); Assert.That(m.Viewer, Is.EqualTo(cmp.Viewer)); } }
public void CompositePostgresType() { var csb = new NpgsqlConnectionStringBuilder(ConnectionString) { ApplicationName = nameof(PostgresType), Pooling = false }; using (var conn = OpenConnection(csb)) { conn.ExecuteNonQuery("CREATE TYPE pg_temp.comp1 AS (x int, some_text text)"); conn.ExecuteNonQuery("CREATE TYPE pg_temp.comp2 AS (comp comp1, comps comp1[])"); conn.ReloadTypes(); using (var cmd = new NpgsqlCommand("SELECT ROW(ROW(8, 'foo')::comp1, ARRAY[ROW(9, 'bar')::comp1, ROW(10, 'baz')::comp1])::comp2", conn)) { using (var reader = cmd.ExecuteReader()) { reader.Read(); var comp2Type = (PostgresCompositeType)reader.GetPostgresType(0); Assert.That(comp2Type.Name, Is.EqualTo("comp2")); Assert.That(comp2Type.FullName, Does.StartWith("pg_temp_") & Does.EndWith(".comp2")); Assert.That(comp2Type.Fields, Has.Count.EqualTo(2)); var field1 = comp2Type.Fields[0]; var field2 = comp2Type.Fields[1]; Assert.That(field1.Name, Is.EqualTo("comp")); Assert.That(field2.Name, Is.EqualTo("comps")); var comp1Type = (PostgresCompositeType)field1.Type; Assert.That(comp1Type.Name, Is.EqualTo("comp1")); var arrType = (PostgresArrayType)field2.Type; Assert.That(arrType.Name, Is.EqualTo("comp1[]")); var elemType = arrType.Element; Assert.That(elemType, Is.SameAs(comp1Type)); } } } }
public void CorrectExceptionIsReturnedToMethod() { ArgumentException ex = Assert.Throws(typeof(ArgumentException), new TestDelegate(TestDelegates.ThrowsArgumentException)) as ArgumentException; Assert.IsNotNull(ex, "No ArgumentException thrown"); Assert.That(ex.Message, Does.StartWith("myMessage")); #if !NETCF && !SILVERLIGHT Assert.That(ex.ParamName, Is.EqualTo("myParam")); #endif ex = Assert.Throws <ArgumentException>( delegate { throw new ArgumentException("myMessage", "myParam"); }) as ArgumentException; Assert.IsNotNull(ex, "No ArgumentException thrown"); Assert.That(ex.Message, Does.StartWith("myMessage")); #if !NETCF && !SILVERLIGHT Assert.That(ex.ParamName, Is.EqualTo("myParam")); #endif ex = Assert.Throws(typeof(ArgumentException), delegate { throw new ArgumentException("myMessage", "myParam"); }) as ArgumentException; Assert.IsNotNull(ex, "No ArgumentException thrown"); Assert.That(ex.Message, Does.StartWith("myMessage")); #if !NETCF && !SILVERLIGHT Assert.That(ex.ParamName, Is.EqualTo("myParam")); #endif ex = Assert.Throws <ArgumentException>(TestDelegates.ThrowsArgumentException) as ArgumentException; Assert.IsNotNull(ex, "No ArgumentException thrown"); Assert.That(ex.Message, Does.StartWith("myMessage")); #if !NETCF && !SILVERLIGHT Assert.That(ex.ParamName, Is.EqualTo("myParam")); #endif }
public void UpdateOnImplicitJoinFails() { ISession s = OpenSession(); ITransaction t = s.BeginTransaction(); var human = new Human { Name = new Name { First = "Steve", Initial = 'E', Last = null } }; var mother = new Human { Name = new Name { First = "Jane", Initial = 'E', Last = null } }; human.Mother = (mother); s.Save(human); s.Save(mother); s.Flush(); t.Commit(); t = s.BeginTransaction(); var e = Assert.Throws <QueryException>( () => s.CreateQuery("update Human set mother.name.initial = :initial").SetString("initial", "F").ExecuteUpdate()); Assert.That(e.Message, Does.StartWith("Implied join paths are not assignable in update")); s.CreateQuery("delete Human where mother is not null").ExecuteUpdate(); s.CreateQuery("delete Human").ExecuteUpdate(); t.Commit(); s.Close(); }
public void CorrectExceptionIsReturnedToMethodAsync() { ArgumentException ex = Assert.ThrowsAsync(typeof(ArgumentException), new AsyncTestDelegate(AsyncTestDelegates.ThrowsArgumentExceptionAsync)) as ArgumentException; Assert.IsNotNull(ex, "No ArgumentException thrown"); Assert.That(ex.Message, Does.StartWith("myMessage")); #if !PORTABLE Assert.That(ex.ParamName, Is.EqualTo("myParam")); #endif ex = Assert.ThrowsAsync <ArgumentException>( delegate { return(AsyncTestDelegates.Delay(5).ContinueWith(t => { throw new ArgumentException("myMessage", "myParam"); }, TaskScheduler.Default)); }); Assert.IsNotNull(ex, "No ArgumentException thrown"); Assert.That(ex.Message, Does.StartWith("myMessage")); #if !PORTABLE Assert.That(ex.ParamName, Is.EqualTo("myParam")); #endif ex = Assert.ThrowsAsync(typeof(ArgumentException), delegate { return(AsyncTestDelegates.Delay(5).ContinueWith(t => { throw new ArgumentException("myMessage", "myParam"); }, TaskScheduler.Default)); }) as ArgumentException; Assert.IsNotNull(ex, "No ArgumentException thrown"); Assert.That(ex.Message, Does.StartWith("myMessage")); #if !PORTABLE Assert.That(ex.ParamName, Is.EqualTo("myParam")); #endif ex = Assert.ThrowsAsync <ArgumentException>(AsyncTestDelegates.ThrowsArgumentExceptionAsync); Assert.IsNotNull(ex, "No ArgumentException thrown"); Assert.That(ex.Message, Does.StartWith("myMessage")); #if !PORTABLE Assert.That(ex.ParamName, Is.EqualTo("myParam")); #endif }
public async Task TestConnectRemoteCalledForStadiaWithScpCommandAsExtraArgAsync( LaunchOption launchOption) { var connectRemoteRecorder = new PlatformFactoryFakeConnectRecorder(); var launcherFactory = CreateLauncherFactory(true, connectRemoteRecorder); var launcher = launcherFactory.Create(_debugEngine, launchOption, "", _gameBinary, _gameBinary, _gameLaunch); ILldbAttachedProgram program = await LaunchAsync(launcher); Assert.That(connectRemoteRecorder.InvocationCount, Is.EqualTo(1)); Assert.That(connectRemoteRecorder.InvocationOptions.Count, Is.EqualTo(1)); string connectRemoteUrl = connectRemoteRecorder.InvocationOptions[0].GetUrl(); // argument for ConnectRemote should start with a standard value, ending with ';' // used as a separator between it and scp command. Assert.That(connectRemoteUrl, Does.StartWith("connect://localhost:10200;")); // path to the scp.exe should be quoted, to check this we add \" to the assertion. Assert.That(connectRemoteUrl, Does.Contain("scp.exe\"")); Assert.That(connectRemoteUrl, Does.Contain("-oStrictHostKeyChecking=yes -oUserKnownHostsFile")); Assert.That(program, Is.Not.Null); program.Stop(); }
public void Test07FileStream() { var tempPath = Path.GetTempPath(); string filePath; using (var file = TempData.CreateFileStream()) { filePath = file.Name; Assert.IsTrue(File.Exists(filePath), "FileStream should exist"); Assert.That(tempPath, Does.StartWith(tempPath)); var file2 = TempData.CreateFileStream(); Assert.AreNotEqual(file.Name, file2.Name, "Path should not match"); Assert.IsTrue(File.Exists(file2.Name), "File should exist"); file2.Dispose(); AssertDisposed(() => file2.Length); } Assert.IsFalse(File.Exists(filePath), "FileStream should NOT exist"); // test for cleanup if leaked { var file2 = TempData.CreateFileStream(); var file2Path = file2.Name; Assert.AreNotEqual(filePath, file2Path, "Path should not match"); Assert.IsTrue(File.Exists(file2.Name), "FileStream should exist"); GC.KeepAlive(file2); // clear GC root for a debug build // ReSharper disable once RedundantAssignment file2 = null; GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); Assert.IsFalse(File.Exists(file2Path), "FileStream should NOT exist"); } }
public void StringStartsWith() { string expectedValue = "XX"; string actualValue = "xxx"; // MSTest MSTestStringAssert.StartsWith(actualValue, expectedValue, "Some context"); // StringAssert.StartsWith failed. String 'xxx' does not start with string 'XX'. Some context // NUnit Assert.That(actualValue, Does.StartWith(expectedValue), () => "Some context"); // Some context // Expected: String starting with "XX" // But was: "xxx" // XUnit XUnitAssert.StartsWith(expectedValue, actualValue); // Assert.StartsWith() Failure // Not found: XX // In value: xx... // Fluent actualValue.Should().StartWith(expectedValue, "SOME REASONS"); // Expected actualValue to start with "XX" because SOME REASONS, but "xxx" differs near "xxx" (index 0). // Shouldly actualValue.ShouldStartWith(expectedValue, "Some context", Case.Sensitive); // actualValue // should start with // "XX" // but was // "xxx" // // Additional Info: // Some context }
public async Task Does_cache_duplicate_requests_async() { ServerCacheOnlyAsync.Count = 0; var request = new ServerCacheOnlyAsync { Id = 1, Value = "foo" }; var response = (await Config.ListeningOn.CombineWith(request.ToGetUrl()) .GetJsonFromUrlAsync(responseFilter: res => { Assert.That(res.GetHeader(HttpHeaders.ContentType), Does.StartWith(MimeTypes.Json)); Assert.That(res.GetHeader(HttpHeaders.CacheControl), Is.Null); })) .FromJson <ServerCacheOnlyAsync>(); Assert.That(ServerCacheOnlyAsync.Count, Is.EqualTo(1)); AssertEquals(response, request); response = (await Config.ListeningOn.CombineWith(request.ToGetUrl()) .GetJsonFromUrlAsync(responseFilter: res => { Assert.That(res.GetHeader(HttpHeaders.ContentType), Does.StartWith(MimeTypes.Json)); Assert.That(res.GetHeader(HttpHeaders.CacheControl), Is.Null); })) .FromJson <ServerCacheOnlyAsync>(); Assert.That(ServerCacheOnlyAsync.Count, Is.EqualTo(1)); AssertEquals(response, request); var client = CreateClient(); response = await client.GetAsync <ServerCacheOnlyAsync>(request); Assert.That(ServerCacheOnlyAsync.Count, Is.EqualTo(1)); AssertEquals(response, request); }
public void Magic_WithRun_Dependencies_Args() { //arrange //act var result = ParseMagic( new[] { ArgumentParser.CommandArgs.Silent, ArgumentParser.CommandArgs.Run, "-s", "--help", "foo" }, null, null, new [] { "prerelease", "--max-file-age=42", "--nuget-source=http://local.site/path/here", "--force-nuget", "--prefer-nuget", "-f" }); //assert Assert.That(result.Run, Is.True); Assert.That(result.Verbosity, Is.EqualTo(Verbosity.ErrorsOnly)); Assert.That(result.RunArgs, Is.Not.Empty.And.EqualTo(new[] { "-s", "--help", "foo" })); Assert.That(result.UnprocessedCommandArgs, Is.Empty); Assert.That(result.DownloadArguments.Target, Does.StartWith(MagicModeFileSystemSystem.GetTempPath()).And.EndsWith(".exe")); Assert.That(result.DownloadArguments.MaxFileAgeInMinutes, Is.EqualTo(42)); }
public void Does_apply_custom_validation() { var client = new JsonServiceClient(Config.ListeningOn); try { var response = client.Send(new RegisterUser { Email = "*****@*****.**", DisplayName = "Test User", FirstName = "Test", LastName = "User", Password = Password, ConfirmPassword = Password, }); Assert.Fail("Should throw"); } catch (WebServiceException ex) { var status = ex.GetResponseStatus(); Assert.That(status.ErrorCode, Is.EqualTo(nameof(ArgumentNullException))); Assert.That(status.Message, Does.StartWith("Value cannot be null.")); Assert.That(status.Errors[0].FieldName, Is.EqualTo(nameof(MyUser.NetworkName))); } }
public void Caculator_Sum_ReturnSuccessfully() { //// Arange //Caculator caculator = new Caculator(); //// Act //int sum = caculator.Sum(3, 4); //// Assert //Assert.AreEqual(7, sum); //StringAssert.StartsWith("ab", "abc"); //CollectionAssert.Contains(new int[] { 1, 3, 5 }, 3); //FileAssert.Exists(@"c:\kms10.log"); //DirectoryAssert.DoesNotExist(@"c:\NoExists"); Assert.That("abcdef", Does.StartWith("ab").And.EndsWith("ef")); //StringAssert.StartsWith("ab", "abcdef"); //StringAssert.EndsWith("efx", "abcdef"); }
public void Expired_licenses_throws_LicenseException() { try { Licensing.RegisterLicense(TestBusiness2000Text); Assert.Fail("Should throw Expired LicenseException"); } catch (LicenseException ex) { ex.Message.Print(); Assert.That(ex.Message, Does.StartWith("This license has expired")); } try { Licensing.RegisterLicense(TestBusiness2000Text); Assert.Fail("Should throw Expired LicenseException"); } catch (LicenseException ex) { ex.Message.Print(); Assert.That(ex.Message, Does.StartWith("This license has expired")); } try { Licensing.RegisterLicense(TestTrial2001Text); Assert.Fail("Should throw Expired LicenseException"); } catch (LicenseException ex) { ex.Message.Print(); Assert.That(ex.Message, Does.StartWith("This trial license has expired") .Or.StartWith("This license has expired")); } }
public void TestAtBogførAsyncKasterArgumentExceptionVedIllegalDato(string illegalValue) { var fixture = new Fixture(); var finansstyringKonfigurationRepositoryMock = MockRepository.GenerateMock <IFinansstyringKonfigurationRepository>(); var finansstyringRepository = new FinansstyringRepository(finansstyringKonfigurationRepositoryMock); Assert.That(finansstyringRepository, Is.Not.Null); var dato = Convert.ToDateTime(illegalValue, new CultureInfo("en-US")); var exception = Assert.Throws <ArgumentException>(() => finansstyringRepository.BogførAsync(fixture.Create <int>(), dato, fixture.Create <string>(), fixture.Create <string>(), fixture.Create <string>(), fixture.Create <string>(), fixture.Create <decimal>(), fixture.Create <decimal>(), fixture.Create <int>()).Wait()); Assert.That(exception, Is.Not.Null); Assert.That(exception.Message, Is.Not.Null); Assert.That(exception.Message, Is.Not.Empty); Assert.That(exception.Message, Does.StartWith(Resource.GetExceptionMessage(ExceptionMessage.IllegalArgumentValue, "dato", dato))); Assert.That(exception.ParamName, Is.Not.Null); Assert.That(exception.ParamName, Is.Not.Empty); Assert.That(exception.ParamName, Is.EqualTo("dato")); Assert.That(exception.InnerException, Is.Null); finansstyringKonfigurationRepositoryMock.AssertWasNotCalled(m => m.FinansstyringServiceUri); }
public void StartsWithTests() { var phrase = "Hello World!"; var greetings = new[] { "Hello!", "Hi!", "Hola!" }; // Classic syntax StringAssert.StartsWith("Hello", phrase); // Constraint Syntax Assert.That(phrase, Does.StartWith("Hello")); // Only available using new syntax Assert.That(phrase, Does.Not.StartWith("Hi!")); Assert.That(phrase, Does.StartWith("HeLLo").IgnoreCase); Assert.That(phrase, Does.Not.StartWith("HI").IgnoreCase); Assert.That(greetings, Is.All.StartsWith("h").IgnoreCase); // Inherited syntax Expect(phrase, StartsWith("Hello")); // Only available using new syntax Expect(phrase, Not.StartsWith("Hi!")); Expect(phrase, StartsWith("HeLLo").IgnoreCase); Expect(phrase, Not.StartsWith("HI").IgnoreCase); Expect(greetings, All.StartsWith("h").IgnoreCase); }
public void parsing_start_and_create_messages() { ActivityMonitor m = new ActivityMonitor(false); StupidStringClient cLaunch = m.Output.RegisterClient(new StupidStringClient()); StupidStringClient.Entry[] dependentLogs = null; string dependentTopic = "A topic 'with' quotes '-\"..." + Environment.NewLine + " and multi-line"; dependentLogs = LaunchAndRunDependentActivityWithTopic(m, dependentTopic); string launchMessage = cLaunch.Entries[0].Text; string topicSetMessage = dependentLogs[0].Text; string startMessage = dependentLogs[1].Text; Assert.That(topicSetMessage, Is.EqualTo(ActivityMonitor.SetTopicPrefix + dependentTopic)); Assert.That(dependentLogs[2].Text, Is.EqualTo("Hello!")); Assert.That(launchMessage, Does.StartWith("Launching dependent activity")); bool launched; bool launchWithTopic; string launchDependentTopic; Assert.That(ActivityMonitor.DependentToken.TryParseLaunchOrCreateMessage(launchMessage, out launched, out launchWithTopic, out launchDependentTopic)); Assert.That(launched); Assert.That(launchWithTopic); Assert.That(launchDependentTopic, Is.EqualTo(dependentTopic)); Assert.That(startMessage, Does.StartWith("Starting dependent activity")); Guid id; DateTimeStamp time; Assert.That(ActivityMonitor.DependentToken.TryParseStartMessage(startMessage, out id, out time)); Assert.That(id, Is.EqualTo(((IUniqueId)m).UniqueId)); Assert.That(time, Is.EqualTo(cLaunch.Entries[0].LogTime)); }
public void Write_OneRowNeedQuoting_CorrectlyQuoted() { var table = new DataTable(); Load(table, new string[] { "a;11" }, "alpha1"); var csvWriter = new CsvWriter(false); using (MemoryStream stream = new MemoryStream()) { StreamWriter streamWriter = new StreamWriter(stream); csvWriter.Write(table, streamWriter); stream.Position = 0; using (StreamReader streamReader = new StreamReader(stream)) { var text = streamReader.ReadToEnd(); var firstCell = text.Split(new string[] { Csv.RecordSeparator }, StringSplitOptions.RemoveEmptyEntries)[0]; Assert.That(firstCell, Does.StartWith(Csv.TextQualifier.ToString())); Assert.That(firstCell, Does.EndWith(Csv.TextQualifier.ToString())); Assert.That(firstCell, Does.Contain(Csv.FieldSeparator.ToString())); } } }
public void IConvTest() { HRESULT hr = HRESULT.E_ACCESSDENIED; var c = (IConvertible)hr; var cv = (IConvertible)HRESULT.E_ACCESSDENIED; var f = System.Globalization.CultureInfo.CurrentCulture.NumberFormat; Assert.That(c.GetTypeCode(), Is.EqualTo(cv.GetTypeCode())); Assert.That(() => c.ToChar(f), Throws.Exception); Assert.That(() => c.ToSByte(f), Throws.Exception); Assert.That(() => c.ToByte(f), Throws.Exception); Assert.That(() => c.ToInt16(f), Throws.Exception); Assert.That(() => c.ToUInt16(f), Throws.Exception); Assert.That(c.ToUInt32(f), Is.EqualTo(unchecked ((uint)HRESULT.E_ACCESSDENIED))); Assert.That(c.ToInt32(f), Is.EqualTo(cv.ToInt32(f))); Assert.That(c.ToInt64(f), Is.EqualTo(cv.ToInt64(f))); Assert.That(c.ToUInt64(f), Is.EqualTo((ulong)unchecked ((uint)HRESULT.E_ACCESSDENIED))); Assert.That(c.ToSingle(f), Is.EqualTo(cv.ToSingle(f))); Assert.That(c.ToDouble(f), Is.EqualTo(cv.ToDouble(f))); Assert.That(c.ToDecimal(f), Is.EqualTo(cv.ToDecimal(f))); Assert.That(() => c.ToDateTime(f), Throws.Exception); Assert.That(c.ToString(f), Does.StartWith("E_ACCESSDENIED")); Assert.That(c.ToType(typeof(int), f), Is.EqualTo(cv.ToType(typeof(int), f))); }
public void Does_execute_ProductsPage_with_Sidebar_CodePage_layout() { var html = BaseUrl.AppendPath("products-sidebar").GetStringFromUrl(); Assert.That(html.NormalizeNewLines(), Does.StartWith(@"<html> <body id=sidebar> <ul> <li><a href='a.html'>A Page</a></li> <li><a href='b.html'>B Page</a></li> </ul> <table class='table'> <thead> <tr> <th>Category</th> <td>Name</td> <td>Price</td> </tr> </thead> <tr><th>Beverages</th><td>Chai</td><td>$18.00</td></tr> <tr><th>Beverages</th><td>Chang</td><td>$19.00</td></tr>".NormalizeNewLines() .Replace("$", System.Globalization.NumberFormatInfo.CurrentInfo.CurrencySymbol))); }
public void CanMoveAsPlayer_WithSneak() { var stats = new List <Stat> { new StatBuilder().With(t => t.AchievementType, StatsProcedures.Stat__TimesMoved).With(t => t.Amount, 8).BuildAndSave() }; var player = new PlayerBuilder() .With(i => i.ActionPoints, 10) .With(i => i.Location, LocationsStatics.STREET_200_SUNNYGLADE_DRIVE) .With(i => i.SneakPercent, 100) .With(p => p.User, new UserBuilder() .With(u => u.Stats, stats) .With(u => u.Id, "bob") .BuildAndSave()) .BuildAndSave(); var logs = player.MoveTo("coffee_shop_patio"); Assert.That(logs.SourceLocationLog, Is.EqualTo("John Doe left toward Carolyne's Coffee Shop (Patio)")); Assert.That(logs.DestinationLocationLog, Is.EqualTo("John Doe entered from Street: 200 Sunnyglade Drive")); Assert.That(logs.ConcealmentLevel, Is.GreaterThan(0)); Assert.That(player.PlayerLogs.ElementAt(0).Message, Does.StartWith( "You moved from <b>Street: 200 Sunnyglade Drive</b> to <b>Carolyne's Coffee Shop (Patio)</b>. (Concealment lvl <b>")); Assert.That(player.PlayerLogs.ElementAt(0).IsImportant, Is.False); Assert.That(player.Location, Is.EqualTo("coffee_shop_patio")); Assert.That(player.ActionPoints, Is.EqualTo(9)); Assert.That(player.User.Stats.First(s => s.AchievementType == StatsProcedures.Stat__TimesMoved).Amount, Is.EqualTo(9)); Assert.That(player.LastActionTimestamp, Is.EqualTo(DateTime.UtcNow).Within(10).Seconds); }
public void Linq14_original() { var context = CreateContext(new Dictionary <string, object> { { "numbersA", new[] { 0, 2, 4, 5, 6, 8, 9 } }, { "numbersB", new[] { 1, 3, 5, 7, 8 } }, }); Assert.That(context.EvaluateScript(@" Pairs where a < b: {{ numbersA |> zip(numbersB) |> where: it[0] < it[1] |> select: { it[0] } is less than { it[1] }\n }} ").NormalizeNewLines(), Does.StartWith(@" Pairs where a < b: 0 is less than 1 0 is less than 3 0 is less than 5 0 is less than 7 0 is less than 8 2 is less than 3 2 is less than 5 2 is less than 7 2 is less than 8 4 is less than 5 4 is less than 7 4 is less than 8 5 is less than 7 5 is less than 8 6 is less than 7 6 is less than 8 ".NormalizeNewLines())); }
public void IConvTest() { Win32Error err = Win32Error.ERROR_ACCESS_DENIED; var c = (IConvertible)err; var cv = (IConvertible)Win32Error.ERROR_ACCESS_DENIED; var f = System.Globalization.CultureInfo.CurrentCulture.NumberFormat; Assert.That(c.GetTypeCode(), Is.EqualTo(cv.GetTypeCode())); Assert.That(() => c.ToChar(f), Throws.Exception); Assert.That(c.ToSByte(f), Is.EqualTo(cv.ToSByte(f))); Assert.That(c.ToByte(f), Is.EqualTo(cv.ToByte(f))); Assert.That(c.ToInt16(f), Is.EqualTo(cv.ToInt16(f))); Assert.That(c.ToUInt16(f), Is.EqualTo(cv.ToUInt16(f))); Assert.That(c.ToInt32(f), Is.EqualTo(cv.ToInt32(f))); Assert.That(c.ToUInt32(f), Is.EqualTo(cv.ToUInt32(f))); Assert.That(c.ToInt64(f), Is.EqualTo(cv.ToInt64(f))); Assert.That(c.ToUInt64(f), Is.EqualTo(cv.ToUInt64(f))); Assert.That(c.ToSingle(f), Is.EqualTo(cv.ToSingle(f))); Assert.That(c.ToDouble(f), Is.EqualTo(cv.ToDouble(f))); Assert.That(c.ToDecimal(f), Is.EqualTo(cv.ToDecimal(f))); Assert.That(() => c.ToDateTime(f), Throws.Exception); Assert.That(c.ToString(f), Does.StartWith("ERROR_ACCESS_DENIED")); Assert.That(c.ToType(typeof(uint), f), Is.EqualTo(cv.ToType(typeof(uint), f))); }
public void Does_cache_MemoryStream_HttpResult_Responses_preserving_ContentType() { CacheStream.Count = 0; var request = new CacheStream { Id = 1, Value = "foo" }; var response = Config.ListeningOn.CombineWith(request.ToGetUrl()) .GetStringFromUrl(responseFilter: res => { Assert.That(res.GetHeader(HttpHeaders.ContentType), Does.StartWith(MimeTypes.Jsv)); Assert.That(res.GetHeader(HttpHeaders.CacheControl), Is.Null); }) .FromJsv <CacheStream>(); Assert.That(CacheStream.Count, Is.EqualTo(1)); AssertEquals(response, request); response = Config.ListeningOn.CombineWith(request.ToGetUrl()) .GetStringFromUrl(responseFilter: res => { Assert.That(res.GetHeader(HttpHeaders.ContentType), Does.StartWith(MimeTypes.Jsv)); Assert.That(res.GetHeader(HttpHeaders.CacheControl), Is.Null); }) .FromJsv <CacheStream>(); Assert.That(CacheStream.Count, Is.EqualTo(1)); AssertEquals(response, request); #if NNETFX var client = new JsvServiceClient(Config.ListeningOn); response = client.Get <CacheStream>(request); Assert.That(CacheStream.Count, Is.EqualTo(1)); AssertEquals(response, request); #endif }
public void NextRecords_Csv_CorrectResults(string text, string recordSeparator, int bufferSize) { using (var stream = new MemoryStream()) { var writer = new StreamWriter(stream); writer.Write(text); writer.Flush(); stream.Position = 0; var reader = new CsvReaderProxy(); using (var streamReader = new StreamReader(stream, Encoding.UTF8, true)) { var extraRead = string.Empty; var values = reader.GetNextRecords(streamReader, recordSeparator, bufferSize, string.Empty, out extraRead); foreach (var value in values) { Assert.That(value, Does.StartWith("abc")); Assert.That(value, Does.EndWith("abc").Or.EndWith("\0").Or.EndWith(recordSeparator)); } } writer.Dispose(); } }
private void AssertFailedInsertExceptionDetailsAndEmptyTable(Exception ex) { // We can get different sort of exceptions. if (ex is PropertyValueException) { // Some drivers/dialects set explicit parameter sizes, in which case we expect NH to // raise a PropertyValueException (to avoid ADO.NET from silently truncating). Assert.That( ex.Message, Does.StartWith("Error dehydrating property value for NHibernate.Test.TypesTest.StringClass.")); Assert.That(ex.InnerException, Is.TypeOf <HibernateException>()); Assert.That( ex.InnerException.Message, Is.EqualTo("The length of the string value exceeds the length configured in the mapping/parameter.")); } else if (Dialect is MsSqlCeDialect && ex is InvalidOperationException) { Assert.That(ex.Message, Does.Contain("max=4000, len=4001")); } else { // In other cases, we expect the database itself to raise an error. This case // will also happen if the driver does set an explicit parameter size, but that // size is larger than the mapped column size. Assert.That(ex, Is.TypeOf <GenericADOException>()); } // In any case, nothing should have been inserted. using (ISession s = OpenSession()) { Assert.That(s.Query <StringClass>().ToList(), Is.Empty); } }
public async Task SameColumnName() { using (var conn = await OpenConnectionAsync()) { await using var _ = await GetTempTableName(conn, out var table1); await using var __ = await GetTempTableName(conn, out var table2); await conn.ExecuteNonQueryAsync($@" CREATE TABLE {table1} (foo INTEGER); CREATE TABLE {table2} (foo INTEGER)"); using (var cmd = new NpgsqlCommand($"SELECT {table1}.foo,{table2}.foo FROM {table1},{table2}", conn)) using (var reader = await cmd.ExecuteReaderAsync(CommandBehavior.SchemaOnly | CommandBehavior.KeyInfo)) { var columns = reader.GetColumnSchema(); Assert.That(columns[0].ColumnName, Is.EqualTo("foo")); Assert.That(columns[0].BaseTableName, Does.StartWith("temp_table")); Assert.That(columns[1].ColumnName, Is.EqualTo("foo")); Assert.That(columns[1].BaseTableName, Does.StartWith("temp_table")); Assert.That(columns[0].BaseTableName, Is.Not.EqualTo(columns[1].BaseTableName)); } } }
public void response_should_send_200() { var obj = CreateInstance().GetResponse(); Assert.That(obj, Is.Not.Null, "IUEB3.GetResponse returned null"); var content = "Hello World, my GUID is " + Guid.NewGuid() + "!"; obj.SetContent(content); obj.SetStatusCode(200); using (var ms = new MemoryStream()) { obj.Send(ms); Assert.That(ms.Length, Is.GreaterThan(0)); ms.Seek(0, SeekOrigin.Begin); using (var sr = new StreamReader(ms)) { var firstLine = sr.ReadLine(); Assert.That(firstLine, Does.StartWith("HTTP/1.")); Assert.That(firstLine, Does.EndWith("200 OK")); } } }
public void Run_RunsExample() { var commandExample = new CommandExample( this.robotMock.Object, this.commandFactoryMock.Object, new CommandExecutionManager()); string outputString; using (var newOut = new StringWriter(CultureInfo.InvariantCulture)) { var previousOut = Console.Out; Console.SetOut(newOut); commandExample.Run(CancellationToken.None); Console.SetOut(previousOut); outputString = newOut.ToString(); } Assert.That(outputString, Does.StartWith("Running command example.")); this.commandMock.Verify(c => c.Execute(), Times.Exactly(6)); this.commandMock.Verify(c => c.Undo(), Times.Exactly(3)); }
public void ReferenceEqualsFailsWhenUsed() { var ex = Assert.Throws <InvalidOperationException>(() => CollectionAssert.ReferenceEquals(string.Empty, string.Empty)); Assert.That(ex.Message, Does.StartWith("CollectionAssert.ReferenceEquals should not be used for Assertions")); }
private void ExpectMessageFromQuery(Action query, string message) { var actualMessage = Assert.Throws <CallSequenceNotFoundException>(() => Received.InOrder(query)).Message; Assert.That(TrimAndFixLineEndings(actualMessage), Does.StartWith(TrimAndFixLineEndings(message))); }