Exemplo n.º 1
0
        public async Task RooValueIsRegisterdAsService()
        {
            // arrange
            var services = new DictionaryServiceProvider(
                typeof(DisposableQuery), new DisposableQuery());

            Schema schema = Schema.Create(c =>
            {
                c.RegisterQueryType <DisposableQuery>();
            });

            var request = new QueryRequest("{ isDisposable }").ToReadOnly();

            var context = new QueryContext(
                schema,
                services.CreateRequestServiceScope(),
                request);

            context.Document = Parser.Default.Parse(request.Query);

            var middleware = new ResolveOperationMiddleware(
                c => Task.CompletedTask, null);

            // act
            await middleware.InvokeAsync(context);

            // assert
            DisposableQuery query = Assert.IsType <DisposableQuery>(
                context.Operation.RootValue);

            Assert.False(query.IsDisposed);
        }
Exemplo n.º 2
0
        public async Task ProvidedRootValueTakesPrecedenceOverService()
        {
            // arrange
            var services = new DictionaryServiceProvider(
                typeof(DisposableQuery), new DisposableQuery());

            Schema schema = Schema.Create(c =>
            {
                c.RegisterQueryType <DisposableQuery>();
            });

            var rootValue = new DisposableQuery();

            var request = new QueryRequest("{ isDisposable }")
            {
                InitialValue = rootValue
            }.ToReadOnly();

            var context = new QueryContext(
                schema,
                services.CreateRequestServiceScope(),
                request);

            context.Document = Parser.Default.Parse(request.Query);

            var middleware = new ResolveOperationMiddleware(
                c => Task.CompletedTask, null);

            // act
            await middleware.InvokeAsync(context);

            // assert
            Assert.True(object.ReferenceEquals(
                            rootValue, context.Operation.RootValue));
        }
        public async Task ExecuteOperationMiddleware_Mutation_ExecutedSerially()
        {
            // arrange
            var state = 0;

            var schema = Schema.Create(
                FileResource.Open("MutationExecutionSchema.graphql"),
                cnf =>
            {
                cnf.BindResolver(() => state)
                .To("Query", "state");
                cnf.BindResolver(() => state)
                .To("CurrentState", "theNumber");
                cnf.BindResolver(
                    ctx => state = ctx.Argument <int>("newNumber"))
                .To("Mutation", "changeTheNumber");
            });

            DocumentNode query = Parser.Default.Parse(
                FileResource.Open("MutationExecutionQuery.graphql"));

            OperationDefinitionNode operationNode = query.Definitions
                                                    .OfType <OperationDefinitionNode>()
                                                    .FirstOrDefault();

            var operation = new Operation
                            (
                query,
                operationNode,
                new VariableValueBuilder(
                    schema,
                    operationNode)
                .CreateValues(new Dictionary <string, object>()),
                schema.MutationType,
                null
                            );

            IReadOnlyQueryRequest request = new QueryRequest("{ a }");

            var observable = new DiagnosticListener("Foo");

            var services = new DictionaryServiceProvider(
                new KeyValuePair <Type, object>(
                    typeof(IErrorHandler),
                    ErrorHandler.Default),
                new KeyValuePair <Type, object>(
                    typeof(DiagnosticListener),
                    observable),
                new KeyValuePair <Type, object>(
                    typeof(DiagnosticSource),
                    observable));

            var context = new QueryContext
                          (
                schema,
                services.CreateRequestServiceScope(),
                request,
                fs => fs.Field.Middleware
                          )
            {
                Document  = query,
                Operation = operation
            };

            var options          = new QueryExecutionOptions();
            var strategyResolver = new ExecutionStrategyResolver(options);

            var diagnostics = new QueryExecutionDiagnostics(
                new DiagnosticListener("Foo"),
                new IDiagnosticObserver[0],
                TracingPreference.Never);

            var middleware = new ExecuteOperationMiddleware(
                c => Task.CompletedTask,
                strategyResolver,
                new Cache <DirectiveMiddlewareCompiler>(10),
                diagnostics);

            // act
            await middleware.InvokeAsync(context);

            // assert
            Assert.NotNull(context.Result);
            context.Result.Snapshot();
        }
        public async Task ValidateMaxComplexityWithMiddlewareWithObjectsAndVar(
            int count, bool valid)
        {
            // arrange
            var schema = Schema.Create(
                @"
                type Query {
                    foo(i: FooInput): String
                        @cost(complexity: 5 multipliers: [""i.index""])
                }

                input FooInput {
                    index : Int
                }
                ",
                c =>
            {
                c.BindResolver(() => "Hello")
                .To("Query", "foo");
            });

            var options = new Mock <IValidateQueryOptionsAccessor>();

            options.SetupGet(t => t.MaxOperationComplexity).Returns(20);
            options.SetupGet(t => t.UseComplexityMultipliers).Returns(true);

            DocumentNode query = Utf8GraphQLParser.Parse(
                "query f($i:Int) { foo(i: { index:$i }) }");

            OperationDefinitionNode operationNode = query.Definitions
                                                    .OfType <OperationDefinitionNode>()
                                                    .FirstOrDefault();

            var operation = new Operation
                            (
                query,
                operationNode,
                new VariableValueBuilder(
                    schema,
                    operationNode)
                .CreateValues(new Dictionary <string, object>
            {
                { "i", count }
            }),
                schema.QueryType,
                null
                            );

            IReadOnlyQueryRequest request =
                QueryRequestBuilder.New()
                .SetQuery("{ a }")
                .Create();

            var services = new DictionaryServiceProvider(
                new KeyValuePair <Type, object>(
                    typeof(IErrorHandler),
                    ErrorHandler.Default));

            var context = new QueryContext
                          (
                schema,
                services.CreateRequestServiceScope(),
                request,
                (f, s) => f.Middleware
                          )
            {
                Document  = query,
                Operation = operation
            };

            var middleware = new MaxComplexityMiddleware(
                c => Task.CompletedTask,
                options.Object,
                null);

            // act
            await middleware.InvokeAsync(context);

            // assert
            if (valid)
            {
                Assert.Null(context.Result);
            }
            else
            {
                context.Result.MatchSnapshot(
                    new SnapshotNameExtension("complexity", count));
            }
        }
        public async Task ValidateMaxComplexityWithMiddleware(
            int count, bool valid)
        {
            // arrange
            var schema = Schema.Create(
                @"
                type Query {
                    foo(i: Int): String
                        @cost(complexity: 5 multipliers: [""i""])
                }
                ",
                c =>
            {
                c.BindResolver(() => "Hello")
                .To("Query", "foo");
            });

            var options = new Mock <IValidateQueryOptionsAccessor>();

            options.SetupGet(t => t.MaxOperationComplexity).Returns(20);
            options.SetupGet(t => t.UseComplexityMultipliers).Returns(true);

            DocumentNode query = Parser.Default.Parse(
                "{ foo(i:" + count + ") }");

            OperationDefinitionNode operationNode = query.Definitions
                                                    .OfType <OperationDefinitionNode>()
                                                    .FirstOrDefault();

            var operation = new Operation
                            (
                query,
                operationNode,
                new VariableValueBuilder(
                    schema,
                    operationNode)
                .CreateValues(new Dictionary <string, object>()),
                schema.QueryType,
                null
                            );

            IReadOnlyQueryRequest request = new QueryRequest("{ a }");

            var services = new DictionaryServiceProvider(
                new KeyValuePair <Type, object>(
                    typeof(IErrorHandler),
                    ErrorHandler.Default));

            var context = new QueryContext
                          (
                schema,
                services.CreateRequestServiceScope(),
                request,
                fs => fs.Field.Middleware
                          )
            {
                Document  = query,
                Operation = operation,
            };

            var middleware = new MaxComplexityMiddleware(
                c => Task.CompletedTask,
                options.Object,
                null);

            // act
            await middleware.InvokeAsync(context);

            // assert
            if (valid)
            {
                Assert.Null(context.Result);
            }
            else
            {
                context.Result.Snapshot(
                    "ValidateMaxComplexityWithMiddleware" +
                    count);
            }
        }