public void All() { // arrange List<String> list = new List<String>() { "Backbone", "Angular", "React" }; // act Boolean actual = list.All(x => x == "Angular" || x == "Backbone" || x == "React"); Boolean actualNotFound = list.All(x => x == "Angular" || x == "React"); // assert Assert.AreEqual(true, actual); Assert.AreEqual(false, actualNotFound); }
public void GenerateProcessedVedeoTest() { //Arrange var calculator = new Mock<IResolutionCalculator>(); var paramFactory = new Mock<IMultimediaAdjusterParamFactory>(); var processedVideoList = new Mock<IProcessedVideoList>(); var processedVideoGenerator = new ProcessedVideoGenerator(calculator.Object, paramFactory.Object, processedVideoList.Object); var videoParam = new VideoAdjusterParam(); var audioParam = new AudioAdjusterParam(); var sizeList = new List<IVideoSize>(); var mp4ProcessedVideos = new List<DomainProcessedVideo> {new DomainProcessedVideo()}; var webmProcessedVideos = new List<DomainProcessedVideo> {new DomainProcessedVideo()}; var metadata = new Mock<IVideoMetadata>(); metadata.Setup(p => p.VideoWidth).Returns(2345); metadata.Setup(p => p.VideoHeight).Returns(345); calculator.Setup(m => m.Calculate(metadata.Object.VideoWidth, metadata.Object.VideoHeight)).Returns(sizeList); paramFactory.Setup(m => m.CreateVideoParam(metadata.Object)).Returns(videoParam); paramFactory.Setup(m => m.CreateAudioParam(metadata.Object)).Returns(audioParam); processedVideoList.Setup(m => m.CreateProcessedVideos(videoParam, audioParam, MetadataConstant.Mp4Container, sizeList, ContentType.Mp4Content)).Returns(mp4ProcessedVideos); processedVideoList.Setup(m => m.CreateProcessedVideos(videoParam, audioParam, MetadataConstant.WebmContainer, sizeList, ContentType.WebmContent)).Returns(webmProcessedVideos); //Act List<DomainProcessedVideo> list = processedVideoGenerator.Generate(metadata.Object); //Assert Assert.AreEqual(mp4ProcessedVideos.Count + webmProcessedVideos.Count, list.Count); Assert.IsTrue(mp4ProcessedVideos.All(p => list.Any(procVid => procVid == p))); Assert.IsTrue(webmProcessedVideos.All(p => list.Any(procVid => procVid == p))); }
public void ShouldRetunAListContaining6ArtistsBasedOnFilterForJoh() { //arange ArtistManager artistManager = new ArtistManager(new EFArtistDAL()); var artistReturnedList = new List<Artist>(); var artistFilter = new ArtistFilter(); artistFilter.ArtistNameAndAliasSearchTerm = "Joh"; List<String> expectedNames = new List<string>(); expectedNames.Add("John Mayer"); expectedNames.Add("Johnny Cash"); expectedNames.Add("Jack Johnson"); expectedNames.Add("John Coltrane"); expectedNames.Add("Elton John"); expectedNames.Add("John Frusciante"); //act artistReturnedList = artistManager.GetAllRecordsBasedOnFilter(artistFilter); List<string> actualNames = new List<string>(); foreach(var artist in artistReturnedList) { actualNames.Add(artist.ArtistName); } // same number of artist and same artits (regardless of order) bool test = expectedNames.All(actualNames.Contains) && expectedNames.Count == actualNames.Count; //assert Assert.AreEqual(true, test); }
public async Task TestFindShortestRouteBetweenAsyncProgress() { var cities = new Cities(); cities.ReadCities(CitiesTestFile); var routes = new Routes(cities); routes.ReadRoutes(LinksTestFile); // do synchronous execution var linksExpected = routes.FindShortestRouteBetween("Basel", "Zürich", TransportMode.Rail); // do asynchronous execution var messages = new List<string>(); var progress = new Progress<string>(msg => messages.Add(msg)); var linksActual = await routes.FindShortestRouteBetweenAsync("Basel", "Zürich", TransportMode.Rail, progress); // let pending tasks execute await Task.Yield(); // ensure that at least 5 progress calls are made Assert.IsTrue(messages.Distinct().Count()>=5, "Less than 5 distinct progress messages"); // ensure that all progress messages end with " done" Assert.IsTrue(messages.All(m => m.EndsWith(" done")), string.Format("Progress message \"{0}\" does not end with \" done\"", messages.FirstOrDefault(m => !m.EndsWith(" done")))); }
public void ListExtensions_All_ReturnsFalseIfOneItemDoesNotMatchPredicate() { var list = new List<Int32>() { 1, 2, 4, 6 }; var result = list.All(x => x % 2 == 0); TheResultingValue(result).ShouldBe(false); }
public void AreAllStringsLongerThan5_ReturnsTrueWhenAllStringsSatisfy() { var stringData = new List<string> { "somethingLonger", "aaaaaaaa", "bbbbbbb", "something" }; var expected = stringData.All(s => s.Length > 5); var result = Ex1.AreAllStringsLongerThan5(stringData); result.Should().BeTrue(); }
public void ListExtensions_All_ReturnsTrueIfAllItemsMatchPredicate() { var list = new List<Int32>() { 2, 4, 6 }; var result = list.All(x => x % 2 == 0); TheResultingValue(result).ShouldBe(true); }
public void AreAllStringsLongerThan5_ReturnsFalseWhenTooShortStringExists() { var stringData = new List<string> {"somethingLonger", "aaaaaaaa", "bbbbbbb", "", "something", "4444"}; var expected = stringData.All(s => s.Length > 5); var result = Ex1.AreAllStringsLongerThan5(stringData); result.Should().BeFalse(); }
public void ListExtensions_All_ReturnsTrueIfListIsEmpty() { var list = new List<Int32>(); var result = list.All(x => x % 2 == 0); TheResultingValue(result).ShouldBe(true); }
public static bool CompareEnumerable(IEnumerable<int> e1, IEnumerable<int> e2) { if (e1 == null || e2 == null) return false; if (ReferenceEquals(e1, e2)) return true; var l1 = new List<int>(e1); var l2 = new List<int>(e2); return l1.Count == l2.Count && l1.All(l2.Remove); }
public void All_abnormal() { // arrange List<String> list = new List<String>() { "Backbone", "Angular", "React" }; // act and assert try { list.All(null); Assert.Fail(); } catch (Exception e) { Assert.IsTrue(e is ArgumentNullException); } }
public void StorageFourStoreAddTriples() { StorageFourStoreDeleteGraph(); StorageFourStoreSaveGraph(); Graph g = new Graph(); List<Triple> ts = new List<Triple>(); ts.Add(new Triple(g.CreateUriNode(new Uri("http://example.org/subject")), g.CreateUriNode(new Uri("http://example.org/predicate")), g.CreateUriNode(new Uri("http://example.org/object")))); FourStoreConnector fourstore = new FourStoreConnector(FourStoreTestUri); fourstore.UpdateGraph("http://example.org/4storeTest", ts, null); fourstore.LoadGraph(g, "http://example.org/4storeTest"); Assert.IsTrue(ts.All(t => g.ContainsTriple(t)), "Added Triple should not have been in the Graph"); }
public void GetUnderlyingType__The_Underlying_Type_Of_A_Property_Can_Be_Obtained() { var properties = new MixedProperties(); var propertyInfo = properties.GetType().GetProperties(); var results = new List<bool> { propertyInfo[0].GetUnderlyingType() == typeof (bool), propertyInfo[1].GetUnderlyingType() == typeof (DateTime), propertyInfo[2].GetUnderlyingType() == typeof (Dog), propertyInfo[3].GetUnderlyingType() == typeof (int), propertyInfo[4].GetUnderlyingType() == typeof (DateTime), propertyInfo[5].GetUnderlyingType() == typeof (string) }; Assert.IsTrue(results.All(r => r)); }
public void IsNullableType__A_Nullable_Property_Can_Be_Detected_As_Nullable() { var properties = new MixedProperties(); var propertyInfo = properties.GetType().GetProperties(); var results = new List<bool> { propertyInfo[0].IsNullableType() == false, propertyInfo[1].IsNullableType() == false, propertyInfo[2].IsNullableType(), propertyInfo[3].IsNullableType() == false, propertyInfo[4].IsNullableType(), propertyInfo[5].IsNullableType() }; Assert.IsTrue(results.All(r => r)); }
public void GetDefaultValue__An_Default_Value_From_A_Property_Can_Be_Obtained() { var properties = new MixedProperties(); var propertyInfo = properties.GetType().GetProperties(); var results = new List<bool> { (bool)propertyInfo[0].GetDefaultValue() == false, (DateTime)propertyInfo[1].GetDefaultValue() == DateTime.MinValue, (Dog)propertyInfo[2].GetDefaultValue() == null, (int)propertyInfo[3].GetDefaultValue() == 0, (DateTime?)propertyInfo[4].GetDefaultValue() == null, (string)propertyInfo[5].GetDefaultValue() == null }; Assert.IsTrue(results.All(r => r)); }
public void GetAllResolutionsForHDVideoTest() { //Arrange const int width = 1920; const int height = 1080; var calculator = new ResolutionCalculator(); var expectedResolution = new List<IVideoSize>() { new VideoSize(640, 360), new VideoSize(854, 480), new VideoSize(1280, 720), new VideoSize(1920, 1080) }; //Act var resolutionList = calculator.Calculate(width, height); //Assert Assert.IsTrue(expectedResolution.All(videoSize => resolutionList.Any(s => s.Width == videoSize.Width && s.Height == videoSize.Height))); }
public void Dispose_MultipleItems_DisposesAllItems() { // Arrange var scope = new Scope(); var disposables = new List<DisposableObject> { new DisposableObject(), new DisposableObject(), new DisposableObject() }; disposables.ForEach(scope.RegisterForDisposal); // Act scope.Dispose(); // Assert Assert.IsTrue(disposables.All(d => d.IsDisposedOnce)); }
public void AsyncDelegateThreading1() { //Arrange var list = new List<GeneralAlgorithm>(); Enumerable.Range(1, 10).Aggregate(list, (whole, next) => { whole.Add(new GeneralAlgorithm(next)); return whole; }); Trace.WriteLine($"[{Environment.CurrentManagedThreadId}] Arrange {DateTime.Now.ToString(Constant.PrecisionFormat)}"); //Act list.ForEach(x => x.EjecutarDelegado()); Thread.Sleep(4000); //Assert Trace.WriteLine($"[{Environment.CurrentManagedThreadId}] Assert {DateTime.Now.ToString(Constant.PrecisionFormat)}"); list.ForEach(x => Trace.WriteLine(x.Result)); Assert.IsTrue(list.All(n => !n.Result.StartsWith($"[{Environment.CurrentManagedThreadId}]"))); }
public async Task StopTest() { //Arrange var dbConnection = new StubIEntityContextConnection { NameOrConnectionStringGet = () => "am-StopTest" }; Database.SetInitializer(new CreateFreshDbInitializer()); var logEntries = new List<LogEntry>(); var log = new StubIFeedback<LogEntry> { ReportAsyncT0CancellationToken = (e, c) => { logEntries.Add(e); Console.WriteLine(e.ToString()); return Task.FromResult(0); } }; var adapter = new Adapter() { AdapterGuid = Guid.Parse("a0f912a6-b8bb-406a-360f-1eb13f50aae4"), IsEnabled = true }; using (var context = new ZvsContext(dbConnection)) { context.Adapters.Add(adapter); await context.SaveChangesAsync(CancellationToken.None); } var isStartedCount = 0; var isStoppedCount = 0; var unitTestingAdapter = new StubUnitTestAdapter { AdapterGuidGet = () => Guid.Parse("a0f912a6-b8bb-406a-360f-1eb13f50aae4"), NameGet = () => "Unit Testing Adapter", DescriptionGet = () => "", OnDeviceTypesCreatingDeviceTypeBuilder = (s) => Task.FromResult(0), OnSettingsCreatingAdapterSettingBuilder = (s) => Task.FromResult(0), StartAsync01 = () => { isStartedCount++; return Task.FromResult(0); }, StopAsync01 = () => { isStoppedCount++; return Task.FromResult(0); } }; var adapterManager = new AdapterManager(new List<ZvsAdapter> { unitTestingAdapter }, dbConnection, log); //act await adapterManager.StartAsync(CancellationToken.None); await adapterManager.StopAsync(CancellationToken.None); //assert Assert.IsTrue(logEntries.All(o => o.Level == LogEntryLevel.Info), "Not all log entries are info level"); Assert.IsTrue(isStartedCount == 1, "Plugin started too many or too few times"); Assert.IsTrue(isStoppedCount == 1, "Plugin stopped too many or too few times"); }
public void Dispose_WithMultipleItemsThatThrow_StillDisposesAllItems() { // Arrange var scope = new Scope(); var disposables = new List<DisposableObject> { new DisposableObject(new Exception()), new DisposableObject(new Exception()), new DisposableObject(new Exception()) }; disposables.ForEach(scope.RegisterForDisposal); try { // Act scope.Dispose(); // Assert Assert.Fail("Exception was expected to bubble up."); } catch { Assert.IsTrue(disposables.All(d => d.IsDisposedOnce)); } }
public async Task ContraLessThanTest() { //Arrange var dbConnection = new StubIEntityContextConnection { NameOrConnectionStringGet = () => "Trigger-ContraLessThanTest" }; Database.SetInitializer(new CreateFreshDbInitializer()); var logEntries = new List<LogEntry>(); var ranstoredCommands = new List<int>(); var log = new StubIFeedback<LogEntry> { ReportAsyncT0CancellationToken = (e, c) => { Console.WriteLine(e.ToString()); logEntries.Add(e); return Task.FromResult(0); } }; var commandProcessor = new StubICommandProcessor { RunCommandAsyncNullableOfInt32StringStringCancellationToken = ( commandId, argument, argument2, cancellationToken) => { if (commandId.HasValue) ranstoredCommands.Add(commandId.Value); return Task.FromResult(Result.ReportSuccess()); } }; Database.SetInitializer(new CreateFreshDbInitializer()); var cts = new CancellationTokenSource(); var triggerManager = new TriggerRunner(log, commandProcessor, dbConnection); await triggerManager.StartAsync(cts.Token); var cmd = new Command(); var dv = new DeviceValue { Value = "first value", ValueType = DataType.STRING, Triggers = new ObservableCollection<DeviceValueTrigger> { new DeviceValueTrigger { Name = "trigger1", IsEnabled = true, Operator = TriggerOperator.LessThan, Value = "1", Command = cmd } } }; var device = UnitTesting.CreateFakeDevice(); device.Values.Add(dv); using (var context = new ZvsContext(dbConnection)) { context.Devices.Add(device); var r = await context.TrySaveChangesAsync(cts.Token); Assert.IsFalse(r.HasError, r.Message); dv.Value = "3"; //Act var r2 = await context.TrySaveChangesAsync(cts.Token); Assert.IsFalse(r2.HasError, r2.Message); } await Task.Delay(700, cts.Token); await triggerManager.StopAsync(cts.Token); //Assert Assert.IsTrue(logEntries.All(o => o.Level != LogEntryLevel.Error), "Expected no error log entries"); Assert.IsTrue(ranstoredCommands.Count == 0, "Trigger runner did not run the correct amount of commands."); }
public async Task MinimumElapsedTest2() { //Add a few items to the queue, and then wait the minimum amount of time specified on the batch processor and check that //both items were processed as a single batch int timeoutMs = 3000; const int expectedBatchID = 1; int batchID = expectedBatchID; await TestSimpleSetup( itemHandler: (req) => batchID, onBatchProcessed: () => batchID++, //Increment the batch ID after each batch gets processed minimumTimeIntervalMs: timeoutMs); ///Enqueue a batch of 3 items and time their completion var results = new List<Task<object>>(); Stopwatch stopwatch = Stopwatch.StartNew(); results.Add(processor.EnqueueAsync(5)); results.Add(processor.EnqueueAsync(6)); results.Add(processor.EnqueueAsync(7)); await Task.WhenAll(results.ToArray()); stopwatch.Stop(); //Verify we waited the minimum amount of time and that all items were processed in the same batch Assert.IsTrue(results.All(r => (int)r.Result == expectedBatchID), "One or more items were not processed in the same batch as the others"); Assert.IsTrue(stopwatch.Elapsed.TotalMilliseconds > timeoutMs, "Not enough time passed before patch was processed"); Console.WriteLine("Items were processed in {0} - timeout was configured for {1} milliseconds", stopwatch.Elapsed, timeoutMs); }
public async Task QuickFireTriggerTest() { var dbConnection = new StubIEntityContextConnection { NameOrConnectionStringGet = () => "Trigger-QuickFireTriggerTest" }; Database.SetInitializer(new CreateFreshDbInitializer()); var logEntries = new List<LogEntry>(); var ranstoredCommands = new List<int>(); //Arrange var log = new StubIFeedback<LogEntry> { ReportAsyncT0CancellationToken = (e, c) => { Console.WriteLine(e.ToString()); logEntries.Add(e); return Task.FromResult(0); } }; var commandProcessor = new StubICommandProcessor { RunCommandAsyncNullableOfInt32StringStringCancellationToken = ( commandId, argument, argument2, cancellationToken) => { if (commandId.HasValue) ranstoredCommands.Add(commandId.Value); return Task.FromResult(Result.ReportSuccess()); } }; var cts = new CancellationTokenSource(); var triggerManager = new TriggerRunner(log, commandProcessor, dbConnection); await triggerManager.StartAsync(cts.Token); var cmd = new Command(); var dv = new DeviceValue { Value = "first value", ValueType = DataType.STRING, Triggers = new ObservableCollection<DeviceValueTrigger> { new DeviceValueTrigger { Name = "trigger1", IsEnabled = true, Operator = TriggerOperator.EqualTo, Value = "some unique value", Command = cmd } } }; var device = UnitTesting.CreateFakeDevice(); device.Values.Add(dv); //Act using (var context = new ZvsContext(dbConnection)) { context.Devices.Add(device); await context.TrySaveChangesAsync(cts.Token); dv.Value = "Not It!"; await context.TrySaveChangesAsync(cts.Token); dv.Value = "not this one"; await context.TrySaveChangesAsync(cts.Token); dv.Value = "some unique value"; await context.TrySaveChangesAsync(cts.Token); dv.Value = "not it"; await context.TrySaveChangesAsync(cts.Token); dv.Value = "some unique value"; await context.TrySaveChangesAsync(cts.Token); Console.WriteLine(context.DeviceValueTriggers.Count()); } await Task.Delay(700, cts.Token); await triggerManager.StopAsync(cts.Token); //Assert Assert.IsTrue(logEntries.All(o => o.Level == LogEntryLevel.Info), "Expected only info type log entries"); Assert.IsTrue(ranstoredCommands.Count == 2, "Trigger runner did not run the correct amount of commands."); Assert.IsTrue(ranstoredCommands.All(o => o == cmd.Id), "Scheduled task runner did not run the correct command."); }
public void WeakEventManagerShouldRemoveWeakListenersEvent() { const int count = 100; var model = new BindingSourceModel(); var listeners = new List<WeakReference>(); IWeakEventManager weakEventManager = CreateWeakEventManager(); for (int i = 0; i < count; i++) { var listenerMock = new EventListenerMock(); weakEventManager.TrySubscribe(model, BindingSourceModel.EventName, listenerMock); listeners.Add(new WeakReference(listenerMock)); listenerMock.Handle = (o, o1) => { }; } GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); model.RaiseEvent(); model.RaiseEvent(); listeners.All(reference => reference.Target == null).ShouldBeTrue(); }
public void WeakEventManagerShouldRemoveWeakListenersPropertyChanged() { const int count = 100; const string propertyName = "test"; var model = new BindingSourceModel(); var listeners = new List<WeakReference>(); IWeakEventManager weakEventManager = CreateWeakEventManager(); for (int i = 0; i < count; i++) { var listenerMock = new EventListenerMock(); weakEventManager.Subscribe(model, propertyName, listenerMock); listeners.Add(new WeakReference(listenerMock)); listenerMock.Handle = (o, o1) => { }; } GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); model.OnPropertyChanged(propertyName + "1"); model.OnPropertyChanged(propertyName); model.OnPropertyChanged(propertyName); listeners.All(reference => reference.Target == null).ShouldBeTrue(); }
public async Task RunSceneAsyncInvalidSceneTest() { //Arrange var dbConnection = new StubIEntityContextConnection { NameOrConnectionStringGet = () => "Scene-RunSceneAsyncInvalidSceneTest" }; Database.SetInitializer(new CreateFreshDbInitializer()); var logEntries = new List<LogEntry>(); var ranstoredCommands = new List<int>(); var log = new StubIFeedback<LogEntry> { ReportAsyncT0CancellationToken = (e, c) => { Console.WriteLine(e.ToString()); logEntries.Add(e); return Task.FromResult(0); } }; var commandProcessor = new StubICommandProcessor { RunCommandAsyncNullableOfInt32StringStringCancellationToken = (commandId, argument, argument2, cancellationToken) => { if (commandId.HasValue) ranstoredCommands.Add(commandId.Value); return Task.FromResult(Result.ReportSuccess()); } }; var cts = new CancellationTokenSource(); var sceneRunner = new SceneRunner(log, commandProcessor, dbConnection); //Act var result = await sceneRunner.RunSceneAsync(-1, cts.Token); //Assert Assert.IsTrue(result.HasError); Assert.IsTrue(logEntries.All(o => o.Level == LogEntryLevel.Warn), "Expected only info type log entries"); Assert.IsTrue(ranstoredCommands.Count == 0, "Scene runner did not run the correct amount of commands."); }
public async Task RunSceneAsyncMultipleCommandSeqenceTest() { //Arrange var dbConnection = new StubIEntityContextConnection { NameOrConnectionStringGet = () => "Scene-RunSceneAsyncMultipleCommandSeqenceTest" }; Database.SetInitializer(new CreateFreshDbInitializer()); var logEntries = new List<LogEntry>(); var ranstoredCommands = new List<int>(); var log = new StubIFeedback<LogEntry> { ReportAsyncT0CancellationToken = (e, c) => { Console.WriteLine(e); logEntries.Add(e); return Task.FromResult(0); } }; var commandProcessor = new StubICommandProcessor { RunCommandAsyncNullableOfInt32StringStringCancellationToken = ( commandId, argument, argument2, cancellationToken) => { if (commandId.HasValue) ranstoredCommands.Add(commandId.Value); Console.WriteLine("Ran command Id:{0}", commandId); return Task.FromResult(Result.ReportSuccessFormat("Ran command Id:{0}", commandId)); } }; var scene = new Scene { Name = "I have one command" }; var cmd1 = new Command { Description = "Command 1" }; var command1 = new SceneStoredCommand { SortOrder = 1, TargetObjectName = "Device 1", Description = "Turn On Device 1", Command = cmd1 }; var cmd2 = new Command { Description = "Command 2" }; var command2 = new SceneStoredCommand { SortOrder = 2, TargetObjectName = "Device 2", Description = "Turn On Device 2", Command = cmd2 }; var cmd3 = new Command { Description = "Command 3" }; var command3 = new SceneStoredCommand { SortOrder = 3, TargetObjectName = "Device 3", Description = "Turn On Device 3", Command = cmd3 }; scene.Commands.Add(command3); scene.Commands.Add(command1); scene.Commands.Add(command2); using (var context = new ZvsContext(dbConnection)) { context.Scenes.Add(scene); await context.SaveChangesAsync(CancellationToken.None); } var cts = new CancellationTokenSource(); var sceneRunner = new SceneRunner(log, commandProcessor, dbConnection); //Act var result = await sceneRunner.RunSceneAsync(scene.Id, cts.Token); Console.WriteLine(result.Message); //Assert Assert.IsFalse(result.HasError); Assert.IsTrue(logEntries.All(o => o.Level == LogEntryLevel.Info), "Expected only info type log entries"); Assert.IsTrue(ranstoredCommands.Count == 3, "Scene runner did not run the correct amount of commands."); Assert.IsTrue(ranstoredCommands[0] == cmd1.Id, "Scene runner did not run the correct command."); Assert.IsTrue(ranstoredCommands[1] == cmd2.Id, "Scene runner did not run the correct command."); Assert.IsTrue(ranstoredCommands[2] == cmd3.Id, "Scene runner did not run the correct command."); }
public async Task TestQuerying() { string fileName = CommaDelimitedFileUnitTest.ComposeFileName(); try { IReadOnlyCollection<string> columnNames = Enumerable.Range(0, CommaDelimitedFileUnitTest.CountColumns) .Select( (int item) => item.ToString(CultureInfo.InvariantCulture)) .ToArray(); ITabularFileAdapter fileStore = null; try { fileStore = new CommaDelimitedFileAdapter(fileName, columnNames); Assert.IsTrue(File.Exists(fileName)); Dictionary<string, string> columnsWritten = columnNames .ToDictionary( (string item) => item, (string item) => Guid.NewGuid().ToString()); IList<string> keys = new List<string>(CommaDelimitedFileUnitTest.CountRows); for (int rowIndex = 0; rowIndex < CommaDelimitedFileUnitTest.CountRows; rowIndex++) { IRow rowWritten = await fileStore.InsertRow(columnsWritten); Assert.IsNotNull(rowWritten); Assert.IsFalse(string.IsNullOrWhiteSpace(rowWritten.Key)); Assert.IsFalse( keys .Any( (string item) => string.Equals(item, rowWritten.Key, StringComparison.OrdinalIgnoreCase))); keys.Add(rowWritten.Key); } IReadOnlyCollection<IRow> rowsRead = await fileStore.Query(columnsWritten); Assert.IsNotNull(rowsRead); Assert.AreEqual(3, rowsRead.Count); Assert.IsTrue( keys .All( (string keyItem) => rowsRead .Any( (IRow rowItem) => string.Equals(keyItem, rowItem.Key, StringComparison.OrdinalIgnoreCase)))); } finally { if (fileStore != null) { fileStore.Dispose(); fileStore = null; } } } finally { if (File.Exists(fileName)) { File.Delete(fileName); } } }
/// <summary> /// Verifies that the two List of Rows are equivalent. /// Two List are equivalent if they have the same Rows in the same quantity, but in any order. /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <param name="columnsComparer">Specify custom comparer for certain columns. The key of dictionary is column name, the value is comparer.</param> /// <returns>True if two lists are equivalent.</returns> private static bool AreRowListEquivalent(List<Row> x, List<Row> y, Dictionary<string, Func<object, object, bool>> columnsComparer = null) { if ((x == null && y != null) || (x != null && y == null)) return false; if (x == null && y == null) return true; return x.Count == y.Count && x.All(xRow => y.Any(yRow => IsRowEqual(xRow, yRow, columnsComparer))); }
public void Spin_Sets_CurrentValue_Randomly_EachCall() { var currentValues = new List<int>(); //should see randomness at least by a 100 spins for(int i = 0; i < 500; i++) { tumbler = new Tumbler(MIN_VALUE, MAX_VALUE); tumbler.Spin(); currentValues.Add(tumbler.CurrentValue); } Assert.IsFalse(currentValues.All<int>(x => x == MIN_VALUE), "Should see randomness at least by a 100 spins"); }