Exemplo n.º 1
0
        /// <summary>
        /// Generate a single <see cref="OpenApiCallback"/> matching the given <see cref="WebHookTrigger"/>
        /// </summary>
        /// <param name="trigger"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        protected OpenApiCallback Generate(WebHookTrigger trigger, OperationFilterContext context)
        {
            var schema = context.SchemaGenerator.GenerateSchema(trigger.PayloadType, context.SchemaRepository);
            var result = new OpenApiCallback();

            result.AddPathItem(RuntimeExpression.Build($"{{$request.body#/{PseudoCamelCase(nameof(IWebHook.Callback))}}}"), new OpenApiPathItem
            {
                Operations = new Dictionary <OperationType, OpenApiOperation>
                {
                    [OperationType.Post] = new OpenApiOperation
                    {
                        OperationId = trigger.Id,
                        Description = trigger.Description,
                        Responses   = _responses,
                        Parameters  = _parameters,
                        RequestBody = new OpenApiRequestBody
                        {
                            Required = true,
                            Content  = new Dictionary <string, OpenApiMediaType>
                            {
                                ["application/json"] = new OpenApiMediaType {
                                    Schema = schema
                                }
                            }
                        },
                    }
                }
            });

            return(result);
        }
Exemplo n.º 2
0
        public override RuntimeValueNode Evaluate()
        {
            var          symbolNode = Operator.Left.Root as SymbolNode;
            Type         symbol;
            RuntimeScope assignmentScope = RuntimeScope;

            if (symbolNode == null && Operator.Left.Root is OperatorAccess)
            {
                var opAccess = Operator.Left.Root as OperatorAccess;
                symbol = opAccess.ReturnSymbol;

                var symbolValue = new RuntimeOperatorAccess(
                    opAccess,
                    RuntimeScope
                    ).Evaluate();
                assignmentScope = symbolValue.RuntimeScope;
            }
            else
            {
                symbol = symbolNode.Symbol;
            }

            var r = new RuntimeExpression(
                Operator.Right,
                RuntimeScope
                ).Evaluate();

            assignmentScope.SetValue(symbol.Name, r);
            return(r);
        }
Exemplo n.º 3
0
        public override RuntimeValueNode Evaluate()
        {
            var left = new RuntimeExpression(
                Operator.Left,
                RuntimeScope
                ).Evaluate();

            var right = (Operator.Right.Root as SymbolNode).Symbol;

            if (left.Type == right)
            {
                return(left);
            }

            var casterFunction = left.RuntimeScope.GetValue($"!as_{ right.Name }");

            var args = left.Type is PrimitiveType ? new RuntimeValueNode[] { left } : new RuntimeValueNode[] {};
            var runtimeCasterFunction = new RuntimeFunction(
                casterFunction.Value as FunctionType,
                casterFunction.RuntimeScope,
                args
                );

            return(runtimeCasterFunction.Evaluate());
        }
Exemplo n.º 4
0
        private void Compile()
        {
            if (DataContext == null)
            {
                throw ExceptionBuilder.PropertyNotInitialized("DataContext");
            }

            if (Text == null || Text.Length == 0)
            {
                throw ExceptionBuilder.PropertyNotInitialized("Text");
            }

            // Compile expression

            ClearCompiledState();
            Compiler       compiler       = new Compiler(_errorCollector);
            ExpressionNode expressionNode = compiler.CompileExpression(Text, _targetType, Scope);

            if (_errorCollector.ErrorsSeen)
            {
                IList <CompilationError> errors = _errorCollector.GetErrors();
                OnCompilationFailed(new CompilationFailedEventArgs(errors));
                throw ExceptionBuilder.ExpressionCompilationFailed(errors);
            }

            OnCompilationSucceeded(EventArgs.Empty);
            _runtimeExpression = ExpressionCompiler.CreateCompiled(expressionNode);
            ILEmitContext.CompleteILCompilation();
        }
Exemplo n.º 5
0
        public void ParseAdvancedCallbackWithReferenceShouldSucceed()
        {
            using (var stream = File.OpenRead(Path.Combine(SampleFolderPath, "advancedCallbackWithReference.yaml")))
            {
                // Act
                var openApiDoc = new OpenApiStreamReader().Read(stream, out var context);

                // Assert
                var path = openApiDoc.Paths.First().Value;
                var subscribeOperation = path.Operations[OperationType.Post];

                var callback = subscribeOperation.Callbacks["simpleHook"];

                context.ShouldBeEquivalentTo(new OpenApiDiagnostic());

                callback.ShouldBeEquivalentTo(
                    new OpenApiCallback
                {
                    Reference = new OpenApiReference
                    {
                        Type = ReferenceType.Callback,
                        Id   = "simpleHook",
                    },
                    PathItems =
                    {
                        [RuntimeExpression.Build("$request.body#/url")]
                            = new OpenApiPathItem
                            {
                                Operations                   =
                                {
                                    [OperationType.Post] =
                                        new OpenApiOperation
                                                    {
                                                    RequestBody          = new OpenApiRequestBody
                                                    {
                                                    Content          =
                                                    {
                                                    ["application/json"] = new OpenApiMediaType
                                                    {
                                                    Schema   = new OpenApiSchema
                                                    {
                                                    Type = "object"
                                                    }
                                                    }
                                                    }
                                                    },
                                                    Responses            = new OpenApiResponses
                                                    {
                                                    ["200"] = new OpenApiResponse
                                                    {
                                                    Description  = "Success"
                                                    }
                                                    }
                                                    }
                                }
                            }
                    }
                });
            }
        }
        public override RuntimeValueNode Evaluate()
        {
            var l = new RuntimeExpression(
                Operator.Left,
                RuntimeScope
                ).Evaluate();
            var r = new RuntimeExpression(
                Operator.Right,
                RuntimeScope
                ).Evaluate();

            RuntimeValueNode res;

            res = l.OpEqual(r);
            if ((bool)res.Value)
            {
                return(res);
            }
            res = l.OpSmaller(r);
            if ((bool)res.Value)
            {
                return(res);
            }
            return(res);
        }
Exemplo n.º 7
0
        public override RuntimeValueNode Evaluate()
        {
            var l = new RuntimeExpression(
                Operator.Left,
                RuntimeScope
                ).Evaluate();

            var res = l.OpEqual(WrapBool(true, l));

            if ((bool)res.Value)
            {
                return(WrapBool(true, res));
            }

            var r = new RuntimeExpression(
                Operator.Right,
                RuntimeScope
                ).Evaluate();

            res = r.OpEqual(WrapBool(true, r));
            if ((bool)res.Value)
            {
                return(WrapBool(true, res));
            }

            return(WrapBool(false, r));
        }
        public void BuildRuntimeExpressionThrowsNullOrWhiteSpace(string expression)
        {
            // Arrange & Act
            Action test = () => RuntimeExpression.Build(expression);

            // Assert
            Assert.Throws <ArgumentException>("expression", test);
        }
        public void CompositeRuntimeExpressionWithInvalidRuntimeExpressions(string expression, string invalidExpression)
        {
            // Arrange & Act
            Action test = () => RuntimeExpression.Build(expression);

            // Assert
            test.ShouldThrow <OpenApiException>().WithMessage(String.Format(SRResource.RuntimeExpressionHasInvalidFormat, invalidExpression));
        }
        public void CompareStaticRuntimeExpressionWorks(string expression)
        {
            // Arrange & Act
            var runtimeExpression1 = RuntimeExpression.Build(expression);
            var runtimeExpression2 = RuntimeExpression.Build(expression);

            // Assert
            Assert.Same(runtimeExpression1, runtimeExpression2);
        }
        public void BuildRuntimeExpressionTwiceCreatesNewEquivalentInstances(string expression)
        {
            // Arrange & Act
            var runtimeExpression1 = RuntimeExpression.Build(expression);
            var runtimeExpression2 = RuntimeExpression.Build(expression);

            // Assert
            Assert.NotSame(runtimeExpression1, runtimeExpression2);
            Assert.Equal(runtimeExpression1, runtimeExpression2);
        }
        public void BuildRuntimeExpressionThrowsInvalidFormat(string expression)
        {
            // Arrange & Act
            Action test = () => RuntimeExpression.Build(expression);

            // Assert
            OpenApiException exception = Assert.Throws <OpenApiException>(test);

            Assert.Equal(String.Format(SRResource.RuntimeExpressionHasInvalidFormat, expression), exception.Message);
        }
        public void CompositeRuntimeExpressionContainsInvalidExpressions(string expression)
        {
            // Arrange

            // Act
            Action test = () => RuntimeExpression.Build(expression);

            // Assert
            Assert.Throws <OpenApiException>(test);
        }
        public void BuildRuntimeExpressionThrowsWithDollarPrefix(string expression)
        {
            // Arrange & Act
            Action test = () => RuntimeExpression.Build(expression);

            // Assert
            OpenApiException exception = Assert.Throws <OpenApiException>(test);

            Assert.Equal(String.Format(SRResource.RuntimeExpressionMustBeginWithDollar, expression), exception.Message);
        }
Exemplo n.º 15
0
        public void ParseBasicCallbackShouldSucceed()
        {
            using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "basicCallback.yaml")))
            {
                // Arrange
                var yamlStream = new YamlStream();
                yamlStream.Load(new StreamReader(stream));
                var yamlNode = yamlStream.Documents.First().RootNode;

                var context    = new ParsingContext();
                var diagnostic = new OpenApiDiagnostic();

                var node = new MapNode(context, diagnostic, (YamlMappingNode)yamlNode);

                // Act
                var callback = OpenApiV3Deserializer.LoadCallback(node);

                // Assert
                diagnostic.ShouldBeEquivalentTo(new OpenApiDiagnostic());

                callback.ShouldBeEquivalentTo(
                    new OpenApiCallback
                {
                    PathItems =
                    {
                        [RuntimeExpression.Build("$request.body#/url")]
                            = new OpenApiPathItem
                            {
                                Operations                  =
                                {
                                    [OperationType.Post] =
                                        new OpenApiOperation
                                            {
                                            RequestBody         = new OpenApiRequestBody
                                            {
                                            Content         =
                                            {
                                            ["application/json"] = null
                                            }
                                            },
                                            Responses           = new OpenApiResponses
                                            {
                                            ["200"] = new OpenApiResponse
                                            {
                                            Description = "Success"
                                            }
                                            }
                                            }
                                }
                            }
                    }
                });
            }
        }
Exemplo n.º 16
0
        public override RuntimeValueNode Evaluate()
        {
            var l = new RuntimeExpression(
                Operator.Left,
                RuntimeScope
                ).Evaluate();
            var r = new RuntimeExpression(
                Operator.Right,
                RuntimeScope
                ).Evaluate();

            return(l.OpDivide(r));
        }
        public void BuildUrlRuntimeExpressionReturnsUrlExpression()
        {
            // Arrange
            string expression = "$url";

            // Act
            var runtimeExpression = RuntimeExpression.Build(expression);

            // Assert
            Assert.NotNull(runtimeExpression);
            var url = Assert.IsType <UrlExpression>(runtimeExpression);

            Assert.Equal(expression, url.Expression);
        }
        public void BuildStatusCodeRuntimeExpressionReturnsStatusCodeExpression()
        {
            // Arrange
            string expression = "$statusCode";

            // Act
            var runtimeExpression = RuntimeExpression.Build(expression);

            // Assert
            Assert.NotNull(runtimeExpression);
            var statusCode = Assert.IsType <StatusCodeExpression>(runtimeExpression);

            Assert.Equal(expression, statusCode.Expression);
        }
        public void BuildMethodRuntimeExpressionReturnsMethodExpression()
        {
            // Arrange
            string expression = "$method";

            // Act
            var runtimeExpression = RuntimeExpression.Build(expression);

            // Assert
            Assert.NotNull(runtimeExpression);
            var method = Assert.IsType <MethodExpression>(runtimeExpression);

            Assert.Equal(expression, method.Expression);
        }
Exemplo n.º 20
0
        /// <summary>
        /// Generate a single <see cref="OpenApiCallback"/> matching the given <see cref="WebHookTrigger"/>
        /// </summary>
        /// <param name="trigger"></param>
        /// <returns></returns>
        protected OpenApiCallback Generate(WebHookTrigger trigger)
        {
            var triggerProperties = new Dictionary <string, OpenApiSchema>(trigger.Template.Properties)
            {
                [PseudoCamelCase(DefaultWebHookSender.TimestampKey)] = new OpenApiSchema {
                    Type = "string", Format = "date-time"
                },
                [PseudoCamelCase(DefaultWebHookSender.TriggerKey)] = new OpenApiSchema {
                    Type = "string"
                },
                [PseudoCamelCase(DefaultWebHookSender.UniqueIdKey)] = new OpenApiSchema {
                    Type = "string", Format = "uuid"
                }
            };

            var result = new OpenApiCallback();

            result.AddPathItem(RuntimeExpression.Build($"{{$request.body#/{PseudoCamelCase(nameof(IWebHook.Callback))}}}"), new OpenApiPathItem
            {
                Operations = new Dictionary <OperationType, OpenApiOperation>
                {
                    [OperationType.Post] = new OpenApiOperation
                    {
                        OperationId = trigger.Id,
                        Description = trigger.Description,
                        Responses   = _responses,
                        Parameters  = _parameters,
                        RequestBody = new OpenApiRequestBody
                        {
                            Required = true,
                            Content  = new Dictionary <string, OpenApiMediaType>
                            {
                                ["application/json"] = new OpenApiMediaType
                                {
                                    Schema = new OpenApiSchema
                                    {
                                        Type       = "object",
                                        Properties = triggerProperties
                                    }
                                }
                            }
                        },
                    }
                }
            });

            return(result);
        }
Exemplo n.º 21
0
        public override RuntimeValueNode Evaluate()
        {
            var ifNode = Node as IfConditionNode;

            var condition_ = new RuntimeExpression(
                ifNode.Expression,
                RuntimeScope
                ).Evaluate();
            var condition = condition_  as RuntimeBoolValueNode;

            if ((bool)condition.Value)
            {
                return(Subscope.Evaluate());
            }
            return(null);
        }
        private static RuntimeExpressionAnyWrapper LoadRuntimeExpressionAnyWrapper(ParseNode node)
        {
            var value = node.GetScalarValue();

            if (value != null && value.StartsWith("$"))
            {
                return(new RuntimeExpressionAnyWrapper
                {
                    Expression = RuntimeExpression.Build(value)
                });
            }

            return(new RuntimeExpressionAnyWrapper
            {
                Any = node.CreateAny()
            });
        }
        public void CompositeRuntimeExpressionContainsExpression()
        {
            // Arrange
            string expression = "This is a composite expression {$url} yay";

            // Act
            var runtimeExpression = RuntimeExpression.Build(expression);

            // Assert
            Assert.NotNull(runtimeExpression);
            var response = Assert.IsType <CompositeExpression>(runtimeExpression);

            Assert.Equal(expression, response.Expression);

            var compositeExpression = runtimeExpression as CompositeExpression;

            Assert.Single(compositeExpression.ContainedExpressions);
        }
        public void CompositeRuntimeExpressionWithoutRecognizedRuntimeExpressions(string expression)
        {
            // Arrange

            // Act
            var runtimeExpression = RuntimeExpression.Build(expression);

            // Assert
            runtimeExpression.Should().NotBeNull();
            runtimeExpression.Should().BeOfType(typeof(CompositeExpression));
            var response = (CompositeExpression)runtimeExpression;

            response.Expression.Should().Be(expression);

            var compositeExpression = runtimeExpression as CompositeExpression;

            // The whole string is treated as the template without any contained expressions.
            compositeExpression.ContainedExpressions.Should().BeEmpty();
        }
Exemplo n.º 25
0
        public override RuntimeValueNode Evaluate()
        {
            var left = new RuntimeExpression(Operator.Left, RuntimeScope).Evaluate();

            if (left == null)
            {
                throw new Exceptions.NullReferenceException((Operator.Left.Root as SymbolNode)?.Symbol, DefiningToken);
            }
            if (!(left is IAccessible))
            {
                throw new Exceptions.RuntimeException($"Symbol is not accessible", left.DefiningToken);
            }

            var leftAccessible = left as IAccessible;

            return(leftAccessible.AccessMember(
                       (Operator as OperatorAccess).MemberToAccess.Name
                       ));
        }
Exemplo n.º 26
0
        /// <summary>
        /// Add a <see cref="OpenApiPathItem"/> into the <see cref="PathItems"/>.
        /// </summary>
        /// <param name="expression">The runtime expression.</param>
        /// <param name="pathItem">The path item.</param>
        public void AddPathItem(RuntimeExpression expression, OpenApiPathItem pathItem)
        {
            if (expression == null)
            {
                throw Error.ArgumentNull(nameof(expression));
            }

            if (pathItem == null)
            {
                throw Error.ArgumentNull(nameof(pathItem));
            }

            if (PathItems == null)
            {
                PathItems = new Dictionary <RuntimeExpression, OpenApiPathItem>();
            }

            PathItems.Add(expression, pathItem);
        }
        public override RuntimeValueNode Evaluate()
        {
            var l = new RuntimeExpression(
                Operator.Left,
                RuntimeScope
                ).Evaluate();
            var r = new RuntimeExpression(
                Operator.Right,
                RuntimeScope
                ).Evaluate();

            var res = l.OpEqual(r);

            return(new RuntimeBoolValueNode(
                       new Parser.Syntax.Expressions.Nodes.Value.BoolValueNode(
                           res.DefiningToken,
                           !(bool)res.Value
                           ),
                       res.RuntimeScope
                       ));
        }
        public void CompositeRuntimeExpressionContainsMultipleExpressions()
        {
            // Arrange
            string expression = "This is a composite expression {$url} yay and {$request.header.foo}";

            // Act
            var runtimeExpression = RuntimeExpression.Build(expression);

            // Assert
            Assert.NotNull(runtimeExpression);
            var response = Assert.IsType <CompositeExpression>(runtimeExpression);

            Assert.Equal(expression, response.Expression);

            var compositeExpression = runtimeExpression as CompositeExpression;

            Assert.Equal(2, compositeExpression.ContainedExpressions.Count);

            Assert.IsType <UrlExpression>(compositeExpression.ContainedExpressions.First());
            Assert.IsType <RequestExpression>(compositeExpression.ContainedExpressions.Last());
        }
        public void CompositeRuntimeExpressionForWebHook()
        {
            // Arrange
            string expression = "http://notificationServer.com?transactionId={$request.body#/id}&email={$request.body#/email}";

            // Act
            var runtimeExpression = RuntimeExpression.Build(expression);

            // Assert
            Assert.NotNull(runtimeExpression);
            var response = Assert.IsType <CompositeExpression>(runtimeExpression);

            Assert.Equal(expression, response.Expression);

            var compositeExpression = runtimeExpression as CompositeExpression;

            Assert.Equal(2, compositeExpression.ContainedExpressions.Count);

            Assert.IsType <RequestExpression>(compositeExpression.ContainedExpressions.First());
            Assert.IsType <RequestExpression>(compositeExpression.ContainedExpressions.Last());
        }
        public void BuildResponseRuntimeExpressionReturnsResponseExpression()
        {
            // Arrange
            string expression = "$response.body#/status";

            // Act
            var runtimeExpression = RuntimeExpression.Build(expression);

            // Assert
            Assert.NotNull(runtimeExpression);
            var response = Assert.IsType <ResponseExpression>(runtimeExpression);

            Assert.Equal(expression, response.Expression);

            Assert.Equal("body#/status", response.Source.Expression);
            Assert.NotNull(response.Source);

            var body = Assert.IsType <BodyExpression>(response.Source);

            Assert.Equal("/status", body.Fragment);
            Assert.Equal("body#/status", body.Expression);
        }