public void JsonSerialiser_WriteObject_Writes_ValueTypes_Correctly()
        {
            var worksheet = new ExcelWorksheetData(TestContext);

            var obj = new ValueTypes()
            {
                BoolValue        = worksheet.Bool("BoolValue"),
                UnusedBool       = worksheet.Bool("UnusedBool"),
                NullableBool     = worksheet.NBool("NullableBool"),
                Int              = worksheet.Int("Int"),
                NullableInt      = worksheet.NInt("NullableInt"),
                Long             = worksheet.Long("Long"),
                NullableLong     = worksheet.NLong("NullableLong"),
                Float            = worksheet.Float("Float"),
                NullableFloat    = worksheet.NFloat("NullableFloat"),
                Double           = worksheet.Double("Double"),
                NullableDouble   = worksheet.NDouble("NullableDouble"),
                DateTime         = worksheet.DateTime("DateTime"),
                NullableDateTime = worksheet.NDateTime("NullableDateTime"),
            };

            _JsonSerialiser.Initialise(typeof(ValueTypes));
            _JsonSerialiser.WriteObject(_Stream, obj);

            Assert.AreEqual(worksheet.EString("Json"), GetJson());
        }
        public void JsonSerialiser_WriteObject_Writes_ValueTypes_Correctly_For_Non_UK_Cultures()
        {
            var worksheet = new ExcelWorksheetData(TestContext);

            foreach (var culture in new string[] { "en-US", "de-DE", "fr-FR", "ru-RU" })
            {
                using (var cultureSwitcher = new CultureSwitcher(culture)) {
                    TestCleanup();
                    TestInitialise();

                    var obj = new ValueTypes()
                    {
                        BoolValue        = worksheet.Bool("BoolValue"),
                        UnusedBool       = worksheet.Bool("UnusedBool"),
                        NullableBool     = worksheet.NBool("NullableBool"),
                        Int              = worksheet.Int("Int"),
                        NullableInt      = worksheet.NInt("NullableInt"),
                        Long             = worksheet.Long("Long"),
                        NullableLong     = worksheet.NLong("NullableLong"),
                        Float            = worksheet.Float("Float"),
                        NullableFloat    = worksheet.NFloat("NullableFloat"),
                        Double           = worksheet.Double("Double"),
                        NullableDouble   = worksheet.NDouble("NullableDouble"),
                        DateTime         = worksheet.DateTime("DateTime"),
                        NullableDateTime = worksheet.NDateTime("NullableDateTime"),
                    };

                    _JsonSerialiser.Initialise(typeof(ValueTypes));
                    _JsonSerialiser.WriteObject(_Stream, obj);

                    var message = String.Format("when culture is {0}", culture);
                    Assert.AreEqual(worksheet.EString("Json"), GetJson(), message);
                }
            }
        }
Пример #3
0
        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);
            }
        }
Пример #4
0
        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");
            _Implementation.IsMlat           = worksheet.Bool("IsMlat");

            var emitExtendedBaseStationFormat = worksheet.Bool("Extended");

            Assert.AreEqual(worksheet.String("Text"), _Implementation.ToBaseStationString(emitExtendedBaseStationFormat));
        }
Пример #5
0
        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);
            }
        }
Пример #6
0
        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 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);
            }
        }
Пример #9
0
        public void AircraftSanityChecker_IsGoodAircraftIcao_Returns_Correct_Value()
        {
            var worksheet = new ExcelWorksheetData(TestContext);
            var icao      = worksheet.EString("ICAO");
            var expected  = worksheet.Bool("Result");

            _Configuration.RawDecodingSettings.SuppressIcao0 = worksheet.Bool("SuppressIcao0");

            var result = _Checker.IsGoodAircraftIcao(icao);

            Assert.AreEqual(expected, result);
        }
        public void Describe_Airport_Formats_Airport_Correctly()
        {
            var worksheet = new ExcelWorksheetData(TestContext);

            var airport = new Airport();
            airport.IcaoCode = worksheet.EString("Icao");
            airport.IataCode = worksheet.EString("Iata");
            airport.Name = worksheet.EString("Name");
            airport.Country = worksheet.EString("Country");

            var result = Describe.Airport(airport, worksheet.Bool("PreferIata"), worksheet.Bool("ShowCode"), worksheet.Bool("ShowName"), worksheet.Bool("ShowCountry"));

            Assert.AreEqual(worksheet.EString("Result"), result);
        }
Пример #11
0
        public void Describe_Airport_Formats_Airport_Correctly()
        {
            var worksheet = new ExcelWorksheetData(TestContext);

            var airport = new Airport();

            airport.IcaoCode = worksheet.EString("Icao");
            airport.IataCode = worksheet.EString("Iata");
            airport.Name     = worksheet.EString("Name");
            airport.Country  = worksheet.EString("Country");

            var result = Describe.Airport(airport, worksheet.Bool("PreferIata"), worksheet.Bool("ShowCode"), worksheet.Bool("ShowName"), worksheet.Bool("ShowCountry"));

            Assert.AreEqual(worksheet.EString("Result"), result);
        }
Пример #12
0
        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 GreatCircleMaths_Bearing_Calculates_Correct_Bearing()
        {
            var worksheet = new ExcelWorksheetData(TestContext);

            var startLatitude = worksheet.NDouble("StartLatitude");
            var startLongitude = worksheet.NDouble("StartLongitude");
            var endLatitude = worksheet.NDouble("EndLatitude");
            var endLongitude = worksheet.NDouble("EndLongitude");
            var currentTrack = worksheet.NDouble("CurrentTrack");
            var expected = worksheet.NDouble("Bearing");

            var actual = GreatCircleMaths.Bearing(startLatitude, startLongitude, endLatitude, endLongitude, currentTrack, worksheet.Bool("ReverseBearing"), worksheet.Bool("IgnoreCurrentTrack"));

            if(expected == null) Assert.IsNull(actual);
            else                 Assert.AreEqual((double)expected, (double)actual, 0.0001);
        }
Пример #14
0
        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 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);
        }
        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 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));
        }
Пример #18
0
        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 LogClient_IsLocal_Is_Conversion_Of_IpAddress_Property()
        {
            var worksheet = new ExcelWorksheetData(TestContext);

            var logClient = new LogClient() { IpAddress = worksheet.EString("IpAddress") };

            Assert.AreEqual(worksheet.Bool("IsLocal"), logClient.IsLocal);
        }
Пример #20
0
        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));
        }
Пример #21
0
        public void Aircraft_UpdateCoordinates_Resets_Coordinates_If_Aircraft_Looks_To_Be_Moving_Impossibly_Quickly()
        {
            // Some aircraft's transponders report the wrong position. Further, some radios misinterpret position updates at
            // extreme ranges. We can guess the position is wrong if the position and timing of two updates would require the
            // aircraft to be moving at incredibly high speeds. When this is detected we should reset the trails, otherwise the
            // user sees long lines drawn across the map, or a scribble effect if the transponder is just reporting nonsense.

            var worksheet = new ExcelWorksheetData(TestContext);

            var time         = DateTime.UtcNow;
            var shortSeconds = 24 * 60 * 60; // seconds in a day

            _Aircraft.DataVersion = time.Ticks;
            _Aircraft.Latitude    = worksheet.Float("Lat1");
            _Aircraft.Longitude   = worksheet.Float("Lng1");
            _Aircraft.Track       = 1;
            _Aircraft.UpdateCoordinates(time, shortSeconds);

            int milliseconds = worksheet.Int("Milliseconds");

            time = time.AddMilliseconds(milliseconds);
            _Aircraft.DataVersion = time.Ticks;
            _Aircraft.Latitude    = worksheet.Float("Lat2");
            _Aircraft.Longitude   = worksheet.Float("Lng2");
            _Aircraft.Track       = 2;
            _Aircraft.UpdateCoordinates(time, shortSeconds);

            if (!worksheet.Bool("ResetTrail"))
            {
                if (milliseconds >= 1000)
                {
                    Assert.AreEqual(2, _Aircraft.FullCoordinates.Count);
                    Assert.AreEqual(2, _Aircraft.ShortCoordinates.Count);
                }
                else
                {
                    Assert.AreEqual(1, _Aircraft.FullCoordinates.Count);
                    Assert.AreEqual(1, _Aircraft.ShortCoordinates.Count);
                    Assert.AreEqual(1, _Aircraft.FullCoordinates[0].Heading);
                    Assert.AreEqual(1, _Aircraft.ShortCoordinates[0].Heading);
                }
            }
            else
            {
                if (milliseconds < 1000)
                {
                    Assert.AreEqual(0, _Aircraft.FullCoordinates.Count);
                    Assert.AreEqual(0, _Aircraft.ShortCoordinates.Count);
                }
                else
                {
                    Assert.AreEqual(1, _Aircraft.FullCoordinates.Count);
                    Assert.AreEqual(1, _Aircraft.ShortCoordinates.Count);
                    Assert.AreEqual(2, _Aircraft.FullCoordinates[0].Heading);
                    Assert.AreEqual(2, _Aircraft.ShortCoordinates[0].Heading);
                }
            }
        }
        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);
        }
Пример #23
0
        public void UniversalPlugAndPlayManager_TakeServerOffInternet_Disconnects_And_Reconnects_WebServer()
        {
            var worksheet = new ExcelWorksheetData(TestContext);

            _Configuration.WebServerSettings.EnableUPnp = true;
            _Configuration.WebServerSettings.UPnpPort   = 8080;
            _Configuration.WebServerSettings.IsOnlyInternetServerOnLan = true;
            _WebServer.Setup(s => s.NetworkIPAddress).Returns("192.168.0.1");
            _WebServer.Setup(s => s.Port).Returns(80);

            var expectedStarts = 0;

            if (worksheet.Bool("StartOnline"))
            {
                _WebServer.Object.Online = true;
                ++expectedStarts;
            }

            _WebServer.SetupSet(s => s.Online = true).Callback(() => {
                Assert.IsFalse(_Manager.PortForwardingPresent);
            });

            var expectedStops = 0;

            if (worksheet.Bool("ExpectServerToggle"))
            {
                ++expectedStarts;
                ++expectedStops;
            }

            _Manager.Initialise();
            if (worksheet.Bool("StartPortForwarded"))
            {
                AddPortMapping(_Description, 8080, "192.168.0.1", 80, "TCP");
                _Manager.PutServerOntoInternet();
            }

            _Manager.StateChanged += _StateChangedEvent.Handler;
            _Manager.TakeServerOffInternet();

            _WebServer.VerifySet(v => v.Online = true, Times.Exactly(expectedStarts));
            _WebServer.VerifySet(v => v.Online = false, Times.Exactly(expectedStops));
        }
Пример #24
0
        public void LogClient_IsLocal_Is_Conversion_Of_IpAddress_Property()
        {
            var worksheet = new ExcelWorksheetData(TestContext);

            var logClient = new LogClient()
            {
                IpAddress = worksheet.EString("IpAddress")
            };

            Assert.AreEqual(worksheet.Bool("IsLocal"), logClient.IsLocal);
        }
Пример #25
0
        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>");
        }
Пример #26
0
        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);
        }
Пример #27
0
        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]);
            }
        }
Пример #28
0
        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);
            }
        }
Пример #29
0
        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);
                    }
                }
            }
        }
Пример #30
0
        public void Airline_IsCharterFlightNumber_Returns_Correct_Value()
        {
            var worksheet    = new ExcelWorksheetData(TestContext);
            var regex        = worksheet.EString("Regex");
            var flightNumber = worksheet.EString("FlightNumber");

            var airline = new Airline()
            {
                CharterFlightPattern = regex
            };
            var actual   = airline.IsCharterFlightNumber(flightNumber);
            var expected = worksheet.Bool("Matches");

            Assert.AreEqual(expected, actual, $"FlightNumber '{flightNumber}' and Regex '{regex}'");
        }
Пример #31
0
        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());
        }
Пример #32
0
        public void Callsign_Ctor_Parses_Callsigns_Correctly()
        {
            var worksheet    = new ExcelWorksheetData(TestContext);
            var callsignText = worksheet.EString("Callsign");

            var callsign = new Callsign(callsignText);

            var message = $"Callsign is '{callsignText}'";

            Assert.AreEqual(worksheet.EString("OriginalCallsign"), callsign.OriginalCallsign, message);
            Assert.AreEqual(worksheet.EString("Code"), callsign.Code, message);
            Assert.AreEqual(worksheet.EString("Number"), callsign.Number, message);
            Assert.AreEqual(worksheet.EString("TrimmedNumber"), callsign.TrimmedNumber, message);
            Assert.AreEqual(worksheet.EString("TrimmedCallsign"), callsign.TrimmedCallsign, message);
            Assert.AreEqual(worksheet.Bool("IsOriginalCallsignValid"), callsign.IsOriginalCallsignValid, message);
        }
Пример #33
0
        public void Cidr_Matches_Compares_Addresses_Correctly()
        {
            var worksheet = new ExcelWorksheetData(TestContext);

            // Uncomment this block if you want to restrict the test to just those rows with a RunThis of true
            // var runThis = worksheet.NBool("RunThis").GetValueOrDefault();
            // if(!runThis) Assert.Fail();

            var cidr    = Cidr.Parse(worksheet.String("CIDR"));
            var address = GetExcelIPAddress(worksheet, "Address");

            var expected = worksheet.Bool("Result");
            var actual   = cidr.Matches(address);

            Assert.AreEqual(expected, actual);
        }
Пример #34
0
        public void StandingDataManager_FindCodeBlock_Works_With_Real_Life_Examples()
        {
            ExcelWorksheetData worksheet = new ExcelWorksheetData(TestContext);

            _Implementation.Load();

            var codeBlock = _Implementation.FindCodeBlock(worksheet.EString("ICAO24"));

            if (worksheet.String("IsMilitary") == null)
            {
                Assert.IsNull(codeBlock);
            }
            else
            {
                Assert.AreEqual(worksheet.EString("Country"), codeBlock.Country);
                Assert.AreEqual(worksheet.Bool("IsMilitary"), codeBlock.IsMilitary);
            }
        }
        public void JsonSerialiser_WriteObject_Honours_Important_DataMember_Attributes()
        {
            var worksheet = new ExcelWorksheetData(TestContext);

            var obj = new Attributes()
            {
                OriginalName          = worksheet.Int("OriginalName"),
                NoEmitDefaultString   = worksheet.EString("NoEmitDefaultString"),
                NoEmitDefaultInt      = worksheet.Int("NoEmitDefaultInt"),
                NoEmitDefaultBool     = worksheet.Bool("NoEmitDefaultBool"),
                NoEmitDefaultLong     = worksheet.Long("NoEmitDefaultLong"),
                NoEmitDefaultDateTime = worksheet.DateTime("NoEmitDefaultDateTime"),
                NoEmitDefaultNullable = worksheet.NBool("NoEmitDefaultNullable"),
            };

            _JsonSerialiser.Initialise(typeof(Attributes));
            _JsonSerialiser.WriteObject(_Stream, obj);

            Assert.AreEqual(worksheet.EString("Json"), GetJson());
        }
Пример #36
0
        public void PipelineRequest_IsInternet_And_ProxyAddress_Are_Accurately_Detected_During_Construction()
        {
            var worksheet       = new ExcelWorksheetData(TestContext);
            var remoteIpAddress = worksheet.EString("RemoteIpAddress");
            var xff             = worksheet.EString("XFF");
            var proxyIpAddress  = worksheet.EString("ProxyIpAddress");
            var clientIpAddress = worksheet.EString("ClientIpAddress");
            var isInternet      = worksheet.Bool("IsInternet");
            var comments        = worksheet.EString("Comments");

            _Request.RemoteIpAddress = remoteIpAddress;
            if (xff != null)
            {
                _Request.Headers.Add("X-Forwarded-For", new string[] { xff });
            }

            Assert.AreEqual(proxyIpAddress, _Request.ProxyIpAddress, comments);
            Assert.AreEqual(clientIpAddress, _Request.ClientIpAddress, comments);
            Assert.AreEqual(isInternet, _Request.IsInternet, 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 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_Disconnects_And_Reconnects_WebServer()
        {
            var worksheet = new ExcelWorksheetData(TestContext);

            _Configuration.WebServerSettings.EnableUPnp = true;
            _Configuration.WebServerSettings.UPnpPort = 8080;
            _Configuration.WebServerSettings.IsOnlyInternetServerOnLan = true;
            _WebServer.Setup(s => s.NetworkIPAddress).Returns("192.168.0.1");
            _WebServer.Setup(s => s.Port).Returns(80);

            var expectedStarts = 0;
            if(worksheet.Bool("StartOnline")) {
                _WebServer.Object.Online = true;
                ++expectedStarts;
            }

            _WebServer.SetupSet(s => s.Online = true).Callback(() => {
                Assert.IsFalse(_Manager.PortForwardingPresent);
            });

            var expectedStops = 0;
            if(worksheet.Bool("ExpectServerToggle")) {
                ++expectedStarts;
                ++expectedStops;
            }

            _Manager.Initialise();
            if(worksheet.Bool("StartPortForwarded")) {
                AddPortMapping(_Description, 8080, "192.168.0.1", 80, "TCP");
                _Manager.PutServerOntoInternet();
            }

            _Manager.StateChanged += _StateChangedEvent.Handler;
            _Manager.TakeServerOffInternet();

            _WebServer.VerifySet(v => v.Online = true, Times.Exactly(expectedStarts));
            _WebServer.VerifySet(v => v.Online = false, Times.Exactly(expectedStops));
        }
        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 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);
        }
        private void DoValidationTest(Action triggerValidation, bool doSuppressExcessiveFileSystemCheck = false)
        {
            var worksheet = new ExcelWorksheetData(TestContext);

            List<ValidationResult> validationResults = new List<ValidationResult>();
            _View.Setup(v => v.ShowValidationResults(It.IsAny<IEnumerable<ValidationResult>>())).Callback((IEnumerable<ValidationResult> results) => {
                foreach(var validationResult in results) validationResults.Add(validationResult);
            });

            int countFileExistsCalls = 0;
            _Provider.Setup(p => p.FileExists(It.IsAny<string>())).Returns(false);
            _Provider.Setup(p => p.FileExists(null)).Callback(() => {throw new NullReferenceException(); });
            _Provider.Setup(p => p.FileExists("FileExists")).Callback(() => countFileExistsCalls++).Returns(true);

            int countFolderExistsCalls = 0;
            _Provider.Setup(p => p.FolderExists(It.IsAny<string>())).Returns(false);
            _Provider.Setup(p => p.FolderExists(null)).Callback(() => {throw new NullReferenceException(); });
            _Provider.Setup(p => p.FolderExists("FolderExists")).Callback(() => countFolderExistsCalls++).Returns(true);

            _Presenter.Initialise(_View.Object);

            _View.Object.BaseStationDatabaseFileName = null;
            _View.Object.OperatorFlagsFolder = null;
            _View.Object.SilhouettesFolder = null;

            for(var i = 1;i <= 3;++i) {
                var uiFieldColumn = String.Format("UIField{0}", i);
                var valueColumn = String.Format("Value{0}", i);
                if(worksheet.String(uiFieldColumn) != null) {
                    switch(worksheet.String(uiFieldColumn)) {
                        case "AcceptableAirborneSpeed":             _View.Object.RawDecodingAcceptableAirborneSpeed = worksheet.Double(valueColumn); break;
                        case "AcceptableAirSurfaceTransitionSpeed": _View.Object.RawDecodingAcceptableAirSurfaceTransitionSpeed = worksheet.Double(valueColumn); break;
                        case "AcceptableSurfaceSpeed":              _View.Object.RawDecodingAcceptableSurfaceSpeed = worksheet.Double(valueColumn); break;
                        case "AcceptIcaoInNonPICount":              _View.Object.AcceptIcaoInNonPICount = worksheet.Int(valueColumn); break;
                        case "AcceptIcaoInNonPISeconds":            _View.Object.AcceptIcaoInNonPISeconds = worksheet.Int(valueColumn); break;
                        case "AcceptIcaoInPI0Count":                _View.Object.AcceptIcaoInPI0Count = worksheet.Int(valueColumn); break;
                        case "AcceptIcaoInPI0Seconds":              _View.Object.AcceptIcaoInPI0Seconds = worksheet.Int(valueColumn); break;
                        case "AirborneGlobalPositionLimit":         _View.Object.RawDecodingAirborneGlobalPositionLimit = worksheet.Int(valueColumn); break;
                        case "BaseStationAddress":                  _View.Object.BaseStationAddress = worksheet.EString(valueColumn); break;
                        case "BaseStationConnectionType":           _View.Object.BaseStationConnectionType = worksheet.ParseEnum<ConnectionType>(valueColumn); break;
                        case "BaseStationPort":                     _View.Object.BaseStationPort = worksheet.Int(valueColumn); break;
                        case "CheckForNewVersionsPeriodDays":       _View.Object.CheckForNewVersionsPeriodDays = worksheet.Int(valueColumn); break;
                        case "DatabaseFileName":                    _View.Object.BaseStationDatabaseFileName = worksheet.EString(valueColumn); break;
                        case "DisplayTimeoutSeconds":               _View.Object.DisplayTimeoutSeconds = worksheet.Int(valueColumn); break;
                        case "FastSurfaceGlobalPositionLimit":      _View.Object.RawDecodingFastSurfaceGlobalPositionLimit = worksheet.Int(valueColumn); break;
                        case "FlagsFolder":                         _View.Object.OperatorFlagsFolder = worksheet.EString(valueColumn); break;
                        case "InitialGoogleMapLatitude":            _View.Object.InitialGoogleMapLatitude = worksheet.Double(valueColumn); break;
                        case "InitialGoogleMapLongitude":           _View.Object.InitialGoogleMapLongitude = worksheet.Double(valueColumn); break;
                        case "InitialGoogleMapZoom":                _View.Object.InitialGoogleMapZoom = worksheet.Int(valueColumn); break;
                        case "InitialRefreshSeconds":               _View.Object.InitialGoogleMapRefreshSeconds = worksheet.Int(valueColumn); break;
                        case "InternetClientTimeoutMinutes":        _View.Object.InternetClientTimeoutMinutes = worksheet.Int(valueColumn); break;
                        case "MinimumRefreshSeconds":               _View.Object.MinimumGoogleMapRefreshSeconds = worksheet.Int(valueColumn); break;
                        case "PicturesFolder":                      _View.Object.PicturesFolder = worksheet.EString(valueColumn); break;
                        case "ReceiverRange":                       _View.Object.RawDecodingReceiverRange = worksheet.Int(valueColumn); break;
                        case "SerialBaudRate":                      _View.Object.SerialBaudRate = worksheet.Int(valueColumn); break;
                        case "SerialComPort":                       _View.Object.SerialComPort = worksheet.EString(valueColumn); break;
                        case "SerialDataBits":                      _View.Object.SerialDataBits = worksheet.Int(valueColumn); break;
                        case "ShortTrailLengthSeconds":             _View.Object.ShortTrailLengthSeconds = worksheet.Int(valueColumn); break;
                        case "SilhouettesFolder":                   _View.Object.SilhouettesFolder = worksheet.EString(valueColumn); break;
                        case "SlowSurfaceGlobalPositionLimit":      _View.Object.RawDecodingSlowSurfaceGlobalPositionLimit = worksheet.Int(valueColumn); break;
                        case "TextToSpeechSpeed":                   _View.Object.TextToSpeechSpeed = worksheet.Int(valueColumn); break;
                        case "TrackingTimeoutSeconds":              _View.Object.TrackingTimeoutSeconds = worksheet.Int(valueColumn); break;
                        case "UPnpPort":                            _View.Object.UPnpPort = worksheet.Int(valueColumn); break;
                        case "WebAuthenticateUser":                 _View.Object.WebServerUserMustAuthenticate = worksheet.Bool(valueColumn); break;
                        case "WebUserName":                         _View.Object.WebServerUserName = worksheet.EString(valueColumn); break;
                        default:                                    throw new NotImplementedException();
                    }
                }
            }

            triggerValidation();
            _View.Verify(v => v.ShowValidationResults(It.IsAny<IEnumerable<ValidationResult>>()), Times.Once());

            if(doSuppressExcessiveFileSystemCheck) {
                validationResults.Clear();

                triggerValidation();
                _View.Verify(v => v.ShowValidationResults(It.IsAny<IEnumerable<ValidationResult>>()), Times.Exactly(2));

                Assert.IsTrue(countFileExistsCalls < 2);
                Assert.IsTrue(countFolderExistsCalls < 2);
            }

            var validationErrorSummary = new StringBuilder();
            foreach(var validationResult in validationResults) {
                if(validationErrorSummary.Length != 0) validationErrorSummary.Append("; ");
                validationErrorSummary.AppendFormat("{0}:{1}", validationResult.Field, validationResult.Message);
            }

            Assert.AreEqual(worksheet.Int("CountErrors"), validationResults.Count(), validationErrorSummary.ToString());
            if(validationResults.Count() > 0) {
                Assert.IsTrue(validationResults.Where(r => r.Field == worksheet.ParseEnum<ValidationField>("Field") &&
                                                           r.Message == worksheet.EString("Message") &&
                                                           r.IsWarning == worksheet.Bool("IsWarning")).Any(),
                              validationErrorSummary.ToString());
            }
        }
        public void WebSite_BaseStationAircraftList_Builds_Arrays_Of_Trail_Coordinates_Correctly()
        {
            var worksheet = new ExcelWorksheetData(TestContext);

            AddBlankAircraft(1);
            var aircraft = _BaseStationAircraft[0];
            Mock<IAircraft> mockAircraft = Mock.Get(aircraft);

            aircraft.Latitude = worksheet.NFloat("ACLat");
            aircraft.Longitude = worksheet.NFloat("ACLng");
            aircraft.Track = worksheet.NFloat("ACTrk");
            aircraft.FirstCoordinateChanged = worksheet.Long("ACFirstCoCh");
            aircraft.LastCoordinateChanged = worksheet.Long("ACLastCoCh");
            aircraft.PositionTime = new DateTime(1970, 1, 1, 0, 0, 0, worksheet.Int("ACPosTimeCh"));
            mockAircraft.Setup(m => m.PositionTimeChanged).Returns(worksheet.Long("ACPosTimeCh"));

            for(int i = 1;i <= 2;++i) {
                var dataVersion = String.Format("Coord{0}DV", i);
                var tick = String.Format("Coord{0}Tick", i);
                var latitude = String.Format("Coord{0}Lat", i);
                var longitude = String.Format("Coord{0}Lng", i);
                var track = String.Format("Coord{0}Trk", i);
                if(worksheet.String(dataVersion) != null) {
                    DateTime dotNetDate = new DateTime(1970, 1, 1, 0, 0, 0, worksheet.Int(tick));
                    var coordinate = new Coordinate(worksheet.Long(dataVersion), dotNetDate.Ticks, worksheet.Float(latitude), worksheet.Float(longitude), worksheet.NFloat(track));
                    aircraft.FullCoordinates.Add(coordinate);
                    aircraft.ShortCoordinates.Add(coordinate);
                }
            }

            _AircraftListAddress.PreviousDataVersion = worksheet.Long("ArgsPrevDV");
            if(worksheet.Bool("ArgsIsPrevAC")) _AircraftListAddress.PreviousAircraft.Add(0);
            _AircraftListAddress.ShowShortTrail = worksheet.Bool("ArgsShort");
            _AircraftListAddress.ResendTrails = worksheet.Bool("ArgsResend");

            var aircraftJson = SendJsonRequest<AircraftListJson>(_AircraftListAddress.Address).Aircraft[0];

            var count = worksheet.Int("Count");
            if(count == 0) {
                Assert.IsNull(aircraftJson.ShortCoordinates);
                Assert.IsNull(aircraftJson.FullCoordinates);
            } else {
                var list = worksheet.Bool("IsShort") ? aircraftJson.ShortCoordinates : aircraftJson.FullCoordinates;
                Assert.AreEqual(count, list.Count);
                for(int i = 0;i < count;++i) {
                    var column = String.Format("R{0}", i);
                    Assert.AreEqual(worksheet.NDouble(column), list[i], "Element {0}", i);
                }
            }

            Assert.AreEqual(worksheet.Bool("ResetTrail"), aircraftJson.ResetTrail);
        }
Пример #45
0
        public void Plugin_ShowWinFormsOptionsUI_Sets_Options_Correctly()
        {
            var worksheet = new ExcelWorksheetData(TestContext);

            SetEnabledOption(worksheet.Bool("Enabled"));
            SetAllowUpdateOfOtherDatabasesOption(worksheet.Bool("AllowUpdateOfOtherDatabases"));
            _Configuration.BaseStationSettings.DatabaseFileName = worksheet.EString("DatabaseFileName");

            _OptionsView.Setup(v => v.DisplayView()).Callback(() => {
                _OptionsView.VerifySet(v => v.PluginEnabled = worksheet.Bool("Enabled"), Times.Once());
                _OptionsView.VerifySet(v => v.AllowUpdateOfOtherDatabases = worksheet.Bool("AllowUpdateOfOtherDatabases"), Times.Once());
                _OptionsView.VerifySet(v => v.DatabaseFileName = worksheet.EString("DatabaseFileName"), Times.Once());
            });

            _Plugin.Startup(_StartupParameters);
            _Plugin.ShowWinFormsOptionsUI();
        }
Пример #46
0
        public void Plugin_Sessions_Are_Created_And_Destroyed_Correctly_From_Startup_Over_Global_Config_Change_To_Shutdown()
        {
            var worksheet = new ExcelWorksheetData(TestContext);

            // Most of the testing takes place when InsertSession (create new session) and UpdateSession (close existing session) are
            // called. The test basically updates the following few parameters and then the Insert / Update calls check them
            int expectInsertCallCount = 0, expectUpdateCallCount = 0;
            string expectInsertFileName = null, expectUpdateFileName = null;
            DateTime localNow = SetProviderTimes(DateTime.Now);
            BaseStationSession lastSessionInserted = null;
            _BaseStationDatabase.Setup(d => d.InsertSession(It.IsAny<BaseStationSession>())).Callback((BaseStationSession session) => {
                lastSessionInserted = session;
                Assert.IsTrue(_BaseStationDatabase.Object.WriteSupportEnabled);
                Assert.AreEqual(expectInsertFileName, _BaseStationDatabase.Object.FileName);
                Assert.AreEqual(null, session.EndTime);
                Assert.AreEqual(localNow, session.StartTime);
                Assert.AreEqual(9821, session.LocationID);
            });
            _BaseStationDatabase.Setup(d => d.UpdateSession(It.IsAny<BaseStationSession>())).Callback((BaseStationSession session) => {
                Assert.IsTrue(_BaseStationDatabase.Object.WriteSupportEnabled);
                Assert.AreEqual(expectUpdateFileName, _BaseStationDatabase.Object.FileName);
                Assert.AreSame(lastSessionInserted, session);
                Assert.AreEqual(localNow, session.EndTime);
            });

            // Create the conditions present at plugin startup
            SetEnabledOption(worksheet.Bool("InitialEnabled"));
            SetAllowUpdateOfOtherDatabasesOption(worksheet.Bool("InitialAllowForeignUpdate"));
            SetConfigurationBaseStationDatabaseFileName(worksheet.EString("InitialDB"));
            expectInsertFileName = worksheet.EString("InitialDB");
            _BaseStationDatabase.Setup(d => d.FileName).Returns(expectInsertFileName);
            SetDBHistory(worksheet.Bool("InitialDBIsVRS"));

            // Start the plugin
            _Plugin.Startup(_StartupParameters);

            // Check that the session was created, or not
            if(worksheet.Bool("ExpectStartOnStartup")) ++expectInsertCallCount;
            _BaseStationDatabase.Verify(d => d.InsertSession(It.IsAny<BaseStationSession>()), Times.Exactly(expectInsertCallCount));
            _BaseStationDatabase.Verify(d => d.UpdateSession(It.IsAny<BaseStationSession>()), Times.Exactly(expectUpdateCallCount));

            // Change the global configuration
            expectUpdateFileName = expectInsertFileName;
            expectInsertFileName = worksheet.EString("GlobalDB");
            _Configuration.BaseStationSettings.DatabaseFileName = expectInsertFileName;
            SetDBHistory(worksheet.Bool("GlobalDBIsVRS"));

            // Raise the events that we expect to see when the filename changes
            _ConfigurationStorage.Raise(c => c.ConfigurationChanged += null, EventArgs.Empty);
            if(expectUpdateFileName != expectInsertFileName) {
                _BaseStationDatabase.Raise(d => d.FileNameChanging += null, EventArgs.Empty);
                _BaseStationDatabase.Setup(d => d.FileName).Returns(expectInsertFileName);
                _BaseStationDatabase.Raise(d => d.FileNameChanged += null, EventArgs.Empty);
            }

            if(worksheet.Bool("ExpectCloseOnConfig")) ++expectUpdateCallCount;
            if(worksheet.Bool("ExpectStartOnConfig")) ++expectInsertCallCount;
            _BaseStationDatabase.Verify(d => d.InsertSession(It.IsAny<BaseStationSession>()), Times.Exactly(expectInsertCallCount));
            _BaseStationDatabase.Verify(d => d.UpdateSession(It.IsAny<BaseStationSession>()), Times.Exactly(expectUpdateCallCount));

            // Shutdown the plugin and make sure sessions are correctly closed etc.
            expectUpdateFileName = expectInsertFileName;

            _Plugin.Shutdown();

            if(worksheet.Bool("ExpectCloseOnShutdown")) ++expectUpdateCallCount;
            _BaseStationDatabase.Verify(d => d.InsertSession(It.IsAny<BaseStationSession>()), Times.Exactly(expectInsertCallCount));
            _BaseStationDatabase.Verify(d => d.UpdateSession(It.IsAny<BaseStationSession>()), Times.Exactly(expectUpdateCallCount));
        }
Пример #47
0
        public void Plugin_ShowWinFormsOptionsUI_Save_Changes()
        {
            var worksheet = new ExcelWorksheetData(TestContext);

            _Plugin.Startup(_StartupParameters);

            _OptionsView.Setup(v => v.DisplayView()).Returns(true);
            _OptionsView.Setup(v => v.PluginEnabled).Returns(worksheet.Bool("Enabled"));
            _OptionsView.Setup(v => v.AllowUpdateOfOtherDatabases).Returns(worksheet.Bool("AllowUpdateOfOtherDatabases"));
            _OptionsView.Setup(v => v.DatabaseFileName).Returns(worksheet.EString("DatabaseFileName"));

            _PluginSettingsStorage.Setup(s => s.Save(It.IsAny<PluginSettings>())).Callback((PluginSettings settings) => {
                Assert.AreEqual(worksheet.Bool("Enabled"), settings.ReadBool(_Plugin, "Enabled"));
                Assert.AreEqual(worksheet.Bool("AllowUpdateOfOtherDatabases"), settings.ReadBool(_Plugin, "AllowUpdateOfOtherDatabases"));
            });

            _ConfigurationStorage.Setup(s => s.Save(It.IsAny<Configuration>())).Callback((Configuration configuration) => {
                Assert.AreEqual(worksheet.EString("DatabaseFileName"), configuration.BaseStationSettings.DatabaseFileName);
            });

            _Plugin.ShowWinFormsOptionsUI();

            _PluginSettingsStorage.Verify(s => s.Save(It.IsAny<PluginSettings>()), Times.Once());
            _ConfigurationStorage.Verify(s => s.Save(It.IsAny<Configuration>()), Times.Once());
        }
        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 FlightSimulatorXPresenter_Requested_Aircraft_Information_Is_Copied_Into_FlightSimulatorAircraftList()
        {
            var worksheet = new ExcelWorksheetData(TestContext);

            _Presenter.Initialise(_View.Object);

            var utcNow = worksheet.DateTime("UtcNow");
            _Provider.Setup(p => p.UtcNow).Returns(utcNow);

            var aircraftInformation = new ReadAircraftInformation() {
                AirspeedIndicated = worksheet.Double("FSXAirspeedIndicated"),
                Altitude = worksheet.Double("FSXAltitude"),
                Latitude = worksheet.Double("FSXLatitude"),
                Longitude = worksheet.Double("FSXLongitude"),
                MaxAirspeedIndicated = worksheet.Double("FSXMaxAirspeedIndicated"),
                Model = worksheet.String("FSXModel"),
                OnGround = worksheet.Bool("FSXOnGround"),
                Operator = worksheet.String("FSXOperator"),
                Registration = worksheet.String("FSXRegistration"),
                Squawk = worksheet.Int("FSXSquawk"),
                TrueHeading = worksheet.Double("FSXTrueHeading"),
                Type = worksheet.String("FSXType"),
                VerticalSpeed = worksheet.Double("FSXVerticalSpeed"),
            };
            _FlightSimulatorX.Raise(f => f.AircraftInformationReceived += null, new EventArgs<ReadAircraftInformation>(aircraftInformation));

            Assert.AreEqual(1, _FSXAircraftList.Count);
            var aircraft = _FSXAircraftList[0];
            Assert.AreEqual(worksheet.String("Icao24"), aircraft.Icao24);
            Assert.AreEqual(worksheet.Int("UniqueId"), aircraft.UniqueId);
            Assert.AreEqual(worksheet.NFloat("Latitude"), aircraft.Latitude);
            Assert.AreEqual(worksheet.NFloat("Longitude"), aircraft.Longitude);
            Assert.AreEqual(utcNow.Ticks, aircraft.DataVersion);
            Assert.AreEqual(worksheet.NFloat("GroundSpeed"), aircraft.GroundSpeed);
            Assert.AreEqual(worksheet.NFloat("Track"), aircraft.Track);
            Assert.AreEqual(worksheet.String("Type"), aircraft.Type);
            Assert.AreEqual(worksheet.String("Model"), aircraft.Model);
            Assert.AreEqual(worksheet.String("Operator"), aircraft.Operator);
            Assert.AreEqual(worksheet.String("Registration"), aircraft.Registration);
            Assert.AreEqual(worksheet.NInt("Squawk"), aircraft.Squawk);
            Assert.AreEqual(worksheet.NInt("Altitude"), aircraft.Altitude);
            Assert.AreEqual(worksheet.NInt("VerticalRate"), aircraft.VerticalRate);
        }
        public void BaseStationAircraftList_MessageReceived_Ignores_Messages_With_Invalid_Icao24()
        {
            var worksheet = new ExcelWorksheetData(TestContext);

            _AircraftList.Start();

            _BaseStationMessage.Icao24 = worksheet.EString("Icao");
            _Port30003Listener.Raise(m => m.Port30003MessageReceived += null, _BaseStationMessageEventArgs);

            bool expectValid = worksheet.Bool("IsValid");
            if(!expectValid) {
                long snapshotTime, snapshotDataVersion;
                Assert.AreEqual(0, _AircraftList.TakeSnapshot(out snapshotTime, out snapshotDataVersion).Count);
            } else {
                Assert.IsNotNull(_AircraftList.FindAircraft(worksheet.Int("UniqueId")));
            }
        }
        public void WebSite_BaseStationAircraftList_AircraftListFilter_Distance_AircraftListFiltered_Correctly()
        {
            var worksheet = new ExcelWorksheetData(TestContext);

            _AircraftListAddress.Filter = _AircraftListFilter;
            _AircraftListAddress.BrowserLatitude = worksheet.Float("BrowserLatitude");
            _AircraftListAddress.BrowserLongitude = worksheet.Float("BrowserLongitude");

            AddBlankAircraft(1);
            _BaseStationAircraft[0].Latitude = worksheet.NFloat("AircraftLatitude");
            _BaseStationAircraft[0].Longitude = worksheet.NFloat("AircraftLongitude");

            _AircraftListFilter.DistanceLower = worksheet.NDouble("DistanceLower");
            _AircraftListFilter.DistanceUpper = worksheet.NDouble("DistanceUpper");

            bool passed = SendJsonRequest<AircraftListJson>(_AircraftListAddress.Address).Aircraft.Count == 1;

            Assert.AreEqual(worksheet.Bool("Passes"), passed);
        }
        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 Aircraft_UpdateCoordinates_Resets_Coordinates_If_Aircraft_Looks_To_Be_Moving_Impossibly_Quickly()
        {
            // Some aircraft's transponders report the wrong position. Further, some radios misinterpret position updates at
            // extreme ranges. We can guess the position is wrong if the position and timing of two updates would require the
            // aircraft to be moving at incredibly high speeds. When this is detected we should reset the trails, otherwise the
            // user sees long lines drawn across the map, or a scribble effect if the transponder is just reporting nonsense.

            var worksheet = new ExcelWorksheetData(TestContext);

            var time = DateTime.UtcNow;
            var shortSeconds = 24 * 60 * 60; // seconds in a day

            _Aircraft.DataVersion = time.Ticks;
            _Aircraft.Latitude = worksheet.Float("Lat1");
            _Aircraft.Longitude = worksheet.Float("Lng1");
            _Aircraft.Track = 1;
            _Aircraft.UpdateCoordinates(time, shortSeconds);

            int milliseconds = worksheet.Int("Milliseconds");

            time = time.AddMilliseconds(milliseconds);
            _Aircraft.DataVersion = time.Ticks;
            _Aircraft.Latitude = worksheet.Float("Lat2");
            _Aircraft.Longitude = worksheet.Float("Lng2");
            _Aircraft.Track = 2;
            _Aircraft.UpdateCoordinates(time, shortSeconds);

            if(!worksheet.Bool("ResetTrail")) {
                if(milliseconds >= 1000) {
                    Assert.AreEqual(2, _Aircraft.FullCoordinates.Count);
                    Assert.AreEqual(2, _Aircraft.ShortCoordinates.Count);
                } else {
                    Assert.AreEqual(1, _Aircraft.FullCoordinates.Count);
                    Assert.AreEqual(1, _Aircraft.ShortCoordinates.Count);
                    Assert.AreEqual(1, _Aircraft.FullCoordinates[0].Heading);
                    Assert.AreEqual(1, _Aircraft.ShortCoordinates[0].Heading);
                }
            } else {
                if(milliseconds < 1000) {
                    Assert.AreEqual(0, _Aircraft.FullCoordinates.Count);
                    Assert.AreEqual(0, _Aircraft.ShortCoordinates.Count);
                } else {
                    Assert.AreEqual(1, _Aircraft.FullCoordinates.Count);
                    Assert.AreEqual(1, _Aircraft.ShortCoordinates.Count);
                    Assert.AreEqual(2, _Aircraft.FullCoordinates[0].Heading);
                    Assert.AreEqual(2, _Aircraft.ShortCoordinates[0].Heading);
                }
            }
        }
        /// <summary>
        /// Reads actual details from a spreadsheet, assuming that the fields are in alphabetical order from the first ordinal passed across.
        /// </summary>
        /// <param name="expected"></param>
        /// <param name="firstOrdinal"></param>
        /// <param name="copyIntoAircraft"></param>
        /// <returns></returns>
        /// <remarks>
        /// The fields, in ascending order of ordinal, are:
        /// AircraftClass, Country, DeRegDate, Engines, FirstCreated, GenericName, ICAOTypeCode, LastModified, Manufacturer, ModeS, ModeSCountry,
        /// OperatorFlagCode, OwnershipStatus, PopularName, PreviousID, RegisteredOwners, Registration, SerialNo, Status, Type, CofACategory, CofAExpiry
        /// CurrentRegDate, FirstRegDate, InfoUrl, Interested, MTOW, PictureUrl1, PictureUrl2, PictureUrl3, TotalHours, UserNotes, UserTag and YearBuilt.
        /// </remarks>
        private BaseStationAircraft LoadAircraftFromSpreadsheet(ExcelWorksheetData worksheet, int firstOrdinal = 0, BaseStationAircraft copyIntoAircraft = null)
        {
            var result = copyIntoAircraft == null ? new BaseStationAircraft() : copyIntoAircraft;

            int ordinal = firstOrdinal;
            result.AircraftClass = worksheet.EString(ordinal++);
            result.Country = worksheet.EString(ordinal++);
            result.DeRegDate = worksheet.EString(ordinal++);
            result.Engines = worksheet.EString(ordinal++);
            result.FirstCreated = worksheet.DateTime(ordinal++);
            result.GenericName = worksheet.EString(ordinal++);
            result.ICAOTypeCode = worksheet.EString(ordinal++);
            result.LastModified = worksheet.DateTime(ordinal++);
            result.Manufacturer = worksheet.EString(ordinal++);
            result.ModeS = worksheet.EString(ordinal++);
            result.ModeSCountry = worksheet.EString(ordinal++);
            result.OperatorFlagCode = worksheet.EString(ordinal++);
            result.OwnershipStatus = worksheet.EString(ordinal++);
            result.PopularName = worksheet.EString(ordinal++);
            result.PreviousID = worksheet.EString(ordinal++);
            result.RegisteredOwners = worksheet.EString(ordinal++);
            result.Registration = worksheet.EString(ordinal++);
            result.SerialNo = worksheet.EString(ordinal++);
            result.Status = worksheet.EString(ordinal++);
            result.Type = worksheet.EString(ordinal++);
            result.CofACategory = worksheet.EString(ordinal++);
            result.CofAExpiry = worksheet.EString(ordinal++);
            result.CurrentRegDate = worksheet.EString(ordinal++);
            result.FirstRegDate = worksheet.EString(ordinal++);
            result.InfoUrl = worksheet.EString(ordinal++);
            result.Interested = worksheet.Bool(ordinal++);
            result.MTOW = worksheet.EString(ordinal++);
            result.PictureUrl1 = worksheet.EString(ordinal++);
            result.PictureUrl2 = worksheet.EString(ordinal++);
            result.PictureUrl3 = worksheet.EString(ordinal++);
            result.TotalHours = worksheet.EString(ordinal++);
            result.UserNotes = worksheet.EString(ordinal++);
            result.UserTag = worksheet.EString(ordinal++);
            result.YearBuilt = worksheet.EString(ordinal++);

            return result;
        }
        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);
        }
        /// <summary>
        /// Returns a mock flight record with values filled from a spreadsheet row, starting from the column number passed across.
        /// </summary>
        /// <param name="expected"></param>
        /// <param name="firstOrdinal"></param>
        /// <returns></returns>
        /// <remarks>
        /// The columns are read in the following order:
        /// AircraftID, Callsign, EndTime, FirstAltitude, FirstGroundSpeed, FirstIsOnGround, FirstLat, FirstLon, FirstSquawk, FirstTrack, FirstVerticalRate, HadAlert,
        /// HadEmergency, HadSpi, LastAltitude, LastGroundSpeed, LastIsOnGround, LastLat, LastLon, LastSquawk, LastTrack, LastVerticalRate, NumADSBMsgRec, NumModeSMsgRec,
        /// NumIDMsgRec, NumSurPosMsgRec, NumAirPosMsgRec, NumAirVelMsgRec, NumSurAltMsgRec, NumSurIDMsgRec, NumAirToAirMsgRec, NumAirCallRepMsgRec, NumPosMsgRec
        /// and StartTime
        /// </remarks>
        private BaseStationFlight LoadFlightFromSpreadsheet(ExcelWorksheetData worksheet, int firstOrdinal = 0, BaseStationFlight copyIntoFlight = null)
        {
            int ordinal = firstOrdinal;

            var aircraft = CreateAircraft();
            aircraft.AircraftID = worksheet.Int(ordinal++);

            var result = copyIntoFlight == null ? CreateFlight(aircraft) : copyIntoFlight;
            result.AircraftID = aircraft.AircraftID;
            result.Callsign = worksheet.EString(ordinal++);
            result.EndTime = worksheet.DateTime(ordinal++);
            result.FirstAltitude = worksheet.Int(ordinal++);
            result.FirstGroundSpeed = worksheet.Float(ordinal++);
            result.FirstIsOnGround = worksheet.Bool(ordinal++);
            result.FirstLat = worksheet.Float(ordinal++);
            result.FirstLon = worksheet.Float(ordinal++);
            result.FirstSquawk = worksheet.Int(ordinal++);
            result.FirstTrack = worksheet.Float(ordinal++);
            result.FirstVerticalRate = worksheet.Int(ordinal++);
            result.HadAlert = worksheet.Bool(ordinal++);
            result.HadEmergency = worksheet.Bool(ordinal++);
            result.HadSpi = worksheet.Bool(ordinal++);
            result.LastAltitude = worksheet.Int(ordinal++);
            result.LastGroundSpeed = worksheet.Float(ordinal++);
            result.LastIsOnGround = worksheet.Bool(ordinal++);
            result.LastLat = worksheet.Float(ordinal++);
            result.LastLon = worksheet.Float(ordinal++);
            result.LastSquawk = worksheet.Int(ordinal++);
            result.LastTrack = worksheet.Float(ordinal++);
            result.LastVerticalRate = worksheet.Int(ordinal++);
            result.NumADSBMsgRec = worksheet.Int(ordinal++);
            result.NumModeSMsgRec = worksheet.Int(ordinal++);
            result.NumIDMsgRec = worksheet.Int(ordinal++);
            result.NumSurPosMsgRec = worksheet.Int(ordinal++);
            result.NumAirPosMsgRec = worksheet.Int(ordinal++);
            result.NumAirVelMsgRec = worksheet.Int(ordinal++);
            result.NumSurAltMsgRec = worksheet.Int(ordinal++);
            result.NumSurIDMsgRec = worksheet.Int(ordinal++);
            result.NumAirToAirMsgRec = worksheet.Int(ordinal++);
            result.NumAirCallRepMsgRec = worksheet.Int(ordinal++);
            result.NumPosMsgRec = worksheet.Int(ordinal++);
            result.StartTime = worksheet.DateTime(ordinal++);

            return result;
        }
        public void WebSite_BaseStationAircraftList_AircraftListFilter_PositionWithin_Works_Correctly()
        {
            var worksheet = new ExcelWorksheetData(TestContext);

            _AircraftListAddress.Filter = _AircraftListFilter;

            AddBlankAircraft(1);
            _BaseStationAircraft[0].Latitude = worksheet.NFloat("Latitude");
            _BaseStationAircraft[0].Longitude = worksheet.NFloat("Longitude");

            _AircraftListFilter.PositionWithin = new Pair<Coordinate>(
                new Coordinate(worksheet.Float("Top"), worksheet.Float("Left")),
                new Coordinate(worksheet.Float("Bottom"), worksheet.Float("Right"))
            );

            var list = SendJsonRequest<AircraftListJson>(_AircraftListAddress.Address);

            Assert.AreEqual(worksheet.Bool("IsInBounds") ? 1 : 0, list.Aircraft.Count);
        }
        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());
            }
        }
        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 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"));
                    }
                }
            }
        }