public void UniversalPlugAndPlayManager_PutServerOntoInternet_Adds_Correct_Mapping_To_Router() { var worksheet = new ExcelWorksheetData(TestContext); _Configuration.WebServerSettings.EnableUPnp = worksheet.Bool("CnfEnabled"); _Configuration.WebServerSettings.UPnpPort = worksheet.Int("CnfUPnpPort"); _WebServer.Setup(s => s.NetworkIPAddress).Returns(worksheet.String("SvrAddress")); _WebServer.Setup(s => s.Port).Returns(worksheet.Int("SvrPort")); _Manager.Initialise(); if (worksheet.String("RtrDescription") != null) { AddPortMapping(worksheet.String("RtrDescription"), worksheet.Int("RtrExtPort"), worksheet.String("RtrIntClient"), worksheet.Int("RtrIntPort"), worksheet.String("RtrProtocol")); } _Manager.StateChanged += _StateChangedEvent.Handler; _Manager.PutServerOntoInternet(); _Provider.Verify(p => p.AddMapping(worksheet.Int("CnfUPnpPort"), "TCP", worksheet.Int("SvrPort"), worksheet.String("SvrAddress"), true, _Description), worksheet.Bool("ExpectAdd") ? Times.Once() : Times.Never()); Assert.AreEqual(worksheet.Bool("ExpectIsPresent"), _Manager.PortForwardingPresent); Assert.AreEqual(worksheet.Bool("ExpectStateChanged") ? 1 : 0, _StateChangedEvent.CallCount); if (_StateChangedEvent.CallCount > 0) { Assert.AreSame(_Manager, _StateChangedEvent.Sender); Assert.IsNotNull(_StateChangedEvent.Args); } }
private void Do_BaseStationMessage_ToBaseStationString_Builds_Valid_BaseStation_Messages_From_A_BaseStationMessage_Object() { var worksheet = new ExcelWorksheetData(TestContext); _Implementation.MessageType = worksheet.ParseEnum <BaseStationMessageType>("MessageType"); _Implementation.TransmissionType = worksheet.ParseEnum <BaseStationTransmissionType>("TransmissionType"); _Implementation.StatusCode = worksheet.ParseEnum <BaseStationStatusCode>("StatusCode"); _Implementation.SessionId = worksheet.Int("SessionId"); _Implementation.AircraftId = worksheet.Int("AircraftId"); _Implementation.Icao24 = worksheet.String("Icao24"); _Implementation.FlightId = worksheet.Int("FlightId"); _Implementation.MessageGenerated = worksheet.DateTime("MessageGenerated"); _Implementation.MessageLogged = worksheet.DateTime("MessageLogged"); _Implementation.Callsign = worksheet.String("Callsign"); _Implementation.Altitude = worksheet.NInt("Altitude"); _Implementation.GroundSpeed = worksheet.NFloat("GroundSpeed"); _Implementation.Track = worksheet.NFloat("Track"); _Implementation.Latitude = worksheet.NDouble("Latitude"); _Implementation.Longitude = worksheet.NDouble("Longitude"); _Implementation.VerticalRate = worksheet.NInt("VerticalRate"); _Implementation.Squawk = worksheet.NInt("Squawk"); _Implementation.SquawkHasChanged = worksheet.NBool("SquawkHasChanged"); _Implementation.Emergency = worksheet.NBool("Emergency"); _Implementation.IdentActive = worksheet.NBool("IdentActive"); _Implementation.OnGround = worksheet.NBool("OnGround"); Assert.AreEqual(worksheet.String("Text"), _Implementation.ToBaseStationString()); }
public void VectorVelocity_Calculates_Velocity_And_Bearing_Correctly() { var worksheet = new ExcelWorksheetData(TestContext); var velocity = new VectorVelocity() { IsWesterlyVelocity = worksheet.Bool("IsWesterlyVelocity"), IsSoutherlyVelocity = worksheet.Bool("IsSoutherlyVelocity"), EastWestVelocity = worksheet.NShort("EastWestVelocity"), EastWestExceeded = worksheet.Bool("EastWestExceeded"), NorthSouthVelocity = worksheet.NShort("NorthSouthVelocity"), NorthSouthExceeded = worksheet.Bool("NorthSouthExceeded"), }; if (worksheet.String("Speed") == null) { Assert.IsNull(velocity.Speed); } else { Assert.AreEqual(worksheet.Double("Speed"), velocity.Speed.Value, 0.000001); } if (worksheet.String("Bearing") == null) { Assert.IsNull(velocity.Bearing); } else { Assert.AreEqual(worksheet.Double("Bearing"), velocity.Bearing.Value, 0.000001); } }
public void WebSite_Image_Correct_Image_Is_Rendered() { ExcelWorksheetData worksheet = new ExcelWorksheetData(TestContext); string pathAndFile = worksheet.String("UrlPath"); _WebSite.AttachSiteToServer(_WebServer.Object); var args = RequestReceivedEventArgsHelper.Create(_Request, _Response, pathAndFile, false); _WebServer.Raise(m => m.RequestReceived += null, args); Assert.AreEqual(true, args.Handled); byte[] content = _OutputStream.ToArray(); var md5Checksum = new StringBuilder(); using (var md5 = MD5.Create()) { foreach (var b in md5.ComputeHash(content)) { md5Checksum.AppendFormat("{0:X2}", b); } } Assert.AreEqual(worksheet.String("MimeType"), _Response.Object.MimeType); Assert.AreEqual(worksheet.Int("Length"), content.Length); Assert.AreEqual(worksheet.String("MD5"), md5Checksum.ToString(), true); }
public void PluginManager_LoadPlugins_Checks_Manifest_Before_Loading_Plugin() { var worksheet = new ExcelWorksheetData(TestContext); _Provider.Setup(p => p.DirectoryGetFiles(It.IsAny <string>(), It.IsAny <string>())).Returns(new string[] { "a" }); _Provider.Setup(p => p.LoadTypes("a")).Returns(new Type[] { typeof(PluginA) }); _Manifest.MinimumVersion = worksheet.EString("MinimumVersion"); _Manifest.MaximumVersion = worksheet.EString("MaximumVersion"); _ApplicationInformation.Setup(a => a.Version).Returns(new Version(worksheet.String("VRSVersion"))); _PluginManager.LoadPlugins(); if (worksheet.Bool("CanLoad")) { Assert.AreEqual(1, _PluginManager.LoadedPlugins.Count); Assert.AreEqual(0, _PluginManager.IgnoredPlugins.Count); } else { Assert.AreEqual(0, _PluginManager.LoadedPlugins.Count); Assert.AreEqual(worksheet.String("IgnoredMessage"), _PluginManager.IgnoredPlugins["a"]); } }
public void NewVersionChecker_CheckForNewVersion_Raises_NewVersionAvailable_When_Appropriate() { var worksheet = new ExcelWorksheetData(TestContext); _NewVersionChecker.NewVersionAvailable += _NewVersionAvailable.Handler; _NewVersionAvailable.EventRaised += (object sender, EventArgs args) => { Assert.AreEqual(true, _NewVersionChecker.IsNewVersionAvailable); }; _ApplicationInformation.Setup(p => p.Version).Returns(new Version(worksheet.String("ApplicationVersion"))); _Provider.Setup(p => p.DownloadFileContent(It.IsAny <string>())).Returns(worksheet.String("WebsiteVersion").Replace(@"\r", "\r").Replace(@"\n", "\n")); _NewVersionChecker.CheckForNewVersion(); if (!worksheet.Bool("IsNewer")) { Assert.AreEqual(0, _NewVersionAvailable.CallCount); } else { Assert.AreEqual(1, _NewVersionAvailable.CallCount); Assert.AreSame(_NewVersionChecker, _NewVersionAvailable.Sender); Assert.IsNotNull(_NewVersionAvailable.Args); } }
public void MimeType_GetForExtension_Returns_Correct_MimeType_For_Extension() { var excelWorkSheet = new ExcelWorksheetData(TestContext); var mimeType = excelWorkSheet.String("MimeType"); var extension = excelWorkSheet.String("Extension"); Assert.AreEqual(mimeType, MimeType.GetForExtension(extension), extension); }
public void MimeType_GetForExtension_Returns_Correct_MimeType_For_Extensions_With_Leading_Full_Stop() { var excelWorkSheet = new ExcelWorksheetData(TestContext); var mimeType = excelWorkSheet.String("MimeType"); var extension = String.Format(".{0}", excelWorkSheet.String("Extension")); Assert.AreEqual(mimeType, MimeType.GetForExtension(extension), extension); }
public void Describe_Bytes_Formats_Bytes_Correctly() { var worksheet = new ExcelWorksheetData(TestContext); using(var switcher = new CultureSwitcher(worksheet.String("Region"))) { Assert.AreEqual(worksheet.String("Description"), Describe.Bytes(worksheet.Long("Bytes"))); } }
public void Describe_Bytes_Formats_Bytes_Correctly() { var worksheet = new ExcelWorksheetData(TestContext); using (var switcher = new CultureSwitcher(worksheet.String("Region"))) { Assert.AreEqual(worksheet.String("Description"), Describe.Bytes(worksheet.Long("Bytes"))); } }
public void MimeType_GetForExtension_Is_Case_Insensitive() { var worksheet = new ExcelWorksheetData(TestContext); var mimeType = worksheet.String("MimeType"); var extension = String.Format(".{0}", worksheet.String("Extension")); Assert.AreEqual(mimeType, MimeType.GetForExtension(extension.ToLower()), extension.ToLower()); Assert.AreEqual(mimeType, MimeType.GetForExtension(extension.ToUpper()), extension.ToUpper()); }
public void MimeType_GetKnownExtensions_Returns_Reasonable_List() { var worksheet = new ExcelWorksheetData(TestContext); var mimeType = worksheet.String("MimeType"); var extension = worksheet.String("Extension"); var extensions = MimeType.GetKnownExtensions(); Assert.IsTrue(extensions.Contains(extension.ToLower())); }
public void Do_ExtractMessageBytes_Extracts_Messages_From_Bytes(bool inputIsText, int blobCount, int extractedCount, Func<byte[], byte[]> alterFirstPacket = null) { var worksheet = new ExcelWorksheetData(TestContext); var comments = worksheet.String("Comments"); var input = new List<byte[]>(); for(var i = 1;i <= blobCount;++i) { var blobColumn = String.Format("Blob{0}", i); if(worksheet.String(blobColumn) != null) { byte[] bytes; if(inputIsText) bytes = Encoding.ASCII.GetBytes(worksheet.String(blobColumn).Replace("\\n", "\n").Replace("\\r", "\r")); else bytes = worksheet.Bytes(blobColumn); if(input.Count == 0 && alterFirstPacket != null) bytes = alterFirstPacket(bytes); input.Add(bytes); } } var expectedOutput = new List<ExtractedBytes>(); for(var i = 1;i <= extractedCount;++i) { var bytesColumn = String.Format("Extracted{0}", i); var parityColumn = String.Format("HadParity{0}", i); var checksumColumn = String.Format("BadChecksum{0}", i); if(worksheet.String(bytesColumn) != null || worksheet.String(checksumColumn) != null) { expectedOutput.Add(new ExtractedBytes() { Bytes = worksheet.Bytes(bytesColumn), HasParity = worksheet.Bool(parityColumn), ChecksumFailed = worksheet.Bool(checksumColumn), }); } } var output = new List<ExtractedBytes>(); foreach(var inputBytes in input) { foreach(var extractedBytes in Extractor.ExtractMessageBytes(inputBytes, 0, inputBytes.Length)) { output.Add((ExtractedBytes)extractedBytes.Clone()); } } Assert.AreEqual(expectedOutput.Count, output.Count, comments); for(var i = 0;i < expectedOutput.Count;++i) { var expected = expectedOutput[i]; var actual = output[i]; Assert.AreEqual(Format, actual.Format); Assert.AreEqual(expected.ChecksumFailed, actual.ChecksumFailed, comments); if(!expected.ChecksumFailed) { Assert.AreEqual(expected.HasParity, actual.HasParity, comments); var actualBytes = new byte[actual.Length]; Array.Copy(actual.Bytes, actual.Offset, actualBytes, 0, actual.Length); Assert.IsTrue(expected.Bytes.SequenceEqual(actualBytes), comments); } } }
private void SpreadsheetTests(Action <ExcelWorksheetData> afterSetFolder) { var worksheet = new ExcelWorksheetData(TestContext); bool checkCacheChanged = worksheet.ColumnExists("CacheChanged"); for (int i = 1; i <= 2; ++i) { string nameColumn = String.Format("File{0}", i); string lastModifiedColumn = String.Format("Time{0}", i); if (!worksheet.ColumnExists(nameColumn)) { continue; } var name = worksheet.String(nameColumn); var time = worksheet.ColumnExists(lastModifiedColumn) ? worksheet.DateTime(lastModifiedColumn) : new DateTime(2999, 12, 31); if (name != null) { _Files.Add(new TestFileInfo(name, time)); } } _Provider.Setup(p => p.GetFilesInFolder(It.IsAny <string>())).Returns(_Files); var folder = worksheet.String("Folder"); if (folder != null) { _DirectoryCache.Folder = folder; } if (worksheet.ColumnExists("LastModified")) { var fileInfo = worksheet.String("LastModified") == null ? null : new TestFileInfo(worksheet.String("FileName"), worksheet.DateTime("LastModified")); _Provider.Setup(p => p.GetFileInfo(worksheet.EString("FileName"))).Returns(fileInfo); } if (checkCacheChanged) { _DirectoryCache.CacheChanged += _CacheChangedEvent.Handler; } if (afterSetFolder != null) { afterSetFolder(worksheet); } Assert.AreEqual(folder, _DirectoryCache.Folder); Assert.AreEqual(worksheet.Bool("Exists"), _DirectoryCache.FileExists(worksheet.EString("SearchFor"))); if (checkCacheChanged) { Assert.AreEqual(worksheet.Bool("CacheChanged") ? 1 : 0, _CacheChangedEvent.CallCount); } }
public void RequestReceivedEventArgs_Constructor_Builds_Properties_From_Request_Correctly() { ExcelWorksheetData worksheet = new ExcelWorksheetData(TestContext); var request = new Mock <IRequest>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties(); var response = new Mock <IResponse>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties(); var headers = new NameValueCollection(); var endPoint = new IPEndPoint(IPAddress.Parse(worksheet.String("ResponseAddress")), 45678); request.Setup(r => r.RemoteEndPoint).Returns(endPoint); request.Setup(r => r.Url).Returns(new Uri(worksheet.EString("Url"))); request.Setup(r => r.RawUrl).Returns(worksheet.EString("RawUrl")); request.Setup(r => r.Headers).Returns(headers); var xForwardedFor = worksheet.EString("XForwardedFor"); if (xForwardedFor != null) { headers.Add("X-Forwarded-For", xForwardedFor); } var args = new RequestReceivedEventArgs(request.Object, response.Object, worksheet.EString("Root")); Assert.AreEqual(worksheet.EString("WebSite"), args.WebSite); Assert.AreEqual(worksheet.EString("PathAndFile"), args.PathAndFile); Assert.AreEqual(worksheet.EString("Path"), args.Path); Assert.AreEqual(worksheet.EString("File"), args.File); Assert.AreEqual(worksheet.EString("ProxyAddress"), args.ProxyAddress); Assert.AreEqual(worksheet.EString("ClientAddress"), args.ClientAddress); Assert.AreEqual(worksheet.Bool("IsInternetRequest"), args.IsInternetRequest); Assert.AreEqual(worksheet.Int("PathCount"), args.PathParts.Count); Assert.AreEqual(worksheet.Int("QueryCount"), args.QueryString.Count); for (var i = 0; i < args.PathParts.Count; ++i) { Assert.AreEqual(worksheet.EString(String.Format("Path{0}", i)), args.PathParts[i]); } for (var i = 0; i < args.QueryString.Count; ++i) { var expectedName = worksheet.String(String.Format("QueryName{0}", i)); var expectedValue = worksheet.String(String.Format("QueryValue{0}", i)); Assert.AreEqual(expectedValue, args.QueryString[expectedName]); } }
public void NewVersionChecker_CheckForNewVersion_Returns_Correct_Value() { var worksheet = new ExcelWorksheetData(TestContext); _ApplicationInformation.Setup(p => p.Version).Returns(new Version(worksheet.String("ApplicationVersion"))); _Provider.Setup(p => p.DownloadFileContent(It.IsAny <string>())).Returns(worksheet.String("WebsiteVersion").Replace(@"\r", "\r").Replace(@"\n", "\n")); bool expected = worksheet.Bool("IsNewer"); Assert.AreEqual(expected, _NewVersionChecker.CheckForNewVersion()); Assert.AreEqual(expected, _NewVersionChecker.IsNewVersionAvailable); }
public void PolarPlotter_Initialise_Initialises_The_Plotter_Correctly() { var worksheet = new ExcelWorksheetData(TestContext); var roundDegrees = 0; var seenArgException = false; try { roundDegrees = worksheet.Int("RoundDegree"); _Plotter.Initialise( worksheet.Double("Latitude"), worksheet.Double("Longitude"), worksheet.Int("LowSlice"), worksheet.Int("HighSlice"), worksheet.Int("SliceHeight"), roundDegrees ); } catch (ArgumentException) { seenArgException = true; } Assert.AreEqual(worksheet.Bool("ArgException"), seenArgException); if (!seenArgException) { var slices = _Plotter.TakeSnapshot(); Assert.AreEqual(worksheet.Double("Latitude"), _Plotter.Latitude); Assert.AreEqual(worksheet.Double("Longitude"), _Plotter.Longitude); Assert.AreEqual(worksheet.Int("RoundDegree"), _Plotter.RoundToDegrees); Assert.AreEqual(worksheet.Int("CountSlices"), slices.Count); var expectedPlotsPerSlice = 360 / roundDegrees; foreach (var slice in slices) { Assert.AreEqual(expectedPlotsPerSlice, slice.PolarPlots.Count); } for (var i = 1; i <= 5; ++i) { var lowName = String.Format("Low{0}", i); var highName = String.Format("High{0}", i); var lowText = worksheet.String(lowName); var highText = worksheet.String(highName); if (lowText != null && highText != null) { var expectedLow = lowText == "Min" ? int.MinValue : int.Parse(lowText); var expectedHigh = highText == "Max" ? int.MaxValue : int.Parse(highText); Assert.IsTrue(slices.Any(r => r.AltitudeLower == expectedLow && r.AltitudeHigher == expectedHigh), "Could not find {0}-{1}", lowText, highText); } } } }
public void Describe_Airport_Formats_Airport_Correctly() { var worksheet = new ExcelWorksheetData(TestContext); var comparer = new IPAddressComparer(); var lhs = worksheet.String("LHS") == null ? null : IPAddress.Parse(worksheet.String("LHS")); var rhs = worksheet.String("RHS") == null ? null : IPAddress.Parse(worksheet.String("RHS")); var expectedResult = worksheet.Int("Result"); var result = comparer.Compare(lhs, rhs); if(expectedResult < 0) Assert.IsTrue(result < 0); else if(expectedResult > 0) Assert.IsTrue(result > 0); else Assert.AreEqual(0, result); }
public void Aircraft_UpdateCoordinates_Replaces_Last_Full_Coordinate_If_Track_Hardly_Changes() { // If an update changes the position but the aircraft remains on the same ground track as the previous position // then there's no need to keep the previous position, it can be replaced with the current one. var worksheet = new ExcelWorksheetData(TestContext); var time = DateTime.Now; var expected = new List <Coordinate>(); for (int i = 1; i <= 4; ++i) { var latInColumn = String.Format("Lat{0}", i); var lngInColumn = String.Format("Lng{0}", i); var trkInColumn = String.Format("Trk{0}", i); var latOutColumn = String.Format("CLat{0}", i); var lngOutColumn = String.Format("CLng{0}", i); var trkOutColumn = String.Format("CTrk{0}", i); if (worksheet.String(latInColumn) != null) { time = time.AddHours(1); _Aircraft.DataVersion = time.Ticks; _Aircraft.Latitude = worksheet.Float(latInColumn); _Aircraft.Longitude = worksheet.Float(lngInColumn); _Aircraft.Track = worksheet.NFloat(trkInColumn); _Aircraft.UpdateCoordinates(time, 300 * 60 * 60); Assert.AreEqual(i, _Aircraft.ShortCoordinates.Count); } if (worksheet.String(latOutColumn) != null) { expected.Add(new Coordinate(0, 0, worksheet.Float(latOutColumn), worksheet.Float(lngOutColumn), worksheet.NFloat(trkOutColumn))); } } Assert.AreEqual(expected.Count, _Aircraft.FullCoordinates.Count); for (int i = 0; i < expected.Count; ++i) { var expCoordinate = expected[i]; var fullCoordinate = _Aircraft.FullCoordinates[i]; Assert.AreEqual(expCoordinate, fullCoordinate, i.ToString()); Assert.AreEqual(expCoordinate.Heading, fullCoordinate.Heading, i.ToString()); } }
private IPAddress GetExcelIPAddress(ExcelWorksheetData worksheet, string columnName) { var expected = worksheet.String(columnName); var result = IPAddress.Parse(expected); return(result); }
public void RequestReceivedEventArgs_Can_Interpret_User_Agent_Correctly() { var worksheet = new ExcelWorksheetData(TestContext); var request = new Mock <IRequest>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties(); var response = new Mock <IResponse>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties(); request.Setup(r => r.RemoteEndPoint).Returns(new IPEndPoint(IPAddress.Parse("1.2.3.4"), 80)); request.Setup(r => r.Url).Returns(new Uri("http://127.0.0.1/Root/Whatever")); request.Setup(r => r.RawUrl).Returns("/Root/Whatever"); request.Setup(r => r.UserAgent).Returns(worksheet.String("UserAgent")); var args = new RequestReceivedEventArgs(request.Object, response.Object, "/Root"); Assert.AreEqual(worksheet.Bool("IsAndroid"), args.IsAndroid); Assert.AreEqual(worksheet.Bool("IsIpad"), args.IsIPad); Assert.AreEqual(worksheet.Bool("IsIPhone"), args.IsIPhone); Assert.AreEqual(worksheet.Bool("IsIPod"), args.IsIPod); }
public void ConnectionSessionLogPresenter_Clicking_ShowSessions_Triggers_Validation() { var worksheet = new ExcelWorksheetData(TestContext); _Presenter.Initialise(_View.Object); _View.Object.StartDate = worksheet.DateTime("StartDate"); _View.Object.EndDate = worksheet.DateTime("EndDate"); ValidationResults validationResults = null; _View.Setup(v => v.ShowValidationResults(It.IsAny <ValidationResults>())).Callback((ValidationResults results) => { validationResults = results; }); _View.Raise(v => v.ShowSessionsClicked += null, EventArgs.Empty); Assert.IsNotNull(validationResults); Assert.AreEqual(worksheet.Int("CountErrors"), validationResults.Results.Count()); if (validationResults.Results.Count() > 0) { Assert.IsTrue(validationResults.Results.Where(r => r.Field == worksheet.ParseEnum <ValidationField>("Field") && r.Message == worksheet.String("Message") && r.IsWarning == worksheet.Bool("IsWarning")).Any()); } }
public void AccessFilter_Allow_Behaves_Correctly() { var worksheet = new ExcelWorksheetData(TestContext); // Uncomment this block to only run tests that have True in the RunThis column //var runThis = worksheet.Bool("RunThis"); //if(!runThis) Assert.Fail(); _Access.DefaultAccess = worksheet.ParseEnum <DefaultAccess>("DefaultAccess"); for (var i = 1; i <= 2; ++i) { var addressColumnName = String.Format("Address{0}", i); var address = worksheet.EString(addressColumnName); if (address != null) { _Access.Addresses.Add(address); } else { break; } } _Filter.Initialise(_Access); var ipAddressText = worksheet.String("IPAddress"); var ipAddress = IPAddress.Parse(ipAddressText); var allow = _Filter.Allow(ipAddress); var expected = worksheet.Bool("Allow"); Assert.AreEqual(expected, allow); }
public void Aircraft_UpdateCoordinates_Trims_Short_Coordinates_After_Time_Limit_Has_Passed() { var worksheet = new ExcelWorksheetData(TestContext); var seconds = worksheet.Int("Seconds"); var baseTime = DateTime.UtcNow; for (int i = 1; i <= 3; ++i) { var secondsGapColumn = String.Format("SecondsGap{0}", i); var latitudeColumn = String.Format("Latitude{0}", i); var longitudeColumn = String.Format("Longitude{0}", i); var trackColumn = String.Format("Track{0}", i); if (worksheet.String(secondsGapColumn) != null) { var utcNow = baseTime.AddSeconds(worksheet.Int(secondsGapColumn)); _Aircraft.DataVersion = utcNow.Ticks; _Aircraft.Latitude = worksheet.NFloat(latitudeColumn); _Aircraft.Longitude = worksheet.NFloat(longitudeColumn); _Aircraft.Track = worksheet.NFloat(trackColumn); _Aircraft.UpdateCoordinates(utcNow, seconds); } } Assert.AreEqual(worksheet.Int("ExpectedCount"), _Aircraft.ShortCoordinates.Count); for (int i = 0; i < _Aircraft.ShortCoordinates.Count; ++i) { var expectedTrackColumn = String.Format("ExpectedTrack{0}", i); Assert.AreEqual(worksheet.NFloat(expectedTrackColumn), _Aircraft.ShortCoordinates[i].Heading, i.ToString()); } }
public void ProximityGadgetAircraftJson_ToModel_Returns_The_Closest_Aircraft() { var worksheet = new ExcelWorksheetData(TestContext); var originLatitude = worksheet.NDouble("GadgetLat"); var originLongitude = worksheet.NDouble("GadgetLng"); var aircraft = CreateAircraft(2); for (int i = 1; i <= 2; ++i) { aircraft[i - 1].Callsign = i.ToString(); aircraft[i - 1].Latitude = worksheet.NFloat(String.Format("AC{0}Lat", i)); aircraft[i - 1].Longitude = worksheet.NFloat(String.Format("AC{0}Lng", i)); } var model = ProximityGadgetAircraftJson.ToModel(aircraft, originLatitude, originLongitude); var closestCallsign = worksheet.String("Closest"); if (closestCallsign == null) { Assert.IsNull(model.ClosestAircraft); } else { Assert.AreEqual(closestCallsign, model.ClosestAircraft.Callsign); } }
public void AirPressureLookup_FindClosest_Returns_Correct_AirPressure_Record() { var worksheet = new ExcelWorksheetData(TestContext); for (var i = 1; i <= 3; ++i) { var latitudeColumn = String.Format("Lat{0}", i); var longitudeColumn = String.Format("Lng{0}", i); if (worksheet.String(latitudeColumn) != null) { _AirPressures.Add(new AirPressure() { Latitude = worksheet.Float(latitudeColumn), Longitude = worksheet.Float(longitudeColumn), AgeSeconds = (short)i, }); } } _Lookup.LoadAirPressures(_AirPressures, _Now); var expected = worksheet.Int("Closest"); var actual = _Lookup.FindClosest(worksheet.Float("Lat"), worksheet.Float("Lng")); Assert.AreEqual(expected, actual.AgeSeconds); }
public void IPEndPointHelper_IsLocalOrLanAddress_Returns_Correct_Values() { ExcelWorksheetData worksheet = new ExcelWorksheetData(TestContext); IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(worksheet.String("IPAddress")), 0); Assert.AreEqual(worksheet.Bool("Expected"), IPEndPointHelper.IsLocalOrLanAddress(endPoint)); }
public void Responder_SendText_Fills_Response_Correctly() { ExcelWorksheetData worksheet = new ExcelWorksheetData(TestContext); string encodingName = worksheet.String("Encoding"); var encoding = encodingName == null ? (Encoding)null : (Encoding)typeof(Encoding).GetProperty(encodingName, BindingFlags.Static | BindingFlags.Public).GetValue(null, null); _Responder.SendText(_Request.Object, _Response.Object, worksheet.EString("Text"), encoding, worksheet.EString("MimeType")); byte[] expectedStreamContent = worksheet.Bytes("ResponseContent"); byte[] actualStreamContent = _OutputStream.ToArray(); Assert.IsTrue(expectedStreamContent.SequenceEqual(actualStreamContent)); Assert.AreEqual(expectedStreamContent.Length, _Response.Object.ContentLength); Assert.AreEqual(worksheet.String("ResponseMimeType"), _Response.Object.MimeType); Assert.AreEqual(HttpStatusCode.OK, _Response.Object.StatusCode); }
public void ModeSTranslator_Translate_Decodes_Packets_Correctly() { for(var conversionMethod = 0;conversionMethod < 2;++conversionMethod) { var worksheet = new ExcelWorksheetData(TestContext); var expectedValue = new SpreadsheetFieldValue(worksheet, 7); var bits = worksheet.String("Packet"); var bytes = TestUtilities.ConvertBitStringToBytes(bits); var reply = conversionMethod == 0 ? _Translator.Translate(bytes.ToArray()) : _Translator.Translate(bytes.ToArray(), 0); foreach(var replyProperty in reply.GetType().GetProperties()) { switch(replyProperty.Name) { case "ACASMessage": Assert.IsTrue(TestUtilities.SequenceEqual(expectedValue.GetBytes("MV"), reply.ACASMessage)); break; case "Altitude": Assert.AreEqual(expectedValue.GetNInt("AC"), reply.Altitude); break; case "AltitudeIsMetric": Assert.AreEqual(expectedValue.GetNBool("AC:M"), reply.AltitudeIsMetric); break; case "ApplicationField": Assert.AreEqual(expectedValue.GetEnum<ApplicationField>("AF"), reply.ApplicationField); break; case "Capability": Assert.AreEqual(expectedValue.GetEnum<Capability>("CA"), reply.Capability); break; case "CommBMessage": Assert.IsTrue(TestUtilities.SequenceEqual(expectedValue.GetBytes("MB"), reply.CommBMessage)); break; case "CommDMessage": Assert.IsTrue(TestUtilities.SequenceEqual(expectedValue.GetBytes("MD"), reply.CommDMessage)); break; case "ControlField": Assert.AreEqual(expectedValue.GetEnum<ControlField>("CF"), reply.ControlField); break; case "CrossLinkCapability": Assert.AreEqual(expectedValue.GetNBool("CC"), reply.CrossLinkCapability); break; case "DownlinkFormat": Assert.AreEqual(worksheet.ParseEnum<DownlinkFormat>("DownlinkFormat"), reply.DownlinkFormat); break; case "DownlinkRequest": Assert.AreEqual(expectedValue.GetNByte("DR", true), reply.DownlinkRequest); break; case "DSegmentNumber": Assert.AreEqual(expectedValue.GetNByte("ND", true), reply.DSegmentNumber); break; case "ElmControl": Assert.AreEqual(expectedValue.GetEnum<ElmControl>("KE"), reply.ElmControl); break; case "ExtendedSquitterMessage": Assert.IsTrue(TestUtilities.SequenceEqual(expectedValue.GetBytes("ME"), reply.ExtendedSquitterMessage)); break; case "ExtendedSquitterSupplementaryMessage": Assert.IsTrue(TestUtilities.SequenceEqual(expectedValue.GetBytes("MEX"), reply.ExtendedSquitterSupplementaryMessage)); break; case "FlightStatus": Assert.AreEqual(expectedValue.GetEnum<FlightStatus>("FS"), reply.FlightStatus); break; case "FormattedIcao24": Assert.AreEqual(worksheet.String("Icao24"), reply.FormattedIcao24); break; case "Icao24": Assert.AreEqual(Convert.ToInt32(worksheet.String("Icao24"), 16), reply.Icao24); break; case "Identity": Assert.AreEqual(expectedValue.GetNShort("ID"), reply.Identity); break; case "NonIcao24Address": Assert.AreEqual(expectedValue.GetNInt("AAX", true), reply.NonIcao24Address); break; case "ParityInterrogatorIdentifier": Assert.AreEqual(expectedValue.GetNInt("PI", true), reply.ParityInterrogatorIdentifier); break; case "PossibleCallsign": Assert.AreEqual(expectedValue.GetString("PC"), reply.PossibleCallsign); break; case "ReplyInformation": Assert.AreEqual(expectedValue.GetNByte("RI", true), reply.ReplyInformation); break; case "SensitivityLevel": Assert.AreEqual(expectedValue.GetNByte("SL", true), reply.SensitivityLevel); break; case "UtilityMessage": Assert.AreEqual(expectedValue.GetNByte("UM", true), reply.UtilityMessage); break; case "VerticalStatus": Assert.AreEqual(expectedValue.GetEnum<VerticalStatus>("VS"), reply.VerticalStatus); break; default: throw new NotImplementedException(); } } } }
public void VectorVelocity_Calculates_Velocity_And_Bearing_Correctly() { var worksheet = new ExcelWorksheetData(TestContext); var velocity = new VectorVelocity() { IsWesterlyVelocity = worksheet.Bool("IsWesterlyVelocity"), IsSoutherlyVelocity = worksheet.Bool("IsSoutherlyVelocity"), EastWestVelocity = worksheet.NShort("EastWestVelocity"), EastWestExceeded = worksheet.Bool("EastWestExceeded"), NorthSouthVelocity = worksheet.NShort("NorthSouthVelocity"), NorthSouthExceeded = worksheet.Bool("NorthSouthExceeded"), }; if(worksheet.String("Speed") == null) Assert.IsNull(velocity.Speed); else Assert.AreEqual(worksheet.Double("Speed"), velocity.Speed.Value, 0.000001); if(worksheet.String("Bearing") == null) Assert.IsNull(velocity.Bearing); else Assert.AreEqual(worksheet.Double("Bearing"), velocity.Bearing.Value, 0.000001); }
public void LogClient_Address_Is_Conversion_Of_IpAddress_Property() { var worksheet = new ExcelWorksheetData(TestContext); var logClient = new LogClient() { IpAddress = worksheet.EString("IpAddress") }; var expected = worksheet.String("Address"); if(expected == null) Assert.IsNull(logClient.Address); else Assert.AreEqual(expected, logClient.Address.ToString()); }
public void PipelineRequest_IsMobileUserAgentString_Decodes_Common_Mobile_UserAgent_Strings() { var worksheet = new ExcelWorksheetData(TestContext); var userAgent = worksheet.EString("UserAgent"); var device = worksheet.String("Device"); var isMobile = worksheet.Bool("IsMobile"); _Request.UserAgent = userAgent; Assert.AreEqual(isMobile, _Request.IsMobileUserAgentString, "{0}: {1}", device, userAgent ?? "<null>"); }
public void StandingDataManager_FindAircraftType_Returns_Correct_Values() { ExcelWorksheetData worksheet = new ExcelWorksheetData(TestContext); _Implementation.Load(); var searchFor = worksheet.String("SearchFor"); var aircraftType = _Implementation.FindAircraftType(searchFor); if (worksheet.Bool("IsNull")) { Assert.AreEqual(null, aircraftType); } else { List <string> manufacturers = new List <string>(); List <string> models = new List <string>(); BuildExpectedList(worksheet, manufacturers, "ManOut1"); BuildExpectedList(worksheet, manufacturers, "ManOut2"); BuildExpectedList(worksheet, models, "ModelOut1"); BuildExpectedList(worksheet, models, "ModelOut2"); Assert.AreEqual(manufacturers.Count, aircraftType.Manufacturers.Count); foreach (string manufacturer in manufacturers) { Assert.IsTrue(aircraftType.Manufacturers.Contains(manufacturer)); } Assert.AreEqual(models.Count, aircraftType.Models.Count); foreach (string model in models) { Assert.IsTrue(aircraftType.Models.Contains(model)); } Assert.AreEqual(worksheet.String("Type"), aircraftType.Type); Assert.AreEqual(worksheet.ParseEnum <WakeTurbulenceCategory>("Wake"), aircraftType.WakeTurbulenceCategory); Assert.AreEqual(worksheet.ParseEnum <EngineType>("EngineType"), aircraftType.EngineType); Assert.AreEqual(worksheet.String("Engines"), aircraftType.Engines); Assert.AreEqual(worksheet.ParseEnum <Species>("Species"), aircraftType.Species); } }
public void UniversalPlugAndPlayManager_TakeServerOffInternet_Removes_Mapping_From_Router() { var worksheet = new ExcelWorksheetData(TestContext); _Configuration.WebServerSettings.EnableUPnp = worksheet.Bool("CnfEnabled"); _Configuration.WebServerSettings.UPnpPort = worksheet.Int("CnfUPnpPort"); _Configuration.WebServerSettings.IsOnlyInternetServerOnLan = worksheet.Bool("CnfOnlyVRSOnNetwork"); _WebServer.Setup(s => s.NetworkIPAddress).Returns(worksheet.String("SvrAddress")); _WebServer.Setup(s => s.Port).Returns(worksheet.Int("SvrPort")); _Manager.Initialise(); if (worksheet.String("RtrDescription") != null) { AddPortMapping(worksheet.String("RtrDescription"), worksheet.Int("RtrExtPort"), worksheet.String("RtrIntClient"), worksheet.Int("RtrIntPort"), worksheet.String("RtrProtocol")); if (_PortMappings[0].Description == _Description && _PortMappings[0].ExternalPort == _Configuration.WebServerSettings.UPnpPort && _PortMappings[0].InternalClient == _WebServer.Object.NetworkIPAddress && _PortMappings[0].InternalPort == _WebServer.Object.Port && _PortMappings[0].Protocol == "TCP") { _Manager.PutServerOntoInternet(); } } _Manager.StateChanged += _StateChangedEvent.Handler; _Manager.TakeServerOffInternet(); _Provider.Verify(p => p.RemoveMapping(worksheet.Int("CnfUPnpPort"), "TCP"), worksheet.Bool("ExpectRemove") ? Times.Once() : Times.Never()); Assert.AreEqual(worksheet.Bool("ExpectIsPresent"), _Manager.PortForwardingPresent); Assert.AreEqual(worksheet.Bool("ExpectStateChanged") ? 1 : 0, _StateChangedEvent.CallCount); if (_StateChangedEvent.CallCount > 0) { Assert.AreSame(_Manager, _StateChangedEvent.Sender); Assert.IsNotNull(_StateChangedEvent.Args); } }
public void BaseStationMessageTranslator_Translate_Translates_Messages_Correctly() { ExcelWorksheetData worksheet = new ExcelWorksheetData(TestContext); BaseStationMessage translated = _Implementation.Translate(worksheet.String("Text"), 123); Assert.AreEqual(Enum.Parse(typeof(BaseStationMessageType), worksheet.String("MessageType")), translated.MessageType); Assert.AreEqual(Enum.Parse(typeof(BaseStationTransmissionType), worksheet.String("TransmissionType")), translated.TransmissionType); Assert.AreEqual(Enum.Parse(typeof(BaseStationStatusCode), worksheet.String("StatusCode")), translated.StatusCode); Assert.AreEqual(worksheet.Int("SessionId"), translated.SessionId); Assert.AreEqual(worksheet.Int("AircraftId"), translated.AircraftId); Assert.AreEqual(worksheet.String("Icao24"), translated.Icao24); Assert.AreEqual(worksheet.Int("FlightId"), translated.FlightId); Assert.AreEqual(worksheet.DateTime("MessageGenerated"), translated.MessageGenerated); Assert.AreEqual(worksheet.DateTime("MessageLogged"), translated.MessageLogged); Assert.AreEqual(worksheet.String("Callsign"), translated.Callsign); Assert.AreEqual(worksheet.NFloat("Altitude"), translated.Altitude); Assert.AreEqual(worksheet.NFloat("GroundSpeed"), translated.GroundSpeed); Assert.AreEqual(worksheet.NFloat("Track"), translated.Track); Assert.AreEqual(worksheet.NDouble("Latitude"), translated.Latitude); Assert.AreEqual(worksheet.NDouble("Longitude"), translated.Longitude); Assert.AreEqual(worksheet.NFloat("VerticalRate"), translated.VerticalRate); Assert.AreEqual(worksheet.NInt("Squawk"), translated.Squawk); Assert.AreEqual(worksheet.NBool("SquawkHasChanged"), translated.SquawkHasChanged); Assert.AreEqual(worksheet.NBool("Emergency"), translated.Emergency); Assert.AreEqual(worksheet.NBool("IdentActive"), translated.IdentActive); Assert.AreEqual(worksheet.NBool("OnGround"), translated.OnGround); Assert.AreEqual(worksheet.Bool("IsMlat"), translated.IsMlat); }
private void RunDataDrivenTest(ExcelWorksheetData worksheet, Func <string, string, bool> isPathAccessible) { var defaultAccess = worksheet.ParseEnum <DefaultAccess>("DefaultAccess"); var exceptCidr1 = worksheet.String("ExceptCIDR1"); var pathFromRoot = worksheet.String("PathFromRoot"); var requestAddress = worksheet.String("RequestAddress"); var requestPathAndFile = worksheet.String("RequestPathAndFile"); var isAccessAllowed = worksheet.Bool("IsAccessAllowed"); var comments = worksheet.String("Comments"); var access = new Access() { DefaultAccess = defaultAccess, }; access.Addresses.Add(exceptCidr1); _Configuration.SetRestrictedPath(pathFromRoot, access); var result = isPathAccessible(requestPathAndFile, requestAddress); Assert.AreEqual(isAccessAllowed, result, comments); }
public void CompactPositionReporting_Encode_Produces_Correct_Results_For_CPR101_Tables() { // The values for this test are all taken directly from the transition latitude test tables in 1090-WP30-12 Proposed New Appendix CPR101. var worksheet = new ExcelWorksheetData(TestContext); var numberOfBits = worksheet.Byte("Bits"); var oddFormat = worksheet.Bool("OddFormat"); var latitude = worksheet.Double("Latitude"); var longitude = worksheet.Double("Longitude"); var globalCoordinate = new GlobalCoordinate(latitude, longitude); var expectedLatitude = Convert.ToInt32(worksheet.String("ExpectedLatitude"), 16); var expectedLongitude = Convert.ToInt32(worksheet.String("ExpectedLongitude"), 16); var dataRow = worksheet.Int("DataRow"); // helps set conditional breakpoints, VSTS doesn't always process rows in ascending order as they appear in the worksheet // In testing some of the input latitudes and longitudes couldn't produce the expected results from table 6-1 etc. of 1090-WP30-12 because of small // rounding errors in the handling of doubles. Switching to decimals didn't help and it would make the code slower because the FPU doesn't work with // decimals. So the "RELatitude" and "RELongitude" columns were added - if they are empty then the code is expected to produce the values in // the Expected columns, which corresponds with the test results from 1090-WP30-12, but if they contain values then these are the actual results after // the rounding error has had its wicked way. In most cases they are 1 out for latitude but that can move the resolved latitude into a different NL and produce // a large difference in longitude. There are very few of these anomalies, they represent errors of a few feet and as this isn't going into an aircraft I can't // say I'm too bothered about them. However I do want them to be obvious in the test data, hence the reason for adding new columns rather than just changing // the expected results. int? reLatitude = null; int? reLongitude = null; if(worksheet.String("RELatitude") != null) { reLatitude = Convert.ToInt32(worksheet.String("RELatitude"), 16); reLongitude = Convert.ToInt32(worksheet.String("RELongitude"), 16); } var coordinate = _Cpr.Encode(globalCoordinate, oddFormat, numberOfBits); Assert.AreEqual(reLatitude ?? expectedLatitude, coordinate.Latitude); Assert.AreEqual(reLongitude ?? expectedLongitude, coordinate.Longitude); Assert.AreEqual(numberOfBits, coordinate.NumberOfBits); Assert.AreEqual(oddFormat, coordinate.OddFormat); }
public void RequestReceivedEventArgs_Constructor_Builds_Properties_From_Request_Correctly() { ExcelWorksheetData worksheet = new ExcelWorksheetData(TestContext); var request = new Mock<IRequest>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties(); var response = new Mock<IResponse>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties(); var headers = new NameValueCollection(); var endPoint = new IPEndPoint(IPAddress.Parse(worksheet.String("ResponseAddress")), 45678); request.Setup(r => r.RemoteEndPoint).Returns(endPoint); request.Setup(r => r.Url).Returns(new Uri(worksheet.EString("Url"))); request.Setup(r => r.RawUrl).Returns(worksheet.EString("RawUrl")); request.Setup(r => r.Headers).Returns(headers); var xForwardedFor = worksheet.EString("XForwardedFor"); if(xForwardedFor != null) headers.Add("X-Forwarded-For", xForwardedFor); var args = new RequestReceivedEventArgs(request.Object, response.Object, worksheet.EString("Root")); Assert.AreEqual(worksheet.EString("WebSite"), args.WebSite); Assert.AreEqual(worksheet.EString("PathAndFile"), args.PathAndFile); Assert.AreEqual(worksheet.EString("File"), args.File); Assert.AreEqual(worksheet.EString("ProxyAddress"), args.ProxyAddress); Assert.AreEqual(worksheet.EString("ClientAddress"), args.ClientAddress); Assert.AreEqual(worksheet.Bool("IsInternetRequest"), args.IsInternetRequest); Assert.AreEqual(worksheet.Int("PathCount"), args.PathParts.Count); Assert.AreEqual(worksheet.Int("QueryCount"), args.QueryString.Count); for(var i = 0;i < args.PathParts.Count;++i) { Assert.AreEqual(worksheet.EString(String.Format("Path{0}", i)), args.PathParts[i]); } for(var i = 0;i < args.QueryString.Count;++i) { var expectedName = worksheet.String(String.Format("QueryName{0}", i)); var expectedValue = worksheet.String(String.Format("QueryValue{0}", i)); Assert.AreEqual(expectedValue, args.QueryString[expectedName]); } }
public void WebServer_Addresses_Are_Reported_Correctly() { var worksheet = new ExcelWorksheetData(TestContext); _WebServer.Root = worksheet.String("Root"); _WebServer.Port = worksheet.NInt("Port") ?? 80; if(worksheet.String("IPAddresses") == null) _Provider.Setup(p => p.GetHostAddresses()).Returns((IPAddress[])null); else { var ipAddresses = new List<IPAddress>(); foreach(var chunk in worksheet.EString("IPAddresses").Split(',')) { if(chunk.Length > 0) ipAddresses.Add(IPAddress.Parse(chunk)); } _Provider.Setup(p => p.GetHostAddresses()).Returns(ipAddresses.ToArray()); } _WebServer.ExternalIPAddress = worksheet.EString("ExternalIPAddress"); _WebServer.ExternalPort = worksheet.NInt("UPnPExternalPort") ?? 80; Assert.AreEqual(worksheet.String("LocalAddress"), _WebServer.LocalAddress); Assert.AreEqual(worksheet.String("NetworkAddress"), _WebServer.NetworkAddress); Assert.AreEqual(worksheet.String("NetworkIPAddress"), _WebServer.NetworkIPAddress); Assert.AreEqual(worksheet.String("ExternalAddress"), _WebServer.ExternalAddress); }
public void Aircraft_UpdateCoordinates_Replaces_Last_Full_Coordinate_If_Track_Hardly_Changes() { // If an update changes the position but the aircraft remains on the same ground track as the previous position // then there's no need to keep the previous position, it can be replaced with the current one. var worksheet = new ExcelWorksheetData(TestContext); var time = DateTime.Now; var expected = new List<Coordinate>(); for(int i = 1;i <= 4;++i) { var latInColumn = String.Format("Lat{0}", i); var lngInColumn = String.Format("Lng{0}", i); var trkInColumn = String.Format("Trk{0}", i); var latOutColumn = String.Format("CLat{0}", i); var lngOutColumn = String.Format("CLng{0}", i); var trkOutColumn = String.Format("CTrk{0}", i); if(worksheet.String(latInColumn) != null) { time = time.AddHours(1); _Aircraft.DataVersion = time.Ticks; _Aircraft.Latitude = worksheet.Float(latInColumn); _Aircraft.Longitude = worksheet.Float(lngInColumn); _Aircraft.Track = worksheet.NFloat(trkInColumn); _Aircraft.UpdateCoordinates(time, 300 * 60 * 60); Assert.AreEqual(i, _Aircraft.ShortCoordinates.Count); } if(worksheet.String(latOutColumn) != null) { expected.Add(new Coordinate(0, 0, worksheet.Float(latOutColumn), worksheet.Float(lngOutColumn), worksheet.NFloat(trkOutColumn))); } } Assert.AreEqual(expected.Count, _Aircraft.FullCoordinates.Count); for(int i = 0;i < expected.Count;++i) { var expCoordinate = expected[i]; var fullCoordinate = _Aircraft.FullCoordinates[i]; Assert.AreEqual(expCoordinate, fullCoordinate, i.ToString()); Assert.AreEqual(expCoordinate.Heading, fullCoordinate.Heading, i.ToString()); } }
public void WebSite_Image_Correct_Image_Is_Rendered() { ExcelWorksheetData worksheet = new ExcelWorksheetData(TestContext); string pathAndFile = worksheet.String("UrlPath"); _WebSite.AttachSiteToServer(_WebServer.Object); var args = RequestReceivedEventArgsHelper.Create(_Request, _Response, pathAndFile, false); _WebServer.Raise(m => m.RequestReceived += null, args); Assert.AreEqual(true, args.Handled); byte[] content = _OutputStream.ToArray(); var md5Checksum = new StringBuilder(); using(var md5 = MD5.Create()) { foreach(var b in md5.ComputeHash(content)) { md5Checksum.AppendFormat("{0:X2}", b); } } Assert.AreEqual(worksheet.String("MimeType"), _Response.Object.MimeType); Assert.AreEqual(worksheet.Int("Length"), content.Length); Assert.AreEqual(worksheet.String("MD5"), md5Checksum.ToString(), true); }
public void BaseStationAircraftList_MessageReceived_Does_Not_Null_Out_Existing_Message_Values() { // We need to make sure that we cope when we get a message that sets a value and then another message with a null for the same value var worksheet = new ExcelWorksheetData(TestContext); _AircraftList.Start(); object messageObject; PropertyInfo messageProperty; var messageColumn = worksheet.String("MessageColumn"); if(!messageColumn.StartsWith("S:")) { messageObject = _BaseStationMessage; messageProperty = typeof(BaseStationMessage).GetProperty(messageColumn); } else { messageColumn = messageColumn.Substring(2); messageObject = _BaseStationMessage.Supplementary = new BaseStationSupplementaryMessage(); messageProperty = typeof(BaseStationSupplementaryMessage).GetProperty(messageColumn); } var aircraftProperty = typeof(IAircraft).GetProperty(worksheet.String("AircraftColumn")); var culture = new CultureInfo("en-GB"); var messageValue = TestUtilities.ChangeType(worksheet.EString("MessageValue"), messageProperty.PropertyType, culture); var aircraftValue = TestUtilities.ChangeType(worksheet.EString("AircraftValue"), aircraftProperty.PropertyType, culture); messageProperty.SetValue(messageObject, messageValue, null); _Port30003Listener.Raise(m => m.Port30003MessageReceived += null, _BaseStationMessageEventArgs); var aircraft = _AircraftList.FindAircraft(0x4008F6); Assert.AreEqual(aircraftValue, aircraftProperty.GetValue(aircraft, null)); messageProperty.SetValue(messageObject, null, null); _Port30003Listener.Raise(m => m.Port30003MessageReceived += null, _BaseStationMessageEventArgs); var outerAircraft = _AircraftList.FindAircraft(0x4008F6); Assert.AreEqual(aircraftValue, aircraftProperty.GetValue(outerAircraft, null)); }
private void Do_BaseStationMessage_ToBaseStationString_Builds_Valid_BaseStation_Messages_From_A_BaseStationMessage_Object() { var worksheet = new ExcelWorksheetData(TestContext); _Implementation.MessageType = worksheet.ParseEnum<BaseStationMessageType>("MessageType"); _Implementation.TransmissionType = worksheet.ParseEnum<BaseStationTransmissionType>("TransmissionType"); _Implementation.StatusCode = worksheet.ParseEnum<BaseStationStatusCode>("StatusCode"); _Implementation.SessionId = worksheet.Int("SessionId"); _Implementation.AircraftId = worksheet.Int("AircraftId"); _Implementation.Icao24 = worksheet.String("Icao24"); _Implementation.FlightId = worksheet.Int("FlightId"); _Implementation.MessageGenerated = worksheet.DateTime("MessageGenerated"); _Implementation.MessageLogged = worksheet.DateTime("MessageLogged"); _Implementation.Callsign = worksheet.String("Callsign"); _Implementation.Altitude = worksheet.NInt("Altitude"); _Implementation.GroundSpeed = worksheet.NFloat("GroundSpeed"); _Implementation.Track = worksheet.NFloat("Track"); _Implementation.Latitude = worksheet.NDouble("Latitude"); _Implementation.Longitude = worksheet.NDouble("Longitude"); _Implementation.VerticalRate = worksheet.NInt("VerticalRate"); _Implementation.Squawk = worksheet.NInt("Squawk"); _Implementation.SquawkHasChanged = worksheet.NBool("SquawkHasChanged"); _Implementation.Emergency = worksheet.NBool("Emergency"); _Implementation.IdentActive = worksheet.NBool("IdentActive"); _Implementation.OnGround = worksheet.NBool("OnGround"); Assert.AreEqual(worksheet.String("Text"), _Implementation.ToBaseStationString()); }
public void Plugin_Flight_Updates_Status_Bool_Values_Correctly() { // These are the Flight record fields that start with "Had". var worksheet = new ExcelWorksheetData(TestContext); SetEnabledOption(true); BaseStationFlight flight = null; _BaseStationDatabase.Setup(d => d.UpdateFlight(It.IsAny<BaseStationFlight>())).Callback((BaseStationFlight f) => { flight = f; }); _Plugin.Startup(_StartupParameters); var messageProperty = typeof(BaseStationMessage).GetProperty(worksheet.String("MsgProperty")); for(int i = 0;i < worksheet.Int("Count");++i) { var message = new BaseStationMessage() { Icao24 = "Z", MessageType = BaseStationMessageType.Transmission, TransmissionType = BaseStationTransmissionType.AirToAir }; var valueText = worksheet.EString(String.Format("MsgValue{0}", i + 1)); messageProperty.SetValue(message, TestUtilities.ChangeType(valueText, messageProperty.PropertyType, CultureInfo.InvariantCulture), null); _Listener.Raise(r => r.Port30003MessageReceived += null, new BaseStationMessageEventArgs(message)); } SetProviderTimes(_Provider.Object.LocalNow.AddMinutes(MinutesBeforeFlightClosed)); _HeartbeatService.Raise(s => s.SlowTick += null, EventArgs.Empty); _BaseStationDatabase.Verify(d => d.UpdateFlight(It.IsAny<BaseStationFlight>()), Times.Once()); var propertyName = worksheet.String("FlightProperty"); var flightProperty = typeof(BaseStationFlight).GetProperty(propertyName); var flightValue = worksheet.EString("FlightValue"); var expectedValue = TestUtilities.ChangeType(flightValue, flightProperty.PropertyType, CultureInfo.InvariantCulture); var actualValue = flightProperty.GetValue(flight, null); Assert.AreEqual(expectedValue, actualValue, propertyName); }
private void SpreadsheetTests(Action<ExcelWorksheetData> afterSetFolder) { var worksheet = new ExcelWorksheetData(TestContext); bool checkCacheChanged = worksheet.ColumnExists("CacheChanged"); for(int i = 1;i <= 2;++i) { string nameColumn = String.Format("File{0}", i); string lastModifiedColumn = String.Format("Time{0}", i); if(!worksheet.ColumnExists(nameColumn)) continue; var name = worksheet.String(nameColumn); var time = worksheet.ColumnExists(lastModifiedColumn) ? worksheet.DateTime(lastModifiedColumn) : new DateTime(2999, 12, 31); if(name != null) _Files.Add(new TestFileInfo(name, time)); } _Provider.Setup(p => p.GetFilesInFolder(It.IsAny<string>())).Returns(_Files); var folder = worksheet.String("Folder"); if(folder != null) _DirectoryCache.Folder = folder; if(worksheet.ColumnExists("LastModified")) { var fileInfo = worksheet.String("LastModified") == null ? null : new TestFileInfo(worksheet.String("FileName"), worksheet.DateTime("LastModified")); _Provider.Setup(p => p.GetFileInfo(worksheet.EString("FileName"))).Returns(fileInfo); } if(checkCacheChanged) _DirectoryCache.CacheChanged += _CacheChangedEvent.Handler; if(afterSetFolder != null) afterSetFolder(worksheet); Assert.AreEqual(folder, _DirectoryCache.Folder); Assert.AreEqual(worksheet.Bool("Exists"), _DirectoryCache.FileExists(worksheet.EString("SearchFor"))); if(checkCacheChanged) Assert.AreEqual(worksheet.Bool("CacheChanged") ? 1 : 0, _CacheChangedEvent.CallCount); }
public void BaseStationAircraftList_Heartbeat_Periodically_Refreshes_Database_Details() { var worksheet = new ExcelWorksheetData(TestContext); _Configuration.BaseStationSettings.DisplayTimeoutSeconds = (MinutesBetweenDetailRefresh * 60) + 1; _ConfigurationStorage.Raise(c => c.ConfigurationChanged += null, EventArgs.Empty); _AircraftList.Start(); // Initialise timer var time = DateTime.UtcNow; _Provider.Setup(p => p.UtcNow).Returns(time); _HeartbeatService.Raise(h => h.FastTick += null, EventArgs.Empty); // Message received when no information exists in database _BaseStationDatabase.Setup(d => d.GetAircraftByCode("4008F6")).Returns((BaseStationAircraft)null); _Port30003Listener.Raise(m => m.Port30003MessageReceived += null, _BaseStationMessageEventArgs); _BaseStationDatabase.Verify(d => d.GetAircraftByCode("4008F6"), Times.Once()); // Heartbeat 1 millisecond before refresh is allowed _Provider.Setup(p => p.UtcNow).Returns(time.AddMinutes(MinutesBetweenDetailRefresh).AddMilliseconds(-1)); _HeartbeatService.Raise(h => h.FastTick += null, EventArgs.Empty); _BaseStationDatabase.Verify(d => d.GetAircraftByCode("4008F6"), Times.Once()); // Setup database record _BaseStationDatabase.Setup(d => d.GetAircraftByCode("4008F6")).Returns(_BaseStationAircraft); var databaseProperty = typeof(BaseStationAircraft).GetProperty(worksheet.String("DatabaseColumn")); var aircraftProperty = typeof(IAircraft).GetProperty(worksheet.String("AircraftColumn")); var culture = new CultureInfo("en-GB"); var databaseValue = TestUtilities.ChangeType(worksheet.EString("DatabaseValue"), databaseProperty.PropertyType, culture); var aircraftValue = TestUtilities.ChangeType(worksheet.EString("AircraftValue"), aircraftProperty.PropertyType, culture); databaseProperty.SetValue(_BaseStationAircraft, databaseValue, null); // Heartbeat on the refresh interval _Provider.Setup(p => p.UtcNow).Returns(time.AddMinutes(MinutesBetweenDetailRefresh)); _HeartbeatService.Raise(h => h.FastTick += null, EventArgs.Empty); var aircraft = _AircraftList.FindAircraft(0x4008F6); Assert.AreEqual(aircraftValue, aircraftProperty.GetValue(aircraft, null)); }
public void NewVersionChecker_CheckForNewVersion_Returns_Correct_Value() { var worksheet = new ExcelWorksheetData(TestContext); _ApplicationInformation.Setup(p => p.Version).Returns(new Version(worksheet.String("ApplicationVersion"))); _Provider.Setup(p => p.DownloadFileContent(It.IsAny<string>())).Returns(worksheet.String("WebsiteVersion").Replace(@"\r", "\r").Replace(@"\n", "\n")); bool expected = worksheet.Bool("IsNewer"); Assert.AreEqual(expected, _NewVersionChecker.CheckForNewVersion()); Assert.AreEqual(expected, _NewVersionChecker.IsNewVersionAvailable); }
public void NewVersionChecker_CheckForNewVersion_Raises_NewVersionAvailable_When_Appropriate() { var worksheet = new ExcelWorksheetData(TestContext); _NewVersionChecker.NewVersionAvailable += _NewVersionAvailable.Handler; _NewVersionAvailable.EventRaised += (object sender, EventArgs args) => { Assert.AreEqual(true, _NewVersionChecker.IsNewVersionAvailable); }; _ApplicationInformation.Setup(p => p.Version).Returns(new Version(worksheet.String("ApplicationVersion"))); _Provider.Setup(p => p.DownloadFileContent(It.IsAny<string>())).Returns(worksheet.String("WebsiteVersion").Replace(@"\r", "\r").Replace(@"\n", "\n")); _NewVersionChecker.CheckForNewVersion(); if(!worksheet.Bool("IsNewer")) Assert.AreEqual(0, _NewVersionAvailable.CallCount); else { Assert.AreEqual(1, _NewVersionAvailable.CallCount); Assert.AreSame(_NewVersionChecker, _NewVersionAvailable.Sender); Assert.IsNotNull(_NewVersionAvailable.Args); } }
public void UniversalPlugAndPlayManager_Trash_Mappings_Removed_During_Initialise() { var worksheet = new ExcelWorksheetData(TestContext); if(worksheet.String("RtrDescription") != null) { AddPortMapping(worksheet.String("RtrDescription"), worksheet.Int("RtrExtPort"), worksheet.String("RtrIntClient"), worksheet.Int("RtrIntPort"), worksheet.String("RtrProtocol")); } _Configuration.WebServerSettings.EnableUPnp = worksheet.Bool("CnfEnabled"); _Configuration.WebServerSettings.UPnpPort = worksheet.Int("CnfUPnpPort"); _Configuration.WebServerSettings.IsOnlyInternetServerOnLan = worksheet.Bool("CnfOnlyVRSOnNetwork"); _WebServer.Setup(s => s.NetworkIPAddress).Returns(worksheet.String("SvrAddress")); _WebServer.Setup(s => s.Port).Returns(worksheet.Int("SvrPort")); _Manager.Initialise(); _Provider.Verify(p => p.RemoveMapping(worksheet.Int("RtrExtPort"), worksheet.String("RtrProtocol")), worksheet.Bool("ExpectRemove") ? Times.Once() : Times.Never()); }
public void UniversalPlugAndPlayManager_TakeServerOffInternet_Removes_Mapping_From_Router() { var worksheet = new ExcelWorksheetData(TestContext); _Configuration.WebServerSettings.EnableUPnp = worksheet.Bool("CnfEnabled"); _Configuration.WebServerSettings.UPnpPort = worksheet.Int("CnfUPnpPort"); _Configuration.WebServerSettings.IsOnlyInternetServerOnLan = worksheet.Bool("CnfOnlyVRSOnNetwork"); _WebServer.Setup(s => s.NetworkIPAddress).Returns(worksheet.String("SvrAddress")); _WebServer.Setup(s => s.Port).Returns(worksheet.Int("SvrPort")); _Manager.Initialise(); if(worksheet.String("RtrDescription") != null) { AddPortMapping(worksheet.String("RtrDescription"), worksheet.Int("RtrExtPort"), worksheet.String("RtrIntClient"), worksheet.Int("RtrIntPort"), worksheet.String("RtrProtocol")); if(_PortMappings[0].Description == _Description && _PortMappings[0].ExternalPort == _Configuration.WebServerSettings.UPnpPort && _PortMappings[0].InternalClient == _WebServer.Object.NetworkIPAddress && _PortMappings[0].InternalPort == _WebServer.Object.Port && _PortMappings[0].Protocol == "TCP") _Manager.PutServerOntoInternet(); } _Manager.StateChanged += _StateChangedEvent.Handler; _Manager.TakeServerOffInternet(); _Provider.Verify(p => p.RemoveMapping(worksheet.Int("CnfUPnpPort"), "TCP"), worksheet.Bool("ExpectRemove") ? Times.Once() : Times.Never()); Assert.AreEqual(worksheet.Bool("ExpectIsPresent"), _Manager.PortForwardingPresent); Assert.AreEqual(worksheet.Bool("ExpectStateChanged") ? 1 : 0, _StateChangedEvent.CallCount); if(_StateChangedEvent.CallCount > 0) { Assert.AreSame(_Manager, _StateChangedEvent.Sender); Assert.IsNotNull(_StateChangedEvent.Args); } }
public void UniversalPlugAndPlayManager_PutServerOntoInternet_Adds_Correct_Mapping_To_Router() { var worksheet = new ExcelWorksheetData(TestContext); _Configuration.WebServerSettings.EnableUPnp = worksheet.Bool("CnfEnabled"); _Configuration.WebServerSettings.UPnpPort = worksheet.Int("CnfUPnpPort"); _WebServer.Setup(s => s.NetworkIPAddress).Returns(worksheet.String("SvrAddress")); _WebServer.Setup(s => s.Port).Returns(worksheet.Int("SvrPort")); _Manager.Initialise(); if(worksheet.String("RtrDescription") != null) { AddPortMapping(worksheet.String("RtrDescription"), worksheet.Int("RtrExtPort"), worksheet.String("RtrIntClient"), worksheet.Int("RtrIntPort"), worksheet.String("RtrProtocol")); } _Manager.StateChanged += _StateChangedEvent.Handler; _Manager.PutServerOntoInternet(); _Provider.Verify(p => p.AddMapping(worksheet.Int("CnfUPnpPort"), "TCP", worksheet.Int("SvrPort"), worksheet.String("SvrAddress"), true, _Description), worksheet.Bool("ExpectAdd") ? Times.Once() : Times.Never()); Assert.AreEqual(worksheet.Bool("ExpectIsPresent"), _Manager.PortForwardingPresent); Assert.AreEqual(worksheet.Bool("ExpectStateChanged") ? 1 : 0, _StateChangedEvent.CallCount); if(_StateChangedEvent.CallCount > 0) { Assert.AreSame(_Manager, _StateChangedEvent.Sender); Assert.IsNotNull(_StateChangedEvent.Args); } }
public void Aircraft_UpdateCoordinates_Trims_Short_Coordinates_After_Time_Limit_Has_Passed() { var worksheet = new ExcelWorksheetData(TestContext); var seconds = worksheet.Int("Seconds"); var baseTime = DateTime.UtcNow; for(int i = 1;i <= 3;++i) { var secondsGapColumn = String.Format("SecondsGap{0}", i); var latitudeColumn = String.Format("Latitude{0}", i); var longitudeColumn = String.Format("Longitude{0}", i); var trackColumn = String.Format("Track{0}", i); if(worksheet.String(secondsGapColumn) != null) { var utcNow = baseTime.AddSeconds(worksheet.Int(secondsGapColumn)); _Aircraft.DataVersion = utcNow.Ticks; _Aircraft.Latitude = worksheet.NFloat(latitudeColumn); _Aircraft.Longitude = worksheet.NFloat(longitudeColumn); _Aircraft.Track = worksheet.NFloat(trackColumn); _Aircraft.UpdateCoordinates(utcNow, seconds); } } Assert.AreEqual(worksheet.Int("ExpectedCount"), _Aircraft.ShortCoordinates.Count); for(int i = 0;i < _Aircraft.ShortCoordinates.Count;++i) { var expectedTrackColumn = String.Format("ExpectedTrack{0}", i); Assert.AreEqual(worksheet.NFloat(expectedTrackColumn), _Aircraft.ShortCoordinates[i].Heading, i.ToString()); } }
public void RawMessageTranslator_Translate_Accepts_Icaos_As_Valid_Based_On_Number_Of_Times_Seen() { var worksheet = new ExcelWorksheetData(TestContext); _Translator.AcceptIcaoInPI0Count = worksheet.Int("PI0Count"); _Translator.AcceptIcaoInPI0Milliseconds = worksheet.Int("PI0Ms"); _Translator.AcceptIcaoInNonPICount = worksheet.Int("NonPICount"); _Translator.AcceptIcaoInNonPIMilliseconds = worksheet.Int("NonPIMs"); IEnumerable<ModeSMessage> messages; switch(worksheet.String("DownlinkFormat").ToUpper()) { case "HASPI": messages = CreateModeSMessagesWithPIField(); break; case "NOPI": messages = CreateModeSMessagesWithNoPIField(); break; default: throw new NotImplementedException(); } foreach(var message in messages) { message.Icao24 = CreateRandomIcao24(); var originalDF = message.DownlinkFormat; var originalParity = message.ParityInterrogatorIdentifier; for(var messageNumber = 1;messageNumber <= 3;++messageNumber) { var timeColumn = String.Format("Msg{0}Time", messageNumber); var acceptedColumn = String.Format("Accepted{0}", messageNumber); var piColumn = String.Format("Msg{0}PI", messageNumber); if(worksheet.String(acceptedColumn) != null) { message.DownlinkFormat = originalDF; message.ParityInterrogatorIdentifier = worksheet.NInt(piColumn); if(message.ParityInterrogatorIdentifier == null && originalParity != null) message.DownlinkFormat = DownlinkFormat.ShortAirToAirSurveillance; else if(message.ParityInterrogatorIdentifier != null && originalParity == null) message.DownlinkFormat = DownlinkFormat.ExtendedSquitter; var now = _NowUtc.AddMilliseconds(worksheet.Int(timeColumn)); _Provider.Setup(r => r.UtcNow).Returns(now); var accepted = _Translator.Translate(now, message, null) != null; var expected = worksheet.Bool(acceptedColumn); Assert.AreEqual(expected, accepted, "{0} message {1}: {2}", originalDF, messageNumber, worksheet.String("Comments")); } } } }
public void BaseStationAircraftList_MessageReceived_Translates_Message_Properties_Into_Existing_Aircraft_Correctly() { var worksheet = new ExcelWorksheetData(TestContext); _AircraftList.Start(); _Port30003Listener.Raise(m => m.Port30003MessageReceived += null, _BaseStationMessageEventArgs); object messageObject; PropertyInfo messageProperty; var messageColumn = worksheet.String("MessageColumn"); if(!messageColumn.StartsWith("S:")) { messageObject = _BaseStationMessage; messageProperty = typeof(BaseStationMessage).GetProperty(messageColumn); } else { messageColumn = messageColumn.Substring(2); messageObject = _BaseStationMessage.Supplementary = new BaseStationSupplementaryMessage(); messageProperty = typeof(BaseStationSupplementaryMessage).GetProperty(messageColumn); } var aircraftProperty = typeof(IAircraft).GetProperty(worksheet.String("AircraftColumn")); var culture = new CultureInfo("en-GB"); var messageValue = TestUtilities.ChangeType(worksheet.EString("MessageValue"), messageProperty.PropertyType, culture); var aircraftValue = TestUtilities.ChangeType(worksheet.EString("AircraftValue"), aircraftProperty.PropertyType, culture); messageProperty.SetValue(messageObject, messageValue, null); _Port30003Listener.Raise(m => m.Port30003MessageReceived += null, _BaseStationMessageEventArgs); var aircraft = _AircraftList.FindAircraft(0x4008F6); Assert.AreEqual(aircraftValue, aircraftProperty.GetValue(aircraft, null)); }
public void WebSite_Image_Renders_Pictures_At_Correct_Size() { var worksheet = new ExcelWorksheetData(TestContext); _Configuration.BaseStationSettings.PicturesFolder = TestContext.TestDeploymentDir; _WebSite.AttachSiteToServer(_WebServer.Object); CreateMonochromeImage("ImageRenderSize.png", worksheet.Int("OriginalWidth"), worksheet.Int("OriginalHeight"), Brushes.Red); _AircraftPictureManager.Setup(p => p.FindPicture(_DirectoryCache.Object, It.IsAny<string>(), It.IsAny<string>())).Returns(Path.Combine(TestContext.TestDeploymentDir, "ImageRenderSize.png")); string pathAndFile = String.Format("/Images/Size-{0}/File-ImageRenderSize/Picture.png", worksheet.String("Size")); _WebServer.Raise(m => m.RequestReceived += null, RequestReceivedEventArgsHelper.Create(_Request, _Response, pathAndFile, false)); using(var siteImage = (Bitmap)Bitmap.FromStream(_OutputStream)) { AssertImageIsMonochrome(siteImage, _Red, worksheet.Int("NewWidth"), worksheet.Int("NewHeight")); } }
public void BaseStationAircraftList_MessageReceived_Fetches_Values_From_Database_For_New_Aircraft() { var worksheet = new ExcelWorksheetData(TestContext); _AircraftList.Start(); var databaseProperty = typeof(BaseStationAircraft).GetProperty(worksheet.String("DatabaseColumn")); var aircraftProperty = typeof(IAircraft).GetProperty(worksheet.String("AircraftColumn")); var culture = new CultureInfo("en-GB"); var databaseValue = TestUtilities.ChangeType(worksheet.EString("DatabaseValue"), databaseProperty.PropertyType, culture); var aircraftValue = TestUtilities.ChangeType(worksheet.EString("AircraftValue"), aircraftProperty.PropertyType, culture); databaseProperty.SetValue(_BaseStationAircraft, databaseValue, null); _Port30003Listener.Raise(m => m.Port30003MessageReceived += null, _BaseStationMessageEventArgs); var aircraft = _AircraftList.FindAircraft(0x4008F6); Assert.AreEqual(aircraftValue, aircraftProperty.GetValue(aircraft, null)); }
public void WebSite_Image_Can_Create_Blank_Images_Dynamically() { ExcelWorksheetData worksheet = new ExcelWorksheetData(TestContext); _WebSite.AttachSiteToServer(_WebServer.Object); var args = RequestReceivedEventArgsHelper.Create(_Request, _Response, worksheet.String("PathAndFile"), false); _WebServer.Raise(m => m.RequestReceived += null, args); if(worksheet.String("Width") == null) { Assert.AreEqual(false, args.Handled); Assert.AreEqual(0, _OutputStream.Length); Assert.AreEqual(0, _Response.Object.ContentLength); } else { using(var siteImage = (Bitmap)Bitmap.FromStream(_OutputStream)) { AssertImageIsMonochrome(siteImage, _Transparent, worksheet.Int("Width"), worksheet.Int("Height")); } } }
public void RawMessageTranslator_Translate_Extracts_Position_From_ADSB_Messages_Correctly() { var worksheet = new ExcelWorksheetData(TestContext); _Translator.ReceiverLocation = ParseGlobalPosition(worksheet.String("ReceiverPosn")); _Translator.ReceiverRangeKilometres = worksheet.Int("Range"); _Translator.GlobalDecodeAirborneThresholdMilliseconds = worksheet.Int("GATS"); _Translator.GlobalDecodeFastSurfaceThresholdMilliseconds = worksheet.Int("GFSTS"); _Translator.GlobalDecodeSlowSurfaceThresholdMilliseconds = worksheet.Int("GSSTS"); _Translator.LocalDecodeMaxSpeedAirborne = worksheet.Double("LAMS"); _Translator.LocalDecodeMaxSpeedTransition = worksheet.Double("LTMS"); _Translator.LocalDecodeMaxSpeedSurface = worksheet.Double("LSMS"); _Translator.SuppressReceiverRangeCheck = worksheet.Bool("SRRC"); _Translator.UseLocalDecodeForInitialPosition = worksheet.Bool("ULD"); DateTime now = DateTime.UtcNow; for(var i = 1;i <= 4;++i) { var millisecondsColumn = String.Format("MSec{0}", i); var cprColumn = String.Format("CPR{0}", i); var speedColumn = String.Format("Spd{0}", i); var positionColumn = String.Format("Posn{0}", i); if(worksheet.String(cprColumn) == null) continue; var cpr = ParseCpr(worksheet.String(cprColumn)); var speed = worksheet.NDouble(speedColumn); var expectedPosition = ParseGlobalPosition(worksheet.String(positionColumn)); if(i != 1 && worksheet.String(millisecondsColumn) != null) { now = now.AddMilliseconds(worksheet.Int(millisecondsColumn)); } var modeSMessage = new ModeSMessage() { DownlinkFormat = DownlinkFormat.ExtendedSquitter, Icao24 = 0x112233, ParityInterrogatorIdentifier = 0 }; var adsbMessage = new AdsbMessage(modeSMessage); switch(cpr.NumberOfBits) { case 17: adsbMessage.MessageFormat = MessageFormat.AirbornePosition; adsbMessage.AirbornePosition = new AirbornePositionMessage() { CompactPosition = cpr }; break; case 19: adsbMessage.MessageFormat = MessageFormat.SurfacePosition; adsbMessage.SurfacePosition = new SurfacePositionMessage() { CompactPosition = cpr, GroundSpeed = speed, }; break; } var baseStationMessage = _Translator.Translate(now, modeSMessage, adsbMessage); var failMessage = String.Format("Failed on message {0}", i); if(expectedPosition == null) { if(baseStationMessage != null) { if(baseStationMessage.Latitude != null || baseStationMessage.Longitude != null) { Assert.Fail(String.Format("Position decoded to {0}/{1} erroneously. {2}", baseStationMessage.Latitude, baseStationMessage.Longitude, failMessage)); } } } else { Assert.IsNotNull(baseStationMessage.Latitude, failMessage); Assert.IsNotNull(baseStationMessage.Longitude, failMessage); Assert.AreEqual(expectedPosition.Latitude, baseStationMessage.Latitude.Value, 0.0001, failMessage); Assert.AreEqual(expectedPosition.Longitude, baseStationMessage.Longitude.Value, 0.0001, failMessage); } } Assert.AreEqual(worksheet.Int("ResetCount"), _PositionResetEvent.CallCount); Assert.AreEqual(worksheet.Int("ResetCount") > 0 ? 1L : 0L, _Statistics.AdsbPositionsReset); Assert.AreEqual(worksheet.Long("BadRange"), _Statistics.AdsbPositionsOutsideRange); Assert.AreEqual(worksheet.Long("BadSpeed"), _Statistics.AdsbPositionsExceededSpeedCheck); }
public void ConnectionSessionLogPresenter_Clicking_ShowSessions_Triggers_Validation() { var worksheet = new ExcelWorksheetData(TestContext); _Presenter.Initialise(_View.Object); _View.Object.StartDate = worksheet.DateTime("StartDate"); _View.Object.EndDate = worksheet.DateTime("EndDate"); IEnumerable<ValidationResult> validationResults = null; _View.Setup(v => v.ShowValidationResults(It.IsAny<IEnumerable<ValidationResult>>())).Callback((IEnumerable<ValidationResult> results) => { validationResults = results; }); _View.Raise(v => v.ShowSessionsClicked += null, EventArgs.Empty); Assert.IsNotNull(validationResults); Assert.AreEqual(worksheet.Int("CountErrors"), validationResults.Count()); if(validationResults.Count() > 0) { Assert.IsTrue(validationResults.Where(r => r.Field == worksheet.ParseEnum<ValidationField>("Field") && r.Message == worksheet.String("Message") && r.IsWarning == worksheet.Bool("IsWarning")).Any()); } }