public async Task Logic_Client_ConnectWithHttps_Async()
        {
            var server = $"https://{Settings.Server}";

            var localClient = new PrtgClient(server, Settings.UserName, client.PassHash, AuthMode.PassHash);

            //Get the method
            var engine  = localClient.GetInternalProperty("RequestEngine");
            var flags   = BindingFlags.NonPublic | BindingFlags.Instance;
            var methods = engine.GetType().GetMethods(flags).Where(m => m.Name == "ExecuteRequestAsync").ToList();
            var method  = methods.First(m => m.GetParameters().Any(p => p.ParameterType.Name == "IJsonParameters"));

            //Construct the parameters
            var parameters = PrtgAPIHelpers.GetPassHashParameters(Settings.Password);

            try
            {
                await(Task <string>) method.Invoke(engine, new object[] { parameters, null });
            }
            catch (WebException ex)
            {
                if (ex.Message != "Server rejected HTTPS connection on port 443. Please confirm expected server protocol and port, PRTG Core Service is running and that any SSL certificate is trusted")
                {
                    throw;
                }
            }
        }
Beispiel #2
0
        public void Action_NotificationTrigger_TriggerChannel_ChannelId_OnSensor()
        {
            var sensor  = client.GetSensors(Property.Tags, FilterOperator.Contains, "wmicpu").First();
            var channel = client.GetChannel(sensor.Id, "Total").Id;

            TestTriggerChannel(sensor.Id, new TriggerChannel(channel), (paramValue, triggerValue, propertyName) =>
            {
                if (propertyName != "Channel")
                {
                    return(false);
                }

                var first  = PrtgAPIHelpers.GetTriggerChannelSource((TriggerChannel)paramValue);
                var second = PrtgAPIHelpers.GetTriggerChannelSource((TriggerChannel)triggerValue);

                if (first is int)
                {
                    Assert.AreEqual(first, ((Channel)second).Id);
                }
                else
                {
                    Assert.AreEqual(((Channel)first).Id, ((Channel)second).Id);
                }

                return(true);
            });
        }
Beispiel #3
0
        private int GetMissingPropertyTarget(ObjectProperty property)
        {
            var category = (ObjectPropertyCategory)PrtgAPIHelpers.GetPropertyCategory(property);

            switch (category)
            {
            case ObjectPropertyCategory.Devices:
            case ObjectPropertyCategory.CredentialsForLinux:
            case ObjectPropertyCategory.CredentialsForVMware:
            case ObjectPropertyCategory.CredentialsForSNMP:
            case ObjectPropertyCategory.CredentialsForDatabases:
            case ObjectPropertyCategory.CredentialsForAmazon:
                return(Settings.Device);

            case ObjectPropertyCategory.HttpSpecific:
            case ObjectPropertyCategory.ProxySettingsForHttp:
                return(Settings.UpSensor);

            case ObjectPropertyCategory.SensorSettingsExeXml:
                return(Settings.ExeXml);

            case ObjectPropertyCategory.SensorFactorySpecific:
                return(Settings.SensorFactory);

            case ObjectPropertyCategory.DatabaseSpecific:
            case ObjectPropertyCategory.Data:
                return(Settings.SqlServerDB);

            default:
                throw new NotImplementedException($"Handler for object category '{category}' is not implemented");
            }
        }
Beispiel #4
0
        public void Data_StreamLogs_SerialVsNonSerial_StartOffset()
        {
            FilterTests.Retry(retry =>
            {
                var parameters = new LogParameters(null, RecordAge.All, 3000)
                {
                    Start = 502
                };

                Logger.LogTestDetail("Retrieving normal logs");
                var normalNoSkip = OrderLogs(client.StreamLogs(RecordAge.All, 3000, true)).ToList();

                Logger.LogTestDetail("Retrieving parallel logs");
                var normal = OrderLogs(client.StreamLogs(parameters)).ToList();

                Logger.LogTestDetail("Retrieving serial logs");
                var serial = OrderLogs(client.StreamLogs(parameters, true)).ToList();

                AssertLogStreamsEqual(normal, serial, true);

                //Sometimes it might fail due to the order of entries at a given datetime being nondeterministic
                try
                {
                    Assert.IsTrue(PrtgAPIHelpers.LogEqualityComparer().Equals(normalNoSkip[501], serial.First()));
                }
                catch (AssertFailedException)
                {
                    var time = serial.First().DateTime;

                    var matchingTime = normalNoSkip.Where(l => l.DateTime == time).ToList();

                    Assert.IsTrue(matchingTime.Any(l => PrtgAPIHelpers.LogEqualityComparer().Equals(l, serial.First())));
                }
            });
        }
        private void TriggerParameters_Create_FromExistingTrigger(NotificationTrigger trigger, TriggerParameters parameters)
        {
            //shouldnt we _actually_ be checking that the values are the same?
            //and, shouldnt we be populating _all_ properties of the trigger first?

            //then, we need to make sure we can clone a trigger into some new parameters and add them successfully
            //and THEN, we need to write some tests for that

            foreach (var paramProp in PrtgAPIHelpers.GetNormalProperties(parameters.GetType()))
            {
                bool found = false;

                foreach (var triggerProp in trigger.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
                {
                    if ((paramProp.Name == "TriggerInternal" && triggerProp.Name == "Trigger") ||
                        (paramProp.Name == "State" && triggerProp.Name == "StateTrigger") ||
                        (paramProp.Name == triggerProp.Name))
                    {
                        found = true;
                        Assert.IsTrue(paramProp.GetValue(parameters) != null, $"Parameter '{paramProp}' was null");
                    }
                }

                if (!found)
                {
                    Assert.Fail($"Couldn't find notification trigger property that corresponded to parameter property '{paramProp.Name}'");
                }
            }
        }
        private void TriggerParameters_AllProperties_HaveValues(TriggerParameters parameters, Func <PropertyInfo, bool> additionalChecks = null)
        {
            if (additionalChecks == null)
            {
                additionalChecks = p => false;
            }

            foreach (var prop in PrtgAPIHelpers.GetNormalProperties(parameters.GetType()))
            {
                var val = prop.GetValue(parameters);

                if (prop.Name.EndsWith("NotificationAction"))
                {
                    Assert.IsTrue(val.ToString() != TriggerParameters.EmptyNotificationAction().ToString(), $"Property '{prop.Name}' had the empty notification action");
                }

                else
                {
                    if (!additionalChecks(prop))
                    {
                        Assert.IsTrue(val != null, $"Property '{prop.Name}' had value did not have a value.");
                    }
                }
            }
        }
        private void TriggerParameters_AllProperties_HaveDefault(TriggerParameters parameters, Func <PropertyInfo, bool> additionalChecks = null)
        {
            TestReflectionHelpers.NullifyProperties(parameters);

            if (additionalChecks == null)
            {
                additionalChecks = p => false;
            }

            foreach (var prop in PrtgAPIHelpers.GetNormalProperties(parameters.GetType()))
            {
                var val = prop.GetValue(parameters);

                if (prop.Name.EndsWith("NotificationAction"))
                {
                    Assert.IsTrue(val.ToString() == TriggerParameters.EmptyNotificationAction().ToString(), $"Property '{prop.Name}' had value {val}");
                }
                else
                {
                    if (!additionalChecks(prop))
                    {
                        Assert.IsTrue(val == null, $"Property '{prop.Name}' was not null");
                    }
                }
            }
        }
Beispiel #8
0
        private void StreamLogs(LogParameters parameters, List <Log> expected, bool retry = false)
        {
            var result = client.StreamLogs(parameters).ToList().OrderBy(d => d.DateTime).ThenBy(d => d.Status).ToList();

            expected = expected.OrderBy(d => d.DateTime).ThenBy(d => d.Status).ToList();

            AssertEx.AreEqualLists(expected, result, PrtgAPIHelpers.LogEqualityComparer(), "Lists were not the same");
        }
Beispiel #9
0
        public void Data_StreamLogs_WithIncorrectPageSize()
        {
            FilterTests.Retry(retry =>
            {
                var correctParameters = new LogParameters(null, RecordAge.Today, 15)
                {
                    PageSize = 5
                };
                var automaticParameters = new LogParameters(null, RecordAge.Today, 15)
                {
                    Start = 0, PageSize = 5
                };
                var manualParameters = new LogParameters(null, RecordAge.Today, 5)
                {
                    Start = 0
                };

                //The real logs that exist on the server. This is what all other requests compare against
                var correctLogs = client.GetLogs(correctParameters);

                //What we get when we make the same request with a starting index of 0. We expect GetLogs to return
                //something equivalent to a normal request, but StreamSensors to contain a duplicate at index 4 and 5
                var automaticLogs       = client.GetLogs(automaticParameters);
                var automaticStreamLogs = client.StreamLogs(automaticParameters, true).ToList();

                //What we get when we manually increment the pages of a stream. We expect to end up with a list
                //identical to our streamed list
                var firstManualLogs = client.GetLogs(manualParameters);
                manualParameters.Page++;
                var secondManualLogs = client.GetLogs(manualParameters);
                manualParameters.Page++;
                var thirdManualLogs = client.GetLogs(manualParameters);

                var allManualLogs = new List <Log>();
                allManualLogs.AddRange(firstManualLogs);
                allManualLogs.AddRange(secondManualLogs);
                allManualLogs.AddRange(thirdManualLogs);

                var comparer = PrtgAPIHelpers.LogEqualityComparer();

                AssertEx.AreEqualLists(correctLogs, automaticLogs, comparer, "Correct logs were not equal to off by one logs", retry);
                AssertEx.AreEqualLists(automaticStreamLogs, allManualLogs, comparer, "Streamed off by one logs were not equal to manual logs", retry);

                Assert.IsTrue(comparer.Equals(automaticStreamLogs[4], automaticStreamLogs[5]));
                Assert.IsTrue(comparer.Equals(allManualLogs[4], allManualLogs[5]));
                //now check none of the OTHER elements are equal to each other

                var automaticDiff = automaticStreamLogs.Where((l, i) => i != 4 && i != 5).ToList();
                var manualDiff    = allManualLogs.Where((l, i) => i != 4 && i != 5).ToList();

                AssertEx.AllListElementsUnique(automaticDiff, comparer);
                AssertEx.AllListElementsUnique(manualDiff, comparer);
            });
        }
Beispiel #10
0
        private void AssertLogStreamsEqual(List <Log> normal, List <Log> serial, bool retry = false)
        {
            var comparer = PrtgAPIHelpers.LogEqualityComparer();

            AssertStreamsEqual(
                normal, serial, comparer,
                e => OrderLogs(e),
                g => OrderLogs(g),
                retry
                );
        }
        public void All_PrtgObjectProperties_HaveArrayLookupProperties()
        {
            var properties    = PrtgObjectFilterTests.GetPrtgObjectProperties(new[] { "NotificationTypes" });
            var propertyTypes = PrtgAPIHelpers.DistinctBy(properties.Select(p => p.PropertyType).Select(ReflectionExtensions.GetUnderlyingType), p => p.Name).ToList();

            var arrayTypes = typeof(DynamicParameterPropertyTypes).GetProperties();

            var missing = propertyTypes.Where(p => arrayTypes.All(a => a.PropertyType.GetElementType() != p) && !p.IsArray && !ReflectionExtensions.IsNullable(p)).ToList();

            if (missing.Count > 0)
            {
                Assert.Fail($"{missing.Count}/{propertyTypes.Count} properties are missing are missing: " + string.Join(", ", missing));
            }
        }
Beispiel #12
0
 public void Data_StreamLogs_WithCorrectPageSize()
 {
     FilterTests.Retry(retry =>
     {
         Stream_WithCorrectPageSize(
             () => client.GetLogs(RecordAge.Today, 15),
             () => client.StreamLogs(RecordAge.Today, 15, true),
             p => client.GetLogs(p),
             PrtgAPIHelpers.LogEqualityComparer(),
             new LogParameters(null, RecordAge.Today, 5),
             1,
             retry
             );
     });
 }
Beispiel #13
0
        private void TriggerParameters_Edit_CanSetUnsetValue(TriggerParameters parameters)
        {
            var properties = PrtgAPIHelpers.GetNormalProperties(parameters.GetType());

            foreach (var prop in properties)
            {
                prop.SetValue(parameters, null);
                if (prop.Name == nameof(TriggerProperty.OnNotificationAction) || prop.Name == nameof(TriggerProperty.OffNotificationAction) || prop.Name == nameof(TriggerProperty.EscalationNotificationAction))
                {
                    Assert.IsTrue(prop.GetValue(parameters).ToString() == TriggerParameters.EmptyNotificationAction().ToString(), $"Property '{prop.Name}' was not empty.");
                }
                else
                {
                    Assert.IsTrue(prop.GetValue(parameters) == null, $"Property '{prop.Name}' was not null.");
                }

                object defaultValue = null;

                if (prop.PropertyType.Name == nameof(TriggerChannel))
                {
                    defaultValue = new TriggerChannel(1234);
                }
                else if (prop.Name == nameof(VolumeTriggerParameters.UnitSize))
                {
                    if (parameters is VolumeTriggerParameters)
                    {
                        defaultValue = TestReflectionUtilities.GetDefaultUnderlying(typeof(DataVolumeUnit)).ToString().ToEnum <DataUnit>();
                    }
                    else
                    {
                        defaultValue = TestReflectionUtilities.GetDefaultUnderlying(prop.PropertyType);
                    }
                }
                else
                {
                    defaultValue = TestReflectionUtilities.GetDefaultUnderlying(prop.PropertyType);
                }

                prop.SetValue(parameters, defaultValue);
                Assert.IsTrue(prop.GetValue(parameters) != null, $"Property '{prop.Name}' was null.");
            }
        }
        private void TriggerParameters_Edit_CanSetUnsetValue(TriggerParameters parameters)
        {
            var properties = PrtgAPIHelpers.GetNormalProperties(parameters.GetType());

            foreach (var prop in properties)
            {
                prop.SetValue(parameters, null);
                if (prop.Name == nameof(TriggerProperty.OnNotificationAction) || prop.Name == nameof(TriggerProperty.OffNotificationAction) || prop.Name == nameof(TriggerProperty.EscalationNotificationAction))
                {
                    Assert.IsTrue(prop.GetValue(parameters).ToString() == TriggerParameters.EmptyNotificationAction().ToString(), $"Property '{prop.Name}' was not empty.");
                }
                else
                {
                    Assert.IsTrue(prop.GetValue(parameters) == null, $"Property '{prop.Name}' was not null.");
                }

                var defaultValue = prop.PropertyType.Name == "TriggerChannel" ? new TriggerChannel(1234) : TestReflectionHelpers.GetDefaultUnderlying(prop.PropertyType);

                prop.SetValue(parameters, defaultValue);
                Assert.IsTrue(prop.GetValue(parameters) != null, $"Property '{prop.Name}' was null.");
            }
        }
        //for edit mode, it IS valid to set fields to null, since that indicates we're not going to edit that field
        //we then also need to analyze the url we get and confirm it doesnt have any fields in it
        //also we need to check when we add something and then nullify it it goes away

        #endregion

        private void TriggerParameters_MandatoryFields_CannotBeNull(TriggerParameters parameters)
        {
            foreach (var prop in PrtgAPIHelpers.GetNormalProperties(parameters.GetType()))
            {
                var attr        = prop.GetCustomAttribute <RequireValueAttribute>();
                var valRequired = attr?.ValueRequired ?? false;

                try
                {
                    prop.SetValue(parameters, null);

                    if (valRequired)
                    {
                        Assert.Fail($"Property '{prop.Name}' requires a value however did not generate an exception.");
                    }
                }
                catch (TargetInvocationException ex)
                {
                    var inner = ex.InnerException as InvalidOperationException;

                    if (inner == null)
                    {
                        throw;
                    }

                    if (!inner.Message.StartsWith("Trigger property"))
                    {
                        throw;
                    }

                    if (!valRequired)
                    {
                        Assert.Fail($"Property '{prop.Name}' does not require a value, however the property responded as if it does.");
                    }
                }
            }
        }
Beispiel #16
0
        public void Data_Query_Take_Until_Matched_TakeIterator()
        {
            Func <SensorParameters, Func <int>, IEnumerable <Sensor> > streamer = (p, c) =>
                                                                                  PrtgAPIHelpers.StreamObjects(client, p, true, c);

            var parameters = new SensorParameters
            {
                SearchFilters = new List <SearchFilter> {
                    new SearchFilter(Property.Name, FilterOperator.Contains, "Pi")
                }
            };

            var iterator = PrtgAPIHelpers.TakeIterator(
                2,
                parameters,
                streamer,
                () => client.GetTotalObjects(parameters.Content, parameters.SearchFilters?.ToArray()),
                r => r.Where(s => s.Name == "Ping")
                );

            var response = iterator.ToList();

            Assert.AreEqual(2, response.Count);
        }
Beispiel #17
0
        private void StreamLogsSerial(LogParameters parameters, List <Log> expected)
        {
            var result = client.StreamLogs(parameters, true).ToList();

            AssertEx.AreEqualLists(expected, result, PrtgAPIHelpers.LogEqualityComparer(), "Lists were not the same");
        }