public void GenerateFullManifest() { ManifestGenerator generator = new ManifestGenerator(); IntegrationRequest request = new IntegrationRequest(BuildCondition.ForceBuild, "Somewhere", null); IntegrationSummary summary = new IntegrationSummary(IntegrationStatus.Success, "A Label", "Another Label", new DateTime(2009, 1, 1)); IntegrationResult result = new IntegrationResult("Test project", "Working directory", "Artifact directory", request, summary); Modification modification1 = GenerateModification("first file", "Add"); Modification modification2 = GenerateModification("second file", "Modify"); result.Modifications = new Modification[] { modification1, modification2 }; List<string> files = new List<string>(); files.Add("first file"); XmlDocument manifest = generator.Generate(result, files.ToArray()); Assert.IsNotNull(manifest); string actualManifest = manifest.OuterXml; string expectedManifest = "<manifest>" + "<header project=\"Test project\" label=\"A Label\" build=\"ForceBuild\" status=\"Unknown\">" + "<modification user=\"johnDoe\" changeNumber=\"1\" time=\"2009-01-01T00:00:00\">" + "<comment>A comment</comment>" + "<file name=\"first file\" type=\"Add\" />" + "<file name=\"second file\" type=\"Modify\" />" + "</modification>" + "</header>" + "<file name=\"first file\" />" + "</manifest>"; Assert.AreEqual(expectedManifest, actualManifest); }
public void GetAllCategories_Test() { var service = Create<BlogEngineService>(); IList<Category> list = new List<Category>(); for (int i = 0; i < 5; i++) { list.Add(Mock<Category>()); } using (Record) { var categoryRepository = Get<ICategoryRepository>(); Expect.Call(categoryRepository.RetrieveAll()).Return(list); } using (Playback) { Category[] result = service.GetAllCategories(); Category[] expected = list.ToArray(); Assert.IsNotNull(result); CollectionAssert.AllItemsAreNotNull(result); CollectionAssert.AreEqual(result, expected); } }
public void Given_a_stable_live_cell_environment_when_a_moment_passes() { var cell_death_locations = new List<Location>(); var cell_birth_locations = new List<Location>(); var world = World.That_is_a_barren_wasteland(); world.When_a_cell_dies = location => cell_death_locations.Add(location); world.When_a_cell_comes_to_life = location => cell_birth_locations.Add(location); world.TouchCellAt(Location.At(0, 0)); world.TouchCellAt(Location.At(0, 1)); world.TouchCellAt(Location.At(1, 0)); world.MomentPassed(); Assert.That(cell_birth_locations, Is.EquivalentTo(new[] { Location.At(0, 0), Location.At(0, 1), Location.At(1, 0), Location.At(1,1) }), "it should have cause the touched cells to be born."); Assert.That(cell_death_locations.ToArray(), Is.Empty, "No cells should have died."); cell_death_locations.Clear(); cell_birth_locations.Clear(); world.MomentPassed(); Assert.That(cell_birth_locations, Is.EquivalentTo(Enumerable.Empty<Location>()), "nothing eventful should have happened"); Assert.That(cell_death_locations.ToArray(), Is.Empty, "nothing eventful should have happened"); }
/// <summary> /// This shows how to get the list of overridable methods in the /// Collection class using reflection only. /// </summary> public void GetMethodsThroughReflection() { Assembly a = Assembly.Load("mscorlib"); Type t = a.GetType("System.Collections.ObjectModel.Collection`1"); List<string> methodNames = new List<string>(); BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.DeclaredOnly | BindingFlags.Public; foreach (MethodInfo m in t.GetMethods(bindingFlags)) { if (m.IsVirtual && !m.IsSpecialName && !m.IsFinal) { methodNames.Add(m.Name); } } List<string> expectedMethodNames = new List<string>(); expectedMethodNames.Add("ClearItems"); expectedMethodNames.Add("InsertItem"); expectedMethodNames.Add("RemoveItem"); expectedMethodNames.Add("SetItem"); StringBuilder sb = new StringBuilder(); foreach (string s in methodNames.ToArray()) { sb.AppendLine(s); } Assert.AreEqual(expectedMethodNames.ToArray(), methodNames.ToArray(), sb.ToString()); }
public void TestBatchDeleteAttributes() { List<ReplaceableAttribute> list = new List<ReplaceableAttribute> (); list.Add (new ReplaceableAttribute ("Test", "Test", true)); List<ReplaceableItem> items = new List<ReplaceableItem> (); ReplaceableItem item0 = new ReplaceableItem ("0", list); items.Add (item0); ReplaceableItem item1 = new ReplaceableItem ("1", list); items.Add (item1); BatchPutAttributesRequest request = new BatchPutAttributesRequest ("Test", items); BatchPutAttributesResponse response = Client.BatchPutAttributes (request).Result; Assert.AreEqual (HttpStatusCode.OK, response.HttpStatusCode); List<Attribute> list2 = new List<Attribute> (); list2.Add (new Attribute ("Test", "Test")); List<Item> items2 = new List<Item> (); items2.Add (new Item ("0", list2.ToArray ())); items2.Add (new Item ("1", list2.ToArray ())); BatchDeleteAttributesRequest request2 = new BatchDeleteAttributesRequest ("Test", items2); BatchDeleteAttributesResponse response2 = Client.BatchDeleteAttributes (request2).Result; Assert.AreEqual (HttpStatusCode.OK, response2.HttpStatusCode); }
/// <summary> /// This shows how to get the list of overridable properties in the /// Exception class using reflection only. /// </summary> public void GetPropertiesThroughReflection() { Assembly a = Assembly.Load("mscorlib"); Type t = a.GetType("System.Exception"); List<string> propertyNames = new List<string>(); BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.DeclaredOnly | BindingFlags.Public; foreach (PropertyInfo p in t.GetProperties(bindingFlags)) { MethodInfo m = p.GetGetMethod(true); if (m.IsVirtual && !m.IsPrivate && !m.IsFinal) { propertyNames.Add(p.Name); } } List<string> expectedPropertyNames = new List<string>(); expectedPropertyNames.Add("Data"); expectedPropertyNames.Add("HelpLink"); expectedPropertyNames.Add("Message"); expectedPropertyNames.Add("Source"); expectedPropertyNames.Add("StackTrace"); StringBuilder sb = new StringBuilder(); foreach (string s in propertyNames.ToArray()) { sb.AppendLine(s); } Assert.AreEqual(expectedPropertyNames.ToArray(), propertyNames.ToArray(), sb.ToString()); }
public void ArrayLiterals() { var array = new[] { 42 }; Assert.AreEqual (typeof(int[]), array.GetType (), "You don't have to specify a type if the elements can be inferred"); Assert.AreEqual (new int[] { 42 }, array, "These arrays are literally equal... But you won't see this string in the error message."); //Are arrays 0-based or 1-based? Assert.AreEqual (42, array [0], "Well, it's either 0 or 1.. you have a 110010-110010 chance of getting it right."); //This is important because... Assert.IsTrue (array.IsFixedSize, "...because Fixed Size arrays are not dynamic"); //Begin RJG // Moved this Throws() call to a separate FixedSizeArraysCannotGrow() method below //...it means we can't do this: array[1] = 13; //Assert.Throws(typeof(FILL_ME_IN), delegate() { array[1] = 13; }); //End RJG //This is because the array is fixed at length 1. You could write a function //which created a new array bigger than the last, copied the elements over, and //returned the new array. Or you could do this: var dynamicArray = new List<int> (); dynamicArray.Add (42); CollectionAssert.AreEqual (array, dynamicArray.ToArray (), "Dynamic arrays can grow"); dynamicArray.Add (13); CollectionAssert.AreEqual ((new int[] { 42, (int)13 }), dynamicArray.ToArray (), "Identify all of the elements in the array"); }
public void TestHourRollOver() { VistaDateTimeIterator testIterator = new VistaDateTimeIterator( new DateTime(2008, 01, 01, 22, 0, 0) , new DateTime(2008, 01, 03) , new TimeSpan(1, 0, 0) ); List<string> values = new List<string>(); while (!testIterator.IsDone()) { testIterator.SetIterEndDate(); // put at start of loop values.Add(testIterator.GetDdrListerPart()); testIterator.AdvanceIterStartDate(); // put at end of loop } int result = string.Concat(values.ToArray()).GetHashCode(); //Spot Check - Count Assert.AreEqual(26, values.Count); String[] strings = values.ToArray(); //Spot Check - Validate Start Value Assert.IsTrue(strings[0].Equals("3080101.22")); //Spot Check - Validate End Value Assert.IsTrue(strings[25].Equals("3080102.23")); //Spot Check - Validate an Intermediate Value Assert.IsTrue(strings[14].Equals("3080102.12")); //Hash Code is not stable acrosss .Net Versions //Assert.AreEqual(1712919498, result); }
public void TestCollectionsGroupReturnsCorrectInnerCollectionNames() { IEnumerable<string> sectionNames = ConfigurationSection.Collections.SectionNames; Assert.IsNotNull(sectionNames); IList<string> names = new List<string>(sectionNames); Assert.AreEqual(2, names.Count); Assert.Contains("col1", names.ToArray()); Assert.Contains("col2", names.ToArray()); }
public void RunUnprocessOnExistingProcessor() { List<ViewProcessorMapping> mappings = new List<ViewProcessorMapping> (); mappings.Add(new ViewProcessorMapping(new TypeMatcher().AllOf(view.GetType()).CreateTypeFilter(), trackingProcessor)); viewProcessorFactory.RunProcessors(view, view.GetType(), mappings.ToArray()); viewProcessorFactory.RunUnprocessors(view, view.GetType(), mappings.ToArray()); Assert.That (trackingProcessor.UnprocessedViews, Is.EquivalentTo(new object[1]{ view })); }
public void CopyConstructorPUT(List<int> values) { AvlTree<int> avlTree = new AvlTree<int>(values); PexAssume.AreDistinctValues<int>(values.ToArray()); List<int> actual = new List<int>(values.Count); foreach(int i in avlTree) { actual.Add(i); } CollectionAssert.AreEquivalent(values.ToArray(), actual.ToArray()); }
public void BenchmarkPolygons() { var factory = GeometryFactory.Default; var holes = new List<ILinearRing>(100); var shell = CreateRing(0, 0, 20, 10000); Benchmark(factory.CreatePolygon(shell, holes.ToArray())); for (var i = 0; i < 100; i += 5) { holes.Add(CreateRing((i % 10) - 5, (i / 10) - 5, 0.4, 500)); Benchmark(factory.CreatePolygon(shell, holes.ToArray())); } }
public void TestOptionsParamParser3() { ParamParser parser = new ParamParser(); List<string> args = new List<string>(); args.Add(TEST_FOLDER); args.Add("/exclude:TrackChanges"); Assert.IsFalse(parser.Parse(args.ToArray())); args.Add("/All"); Assert.IsTrue(parser.Parse(args.ToArray())); }
private static AnalysisOccurrence[] GetParaAnalyses(IStTxtPara para) { var result = new List<AnalysisOccurrence>(); var point1 = new AnalysisOccurrence(para.SegmentsOS[0], 0); if (!point1.IsValid) return result.ToArray(); do { if (point1.HasWordform) result.Add(point1); point1 = point1.NextWordform(); } while (point1 != null && point1.IsValid); return result.ToArray(); }
public void ExecuteRunsSuccessAndFailureTasks() { // Initialise the task var subTasks = new List<ParallelTestTask>(); for (var loop = 1; loop <= 5; loop++) { subTasks.Add(new ParallelTestTask { TaskNumber = loop, Result = loop >= 3 ? IntegrationStatus.Failure : IntegrationStatus.Success }); } var task = new ParallelTask { Tasks = subTasks.ToArray() }; // Setup the mocks var logger = mocks.DynamicMock<ILogger>(); var result = GenerateResultMock(false); mocks.ReplayAll(); // Run the actual task task.Run(result); // Verify the results mocks.VerifyAll(); Assert.AreEqual(IntegrationStatus.Failure, result.Status, "Status does not match"); }
public void TestCoalesce2() { StreamSink<int> s = new StreamSink<int>((x, y) => x + y); List<int> @out = new List<int>(); using (s.Listen(@out.Add)) { Transaction.RunVoid(() => { s.Send(1); s.Send(2); s.Send(3); s.Send(4); s.Send(5); }); Transaction.RunVoid(() => { s.Send(6); s.Send(7); s.Send(8); s.Send(9); s.Send(10); }); } CollectionAssert.AreEqual(new[] { 15, 40 }, @out.ToArray()); }
// The purpose of this test is to make sure that // new encodings added to I18N are also listed in the // returned array from Encoding.GetEncodings() so that // we can make sure to put additional encodings into // Encoding.GetEncodings() code. public void EncodingGetEncodingsReturnsAll () { // Make sure that those I18N assemblies are loaded. string basePath = Assembly.GetAssembly (typeof (int)).CodeBase; basePath = basePath.Substring (0, basePath.LastIndexOf ('/')); Assert.IsNotNull (Assembly.LoadFrom (basePath + "/I18N.West.dll"), "West"); Assert.IsNotNull (Assembly.LoadFrom (basePath + "/I18N.CJK.dll"), "CJK"); Assert.IsNotNull (Assembly.LoadFrom (basePath + "/I18N.MidEast.dll"), "MidEast"); Assert.IsNotNull (Assembly.LoadFrom (basePath + "/I18N.Rare.dll"), "Rare"); Assert.IsNotNull (Assembly.LoadFrom (basePath + "/I18N.Other.dll"), "Other"); List<int> list = new List<int> (); for (int i = 1; i < 0x10000; i++) { // Do this in a method to work around #5432 GetEncoding (i, list); } int [] reference = list.ToArray (); EncodingInfo [] infos = Encoding.GetEncodings (); int [] actual = new int [infos.Length]; for (int i = 0; i < infos.Length; i++) actual [i] = infos [i].CodePage; Assert.AreEqual (reference, actual); }
public static List<QualityProfileItem> GetDefaultQualities(params Quality[] allowed) { var qualities = new List<Quality> { Quality.SDTV, Quality.WEBDL480p, Quality.DVD, Quality.HDTV720p, Quality.HDTV1080p, Quality.RAWHD, Quality.WEBDL720p, Quality.Bluray720p, Quality.WEBDL1080p, Quality.Bluray1080p }; if (allowed.Length == 0) allowed = qualities.ToArray(); var items = qualities .Except(allowed) .Concat(allowed) .Select(v => new QualityProfileItem { Quality = v, Allowed = allowed.Contains(v) }).ToList(); return items; }
public void NUnitTestRunnerAddedToTestRunnersCreatedList() { List<NUnitTestRunner> expectedRunners = new List<NUnitTestRunner>(); expectedRunners.Add(testRunner); Assert.AreEqual(expectedRunners.ToArray(), testFramework.NUnitTestRunnersCreated.ToArray()); }
public void ShouldBeUnique() { var generatedIds = new ConcurrentBag<Guid>(); var tasks = new List<Task>(); var i = Count; while (i-- > 0) { tasks.Add( Task.Factory.StartNew( () => { for (var j = 0; j < 100; j++) { var id = SeqGuid.NewGuid(); generatedIds.Add(id); } })); } Task.WaitAll(tasks.ToArray()); Assert.That(new HashSet<Guid>(generatedIds).Count, Is.EqualTo(Count * 100)); }
public void TestConcurrentAccess() { Init(); var path = GetTestPath("TestMtLogImitation"); var filePath = Path.Combine(path, "TestFile.log"); var ids = new List<string>(); var position = 0L; Trace.WriteLine("Writing the file"); FillWithZeros(filePath); StartShipperService(); for (var i = 0; i < 5; i++) { var line = GetLog(ids, 1); var splitIndex = line.Length / 2; AppendToLog(filePath, ref position, line.Substring(0, splitIndex), null); Thread.Sleep(TimeSpan.FromSeconds(2)); AppendToLog(filePath, ref position, line.Substring(splitIndex), null); } GetAndValidateRecords(ids.ToArray()); StopShipperService(); }
public void Run(string[] args, string sourceFile, string targetFile, bool checkOutput) { // console programs' Main are static, so lock concurrent access to // a test code. we use a private field to lock upon lock (locked) { List<string> completeArgs = new List<string>(args.Length + 2); for (int i = 0; i < args.Length; ++i) completeArgs.Add(args[i]); completeArgs.Add(sourceFile); completeArgs.Add(targetFile); File.Delete(targetFile); BitMiracle.TiffCP.Program.Main(completeArgs.ToArray()); string sampleFile = targetFile.Replace(@"\Output.Tiff\", @"\Expected.Tiff\"); Assert.IsTrue(File.Exists(targetFile)); if (checkOutput) FileAssert.AreEqual(sampleFile, targetFile); } }
public void CanThrottle1Per3Seconds() { var f = new TestRequestFactory(); var t = new ThrottedRequestQueue(TimeSpan.FromSeconds(3), 1, 10); var sw = new Stopwatch(); sw.Start(); var handles = new List<WaitHandle>(); for (int i = 0; i < 3; i++) { var gate = new AutoResetEvent(false); handles.Add(gate); f.CreateTestRequest("foo" + i); const string url = "http://tmpuri.org"; var r = f.Create(url); int i1 = i; t.Enqueue(url, r, (ar, ignored) => { string expected = "foo" + i1; var response = r.EndGetResponse(ar); var actual = new StreamReader(response.GetResponseStream()).ReadToEnd(); Trace.WriteLine(actual); Assert.AreEqual(expected, actual); gate.Set(); }); } WaitHandle.WaitAll(handles.ToArray()); sw.Stop(); Assert.GreaterOrEqual(sw.ElapsedMilliseconds, 5800, "3 requests, 2 throttled - expect almost 6 seconds delay for 3 requests"); }
BuildProperty [] GetProperties (BuildPropertyGroup bpg) { List<BuildProperty> list = new List<BuildProperty> (); foreach (BuildProperty bp in bpg) list.Add (bp); return list.ToArray (); }
public void TestListenerWithNonSmartRouting() { var map = Client.GetMap<string, string>(TestSupport.RandomString()); var keys = TestSupport.RandomArray(TestSupport.RandomString, 10); var registrations = new List<string>(); var tasks = new List<Task>(); foreach (var key in keys) { var tcs = new TaskCompletionSource<bool>(); var id = map.AddEntryListener(new EntryAdapter<string, string> { Added = e => tcs.SetResult(true) }, key, false); registrations.Add(id); tasks.Add(tcs.Task); } foreach (var key in keys) { map.Put(key, TestSupport.RandomString()); } Assert.IsTrue(Task.WaitAll(tasks.ToArray(), 500), "Did not get all entry added events within 500ms"); foreach (var id in registrations) { Assert.IsTrue(map.RemoveEntryListener(id)); } }
public static StringBuilder SetComplexTypes(List<string> strlist, IList<int> intlist, Dictionary<string, int> map, string[] strarray, int[] intarray) { StringBuilder sb = new StringBuilder(); sb.Append(string.Join(",", strlist.ToArray())); sb.Append("|"); sb.Append(string.Join(",", intlist.Select(i => i.ToString()).ToArray())); sb.Append("|"); sb.Append(string.Join(",", map.Keys.OrderBy(x => x).Select(i => i.ToString()).ToArray())); sb.Append("|"); sb.Append(string.Join(",", map.Values.OrderBy(x => x).Select(i => i.ToString()).ToArray())); sb.Append("|"); sb.Append(string.Join(",", strarray)); sb.Append("|"); sb.Append(string.Join(",", intarray.Select(i => i.ToString()).ToArray())); return sb; }
public void it_should_reset_a_new_battle() { var ds = CreateSample(30, null); var raceEvents = new List<OverlayData.RaceEvent>(); var re = new RemovalEdits(raceEvents); var markerB = re.For(InterestState.Battle); var markerI = re.For(InterestState.Incident); markerB.Start(); re.Process(ds, 10.Seconds()); markerB.Start(); re.Process(ds, 15.Seconds()); markerB.Stop(); re.Process(ds, 18.Seconds()); markerI.Start(); re.Process(ds, 20.Seconds()); markerI.Stop(); re.Process(ds, 22.Seconds()); Assert.That(raceEvents.ToArray(), Is.EqualTo( new[] { new OverlayData.RaceEvent { StartTime = 10d, EndTime = 15d, Interest = InterestState.Battle}, new OverlayData.RaceEvent { StartTime = 15d, EndTime = 18d, Interest = InterestState.Battle}, new OverlayData.RaceEvent { StartTime = 20d, EndTime = 22d, Interest = InterestState.Incident}, })); }
public void PathCombineTestCase() { var list = new List<String> { @"C:\", "Temp", "Test", "test.xml" }; var expected = Path.Combine( list.ToArray() ); var actual = list.PathCombine(); Assert.AreEqual( expected, actual ); }
public void AllSimpleTests() { var defaultProvider = MakeDefaultProvider(); var simpleTests = Directory.GetFiles( Path.GetFullPath(Path.Combine(ComparisonTest.TestSourceFolder, "SimpleTestCases")), "*.cs" ); var failureList = new List<string>(); foreach (var filename in simpleTests) { Console.Write("// {0} ... ", Path.GetFileName(filename)); try { // We reuse the same type info provider for all the tests in this folder so they run faster using (var test = new ComparisonTest(filename, null, defaultProvider)) test.Run(); } catch (Exception ex) { failureList.Add(Path.GetFileNameWithoutExtension(filename)); if (ex.Message == "JS test failed") Debug.WriteLine(ex.InnerException); else Debug.WriteLine(ex); } } Assert.AreEqual(0, failureList.Count, String.Format("{0} test(s) failed:\r\n{1}", failureList.Count, String.Join("\r\n", failureList.ToArray())) ); }
public void TestDuplicateTransaction() { BlockMessage validBlock1 = BlockMessage.Read(new BitcoinStreamReader(new MemoryStream(KnownBlocks.Block100001))); BlockMessage validBlock2 = BlockMessage.Read(new BitcoinStreamReader(new MemoryStream(KnownBlocks.Block100002))); Assert.True(BlockContentValidator.IsMerkleTreeValid(validBlock1)); Assert.True(BlockContentValidator.IsMerkleTreeValid(validBlock2)); Assert.That(validBlock1.Transactions.Length, Is.EqualTo(12)); Assert.That(validBlock2.Transactions.Length, Is.EqualTo(9)); List<Tx> transactions1 = new List<Tx>(validBlock1.Transactions); transactions1.Add(validBlock1.Transactions[8]); transactions1.Add(validBlock1.Transactions[9]); transactions1.Add(validBlock1.Transactions[10]); transactions1.Add(validBlock1.Transactions[11]); BlockMessage invalidBlock1 = new BlockMessage(validBlock1.BlockHeader, transactions1.ToArray()); List<Tx> transactions2 = new List<Tx>(validBlock2.Transactions); transactions2.Add(validBlock2.Transactions[8]); BlockMessage invalidBlock2 = new BlockMessage(validBlock2.BlockHeader, transactions2.ToArray()); Assert.That(MerkleTreeUtils.GetTreeRoot(invalidBlock1.Transactions), Is.EqualTo(invalidBlock1.BlockHeader.MerkleRoot)); Assert.That(MerkleTreeUtils.GetTreeRoot(invalidBlock2.Transactions), Is.EqualTo(invalidBlock2.BlockHeader.MerkleRoot)); Assert.False(BlockContentValidator.IsMerkleTreeValid(invalidBlock1)); Assert.False(BlockContentValidator.IsMerkleTreeValid(invalidBlock2)); }