コード例 #1
0
        public async Task ParseQueryMiddleware_ValidQuery_DocumentIsSet()
        {
            // arrange
            Schema schema = CreateSchema();

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

            var context = new QueryContext
                          (
                schema,
                MiddlewareTools.CreateEmptyRequestServiceScope(),
                request,
                (f, s) => f.Middleware
                          );

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

            var middleware = new ParseQueryMiddleware(
                c => Task.CompletedTask,
                new DefaultQueryParser(),
                new Cache <ICachedQuery>(10),
                diagnostics,
                null);

            // act
            await middleware.InvokeAsync(context);

            // assert
            Assert.NotNull(context.Document);
            context.Document.MatchSnapshot();
        }
コード例 #2
0
        public async Task ExecuteWithNonNullVariableNull_Error()
        {
            // arrange
            var variableValues =
                new Dictionary <string, object>()
            {
                { "a", NullValueNode.Default }
            };

            Schema         schema   = CreateSchema();
            IQueryExecutor executor = schema.MakeExecutable();
            var            request  =
                QueryRequestBuilder.New()
                .SetQuery("query x($a: String!) { b(a: $a) }")
                .SetVariableValues(variableValues)
                .Create();

            // act
            IExecutionResult result = await executor.ExecuteAsync(request);

            // assert
            Assert.NotNull(result.Errors);
            result.MatchSnapshot();
        }
コード例 #3
0
 public static IReadOnlyQueryRequest Create(string query) =>
 QueryRequestBuilder.New().SetQuery(query).Create();
コード例 #4
0
        public async Task ActivePersistedQueries_SaveQuery_InvalidHash_MD5(
            HashFormat format)
        {
            // arrange
            var serviceCollection = new ServiceCollection();

            // configure presistence
            serviceCollection.AddGraphQLSchema(b => b
                                               .AddDocumentFromString("type Query { foo: String }")
                                               .AddResolver("Query", "foo", "bar"));
            serviceCollection.AddQueryExecutor(b => b
                                               .AddMD5DocumentHashProvider(format)
                                               .UseActivePersistedQueryPipeline());

            // add in-memory query storage
            serviceCollection.AddSingleton <InMemoryQueryStorage>();
            serviceCollection.AddSingleton <IReadStoredQueries>(sp =>
                                                                sp.GetRequiredService <InMemoryQueryStorage>());
            serviceCollection.AddSingleton <IWriteStoredQueries>(sp =>
                                                                 sp.GetRequiredService <InMemoryQueryStorage>());

            IServiceProvider services =
                serviceCollection.BuildServiceProvider();

            IQueryExecutor executor =
                services.GetRequiredService <IQueryExecutor>();

            var hashProvider =
                services.GetRequiredService <IDocumentHashProvider>();
            var storage = services.GetRequiredService <InMemoryQueryStorage>();

            var    query = new QuerySourceText("{ foo }");
            string hash  = hashProvider.ComputeHash(query.AsSpan());

            // act and assert
            IExecutionResult result = await executor.ExecuteAsync(
                QueryRequestBuilder.New()
                .SetQueryName(hash)
                .AddExtension("persistedQuery",
                              new Dictionary <string, object>
            {
                { hashProvider.Name, hash }
            })
                .Create());

            result.MatchSnapshot(new SnapshotNameExtension(
                                     "Query_Not_Found_" + format));

            result = await executor.ExecuteAsync(
                QueryRequestBuilder.New()
                .SetQueryName(hash)
                .SetQuery("{ foo }")
                .AddExtension("persistedQuery",
                              new Dictionary <string, object>
            {
                { hashProvider.Name, hash }
            })
                .Create());

            result.MatchSnapshot(new SnapshotNameExtension(
                                     "Query_Stored_" + format));

            result = await executor.ExecuteAsync(
                QueryRequestBuilder.New()
                .SetQueryName(hash)
                .AddExtension("persistedQuery",
                              new Dictionary <string, object>
            {
                { hashProvider.Name, hash }
            })
                .Create());

            result.MatchSnapshot(new SnapshotNameExtension(
                                     "Query_Loaded_From_Cache_" + format));
        }
コード例 #5
0
        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));
            }
        }
コード例 #6
0
        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.ArgumentValue <int>("newNumber"))
                .To("Mutation", "changeTheNumber");
            });

            DocumentNode query = Utf8GraphQLParser.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 =
                QueryRequestBuilder.New()
                .SetQuery("{ a }")
                .Create();

            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,
                (f, s) => f.Middleware
                          )
            {
                CachedQuery = new CachedQuery("{ a }", query),
                Document    = query,
                QueryKey    = "foo",
                Operation   = operation
            };

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

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

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

            // act
            await middleware.InvokeAsync(context);

            // assert
            context.Result.MatchSnapshot();
        }