public void WhenModelIsSet_IsValidIsUpdated() { var vm = new SchedulerViewModel(); var model = new SchedulerDescriptorEditMock(); var propertiesChanged = new List<string>(); model.MakeValid(); vm.PropertyChanged += (o, e) => propertiesChanged.Add(e.PropertyName); // Act. vm.Model = model; Assert.IsTrue(vm.IsValid); Assert.IsTrue(propertiesChanged.Any(p => p == "IsValid")); model = new SchedulerDescriptorEditMock(); model.MakeInvalid(); propertiesChanged.Clear(); // Act. vm.Model = model; Assert.IsFalse(vm.IsValid); Assert.IsTrue(propertiesChanged.Any(p => p == "IsValid")); }
public void WaitForDuration_OrderOfExecution() { var values = new List<int>(); _helper.New(300, () => values.Add(3)); _helper.New(200, () => values.Add(2)); _helper.New(100, () => values.Add(1)); Assert.IsFalse(values.Any()); _gameTime.Time += TimeSpan.FromMilliseconds(50); Assert.IsFalse(values.Any()); _gameTime.Time += TimeSpan.FromMilliseconds(500); Assert.AreEqual(3, values.Count); Assert.AreEqual(1, values[0]); Assert.AreEqual(2, values[1]); Assert.AreEqual(3, values[2]); }
public void CanParseMultiTabledDeps2() { //arrange var query = "SELECT players.id,players.homeworld_id,orbital_objects.star_system_id,(SELECT foo from bar) FROM players,second" + "\n,"+ "\nthird" + "\n , fourth ,fifth"+ "\nJOIN colonies ON colonies.orbital_object_id = players.homeworld_id AND colonies.player_id={0}" + "\nJOIN orbital_objects ON orbital_objects.id = colonies.orbital_object_id" + "\nWHERE homeworld_id NOT NULL"; var expected = new List<string>(){ "colonies", "players", "orbital_objects", "second", "third", "fourth", "fifth", "bar" }; //act var result = SQLParser.ExtractTableDependencies(query); //assert Assert.IsTrue(!expected.Any(e => !result.Contains(e))); Assert.AreEqual(expected.Count(), result.Count()); }
public void PopTest() { var list = new List<String> { "1" }; Assert.AreEqual("1", list.Pop()); Assert.IsFalse(list.Any()); }
public int[][] ThreeSum(int[] num) { List<int[]> result = new List<int[]>(); var sortedNums = num.OrderBy(n => n).ToArray(); // sort first for (int i = 0; i < sortedNums.Length - 2; i++) { int left = i + 1; int right = sortedNums.Length - 1; while (left < right) { int tmp = sortedNums[i] + sortedNums[left] + sortedNums[right]; if (tmp > 0) { right--; } else if (tmp < 0) { left++; } else { if (!result.Any(r => r[0] == sortedNums[i] && r[1] == sortedNums[left] && r[2] == sortedNums[right])) { result.Add(new[] { sortedNums[i], sortedNums[left], sortedNums[right] }); } right--; left++; } } } return result.ToArray(); }
public void PingLocalhostWithCloseWillNotFail() { const string HOST = "127.0.0.1"; const int MAX_CNT = 100; List<ToolPing> responseList = new List<ToolPing>(); Exception responseException = null; ITikCommand pingCommand = Connection.LoadAsync<ToolPing>( ping => responseList.Add(ping), //read callback exception => responseException = exception, //exception callback Connection.CreateParameter("address", HOST), Connection.CreateParameter("count", MAX_CNT.ToString()), Connection.CreateParameter("size", "64")); Thread.Sleep(3 * 1000); Connection.Close(); Thread.Sleep(2* 1000); Assert.IsTrue(!Connection.IsOpened); Assert.IsNull(responseException); Assert.IsTrue(responseList.Count < MAX_CNT); Assert.IsTrue(!responseList.Any(ping => ping.Host != HOST)); RecreateConnection(); //Cleanup }
public void TestAllChildAreaTypesThatHaveGroupingsAlsoHaveDefaultParentOptionsDefined() { var childAreaTypeIdsWithParents = GetChildAreaTypeIdsThatHaveParentOptionDefined( ProfileIds.Undefined); var areaTypeIdsOnGroupings = ReaderFactory.GetGroupDataReader() .GetDistinctGroupingAreaTypeIdsForAllProfiles(); var areaTypeIdsWithoutAnyParents = new List<int>(); foreach (var areaTypeId in areaTypeIdsOnGroupings) { if (childAreaTypeIdsWithParents.Contains(areaTypeId) == false) { areaTypeIdsWithoutAnyParents.Add(areaTypeId); } } // Assert if (areaTypeIdsWithoutAnyParents.Any()) { Assert.Fail( "Default parent area type option not defined for child area type Id(s): " + string.Join(",",areaTypeIdsWithoutAnyParents) + Environment.NewLine + "You need to add row(s) to WS_ProfileParentAreaOptions"); } Assert.IsTrue(true); }
public void CheckRecurringPayments_None_NewEntryForRecurring() { var repoSetup = new Mock<IPaymentRepository>(); var resultList = new List<Payment>(); var testList = new List<Payment> { new Payment { Id = 1, Amount = 99, ChargedAccountId = 2, ChargedAccount = new Account {Id = 2}, Date = DateTime.Now.AddDays(-3), RecurringPaymentId = 3, RecurringPayment = new RecurringPayment { Id = 3, Recurrence = (int) PaymentRecurrence.Daily, ChargedAccountId = 2, ChargedAccount = new Account {Id = 2}, Amount = 95 }, IsCleared = true, IsRecurring = true }, new Payment { Id = 2, Amount = 105, Date = DateTime.Now.AddDays(-3), ChargedAccountId = 2, ChargedAccount = new Account {Id = 2}, RecurringPaymentId = 4, RecurringPayment = new RecurringPayment { Id = 4, Recurrence = (int) PaymentRecurrence.Weekly, ChargedAccountId = 2, ChargedAccount = new Account {Id = 2}, Amount = 105 }, IsRecurring = true } }; repoSetup.Setup(x => x.Save(It.IsAny<Payment>())) .Callback((Payment payment) => resultList.Add(payment)); repoSetup.SetupGet(x => x.Data).Returns(new ObservableCollection<Payment>(testList)); repoSetup.Setup(x => x.LoadRecurringList(null)).Returns(testList); new RecurringPaymentManager(repoSetup.Object).CheckRecurringPayments(); resultList.Any().ShouldBeTrue(); resultList.First().Amount.ShouldBe(95); resultList.First().ChargedAccountId.ShouldBe(2); resultList.First().RecurringPaymentId.ShouldBe(3); }
public static void Main(string[] args) { foreach (var type in Assembly.GetExecutingAssembly().GetTypes()) { if (type.GetCustomAttributes<TestClassAttribute>().Any()) { var ls = new List<Exception>(); object instance = null; foreach (var method in type.GetMethods()) { if (method.GetCustomAttributes<TestMethodAttribute>().Any()) { instance = instance ?? type.GetConstructor(System.Type.EmptyTypes).Invoke(new object[0]); try { method.Invoke(instance, new object[0]); } catch (Exception ex) { ls.Add(ex); } } } if (ls.Any()) { var message = string.Join(Environment.NewLine, ls.Select(ex => ex.InnerException.Message)); Debug.WriteLine("Error: " + message); Console.WriteLine("Error: " + message); } } } }
public void GetAssemblies_ReturnsAllControllerAssemblies() { var initializer = new DummyInitializer(); var assemblyFiles = new string[] { "No Controllers", "No Controllers", "Controllers", "No Controllers", "Controllers" }; initializer.GetAssemblyFileNamesMock = () => assemblyFiles; initializer.IsControllerContainerMock = asmFileName => asmFileName.Equals("Controllers"); var triedToLoad = new List<string>(2); initializer.LoadAssemblyMock = asmFileName => { triedToLoad.Add(asmFileName); return Assembly.GetExecutingAssembly(); }; var triedToInitializeContainers = new List<string>(2); initializer.InitializeControllerContainerMock = assembly => { triedToInitializeContainers.Add(assembly.FullName); }; var result = initializer.GetAssembliesPublic(); Assert.AreEqual(2, result.Count(), "Not all controller assemblies were returned."); Assert.AreEqual(2, triedToLoad.Count, "Not all controller assemblies were loaded."); Assert.AreEqual(2, triedToInitializeContainers.Count, "Not all controller assemblies were initialized."); Assert.IsFalse(triedToLoad.Any(asmFile => !asmFile.Equals("Controllers")), "Some assemblies were loaded that were not controller assemblies."); }
public void CommanderTests() { InitializeDatastore.Run(); var message = new Commander(new PublicMessage("!playlist"), new MessageProcessor(null)).Run(); Assert.IsTrue(message.OriginalText == "Playlist at last.fm/user/StevenBonnellII"); message = new Commander(new PublicMessage("!rules"), new MessageProcessor(null)).Run(); Assert.IsTrue(message.OriginalText == "github.com/destinygg/bot"); message = new Commander(new PublicMessage("!refer"), new MessageProcessor(null)).Run(); Assert.IsTrue(message.OriginalText == "destiny.gg/amazon ☜(゚ヮ゚☜) Amazon referral ☜(⌒▽⌒)☞ 25$ off Sprint network (☞゚ヮ゚)☞ destiny.gg/ting"); message = new Commander(new PublicMessage("!irc"), new MessageProcessor(null)).Run(); Assert.IsTrue(message.OriginalText == "IRC will be implemented Soon™. For now, chat is echoed to Rizon IRC at qchat.rizon.net/?channels=#destinyecho . Forwarding of IRC chat to Destiny.gg Chat is available"); message = new Commander(new PublicMessage("!time"), new MessageProcessor(null)).Run(); Assert.IsTrue(message.OriginalText.Contains(" Central Steven Time")); message = new Commander(new PublicMessage("!live"), new MessageProcessor(null)).Run(); var liveAnswers = new List<string> { "Live with ", "Destiny is live! With ", "Stream went offline in the past ~10m", "Stream offline for " }; Assert.IsTrue(liveAnswers.Any(x => message.OriginalText.Contains(x))); message = new Commander(new PublicMessage("!blog"), new MessageProcessor(null)).Run(); Assert.IsTrue(message.OriginalText.Contains(" posted ")); message = new Commander(new PublicMessage("!starcraft"), new MessageProcessor(null)).Run(); Assert.IsTrue(message.OriginalText.Contains(" game on ")); message = new Commander(new PublicMessage("!song"), new MessageProcessor(null)).Run(); var songAnswers = new List<string> { "No song played/scrobbled. Played ", " last.fm/user/stevenbonnellii" }; Assert.IsTrue(songAnswers.Any(x => message.OriginalText.Contains(x))); message = new Commander(new PublicMessage("!earliersong"), new MessageProcessor(null)).Run(); Assert.IsTrue(message.OriginalText.Contains(" played before ")); message = new Commander(new PublicMessage("!twitter"), new MessageProcessor(null)).Run(); Assert.IsTrue(message.OriginalText.Contains(" ago: ")); message = new Commander(new PublicMessage("!youtube"), new MessageProcessor(null)).Run(); Assert.IsTrue(message.OriginalText.Contains(" ago youtu.be/")); }
public Int32 GetMaxHeight(List<Box> boxes) { Contract.Requires(boxes != null); // Contract.Requires(boxes.HaveUniqueIndexes()); if (!boxes.Any()) return 0; var sortedBoxes = boxes.OrderByDescending(box => box.Width); // Instead of memoizing maxes for each possible combination of boxes, just memoize one value per one box. Such value represents // the height of tallest stack having given box at the bottom. // This works because when we memoize for the first time a max having given box at the bottom, it will never be overriden. Dictionary<String, Int32> memoizedMaxes = new Dictionary<String, Int32>(); var max = sortedBoxes.Select(bottomBox => { return bottomBox.Height + GetMaxHeightDFS(sortedBoxes.TakeSmallerThan(bottomBox), memoizedMaxes); }).Max(); // DEBUG Console.Out.WriteLine("maxes keys: "+memoizedMaxes.Keys.Count); foreach (var key in memoizedMaxes.Keys) Console.Out.WriteLine("key = {0}", key); // /DEBUG return max; }
public void PlayExecutesSamePlayerOrderInEachRound() { var players = new[] { "Horse", "Car", "Hat" }; var mockTurn = new Mock<ITurn>(); var game = new Game(players, mockTurn.Object, new GuidShuffler<String>()); var controller = new GameController(game); var turnsTaken = new List<String>(); mockTurn.Setup(m => m.Take(It.IsAny<String>())).Callback((String p) => turnsTaken.Add(p)); controller.Play(); var lastRoundTurns = Enumerable.Empty<String>(); while (turnsTaken.Any()) { var roundTurns = turnsTaken.Take(players.Count()); if (lastRoundTurns.Any()) { for (var i = 0; i < lastRoundTurns.Count(); i++) Assert.AreEqual(roundTurns.ElementAt(i), lastRoundTurns.ElementAt(i)); } lastRoundTurns = roundTurns; turnsTaken.RemoveRange(0, players.Count()); } }
public void Initialize_Test() { var model = new NavigationItemEditMock(123); var parentMock = Mock.Create<INavigationGroupViewModel>(); var target = new NavigationItemViewModel(); var propertiesChanged = new List<string>(); target.PropertyChanged += (o, e) => propertiesChanged.Add(e.PropertyName); target.Initialize(model, parentMock); Assert.AreSame(model, target.Model); Assert.AreSame(parentMock, target.Parent); Assert.IsTrue(propertiesChanged.Any(p => p == "IsVisible")); Assert.IsTrue(propertiesChanged.Any(p => p == "Model")); Assert.IsTrue(propertiesChanged.Any(p => p == "Parent")); }
public void ListExtensions_Any_ReturnsTrueIfListContainsItems() { var list = new List<Int32>() { 1 }; var result = list.Any(); TheResultingValue(result).ShouldBe(true); }
public void ListExtensions_AnyWithPredicate_ReturnsFalseIfListDoesNotContainMatchingItems() { var list = new List<Int32>() { 1, 3 }; var result = list.Any(x => x % 2 == 0); TheResultingValue(result).ShouldBe(false); }
public void ListExtensions_Any_ReturnsFalseIfListDoesNotContainItems() { var list = new List<Int32>(); var result = list.Any(); TheResultingValue(result).ShouldBe(false); }
public void Collection() { var list = new List<Person> { new Person{Name = "bob", Age = 10} }; Assert.IsTrue(list.Any(it => it.Age == 20)); }
public void Any() { // arrange List<String> list = new List<String>() { "Backbone", "Angular", "React" }; List<String> listEmpty = new List<String>() { }; // act Boolean actual = list.Any(x => x == "Angular"); Boolean actualNotFound = list.Any(x => x == "jquery"); Boolean actualNotEmpty = list.Any(); Boolean actualEmpty = listEmpty.Any(); // assert Assert.AreEqual(true, actual); Assert.AreEqual(false, actualNotFound); Assert.AreEqual(true, actualNotEmpty); Assert.AreEqual(false, actualEmpty); }
/// <summary> /// <see cref="CodeFixProvider"/>によるコードの修正を検証します。 /// </summary> /// <param name="oldSource">修正前のソースコード</param> /// <param name="newSource">修正後のソースコード</param> /// <param name="codeFixIndex">修正する箇所か複数ある場合に、それを特定するインデックス</param> /// <param name="allowNewCompilerDiagnostics">修正後に他の警告がある場合、テストを失敗させる場合は<see langword="true"/></param> protected void VerifyFix(string oldSource, string newSource, int? codeFixIndex = null, bool allowNewCompilerDiagnostics = false) { var analyzer = GetDiagnosticAnalyzer(); var codeFixProvider = GetCodeFixProvider(); var document = CreateProject(new[] { oldSource }).Documents.First(); var analyzerDiagnostics = GetSortedDiagnosticsFromDocuments(analyzer, new[] { document }); var compilerDiagnostics = document.GetCompilerDiagnostics(); var attempts = analyzerDiagnostics.Length; for (int i = 0; i < attempts; ++i) { var actions = new List<CodeAction>(); var context = new CodeFixContext(document, analyzerDiagnostics[0], (a, d) => actions.Add(a), CancellationToken.None); codeFixProvider.RegisterCodeFixesAsync(context).Wait(); if (!actions.Any()) { break; } if (codeFixIndex != null) { document = document.ApplyFix(actions.ElementAt((int)codeFixIndex)); break; } document = document.ApplyFix(actions.ElementAt(0)); analyzerDiagnostics = GetSortedDiagnosticsFromDocuments(analyzer, new[] { document }); var newCompilerDiagnostics = GetNewDiagnostics(compilerDiagnostics, document.GetCompilerDiagnostics()); //check if applying the code fix introduced any new compiler diagnostics if (!allowNewCompilerDiagnostics && newCompilerDiagnostics.Any()) { // Format and get the compiler diagnostics again so that the locations make sense in the output document = document.WithSyntaxRoot(Formatter.Format(document.GetSyntaxRootAsync().Result, Formatter.Annotation, document.Project.Solution.Workspace)); newCompilerDiagnostics = GetNewDiagnostics(compilerDiagnostics, document.GetCompilerDiagnostics()); Assert.IsTrue(false, string.Format("Fix introduced new compiler diagnostics:\r\n{0}\r\n\r\nNew document:\r\n{1}\r\n", string.Join("\r\n", newCompilerDiagnostics.Select(d => d.ToString())), document.GetSyntaxRootAsync().Result.ToFullString())); } //check if there are analyzer diagnostics left after the code fix if (!analyzerDiagnostics.Any()) { break; } } //after applying all of the code fixes, compare the resulting string to the inputted one var actual = document.GetStringFromDocument(); Assert.AreEqual(newSource, actual); }
public void Validate_And_Give_No_Error_On_Module11_With_Number_22934() { Modulo11ObjectMock objectMock = new Modulo11ObjectMock { Modulo11 = 22934 }; IList<string> errors = new List<string>(); IValidationAttribute attribute = new Modulo11Attribute(); attribute.Validate(objectMock, ReflectionUtility.GetMemberInfo(() => objectMock.Modulo11), errors); Assert.IsFalse(errors.Any()); }
public void TestAddCustomer() { var customers = new List<Customer>(); this._fakePersistence.Setup(p => p.Add(It.IsAny<Customer>())).Callback<Customer>(customers.Add); this._target.CreateCustomer(string.Empty, string.Empty, string.Empty, new Address()); Assert.IsTrue(customers.Any()); }
public void Save_WithOneStringParameter_ShouldBeAbleToMock() { const string testFileName = "Test"; List<string> saveCalls = new List<string>(); Mock<IXmlDocument> xmlDocumentMock = new Mock<IXmlDocument>(); xmlDocumentMock.Setup(xmlDocument => xmlDocument.Save(testFileName)).Callback<string>(saveCalls.Add); Assert.IsFalse(saveCalls.Any()); xmlDocumentMock.Object.Save(testFileName); Assert.AreEqual(1, saveCalls.Count); Assert.AreEqual(testFileName, saveCalls[0]); }
public void LoadXml_ShouldBeAbleToMock() { const string testXml = "Test"; List<string> loadXmlCalls = new List<string>(); Mock<IXmlDocument> xmlDocumentMock = new Mock<IXmlDocument>(); xmlDocumentMock.Setup(xmlDocument => xmlDocument.LoadXml(testXml)).Callback<string>(loadXmlCalls.Add); Assert.IsFalse(loadXmlCalls.Any()); xmlDocumentMock.Object.LoadXml(testXml); Assert.AreEqual(1, loadXmlCalls.Count); Assert.AreEqual(testXml, loadXmlCalls[0]); }
public void WhenSettingNoErrorsForPropertyWithNoErrors_ThenDoesNotNotifyChangesAndHasNoErrors() { List<string> validatedProperties = new List<string>(); var validation = new ErrorsContainer<ValidationResult>(pn => validatedProperties.Add(pn)); validation.SetErrors("property1", new ValidationResult[0]); Assert.IsFalse(validation.HasErrors); Assert.IsFalse(validation.GetErrors("property1").Any()); Assert.IsFalse(validatedProperties.Any()); }
public void TestCreateBasket() { var product = new BasketProduct { ProductId = 1 }; var baskets = new List<Basket>(); this._fakePersistence.Setup(p => p.Add(It.IsAny<Basket>())).Callback<Basket>(baskets.Add); this._target.CreateBasket(product); Assert.IsTrue(baskets.Any()); }
public void TestNextPermutation_DifferentValues_NFactorialPermutations_AllUnique() { var list = TestHelper.Wrap(new List<int>() { 1, 2, 3, 4, 5, }); // initially sorted List<int[]> permutations = new List<int[]>() { list.ToArray() }; while (list.NextPermutation(Comparer<int>.Default.Compare)) { Assert.IsFalse(permutations.Any(item => list.IsEqualTo(item.ToSublist())), "The same permutation appeared twice."); permutations.Add(list.ToArray()); } Assert.AreEqual(120, permutations.Count, "Not all permutations were found."); TestHelper.CheckHeaderAndFooter(list); }
private static void WriteResults(String word, List<String> anagrams) { if (anagrams != null && anagrams.Any()) { Console.WriteLine("{0} anagrams found for '{1}'", anagrams.Count() - 1, word); Console.WriteLine(); anagrams.ForEach(Console.WriteLine); } else { Console.Write("No anagrams found for {0}", word); } }
public void CanPopulateMovieCast() { var children = new List<IDegree>(); var degree = new Mock<IDegree>(); degree.Setup(mock => mock.Children).Returns(children); degree.Setup(mock => mock.Id).Returns("9737"); degree.Setup(mock => mock.Type).Returns(DegreeType.Movie); _searchService.PopulateChildren(degree.Object); Assert.IsTrue(children.Any()); }
public void Parser_Generates_Unique_Session_Id_And_Assigns_It_To_Records() { // Setup IList<LogRecord> records = new List<LogRecord>(); _parser.StoreRecordMethod = (r => records.Add(r)); // Act Guid sessionId = _parser.ParseLog(_generalLogSource); // Verify Assert.AreNotEqual(new Guid(), sessionId, "Session Id was incorrectly set to an empty GUID"); Assert.IsFalse(records.Any(x => x.SessionId != sessionId), "Not all log records were created with the correct session Id"); }