public void ReturnAllZones() { _client.Id = _noipClientId; _client.Key = _noipClientKey; Assert.IsTrue(_client.IsRegistered); using (ShimsContext.Create()) { ShimWebClient.AllInstances.DownloadStringString = (client, s) => @" <?xml version=""1.0"" ?> <noip_host_list email=""fakeEmail"" enhanced=""false"" webserver=""""> <domain name=""NoIPDDNS"" type=""plus""> <host name=""Host1"" group="""" wildcard=""false"" ></host> </domain> </noip_host_list> "; var results = _client.GetZones() as HashSet <Zone>; var expectedResults = new HashSet <Zone> { new Zone("NoIPDDNS", ZoneType.Plus) }; Assert.IsNotNull(results); Assert.IsTrue(expectedResults.SequenceEqual(results)); } }
public void TestEqualityAgainstOtherTypes() { var notName = Maybe <string> .Not; Assert.NotEqual(notName, "hi"); Assert.NotEqual("hi", notName); var hiName = Maybe.From("hi"); // ReSharper disable SuspiciousTypeConversion.Global Assert.False(hiName.Equals("hi")); Assert.False("hi".Equals(hiName)); Assert.False(((object)hiName).Equals("hi")); // ReSharper restore SuspiciousTypeConversion.Global Assert.True(hiName == "hi"); Assert.False(hiName != "hi"); Assert.True("hi" == hiName); Assert.False("hi" != hiName); var hs = new HashSet <Maybe <int> > { 1, 2, Maybe <int> .Not, Maybe.From(1), Maybe.From(2) }; Assert.Equal(3, hs.Count); Assert.True(hs.SequenceEqual(new[] { Maybe.From(1), Maybe.From(2), Maybe <int> .Not })); }
public void ReturnAllZones() { _client.Id = _noipClientId; _client.Key = _noipClientKey; Assert.IsTrue(_client.IsRegistered); using (ShimsContext.Create()) { ShimWebClient.AllInstances.DownloadStringString = (client, s) => @" <?xml version=""1.0"" ?> <noip_host_list email=""fakeEmail"" enhanced=""false"" webserver=""""> <domain name=""NoIPDDNS"" type=""plus""> <host name=""Host1"" group="""" wildcard=""false"" ></host> </domain> </noip_host_list> "; var results = _client.GetZones() as HashSet<Zone>; var expectedResults = new HashSet<Zone> { new Zone("NoIPDDNS", ZoneType.Plus) }; Assert.IsNotNull(results); Assert.IsTrue(expectedResults.SequenceEqual(results)); } }
public void CanGetGenerateTheCorrectBackupName() { var configuration = new PeriodicBackupConfiguration { LocalSettings = new LocalSettings(), S3Settings = new S3Settings(), GlacierSettings = new GlacierSettings(), AzureSettings = new AzureSettings(), GoogleCloudSettings = new GoogleCloudSettings(), FtpSettings = new FtpSettings(), }; var allDestinations = new HashSet <string>(Enum.GetValues(typeof(PeriodicBackupConfiguration.BackupDestination)) .Cast <PeriodicBackupConfiguration.BackupDestination>().Where(x => x != PeriodicBackupConfiguration.BackupDestination.None) .Select(backupDestination => { var str = backupDestination.ToString(); var fieldInfo = typeof(PeriodicBackupConfiguration.BackupDestination).GetField(str); var attributes = (DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false); return(attributes.Length > 0 ? attributes[0].Description : str); })); var destinations = configuration.GetFullBackupDestinations(); Assert.True(allDestinations.SequenceEqual(destinations)); }
public void SequenceTest(string[] input) { HashSet <string> set = HashSetPool <string> .Shared.Rent(input); Assert.True(set.SequenceEqual(input)); HashSetPool <string> .Shared.Return(set); }
public void Update() { //Hard-coded half-a-second update cnt = (++cnt) % 30; if (cnt != 0) { return; } if (previousMutualConnectionGrids == null) { previousMutualConnectionGrids = MyAntennaSystem.Static.GetMutuallyConnectedGrids(m_openInventoryInteractedEntityRepresentative); } if (previousShipInfo == null) { previousShipInfo = GetAllCubeGridsInfo(); } var currentMutualConnectionGrids = MyAntennaSystem.Static.GetMutuallyConnectedGrids(m_openInventoryInteractedEntityRepresentative); var currentShipInfo = GetAllCubeGridsInfo(); if (!previousMutualConnectionGrids.SetEquals(currentMutualConnectionGrids)) { PopulateMutuallyConnectedCubeGrids(currentMutualConnectionGrids); } if (!previousShipInfo.SequenceEqual(currentShipInfo)) { PopulateOwnedCubeGrids(currentShipInfo); } previousMutualConnectionGrids = currentMutualConnectionGrids; previousShipInfo = currentShipInfo; }
public static void Parce(IConnectionStringBuilder conn, ICPath path) { List <AD> listAD = new List <AD>(); IDataParser paserProduct = new ParcerProduct(listAD); paserProduct.SetConnection(conn); paserProduct.Select(path); HashSet <AD> distinctAD = new HashSet <AD>(listAD, new SameADComparer()); ADMapper mapper = new ADMapper(Directory.GetCurrentDirectory() + "\\storage.xml"); HashSet <AD> storedListAD = new HashSet <AD>(new SameADComparer()); foreach (AD o in mapper.ReadAll()) { storedListAD.Add(o); } distinctAD = new HashSet <AD>(distinctAD.Except(storedListAD, new SameADComparer()), new SameADComparer()); if (storedListAD.SequenceEqual(storedListAD.Union(distinctAD, new SameADComparer()), new SameADComparer()) == false) { // ShowBalloon("Новые товары", GetShortInfoAD(distinctAD, 3)); foreach (AD ad in distinctAD) { Console.WriteLine(ad); } listAD = storedListAD.Union(distinctAD).ToList(); mapper.WriteAll(listAD); } }
public void SubclassingTypeSet_HasNotChanged() { // New records need to be added here. HashSet <string> expectedAuditRecords = new HashSet <string>() { "NuGetGallery.Auditing.CertificateAuditRecord", "NuGetGallery.Auditing.DeleteAccountAuditRecord", "NuGetGallery.Auditing.FailedAuthenticatedOperationAuditRecord", "NuGetGallery.Auditing.FeatureFlagsAuditRecord", "NuGetGallery.Auditing.PackageAuditRecord", "NuGetGallery.Auditing.PackageRegistrationAuditRecord", "NuGetGallery.Auditing.ReservedNamespaceAuditRecord", "NuGetGallery.Auditing.UserAuditRecord", "NuGetGallery.Auditing.UserSecurityPolicyAuditRecord" }; var actualAuditRecordTypeNames = typeof(AuditRecord).Assembly.GetTypes() .Where(type => type.IsClass && !type.IsAbstract && type.IsSubclassOf(typeof(AuditRecord))) .Select(type => type.FullName) .OrderBy(typeName => typeName) .ToArray(); Assert.True(expectedAuditRecords.SequenceEqual(actualAuditRecordTypeNames), $"Audit record types have been {(actualAuditRecordTypeNames.Length > expectedAuditRecords.Count ? "added" : "removed")}. " + $"Please evaluate this change against known {nameof(AuditingService)} implementations."); }
public void TCollection_Set_Equals_Primitive_Different_Test() { var collection1 = new HashSet <int> { 1, 2, 3 }; var collection2 = new HashSet <int> { 1, 2 }; Assert.IsFalse(TCollections.Equals(collection1, collection2)); Assert.IsFalse(collection1.SequenceEqual(collection2)); collection2.Add(4); Assert.IsFalse(TCollections.Equals(collection1, collection2)); Assert.IsFalse(collection1.SequenceEqual(collection2)); }
/// <summary> /// Subscribes this EventSocket to one or more custom events. /// </summary> /// <param name="events">The custom event names to subscribe to.</param> /// <returns>A Task.</returns> public async Task SubscribeCustomEvents(params string[] events) { if (!customEvents.SequenceEqual(events)) { customEvents.UnionWith(events); // ensures we are always at least using the default minimum events await SubscribeEvents(); } }
private async Task DoCheck() { if (!this.timer.Enabled) { return; } if (this.consideredPackages == null) { return; } Logger.Debug("Checking for running apps."); try { this.timer.Stop(); var wrapper = new TaskListWrapper(); IList <TaskListWrapper.AppProcess> table; try { table = await wrapper.GetBasicAppProcesses("running").ConfigureAwait(false); } catch (Exception e) { Logger.Warn(e, "Could not get the list of running processes."); return; } var nowRunning = new HashSet <string>(); foreach (var item in table) { Logger.Debug($"PID = {item.ProcessId}, Name = {item.PackageName}, Memory = {item.MemoryUsage}, Image = {item.ImageName}"); nowRunning.Add(item.PackageName); } if (this.previouslyRunningAppIds != null && nowRunning.SequenceEqual(this.previouslyRunningAppIds)) { Logger.Debug("The list of running apps has not changed."); return; } Logger.Info("Notifying about updated app state."); this.previouslyRunningAppIds = nowRunning; this.Publish(new ActivePackageFullNames(nowRunning)); } catch (Exception e) { Logger.Error(e); throw; } finally { this.timer.Start(); } }
public bool Equals(FunctionAnalysis2ndPass rhs, out string[] _differences) { var differences = new List <string>(); if (rhs == this) { _differences = null; return(true); } if (!EscapingVariables.SequenceEqual(rhs.EscapingVariables)) { differences.Add("EscapingVariables"); } if (!ModifiedVariables.SequenceEqual(rhs.ModifiedVariables)) { differences.Add("ModifiedVariables"); } if (ResultIsNew != rhs.ResultIsNew) { differences.Add("ResultIsNew"); } if (ResultVariable != rhs.ResultVariable) { differences.Add("ResultVariable"); } if (!VariableAliases.SequenceEqual(rhs.VariableAliases)) { differences.Add("VariableAliases"); } if (ViolatesThisReferenceImmutability != rhs.ViolatesThisReferenceImmutability) { differences.Add("ViolatesThisReferenceImmutability"); } if (IsPure != rhs.IsPure) { differences.Add("IsPure"); } if (differences.Count > 0) { _differences = differences.ToArray(); return(false); } else { _differences = null; return(true); } }
public void DefaultComparerOfTypeIsUsedRegardlessOfCollection() { ICollection<string> set = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "abc", }; Assert.IsTrue(set.Contains("ABC")); Assert.AreEqual(1, set.Count); Assert.IsFalse(set.SequenceEqual(new[] { "ABC" })); }
public override bool Equals(object o) { if (o == null || !(o is RoutineDirectives)) { return(false); } RoutineDirectives rtype = (RoutineDirectives)o; return(Callconv == rtype.Callconv && generaldirs.SequenceEqual(rtype.generaldirs)); }
public void CopyTo() { var array = new HashSet <int> { 1, 2, 3, 4, 5, 6, 7, 8 }; var act = array.ToAsyncEnumerable(); var exp = new int[8]; (act as ICollection <int>).CopyTo(exp, 0); array.SequenceEqual(exp).ShouldBeTrue(); }
private void HandleAttackable(KeyboardState ks) { List <Entity> canBeAttackedList = AttackableSortCowNearby(); if (canBeAttackedList.Count > 0) { List <Entity> attackableList = canBeAttackedList.ToList(); HashSet <Entity> hash = new HashSet <Entity>(canBeAttackedList); IAttackable attackableOnFocus = null; if (!hash.SequenceEqual(_previousFocusInteractables)) { _focusNumber = 0; } if (_focusNumber < attackableList.Count && attackableList[_focusNumber] != null) { var interactable = attackableList[_focusNumber] as IAttackable; if (interactable != null) { interactable.OnFocus = true; attackableOnFocus = interactable; } } if (_previousAttackableOnFocus != null && (attackableOnFocus != null && attackableOnFocus != _previousAttackableOnFocus || _focusNumber != 0 && _focusNumber == attackableList.Count)) { _previousAttackableOnFocus.OnFocus = false; } foreach (var attackable in _previousFocusAttackables.Where(attackable => !hash.Contains(attackable)).Select(attackable => (IAttackable)attackable)) { attackable.OnFocus = false; } if (ks.IsKeyDown(Keys.R) && _prevKeyState.IsKeyUp(Keys.R) && attackableOnFocus != null) { attackableOnFocus.GetDamage(10); } _previousAttackableOnFocus = attackableOnFocus; _previousFocusAttackables = hash; } else { _focusNumber = 0; if (_previousAttackableOnFocus != null) { _previousAttackableOnFocus.OnFocus = false; } } }
public void SetComparer_SequenceEqualTests() { SCG.List <T> objects = new SCG.List <T>() { CreateT(1), CreateT(2), CreateT(3), CreateT(4), CreateT(5), CreateT(6) }; var set = new HashSet <HashSet <T> >() { new HashSet <T> { objects[0], objects[1], objects[2] }, new HashSet <T> { objects[3], objects[4], objects[5] } }; var noComparerSet = new HashSet <HashSet <T> >() { new HashSet <T> { objects[0], objects[1], objects[2] }, new HashSet <T> { objects[3], objects[4], objects[5] } }; var comparerSet = new HashSet <HashSet <T> >(HashSet <T> .CreateSetComparer()) { new HashSet <T> { objects[0], objects[1], objects[2] }, new HashSet <T> { objects[3], objects[4], objects[5] } }; Assert.True(noComparerSet.SequenceEqual(set)); // Unlike the .NET HashSet, ours is structurally equatable by default Assert.True(noComparerSet.SequenceEqual(set, HashSet <T> .CreateSetComparer())); Assert.True(comparerSet.SequenceEqual(set)); // Unlike the .NET HashSet, ours is structurally equatable by default }
public void SetComparer_SequenceEqualTests() { List <T> objects = new List <T>() { CreateT(1), CreateT(2), CreateT(3), CreateT(4), CreateT(5), CreateT(6) }; var set = new HashSet <HashSet <T> >() { new HashSet <T> { objects[0], objects[1], objects[2] }, new HashSet <T> { objects[3], objects[4], objects[5] } }; var noComparerSet = new HashSet <HashSet <T> >() { new HashSet <T> { objects[0], objects[1], objects[2] }, new HashSet <T> { objects[3], objects[4], objects[5] } }; var comparerSet = new HashSet <HashSet <T> >(HashSet <T> .CreateSetComparer()) { new HashSet <T> { objects[0], objects[1], objects[2] }, new HashSet <T> { objects[3], objects[4], objects[5] } }; Assert.False(noComparerSet.SequenceEqual(set)); Assert.True(noComparerSet.SequenceEqual(set, HashSet <T> .CreateSetComparer())); Assert.False(comparerSet.SequenceEqual(set)); }
public void TCollection_Set_Equals_Primitive_Test() { var collection1 = new HashSet <int> { 1, 2, 3 }; var collection2 = new HashSet <int> { 1, 2, 3 }; Assert.IsTrue(TCollections.Equals(collection1, collection2)); Assert.IsTrue(collection1.SequenceEqual(collection2)); }
public static char Get(HashSet <Point> points) { foreach ((char letter, var glyph) in _alphabet) { if (points.SequenceEqual(glyph)) { return(letter); } } return('?'); }
public void GetSubcategoriesOfCagetoryId_Returns_SubCategories(int id, params int?[] result) { var expectedResult = new HashSet <int?>(); expectedResult.Add(id); if (result != null) { expectedResult.UnionWith(result); } var actuallResult = ((ICollection <int?>)(categoryService.GetSubcategoriesOfCagetoryId(id).OrderBy(x => x))).ToArray(); Assert.True(expectedResult.SequenceEqual(actuallResult)); }
public void SaveLoad_HashSet_Ints() { var SAVED_VALUE = new HashSet <int>() { 0, 1, 2, 3 }; var file = new MemoryDataFile(); file.Set(SAVED_VALUE_KEY, SAVED_VALUE); var loadedValue = file.Get <HashSet <int> >(SAVED_VALUE_KEY); Assert.IsTrue(SAVED_VALUE.SequenceEqual(loadedValue)); }
public void TCollection_Set_Equals_OneAndTheSameObject_Test() { var collection1 = new HashSet <ExampleClass> { new ExampleClass { X = 1 }, new ExampleClass { X = 2 } }; var collection2 = collection1; // references to one and the same collection Assert.IsTrue(TCollections.Equals(collection1, collection2)); Assert.IsTrue(collection1.SequenceEqual(collection2)); }
public override bool Equals(object o) { if (this == o) { return(true); } if (o == null || GetType() != o.GetType()) { return(false); } Set set = (Set)o; return(value != null?value.SequenceEqual(set.value) : set.value == null); }
public void ValueEquals_DiffOrderInt32HashSet_ReturnsFalse() { var o1 = new HashSet <int>() { 1, 2, 3 }; var o2 = new HashSet <int>() { 2, 3, 1 }; Assert.IsFalse(o1.Equals(o2)); Assert.IsTrue(o1.SetEquals(o2)); Assert.IsFalse(o1.SequenceEqual(o2)); Assert.IsFalse(o1.ValueEquals(o2)); }
public void TestComplicated() { AbstractJobProcessor jobProcessor = new SimpleJobProcessor(); var job = new Job(); var runTimes = new List <DateTime>(); jobProcessor.JobStarted += (object s, JobEventArgs a) => runTimes.Add(a.DateTime); job.Settings = new ScheduleSettings(); job.Settings.StartDate = new DateTime(2014, 11, 20); job.Settings.SetFrequency(ReccurPeriodTimeUnit.Weekly, 1); job.Settings.ActiveWeekDays.Add(DayOfWeek.Monday); job.Settings.ActiveWeekDays.Add(DayOfWeek.Wednesday); job.Settings.DailyFrequency.PeriodTimeUnit = DailyFrequency.TimeUnit.Hour; job.Settings.DailyFrequency.PeriodTimeUnitCount = 7; job.Settings.DailyFrequency.EndingAt = new TimeSpan(hours: 20, minutes: 0, seconds: 0); job.Settings.EndDate = new DateTime(2015, 5, 10); job.Settings.HasEndDate = true; var allDates = new HashSet <DateTime>(); for (var dt = new DateTime(2014, 10, 20).AddMinutes(-1); dt < new DateTime(2015, 10, 2); dt = dt.AddMinutes(15)) { jobProcessor.RunIfTime(job, dt); if (dt < job.Settings.StartDate) { continue; } if (job.Settings.ActiveWeekDays.Contains(dt.DayOfWeek) && !allDates.Contains(dt.Date) && dt <= job.Settings.EndDate && dt.TimeOfDay <= job.Settings.DailyFrequency.EndingAt.Value) { allDates.Add(dt.Date); } } var runDates = runTimes.Select(dt => dt.Date).Distinct().ToList(); Assert.IsTrue(allDates.SequenceEqual(runDates)); Assert.AreEqual(runDates.Count * 3, runTimes.Count); }
/// <summary> /// Indicates whether the current object is equal to another object of the same type. /// </summary> /// <returns> /// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false. /// </returns> /// <param name="other">An object to compare with this object.</param> public bool Equals(IClass <F> other) { if (ReferenceEquals(null, other)) { return(false); } if (ReferenceEquals(this, other)) { return(true); } if (other.GetType() != GetType()) { return(false); } return(Name.Equals(other.Name) && Features.SequenceEqual(other.Features)); }
public override bool Equals(object obj) { return(obj is TweakSettings settings && FadeTime == settings.FadeTime && InstantSkip == settings.InstantSkip && SkipGameplayDelay == settings.SkipGameplayDelay && BetterCasePicker == settings.BetterCasePicker && FixFER == settings.FixFER && BombHUD == settings.BombHUD && ShowEdgework == settings.ShowEdgework && HideTOC.SequenceEqual(settings.HideTOC) && Mode == settings.Mode && MissionSeed == settings.MissionSeed && CaseGenerator == settings.CaseGenerator && CaseColors.SequenceEqual(settings.CaseColors) && PinnedSettings.SequenceEqual(settings.PinnedSettings)); }
public async Task EnumerateParentCategoriesByItemAsync() { var items = _data.Items.Entities; var categories = items .Select(i => i.CategoryId) .GroupBy(i => i) .Select(grp => grp.First()).ToList(); HashSet <Category> expected = new HashSet <Category>(); categories.ForEach(async c => await GetCategoryParentsAsync(c, expected)); var actual = await _service.EnumerateParentCategoriesAsync(new EntitySpecification <Category>(c => categories.Contains(c.Id))); expected.SequenceEqual(actual); //Equal(expected, actual); }
public void AddingGroupUpdatesLastAcceddedOnLastModifiedOn() { Smock.Run(ctx => { // Assign Init(); var expectedGroup = new HashSet<Group> { new Group(TestConstants.GROUP_NAME + "`") }; // Shim var utcNow = DateTime.UtcNow.AddMonths(18); ctx.Setup(() => DateTime.UtcNow).Returns(utcNow); // Act _group.Groups.Add(expectedGroup.First()); // Assert Assert.IsTrue(expectedGroup.SequenceEqual(_group.Groups)); Assert.AreEqual(utcNow, _group.LastAccessedOn); Assert.AreEqual(utcNow, _group.LastModifiedOn); }); }
public void AddingEntryUpdatesLastAccessOnLastModifiedOn() { Smock.Run(ctx => { // Assign Init(); var expectedEntry = new HashSet<Entry> { new Entry() }; // Shim var utcNow = DateTime.UtcNow.AddMonths(18); ctx.Setup(() => DateTime.UtcNow).Returns(utcNow); // Act _group.Entries.Add(expectedEntry.First()); // Assert Assert.IsTrue(expectedEntry.SequenceEqual(_group.Entries)); Assert.AreEqual(utcNow, _group.LastAccessedOn); Assert.AreEqual(utcNow, _group.LastModifiedOn); }); }
public override bool Equals(object obj) { if (this == obj) { return(true); } if (typeof(SyntaxTree) != obj.GetType()) { return(false); } var tree = obj as SyntaxTree; return(((namespaces == null && tree.namespaces == null) || (namespaces != null && tree.namespaces != null && namespaces.SequenceEqual(tree.namespaces))) && ((objects == null && tree.objects == null) || (objects != null && tree.objects != null && objects.SequenceEqual(tree.objects)))); }
public void TryReadFromFileTest_ExistingFile_ShouldReturnThatObject() { // arrange var input = new HashSet <string>() { "one", "two", "three" }; const string filePath = "Test_TryReadFromFileTest_ExistingFile_ShouldReturnThatObject.bin"; // act ChessGameSerializer.SaveInFile(filePath, input); HashSet <string> fromFile = ChessGameSerializer.TryReadFromFile <HashSet <string> >(filePath); // assert Assert.True(fromFile.SequenceEqual(input)); // clear Assert.True(ChessGameSerializer.ClearFile(filePath)); }
public void WatchSyncState(CmdArgsWatchSyncState args) { var ops = GetOperations(); var stopWatch = System.Diagnostics.Stopwatch.StartNew(); HashSet <string> lastWaitSet = new HashSet <string>(); Func <SubscriberState, bool> filter = ignored => true; if (args.PublicUpdateNotifyUrl != null) { var pubUri = new Uri(args.PublicUpdateNotifyUrl); filter = (s) => { return(pubUri.Equals(s.PublicUpdateNotifyUri)); }; } IEnumerable <SubscriberState> outOfSync = ops.NotAtTargetState().Where(filter); while (outOfSync.Any()) { var ids = outOfSync.Select(sub => sub.Id); var currWaitSet = new HashSet <string>(ids); if (!currWaitSet.SequenceEqual(lastWaitSet)) { WriteToOutput("Waiting for the following subscribers to catch up."); WriteToOutput("==================================================="); foreach (var sub in outOfSync) { WriteToOutput("Id : {0}", sub.Id); WriteToOutput("PublicUri : {0}", sub.PublicUpdateNotifyUri); WriteToOutput("PrivateUri : {0}", sub.PrivateUpdateNotifyUri); } WriteToOutput("==================================================="); lastWaitSet = currWaitSet; } if (args.PollInterval <= 0) { return; } ops.WaitForStateChange(TimeSpan.FromSeconds(args.PollInterval)); outOfSync = ops.NotAtTargetState().Where(filter); } WriteToOutput("Subscribers all up to date."); }
public void ReturnAllZonesWithBadPasswordAndThrowException() { _client.Id = _noipClientId; _client.Key = "BadPass"; Assert.IsTrue(_client.IsRegistered); using (ShimsContext.Create()) { ShimWebClient.AllInstances.DownloadStringString = (client, s) => @"bad password"; var results = _client.GetZones() as HashSet<Zone>; var expectedResults = new HashSet<Zone> { new Zone("NoIPDDNS", ZoneType.Plus) }; Assert.IsNotNull(results); Assert.IsTrue(expectedResults.SequenceEqual(results)); } }
public void ReturnHostForGivenZoneAndLocallyResolveIpAddress() { _client.Id = _noipClientId; _client.Key = _noipClientKey; Assert.IsTrue(_client.IsRegistered); const string shimAddress = "127.0.0.1"; using (ShimsContext.Create()) { ShimWebClient.AllInstances.DownloadStringString = (client, s) => @" <?xml version=""1.0"" ?> <noip_host_list email=""fakeEmail"" enhanced=""false"" webserver=""""> <domain name=""NoIPDDNS"" type=""plus""> <host name=""Host1"" group="""" wildcard=""false"" ></host> <host name=""Host2"" group="""" wildcard=""true"" ></host> </domain> </noip_host_list> "; ShimDnsClient.AllInstances.ResolveStringRecordTypeRecordClass = (dnsClient, s, arg3, arg4) => { switch (s) { case "Host1": return new DnsMessage { IsEDnsEnabled = true, IsRecursionAllowed = true, IsRecursionDesired = true, ReturnCode = ReturnCode.NoError, AnswerRecords = new List<DnsRecordBase> { new ARecord("Host1", 60, IPAddress.Parse(shimAddress)) } }; case "Host2": return new DnsMessage { IsEDnsEnabled = true, IsRecursionAllowed = true, IsRecursionDesired = true, ReturnCode = ReturnCode.NoError, AnswerRecords = new List<DnsRecordBase> { new ARecord("Host1", 60, IPAddress.Parse(shimAddress)) } }; default: return null; } }; _client.Dns = new DnsResolver(); var zones = _client.GetZones(); var results = _client.GetHosts(zones.First()); var expectedResults = new HashSet<Host> { new Host("Host1") {Address = IPAddress.Parse(shimAddress)}, new Host("Host2") {Address = IPAddress.Parse(shimAddress), Wildcard = true} }; Assert.IsNotNull(results); Assert.IsTrue(expectedResults.SequenceEqual(results)); } }
public void TestComplicated() { AbstractJobProcessor jobProcessor = new SimpleJobProcessor(); var job = new Job(); var runTimes = new List<DateTime>(); jobProcessor.JobStarted += (object s, JobEventArgs a) => runTimes.Add(a.DateTime); job.Settings = new ScheduleSettings(); job.Settings.StartDate = new DateTime(2014, 11, 20); job.Settings.SetFrequency(ReccurPeriodTimeUnit.Weekly, 1); job.Settings.ActiveWeekDays.Add(DayOfWeek.Monday); job.Settings.ActiveWeekDays.Add(DayOfWeek.Wednesday); job.Settings.DailyFrequency.PeriodTimeUnit = DailyFrequency.TimeUnit.Hour; job.Settings.DailyFrequency.PeriodTimeUnitCount = 7; job.Settings.DailyFrequency.EndingAt = new TimeSpan(hours: 20, minutes: 0, seconds: 0); job.Settings.EndDate = new DateTime(2015, 5, 10); job.Settings.HasEndDate = true; var allDates = new HashSet<DateTime>(); for (var dt = new DateTime(2014, 10, 20).AddMinutes(-1); dt < new DateTime(2015, 10, 2); dt = dt.AddMinutes(15)) { jobProcessor.RunIfTime(job, dt); if (dt < job.Settings.StartDate) continue; if (job.Settings.ActiveWeekDays.Contains(dt.DayOfWeek) && !allDates.Contains(dt.Date) && dt <= job.Settings.EndDate && dt.TimeOfDay <= job.Settings.DailyFrequency.EndingAt.Value) { allDates.Add(dt.Date); } } var runDates = runTimes.Select(dt => dt.Date).Distinct().ToList(); Assert.IsTrue(allDates.SequenceEqual(runDates)); Assert.AreEqual(runDates.Count * 3, runTimes.Count); }
public void RunTestsOfJUUTTestClassWithFailingTestMethod() { TestClassSession session = new TestClassSession(typeof(TestClassMockWithFailingTestMethod)); session.AddAll(); TestRunner runner = new SimpleTestRunner(); ClassReport classReport = runner.Run(session); AssertThatTheMethodsAreCalledInTheCorrectOrderAfterRunningATestWithFailingTestMethod(); //Checking the returned test reports ICollection<MethodReport> reports = classReport.MethodReports; ICollection<MethodReport> expectedReports = new HashSet<MethodReport>(); expectedReports.Add(new MethodReport(typeof(TestClassMockWithFailingTestMethod).GetMethod("FailingTest"), new NullReferenceException("Failing test method."))); expectedReports.Add(new MethodReport(typeof(TestClassMockWithFailingTestMethod).GetMethod("WorkingTest"))); AssertEx.That(reports.Count, Is.EqualTo(2)); Assert.IsTrue(expectedReports.SequenceEqual(reports)); }
public void TestimmediateLeftRecursion() { Grammar g = new Grammar( "parser grammar t;\n" + "s : a ;\n" + "a : a A | B;" ); var leftRecursive = g.GetLeftRecursiveRules(); //Set expectedRules = new HashSet() {{add("a");}}; var expectedRules = new HashSet<string>(); expectedRules.Add( "a" ); Assert.IsTrue( expectedRules.SequenceEqual( ruleNames( leftRecursive ) ) ); }
public void TestCycleInsideRuleDoesNotForceInfiniteRecursion() { Grammar g = new Grammar( "parser grammar t;\n" + "s : a ;\n" + "a : (A|)+ B;\n" ); // before I added a visitedStates thing, it was possible to loop // forever inside of a rule if there was an epsilon loop. var leftRecursive = g.GetLeftRecursiveRules(); var expectedRules = new HashSet<Rule>(); Assert.IsTrue( expectedRules.SequenceEqual( leftRecursive ) ); }
public void TestIndirectLeftRecursion() { Grammar g = new Grammar( "parser grammar t;\n" + "s : a ;\n" + "a : b | A ;\n" + "b : c ;\n" + "c : a | C ;\n" ); var leftRecursive = g.GetLeftRecursiveRules(); //Set expectedRules = new HashSet() {{add("a"); add("b"); add("c");}}; var expectedRules = new HashSet<string>(); expectedRules.Add( "a" ); expectedRules.Add( "b" ); expectedRules.Add( "c" ); Assert.IsTrue( expectedRules.SequenceEqual( ruleNames( leftRecursive ) ) ); }
public void TestIndirectRecursionLoop3() { Grammar g = new Grammar( "parser grammar t;\n" + "s : a ;\n" + "a : i b X ;\n" + // should see through i "b : a B ;\n" + "i : ;\n" + "d : e ;\n" + "e : d ;\n" ); DecisionProbe.verbose = true; // make sure we get all error info ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); var leftRecursive = g.GetLeftRecursiveRules(); var expectedRules = new HashSet<string>() { "a", "b", "d", "e" }; Assert.IsTrue( expectedRules.SequenceEqual( ruleNames( leftRecursive ) ) ); Assert.AreEqual(1, equeue.errors.Count); Message msg = equeue.errors[0]; Assert.IsTrue(msg is LeftRecursionCyclesMessage, "expecting left recursion cycles; found " + msg.GetType().Name); LeftRecursionCyclesMessage cyclesMsg = (LeftRecursionCyclesMessage)msg; // cycle of [a, b] ICollection result = cyclesMsg.cycles; var expecting = new HashSet<string>() { "a", "b", "d", "e" }; Assert.IsTrue( expecting.SequenceEqual( ruleNames2( result ) ) ); }
public void TestHoistedGatedSynPred2() { Grammar g = new Grammar( "parser grammar t;\n" + "x : (X)=> (X|Y)\n" + " | X\n" + " ;\n"); string expecting = ".s0-X->.s1" + NewLine + ".s0-Y&&{synpred1_t}?->:s2=>1" + NewLine + ".s1-{synpred1_t}?->:s2=>1" + NewLine + ".s1-{true}?->:s3=>2" + NewLine; int[] unreachableAlts = null; int[] nonDetAlts = null; string ambigInput = null; int[] danglingAlts = null; int numWarnings = 0; checkDecision(g, 1, expecting, unreachableAlts, nonDetAlts, ambigInput, danglingAlts, numWarnings); HashSet<string> preds = g.synPredNamesUsedInDFA; HashSet<string> expectedPreds = new HashSet<string>(); //{{add("synpred1_t");}}; expectedPreds.Add("synpred1_t"); Assert.IsTrue(expectedPreds.SequenceEqual(preds), "predicate names not recorded properly in grammar"); }
public void TestIndirectRecursionLoop() { Grammar g = new Grammar( "parser grammar t;\n" + "s : a ;\n" + "a : b X ;\n" + "b : a B ;\n" ); DecisionProbe.verbose = true; // make sure we get all error info ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); HashSet<Rule> leftRecursive = g.GetLeftRecursiveRules(); //Set expectedRules = // new HashSet() {{add("a"); add("b");}}; var expectedRules = new HashSet<string>(); expectedRules.Add( "a" ); expectedRules.Add( "b" ); Assert.IsTrue( expectedRules.SequenceEqual( ruleNames( leftRecursive ) ) ); Assert.AreEqual(1, equeue.errors.Count); Message msg = equeue.errors[0]; Assert.IsTrue(msg is LeftRecursionCyclesMessage, "expecting left recursion cycles; found " + msg.GetType().Name); LeftRecursionCyclesMessage cyclesMsg = (LeftRecursionCyclesMessage)msg; // cycle of [a, b] ICollection result = cyclesMsg.cycles; var expecting = new HashSet<string>(); //{{add("a"); add("b");}}; expecting.Add( "a" ); expecting.Add( "b" ); Assert.IsTrue( expecting.SequenceEqual( ruleNames2( result ) ) ); }