Ejemplo n.º 1
0
        public void JSONSerializationOfOneRuleWithoutConditionsWithoutTimeWindowIsCorrect()
        {
            // Arrange
            var rule = new RuleApiModel
            {
                Enabled     = true,
                Id          = Guid.NewGuid().ToString(),
                Name        = Guid.NewGuid().ToString(),
                Description = Guid.NewGuid().ToString(),
                GroupId     = Guid.NewGuid().ToString(),
                Severity    = Guid.NewGuid().ToString(),
                Calculation = SOURCE_NO_AGGREGATION
            };

            // Act
            var target = new AsaRefDataRule(rule);
            var json   = JsonConvert.SerializeObject(target);

            this.log.WriteLine("JSON: " + json);

            // Assert
            var expectedJSON = JsonConvert.SerializeObject(new
            {
                Id                = rule.Id,
                Name              = rule.Name,
                Description       = rule.Description,
                GroupId           = rule.GroupId,
                Severity          = rule.Severity,
                AggregationWindow = ASA_AGGREGATION_NONE,
                Fields            = new string[] { },
                __rulefilterjs    = "return true;"
            });

            Assert.Equal(expectedJSON, json);
        }
        public void ItExportsRulesToTempFile()
        {
            // Arrange
            var rule1 = new RuleApiModel {
                Enabled = true, Name = "rule alpha"
            };
            var rule2 = new RuleApiModel {
                Enabled = true, Name = "rule beta"
            };
            var rules = new List <RuleApiModel> {
                rule1, rule2
            };

            var filename = Guid.NewGuid().ToString();

            this.fileWrapper.Setup(x => x.GetTempFileName()).Returns(filename);

            // Act
            this.target.ExportRulesToAsaAsync(rules, DateTimeOffset.UtcNow)
            .Wait(TimeSpan.FromSeconds(TEST_TIMEOUT));

            // Assert
            this.fileWrapper.Verify(
                x => x.WriteAllText(filename, It.Is <string>(s => s.Contains(rule1.Name) && s.Contains(rule2.Name))),
                Times.Once);
        }
Ejemplo n.º 3
0
        public void JSONSerializationOfOneRuleWithConditionsWithTimeWindowIsCorrect(string sourceOperator, string jsOperator)
        {
            // Arrange
            var rule = new RuleApiModel
            {
                Enabled     = true,
                Id          = Guid.NewGuid().ToString(),
                Name        = Guid.NewGuid().ToString(),
                Description = Guid.NewGuid().ToString(),
                GroupId     = Guid.NewGuid().ToString(),
                Severity    = Guid.NewGuid().ToString(),
                Calculation = SOURCE_AVG_AGGREGATOR,
                TimePeriod  = SOURCE_5MINS_AGGREGATION,
                Conditions  = new List <ConditionApiModel>
                {
                    new ConditionApiModel
                    {
                        Field    = Guid.NewGuid().ToString("N"),
                        Operator = sourceOperator,
                        Value    = (new Random().Next(-10000, 10000) / 1.1).ToString()
                    },
                    new ConditionApiModel
                    {
                        Field    = Guid.NewGuid().ToString("N"),
                        Operator = sourceOperator,
                        Value    = new Random().Next(-10000, 10000).ToString()
                    },
                    new ConditionApiModel
                    {
                        Field    = Guid.NewGuid().ToString("N"),
                        Operator = sourceOperator,
                        Value    = (new Random().Next(-10000, 10000) / 1.3).ToString()
                    },
                }
            };

            // Act
            var target = new AsaRefDataRule(rule);
            var json   = JsonConvert.SerializeObject(target);

            this.log.WriteLine("JSON: " + json);

            // Assert
            var cond1        = $"record.__aggregates.{rule.Conditions[0].Field}{ASA_JS_AVG_FIELD} {jsOperator} {rule.Conditions[0].Value}";
            var cond2        = $"record.__aggregates.{rule.Conditions[1].Field}{ASA_JS_AVG_FIELD} {jsOperator} {rule.Conditions[1].Value}";
            var cond3        = $"record.__aggregates.{rule.Conditions[2].Field}{ASA_JS_AVG_FIELD} {jsOperator} {rule.Conditions[2].Value}";
            var expectedJSON = JsonConvert.SerializeObject(new
            {
                Id                = rule.Id,
                Name              = rule.Name,
                Description       = rule.Description,
                GroupId           = rule.GroupId,
                Severity          = rule.Severity,
                AggregationWindow = ASA_AGGREGATION_WINDOW_TUMBLING_5MINS,
                Fields            = rule.Conditions.Select(x => x.Field),
                __rulefilterjs    = $"return ({cond1} && {cond2} && {cond3}) ? true : false;"
            });

            Assert.Equal(expectedJSON, json);
        }
        public void ItExportsRulesToBlob()
        {
            // Arrange
            var time     = DateTimeOffset.UtcNow;
            var blobfile = Guid.NewGuid().ToString();

            var rule = new RuleApiModel {
                Enabled = true, Name = "rule alpha"
            };
            var rules = new List <RuleApiModel> {
                rule
            };

            var filename = Guid.NewGuid().ToString();

            this.fileWrapper.Setup(x => x.GetTempFileName()).Returns(filename);

            this.blobStorageConfig.SetupGet(x => x.ReferenceDataDateFormat).Returns("yyyy-MM-dd");
            this.blobStorageConfig.SetupGet(x => x.ReferenceDataTimeFormat).Returns("HH-mm");
            this.blobStorageConfig.SetupGet(x => x.ReferenceDataRulesFileName).Returns(blobfile);

            // Act
            this.target.ExportRulesToAsaAsync(rules, time)
            .Wait(TimeSpan.FromSeconds(TEST_TIMEOUT));

            // Assert
            var blobName = $"{time:yyyy-MM-dd/HH-mm}/{blobfile}";

            this.blobStorageHelper.Verify(
                x => x.WriteBlobFromFileAsync(blobName, filename),
                Times.Once);
        }
Ejemplo n.º 5
0
        public void ConstructorTest()
        {
            var rules = new RuleApiModel[] { };

            mockRules
            .Setup(x => x.GetAllAsync())
            .ReturnsAsync(rules);

            mockWriter
            .Setup(x => x.OpenAsync(It.IsAny <IStorageServiceConfig>()))
            .Returns(Task.FromResult(0));

            var unused = new Alarms(
                logger,
                new ServicesConfig {
                AlarmsStorageServiceConfig = null
            },
                mockRules.Object,
                mockRulesEvaluation.Object,
                mockWriter.Object);

            mockRules
            .Verify(x => x.GetAllAsync(), Times.Once);

            mockWriter
            .Verify(x => x.OpenAsync(It.IsAny <IStorageServiceConfig>()), Times.Once);
        }
Ejemplo n.º 6
0
        public RulesEvaluationResult Evaluate(RuleApiModel rule, RawMessage message)
        {
            var result = new RulesEvaluationResult();

            if (GroupContainsDevice(message.DeviceId, rule.GroupId))
            {
                logger.Debug($"Evaluating rule {rule.Description} for device {message.DeviceId} with {rule.Conditions.Count()} conditions", () => { });

                var descriptions = new List <string>();
                foreach (var c in rule.Conditions)
                {
                    var eval = EvaluateCondition(c, message);
                    // perf: all conditions must match, break as soon as one doesn't
                    if (!eval.Match)
                    {
                        return(result);
                    }
                    descriptions.Add(eval.Message);
                }

                result.Match   = true;
                result.Message = string.Join("; ", descriptions);
            }
            else
            {
                logger.Debug($"Skipping rule {rule.Description} because device {message.DeviceId} doesn't belong to group {rule.GroupId}", () => { });
            }

            return(result);
        }
        public void EvaluateTest()
        {
            var evaluation = new RulesEvaluation(
                logger,
                mockDeviceGroups.Object);

            // Repeat times for broader coverage
            foreach (var unused in Enumerable.Range(0, 10))
            {
                var totalConditions = rand.Next(3, 10);

                var message = rand.NextRawMessage();

                var rule = new RuleApiModel
                {
                    GroupId    = rand.NextString(),
                    Conditions = Enumerable.Range(0, totalConditions).Select(i => GenerateCondition(message, true)).ToList()
                };

                mockDeviceGroups
                .Setup(x => x.GetDevicesAsync(
                           It.IsAny <string>()))
                .ReturnsAsync(new[] { message.DeviceId });

                var result = evaluation.Evaluate(rule, message);

                mockDeviceGroups
                .Verify(x => x.GetDevicesAsync(
                            It.Is <string>(s => s == rule.GroupId)),
                        Times.Once);

                Assert.True(result.Match);
            }
        }
        public void ItCanBeSerializedToJson()
        {
            // Arrange
            var rule = new RuleApiModel {
                Enabled = true
            };

            // Act
            var target = new AsaRefDataRule(rule);
            var json   = JsonConvert.SerializeObject(target);

            this.log.WriteLine("JSON: " + json);

            // Assert
            var expectedJSON = JsonConvert.SerializeObject(new
            {
                Id                = (string)null,
                Name              = (string)null,
                Description       = (string)null,
                GroupId           = (string)null,
                Severity          = (string)null,
                AggregationWindow = (string)null,
                Fields            = new string[] { },
                Actions           = new List <IActionApiModel>(),
                __rulefilterjs    = "return true;"
            });

            Assert.Equal(expectedJSON, json);
        }
Ejemplo n.º 9
0
        public void InstancesWithDifferentDataAreDifferent()
        {
            // Arrange
            var x = new RuleApiModel
            {
                Id          = Guid.NewGuid().ToString(),
                Name        = Guid.NewGuid().ToString(),
                Enabled     = true,
                Description = Guid.NewGuid().ToString(),
                GroupId     = Guid.NewGuid().ToString(),
                Severity    = Guid.NewGuid().ToString(),
                Conditions  = new List <ConditionApiModel>()
            };
            var y1 = Clone(x);
            var y2 = Clone(x);
            var y3 = Clone(x);
            var y4 = Clone(x);
            var y5 = Clone(x);

            y1.Id       += "x";
            y2.Name     += "x";
            y3.Enabled   = !y3.Enabled;
            y4.GroupId  += "x";
            y5.Severity += "x";

            // Assert
            Assert.False(x.Equals(y1));
            Assert.False(x.Equals(y2));
            Assert.False(x.Equals(y3));
            Assert.False(x.Equals(y4));
            Assert.False(x.Equals(y5));
        }
        public AsaRefDataRule(RuleApiModel rule) : this()
        {
            if (!rule.Enabled || rule.Deleted)
            {
                return;
            }

            this.Id                = rule.Id;
            this.Name              = rule.Name;
            this.Description       = rule.Description;
            this.GroupId           = rule.GroupId;
            this.Severity          = rule.Severity;
            this.AggregationWindow = GetAggregationWindowValue(rule.Calculation, rule.TimePeriod);

            this.Fields     = new List <string>();
            this.conditions = new List <Condition>();
            foreach (var c in rule.Conditions)
            {
                var condition = new Condition
                {
                    Calculation = rule.Calculation,
                    Field       = c.Field,
                    Operator    = c.Operator,
                    Value       = c.Value
                };
                this.conditions.Add(condition);
                this.Fields.Add(c.Field);
            }

            if (rule.Actions != null && rule.Actions.Count >= 0)
            {
                this.Actions = rule.Actions;
            }
        }
Ejemplo n.º 11
0
        public async Task GetAllAsyncTest()
        {
            var ruleList = new RuleApiModel[] { };
            var model    = new RuleListApiModel
            {
                Items = ruleList
            };

            mockHttpClient
            .Setup(x => x.GetAsync <RuleListApiModel>(
                       It.IsAny <string>(),
                       It.IsAny <string>(),
                       It.IsAny <bool>()))
            .ReturnsAsync(model);

            var result = await rules.GetAllAsync();

            Assert.Equal(result, ruleList);

            mockHttpClient
            .Verify(x => x.GetAsync <RuleListApiModel>(
                        It.Is <string>(s => s == $"{config.MonitoringRulesUrl}/rules"),
                        It.IsAny <string>(),
                        It.Is <bool>(b => !b)),
                    Times.Once);
        }
        private void VerifyRuleContents(
            RuleApiModel ruleRequest,
            RuleApiModel ruleResponse,
            IHttpResponse response,
            bool includesActions = false)
        {
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.Equal(ruleRequest.Name, ruleResponse.Name);
            Assert.Equal(ruleRequest.Description, ruleResponse.Description);
            Assert.Equal(ruleRequest.GroupId, ruleResponse.GroupId);
            Assert.Equal(ruleRequest.Severity, ruleResponse.Severity);
            Assert.Equal(ruleRequest.Enabled, ruleResponse.Enabled);
            Assert.Equal(ruleRequest.Calculation, ruleResponse.Calculation);
            Assert.Equal(ruleRequest.Conditions[0].Field, ruleResponse.Conditions[0].Field);
            Assert.Equal(ruleRequest.Conditions[0].Operator, ruleResponse.Conditions[0].Operator);
            Assert.Equal(ruleRequest.Conditions[0].Value, ruleResponse.Conditions[0].Value);

            if (includesActions)
            {
                Assert.NotEmpty(ruleResponse.Actions);
                Assert.Equal(ruleRequest.Actions[0].Type, ruleResponse.Actions[0].Type);
                var requestParameters  = ruleRequest.Actions[0].Parameters;
                var responseParameters = ruleResponse.Actions[0].Parameters;
                Assert.Equal(requestParameters["Subject"], responseParameters["Subject"]);
                Assert.Equal(requestParameters["Notes"], responseParameters["Notes"]);
                Assert.Equal(((JArray)requestParameters["Recipients"])[0], ((JArray)responseParameters["Recipients"])[0]);
            }
        }
Ejemplo n.º 13
0
        public void EmptyInstancesAreEqual()
        {
            // Arrange
            var x = new RuleApiModel();
            var y = new RuleApiModel();

            // Assert
            Assert.True(x.Equals(y));
        }
        private IHttpResponse GetRuleFromTelemetryService(RuleApiModel ruleRequest)
        {
            var request = new HttpRequest(Constants.TELEMETRY_ADDRESS + RULES_ENDPOINT_SUFFIX);

            request.AddHeader("Content-Type", "application/json");
            request.SetContent(JsonConvert.SerializeObject(ruleRequest));

            return(this.httpClient.PostAsync(request).Result);
        }
Ejemplo n.º 15
0
        public async Task <RuleApiModel> PutAsync(
            [FromRoute] string id,
            [FromBody] RuleApiModel rule)
        {
            if (rule == null)
            {
                throw new InvalidInputException("Rule not provided in request body.");
            }

            //Ensure the id on the model matches the route
            rule.Id = id;
            Rule updatedRule = await this.ruleService.UpsertIfNotDeletedAsync(rule.ToServiceModel());

            return(new RuleApiModel(updatedRule, false));
        }
        private RuleApiModel GetSampleRuleWithCalculation(string calculation, string timePeriod, bool includeActions = false)
        {
            var condition = new ConditionApiModel()
            {
                Field    = "pressure",
                Operator = "GreaterThan",
                Value    = "150"
            };

            var conditions = new List <ConditionApiModel> {
                condition
            };

            RuleApiModel result = new RuleApiModel()
            {
                Name        = calculation + " Test Rule",
                Description = "Test Description",
                GroupId     = DEFAULT_CHILLERS_GROUP_ID,
                Severity    = "Info",
                Enabled     = true,
                Calculation = calculation,
                TimePeriod  = timePeriod,
                Conditions  = conditions
            };

            if (includeActions)
            {
                var parameters = new Dictionary <string, object>
                {
                    { "Notes", "Fake Note" },
                    { "Subject", "Fake Subject" }
                };
                var emails = new JArray {
                    "*****@*****.**"
                };
                parameters.Add("Recipients", emails);
                ActionApiModel action = new ActionApiModel
                {
                    Type       = "Email",
                    Parameters = parameters
                };
                result.Actions = new List <ActionApiModel> {
                    action
                };
            }

            return(result);
        }
        public void JSONSerializationOfRulesWithMinMaxAvgEtcAggregationIsCorrect(string aggregator, string jsField)
        {
            // Arrange
            var rule = new RuleApiModel
            {
                Enabled     = true,
                Id          = Guid.NewGuid().ToString(),
                Name        = Guid.NewGuid().ToString(),
                Description = Guid.NewGuid().ToString(),
                GroupId     = Guid.NewGuid().ToString(),
                Severity    = Guid.NewGuid().ToString(),
                Actions     = new List <IActionApiModel>()
                {
                    GetSampleActionData()
                },
                Calculation = aggregator,
                TimePeriod  = SOURCE_5MINS_AGGREGATION,
                Conditions  = new List <ConditionApiModel>
                {
                    new ConditionApiModel {
                        Field = "foo", Operator = ">", Value = "123"
                    }
                }
            };

            // Act
            var target = new AsaRefDataRule(rule);
            var json   = JsonConvert.SerializeObject(target);

            this.log.WriteLine("JSON: " + json);

            // Assert
            var cond1        = $"record.__aggregates.{rule.Conditions[0].Field}{jsField} > {rule.Conditions[0].Value}";
            var expectedJSON = JsonConvert.SerializeObject(new
            {
                Id                = rule.Id,
                Name              = rule.Name,
                Description       = rule.Description,
                GroupId           = rule.GroupId,
                Severity          = rule.Severity,
                AggregationWindow = ASA_AGGREGATION_WINDOW_TUMBLING_5MINS,
                Fields            = rule.Conditions.Select(x => x.Field),
                Actions           = rule.Actions,
                __rulefilterjs    = $"return ({cond1}) ? true : false;"
            });

            Assert.Equal(expectedJSON, json);
        }
Ejemplo n.º 18
0
        private async Task LoadAllRulesAsync()
        {
            logger.Debug("Loading rules...", () => { });
            IEnumerable <RuleApiModel> result = new RuleApiModel[] { };

            try
            {
                result = (await rules.GetAllAsync()).Where(r => r.Enabled);
                logger.Info($"Monitoring rules loaded: {result.Count()} rules", () => { });
            }
            catch
            {
                logger.Error("Unable to load monitoring rules", () => { });
            }

            monitoringRules = result;
        }
Ejemplo n.º 19
0
        public void NonEmptyInstancesWithSameDataAreEqual()
        {
            // Arrange: rule without conditions
            var x = new RuleApiModel
            {
                Id          = Guid.NewGuid().ToString(),
                Name        = Guid.NewGuid().ToString(),
                Enabled     = true,
                Description = Guid.NewGuid().ToString(),
                GroupId     = Guid.NewGuid().ToString(),
                Severity    = Guid.NewGuid().ToString(),
                Conditions  = new List <ConditionApiModel>(),
                Deleted     = false
            };
            var y = Clone(x);

            // Assert
            Assert.True(x.Equals(y));

            // Arrange: rule with conditions
            x = new RuleApiModel
            {
                Id          = Guid.NewGuid().ToString(),
                Name        = Guid.NewGuid().ToString(),
                Enabled     = true,
                Description = Guid.NewGuid().ToString(),
                GroupId     = Guid.NewGuid().ToString(),
                Severity    = Guid.NewGuid().ToString(),
                Conditions  = new List <ConditionApiModel>
                {
                    new ConditionApiModel {
                        Field = "temp", Operator = ">=", Value = "75"
                    },
                    new ConditionApiModel {
                        Field = "hum", Operator = "gt", Value = "50"
                    },
                }
            };
            y = Clone(x);

            // Assert
            Assert.True(x.Equals(y));
        }
Ejemplo n.º 20
0
        public void InstancesWithDifferentConditionsAreDifferent()
        {
            // Arrange: different number of conditions
            var x = new RuleApiModel
            {
                Conditions = new List <ConditionApiModel>()
            };
            var y = Clone(x);

            y.Conditions.Add(new ConditionApiModel());

            // Assert
            Assert.False(x.Equals(y));

            // Arrange: different field
            x.Conditions = new List <ConditionApiModel>
            {
                new ConditionApiModel {
                    Field = "x", Operator = ">=", Value = "5"
                }
            };
            y = Clone(x);
            y.Conditions[0].Field = "y";

            // Assert
            Assert.False(x.Equals(y));

            // Arrange: different operator
            y = Clone(x);
            y.Conditions[0].Operator = "<";

            // Assert
            Assert.False(x.Equals(y));

            // Arrange: different value
            y = Clone(x);
            y.Conditions[0].Value = "123";

            // Assert
            Assert.False(x.Equals(y));
        }
        public void JSONSerializationOfOneRuleWithoutConditionsWithTimeWindowIsCorrect(long sourceAggr, string asaAggr)
        {
            // Arrange
            var rule = new RuleApiModel
            {
                Enabled     = true,
                Id          = Guid.NewGuid().ToString(),
                Name        = Guid.NewGuid().ToString(),
                Description = Guid.NewGuid().ToString(),
                GroupId     = Guid.NewGuid().ToString(),
                Severity    = Guid.NewGuid().ToString(),
                Actions     = new List <IActionApiModel>()
                {
                    GetSampleActionData()
                },
                Calculation = SOURCE_AVG_AGGREGATOR,
                TimePeriod  = sourceAggr
            };

            // Act
            var target = new AsaRefDataRule(rule);
            var json   = JsonConvert.SerializeObject(target);

            this.log.WriteLine("JSON: " + json);

            // Assert
            var expectedJSON = JsonConvert.SerializeObject(new
            {
                Id                = rule.Id,
                Name              = rule.Name,
                Description       = rule.Description,
                GroupId           = rule.GroupId,
                Severity          = rule.Severity,
                AggregationWindow = asaAggr,
                Fields            = new string[] { },
                Actions           = rule.Actions,
                __rulefilterjs    = "return true;"
            });

            Assert.Equal(expectedJSON, json);
        }
Ejemplo n.º 22
0
        public async Task <RuleApiModel> PostAsync(
            [FromQuery] string template,
            [FromBody] RuleApiModel rule)
        {
            if (!string.IsNullOrEmpty(template))
            {
                // create rules from template
                await this.ruleService.CreateFromTemplateAsync(template);

                return(null);
            }

            // create rule from request body
            if (rule == null)
            {
                throw new InvalidInputException("Rule not provided in request body.");
            }
            Rule newRule = await this.ruleService.CreateAsync(rule.ToServiceModel());

            return(new RuleApiModel(newRule, false));
        }
        public void UnmatchDeviceGroupTest()
        {
            var evaluation = new RulesEvaluation(
                logger,
                mockDeviceGroups.Object);

            mockDeviceGroups
            .Setup(x => x.GetDevicesAsync(
                       It.IsAny <string>()))
            .ReturnsAsync(new string[] { });

            var rule = new RuleApiModel
            {
                GroupId = rand.NextString()
            };

            var message = rand.NextRawMessage();

            var result = evaluation.Evaluate(rule, message);

            Assert.False(result.Match);
        }
Ejemplo n.º 24
0
        private async Task CreateAlarmAsync(
            RuleApiModel rule,
            RawMessage deviceMessage,
            string alarmDescription)
        {
            var created = DateTime.UtcNow;

            var alarm = new Alarm
            {
                Id                  = Guid.NewGuid().ToString(),
                DateCreated         = created,
                DateModified        = created,
                MessageReceivedTime = deviceMessage.ReceivedTime,
                Description         = alarmDescription,
                DeviceId            = deviceMessage.DeviceId,
                Status              = NewAlarmStatus,
                RuleId              = rule.Id,
                RuleServerity       = rule.Severity,
                RuleDescription     = rule.Description
            };

            await documentWriter.WriteAsync(AlarmToDocument(alarm));
        }
        public void NonEmptyInstancesWithSameDataAreEqual()
        {
            // Arrange: rule without conditions
            var x = new RuleApiModel
            {
                Id          = Guid.NewGuid().ToString(),
                Name        = Guid.NewGuid().ToString(),
                Enabled     = true,
                Description = Guid.NewGuid().ToString(),
                GroupId     = Guid.NewGuid().ToString(),
                Severity    = Guid.NewGuid().ToString(),
                Conditions  = new List <ConditionApiModel>(),
                Deleted     = false
            };
            var y = Clone(x);

            // Assert
            Assert.True(x.Equals(y));

            // Arrange: rule with conditions
            x = new RuleApiModel
            {
                Id          = Guid.NewGuid().ToString(),
                Name        = Guid.NewGuid().ToString(),
                Enabled     = true,
                Description = Guid.NewGuid().ToString(),
                GroupId     = Guid.NewGuid().ToString(),
                Severity    = Guid.NewGuid().ToString(),
                Conditions  = new List <ConditionApiModel>
                {
                    new ConditionApiModel {
                        Field = "temp", Operator = ">=", Value = "75"
                    },
                    new ConditionApiModel {
                        Field = "hum", Operator = "gt", Value = "50"
                    },
                }
            };
            y = Clone(x);

            // Assert
            Assert.True(x.Equals(y));

            // Arrange: rule with actions
            x.Actions = new List <IActionApiModel>
            {
                new EmailActionApiModel
                {
                    Type       = ActionType.Email,
                    Parameters = new Dictionary <string, object>
                    {
                        { "Notes", "Sample Note" },
                        { "Recipients", new List <string> {
                              "*****@*****.**", "*****@*****.**"
                          } }
                    }
                }
            };
            y = Clone(x);

            // Assert
            Assert.True(x.Equals(y));
        }
        private void CreateRuleWithCalculation(string calculation, string timePeriod, ref string id, bool includeActions)
        {
            var condition = new ConditionApiModel()
            {
                Field    = "temperature",
                Operator = "GreaterThan",
                Value    = "1"
            };

            var conditions = new List <ConditionApiModel> {
                condition
            };

            var newRule = new RuleApiModel()
            {
                Id          = id,
                Name        = calculation + " Faulty Test Rule " + DateTime.UtcNow.ToString("yyyyMMddHHmmss") + "-" + Guid.NewGuid(),
                Description = "Test Description",
                GroupId     = DEFAULT_CHILLERS_GROUP_ID,
                Severity    = "Info",
                Enabled     = true,
                Calculation = calculation,
                TimePeriod  = timePeriod,
                Conditions  = conditions
            };

            if (includeActions)
            {
                var parameters = new Dictionary <string, object>
                {
                    { "Notes", "Fake Note" },
                    { "Subject", "Fake Subject" }
                };
                var emails = new JArray {
                    "*****@*****.**"
                };
                parameters.Add("Recipients", emails);
                ActionApiModel action = new ActionApiModel
                {
                    Type       = "Email",
                    Parameters = parameters
                };
                newRule.Actions = new List <ActionApiModel> {
                    action
                };
            }

            var request = new HttpRequest(Constants.TELEMETRY_ADDRESS + RULES_ENDPOINT_SUFFIX);

            request.AddHeader("Content-Type", "application/json");
            request.SetContent(JsonConvert.SerializeObject(newRule));

            var response     = this.httpClient.PostAsync(request).Result;
            var ruleResponse = JsonConvert.DeserializeObject <RuleApiModel>(response.Content);

            // Update the saved rule ID
            id = ruleResponse.Id;

            // Dispose after tests run
            this.disposeRulesList.Add(ruleResponse.Id);
        }
Ejemplo n.º 27
0
        public static async Task SetupRules(IContainer container)
        {
            var ruleService = container.Resolve <IRules>();
            var logger      = container.Resolve <ILogger>();

            var allRules = ruleService.GetAllAsync().Result;

            allRules = allRules.Where(r => r.GroupId.Equals("toilet", StringComparison.OrdinalIgnoreCase));

            RuleApiModel heatingOnRule;
            RuleApiModel heatingOffRule;

            var result = allRules.Where(r => r.Name.Equals("turn-on-heating", StringComparison.OrdinalIgnoreCase));

            if (result != null && result.Count() > 0)
            {
                // heating-on rule already exists
                heatingOnRule = result.Last();
            }
            else
            {
                // Create new rules
                heatingOnRule = new RuleApiModel
                {
                    Name        = "turn-on-heating",
                    Enabled     = true,
                    Description = "Time to turn on hearing for user's smart toilet",
                    GroupId     = "toilet",
                    Severity    = "info",
                    Conditions  = new List <ConditionApiModel>
                    {
                        new ConditionApiModel
                        {
                            Field    = "time",
                            Operator = "Equals",
                            Value    = "5 PM"
                        },

                        new ConditionApiModel
                        {
                            Field    = "heatingStatus",
                            Operator = "Equals",
                            Value    = "off"
                        }
                    }
                };

                RuleApiModel heatingOnRuleResponse = null;

                try
                {
                    heatingOnRuleResponse = await ruleService.CreateAsync(heatingOnRule);

                    logger.Info($"Create heating-on rule succeeded, rule ID: {heatingOnRuleResponse.Id}", () => { });
                }
                catch (Exception e)
                {
                    logger.Error($"Create heating-on rule failed, error details: {e.Message}", () => { });
                }
            }

            result = allRules.Where(r => r.Name.Equals("turn-off-heating", StringComparison.OrdinalIgnoreCase));
            if (result != null && result.Count() > 0)
            {
                // heating-off rule already exists
                heatingOffRule = result.Last();
            }
            else
            {
                heatingOffRule = new RuleApiModel
                {
                    Name        = "turn-off-heating",
                    Enabled     = true,
                    Description = "Time to turn off hearing for user's smart toilet",
                    GroupId     = "toilet",
                    Severity    = "info",
                    Conditions  = new List <ConditionApiModel>
                    {
                        new ConditionApiModel
                        {
                            Field    = "time",
                            Operator = "Equals",
                            Value    = "5:15 PM"
                        },

                        new ConditionApiModel
                        {
                            Field    = "heatingStatus",
                            Operator = "Equals",
                            Value    = "on"
                        }
                    }
                };

                RuleApiModel heatingOffRuleResponse = null;

                try
                {
                    heatingOffRuleResponse = await ruleService.CreateAsync(heatingOffRule);

                    logger.Info($"Create heating-off rule succeeded, rule ID: {heatingOffRuleResponse.Id}", () => { });
                }
                catch (Exception e)
                {
                    logger.Error($"Create heating-off rule failed, error details: {e.Message}", () => { });
                }
            }
        }
Ejemplo n.º 28
0
 public async Task <RuleApiModel> CreateAsync(RuleApiModel rule)
 {
     return(await httpClient.PostAsync <RuleApiModel>(uri, rule, "monitoring rules"));
 }
Ejemplo n.º 29
0
        public async Task <RuleApiModel> UpsertAsync(string id, RuleApiModel rule)
        {
            string requestUri = $"{uri}/{id}";

            return(await httpClient.PutAsync <RuleApiModel>(requestUri, rule, "monitoring rules"));
        }