Ejemplo n.º 1
0
        public async Task DefaultValueIsInputObject()
        {
            // arrange
            var query = FileResource.Open("IntrospectionQuery.graphql");
            IRequestExecutor executor = SchemaBuilder.New()
                                        .AddQueryType <BarType>()
                                        .ModifyOptions(o => o.RemoveUnreachableTypes = false)
                                        .Create()
                                        .MakeExecutable();

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

            // assert
            Assert.Null(result.Errors);
            result.MatchSnapshot();
        }
Ejemplo n.º 2
0
        protected async Task <IExecutionResult> ExecuteSingleAsync(
            HttpContext context,
            IRequestExecutor requestExecutor,
            IHttpRequestInterceptor requestInterceptor,
            GraphQLRequest request,
            OperationType[]?allowedOperations = null)
        {
            QueryRequestBuilder requestBuilder = QueryRequestBuilder.From(request);

            requestBuilder.SetAllowedOperations(allowedOperations);

            await requestInterceptor.OnCreateAsync(
                context, requestExecutor, requestBuilder, context.RequestAborted);

            return(await requestExecutor.ExecuteAsync(
                       requestBuilder.Create(), context.RequestAborted));
        }
        public async Task Create_Or_BooleanEqual_Expression()
        {
            // arrange
            IRequestExecutor tester =
                await _fixture.GetOrCreateSchema <Foo, FooFilterType>(_fooEntitiesCypher);

            // act
            const string query1 =
                "{ root(where: {or: [{ bar: { eq: true}}, { bar: { eq: false}}]} ){ bar }}";
            IExecutionResult res1 = await tester.ExecuteAsync(
                QueryRequestBuilder.New()
                .SetQuery(query1)
                .Create());

            // assert
            res1.MatchDocumentSnapshot("or");
        }
        public async Task Intercept_Resolver_Result_With_Listener()
        {
            // arrange
            var listener = new TestListener();
            IRequestExecutor executor = await CreateExecutorAsync(c => c
                                                                  .AddDiagnosticEventListener(_ => listener)
                                                                  .AddStarWarsTypes()
                                                                  .Services
                                                                  .AddStarWarsRepositories());

            // act
            IExecutionResult result = await executor.ExecuteAsync("{ hero { name } }");

            // assert
            Assert.Null(result.Errors);
            Assert.Collection(listener.Results, r => Assert.IsType <Droid>(r));
        }
Ejemplo n.º 5
0
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        foreach (NameString schemaName in _schemaNames)
        {
            // initialize services
            IRequestExecutor executor =
                await _executorResolver.GetRequestExecutorAsync(schemaName, stoppingToken);

            // initialize pipeline with warmup request
            IQueryRequest warmupRequest = QueryRequestBuilder.New()
                                          .SetQuery("{ __typename }")
                                          .AllowIntrospection()
                                          .Create();

            await executor.ExecuteAsync(warmupRequest, stoppingToken);
        }
    }
        public async Task AddSynchronizedService()
        {
            Snapshot.FullName();

            IRequestExecutor executor =
                await new ServiceCollection()
                .AddSingleton <SayHelloService>()
                .AddGraphQL()
                .AddQueryType <QueryWellKnownService>()
                .RegisterService <SayHelloService>(ServiceKind.Synchronized)
                .ModifyRequestOptions(o => o.IncludeExceptionDetails = true)
                .BuildRequestExecutorAsync();

            Assert.False(executor.Schema.QueryType.Fields["sayHello"].IsParallelExecutable);

            await executor.ExecuteAsync("{ sayHello }").MatchSnapshotAsync();
        }
Ejemplo n.º 7
0
        public async Task AutoMerge_Execute()
        {
            // arrange
            using var cts = new CancellationTokenSource(20_000);
            NameString         configurationName = "C" + Guid.NewGuid().ToString("N");
            IHttpClientFactory httpClientFactory = CreateDefaultRemoteSchemas(configurationName);

            IDatabase database = _connection.GetDatabase();

            while (!cts.IsCancellationRequested)
            {
                if (await database.SetLengthAsync(configurationName.Value) == 4)
                {
                    break;
                }

                await Task.Delay(150, cts.Token);
            }

            IRequestExecutor executor =
                await new ServiceCollection()
                .AddSingleton(httpClientFactory)
                .AddGraphQL()
                .AddQueryType(d => d.Name("Query"))
                .AddRemoteSchemasFromRedis(configurationName, _ => _connection)
                .BuildRequestExecutorAsync(cancellationToken: cts.Token);

            // act
            IExecutionResult result = await executor.ExecuteAsync(
                @"{
                    me {
                        id
                        name
                        reviews {
                            body
                            product {
                                upc
                            }
                        }
                    }
                }",
                cts.Token);

            // assert
            result.ToJson().MatchSnapshot();
        }
        public async Task InputType_Literal_CannotBeParsed()
        {
            // arrange
            var schema = Schema.Create(t =>
            {
                t.RegisterQueryType <QueryType>();
            });

            IRequestExecutor executor = schema.MakeExecutable();

            // act
            IExecutionResult result = await executor.ExecuteAsync(
                "{ nameToString(name: \"  \") }");

            // assert
            result.MatchSnapshot();
        }
        public async Task OutputType_ClrValue_CannotBeConverted()
        {
            // arrange
            var schema = Schema.Create(t =>
            {
                t.RegisterQueryType <QueryType>();
            });

            IRequestExecutor executor = schema.MakeExecutable();

            // act
            IExecutionResult result = await executor.ExecuteAsync(
                "{ stringToName(name: \"  \") }");

            // assert
            result.MatchSnapshot();
        }
Ejemplo n.º 10
0
        public async Task GetItems_With_Paging__DescSorting_AllItems_Are_Returned_DescSorted()
        {
            // arrange
            IServiceProvider services = new ServiceCollection()
                                        .AddSingleton <IMongoCollection <Parent> >(sp =>
            {
                IMongoDatabase database = _mongoResource.CreateDatabase();
                IMongoCollection <Parent> collection = database.GetCollection <Parent>("col");
                collection.InsertMany(new[]
                {
                    new Parent {
                        Model = new Model {
                            Foo = "abc", Bar = 1, Baz = true
                        }
                    },
                    new Parent {
                        Model = new Model {
                            Foo = "def", Bar = 2, Baz = false
                        }
                    }
                });
                return(collection);
            })
                                        .AddGraphQL()
                                        .AddQueryType <QueryType>()
                                        .Services
                                        .BuildServiceProvider();

            IRequestExecutor executor =
                await services.GetRequiredService <IRequestExecutorResolver>()
                .GetRequestExecutorAsync();

            IReadOnlyQueryRequest request = QueryRequestBuilder.New()
                                            .SetQuery(
                "{ paging(order_by: { model: { foo: DESC } }) " +
                "{ nodes { model { foo } } } }")
                                            .Create();

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

            // assert
            Assert.Null(result.Errors);
            result.MatchSnapshot();
        }
Ejemplo n.º 11
0
        public async Task AutoMerge_Execute_Inline_Fragment()
        {
            // arrange
            IHttpClientFactory httpClientFactory =
                Context.CreateDefaultRemoteSchemas();

            IRequestExecutor executor =
                await new ServiceCollection()
                .AddSingleton(httpClientFactory)
                .AddGraphQL()
                .AddRemoteSchema(Context.ContractSchema)
                .AddRemoteSchema(Context.CustomerSchema)
                .AddTypeExtensionsFromString(
                    @"extend type Customer {
                            contracts: [Contract!]
                                @delegate(
                                    schema: ""contract"",
                                    path: ""contracts(customerId:$fields:id)"")
                        }")
                .ModifyRequestOptions(o => o.IncludeExceptionDetails = true)
                .BuildRequestExecutorAsync();

            // act
            IExecutionResult result = await executor.ExecuteAsync(
                @"{
                    customer(id: ""Q3VzdG9tZXIKZDE="") {
                        name
                        consultant {
                            name
                        }
                        contracts {
                            id
                            ... on LifeInsuranceContract {
                                premium
                            }
                            ... on SomeOtherContract {
                                expiryDate
                            }
                        }
                    }
                }");

            // assert
            result.MatchSnapshot();
        }
Ejemplo n.º 12
0
    public async Task PayloadMiddleware_Should_TransformPayload_When_ItIsATask()
    {
        // Arrange
        IRequestExecutor executor =
            await new ServiceCollection()
            .AddGraphQL()
            .AddQueryType <Query>()
            .AddMutationType <MutationTask>()
            .EnableMutationConventions()
            .BuildRequestExecutorAsync();

        // Act
        IExecutionResult res = await executor
                               .ExecuteAsync(@"
                    mutation {
                        createTask {
                            foo {
                                bar
                            }
                        }
                        createValueTask {
                            foo {
                                bar
                            }
                        }
                        createTaskNoName {
                            foo {
                                bar
                            }
                        }
                        createValueTaskNoName {
                            foo {
                                bar
                            }
                        }
                    }
                ");

        // Assert
        res.ToJson().MatchSnapshot();
        SnapshotFullName fullName     = Snapshot.FullName();
        SnapshotFullName snapshotName = new(fullName.Filename + "_schema", fullName.FolderPath);

        executor.Schema.Print().MatchSnapshot(snapshotName);
    }
Ejemplo n.º 13
0
        public async Task AutoMerge_AddLocal_Field_Execute()
        {
            // arrange
            NameString         configurationName = "C" + Guid.NewGuid().ToString("N");
            IHttpClientFactory httpClientFactory = CreateDefaultRemoteSchemas(configurationName);

            IDatabase database = _connection.GetDatabase();

            for (var i = 0; i < 10; i++)
            {
                if (await database.SetLengthAsync(configurationName.Value) == 4)
                {
                    break;
                }

                await Task.Delay(150);
            }

            IRequestExecutor executor =
                await new ServiceCollection()
                .AddSingleton(httpClientFactory)
                .AddGraphQL(configurationName)
                .AddQueryType(d => d.Name("Query").Field("local").Resolve("I am local."))
                .AddRemoteSchemasFromRedis(configurationName, s => _connection)
                .BuildRequestExecutorAsync(configurationName);

            // act
            IExecutionResult result = await executor.ExecuteAsync(
                @"{
                    me {
                        id
                        name
                        reviews {
                            body
                            product {
                                upc
                            }
                        }
                    }
                    local
                }");

            // assert
            result.ToJson().MatchSnapshot();
        }
        public static Task <IExecutionResult> ExecuteAsync(
            this IRequestExecutor executor,
            IReadOnlyQueryRequest request)
        {
            if (executor is null)
            {
                throw new ArgumentNullException(nameof(executor));
            }

            if (request is null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            return(executor.ExecuteAsync(
                       request,
                       CancellationToken.None));
        }
Ejemplo n.º 15
0
        public async Task UseDataLoader_Schema_GroupedDataloader_Multiple_Execute()
        {
            // arrange
            IRequestExecutor executor = SchemaBuilder.New()
                                        .AddQueryType <Query>(
                x => x.BindFieldsExplicitly()
                .Field(y => y.Multiple)
                .UseDataloader <TestGroupedLoader>())
                                        .Create()
                                        .MakeExecutable();

            // act
            IExecutionResult result = await executor.ExecuteAsync(
                QueryRequestBuilder.Create(@"{ multiple { id }}"));

            // assert
            result.ToJson().MatchSnapshot();
        }
Ejemplo n.º 16
0
        public async Task Integration_List_ListValues_Object()
        {
            // arrange
            IRequestExecutor executor = await new ServiceCollection()
                                        .AddGraphQL()
                                        .AddQueryType <Query>()
                                        .BuildRequestExecutorAsync();

            // act
            IExecutionResult result = await executor.ExecuteAsync(
                QueryRequestBuilder
                .New()
                .SetQuery("{ objects(values: [{ bar: 1 }, { bar: 2 }]) { bar } }")
                .Create());

            // assert
            result.ToJson().MatchSnapshot();
        }
Ejemplo n.º 17
0
    public async Task ErrorMiddleware_Should_MapMultipleFactories_When_InterfaceIsUsed()
    {
        // Arrange
        IRequestExecutor executor =
            await BuildSchemaAsync(
                () => throw new NullReferenceException(),
                field => field.Error <CustomErrorPayloadErrorFactory>());

        // Act
        IExecutionResult res = await executor.ExecuteAsync(_query);

        // Assert
        res.ToJson().MatchSnapshot();
        SnapshotFullName fullName     = Snapshot.FullName();
        SnapshotFullName snapshotName = new(fullName.Filename + "_schema", fullName.FolderPath);

        executor.Schema.Print().MatchSnapshot(snapshotName);
    }
        public async Task JustTotalCount()
        {
            Snapshot.FullName();

            IRequestExecutor executor = await CreateSchemaAsync();


            IExecutionResult result = await executor
                                      .ExecuteAsync(
                @"
                {
                    foos {
                        totalCount
                    }
                }");

            result.MatchDocumentSnapshot();
        }
        public async Task List_NonNullElementHasError(string fieldType)
        {
            // arrange
            IRequestExecutor executor = CreateExecutor();

            IReadOnlyQueryRequest request =
                QueryRequestBuilder.New()
                .SetQuery($"{{ foo {{ {fieldType} {{ c }} }} }}")
                .AddProperty("b", null)
                .Create();

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

            // assert
            result.MatchSnapshot(fieldType);
        }
Ejemplo n.º 20
0
        public async Task ExecuteQueryThatReturnsId_IdShouldBeOpaque()
        {
            // arrange
            var schema = Schema.Create(t =>
            {
                t.RegisterQueryType <SomeQuery>();
                t.UseGlobalObjectIdentifier();
            });

            IRequestExecutor executor = schema.MakeExecutable();

            // act
            IExecutionResult result =
                await executor.ExecuteAsync("{ id string }");

            // assert
            result.ToJson().MatchSnapshot();
        }
Ejemplo n.º 21
0
        public async Task SchemaBuilder_AddResolver()
        {
            // arrange
            var sourceText = "type Query { hello: String }";

            // act
            ISchema schema = SchemaBuilder.New()
                             .AddDocumentFromString(sourceText)
                             .AddResolver("Query", "hello", () => "World")
                             .Create();

            // assert
            IRequestExecutor executor = schema.MakeExecutable();
            IExecutionResult result   =
                await executor.ExecuteAsync("{ hello }");

            result.ToJson().MatchSnapshot();
        }
        public static Task <IExecutionResult> ExecuteAsync(
            this IRequestExecutor executor,
            Action <IQueryRequestBuilder> buildRequest)
        {
            if (executor is null)
            {
                throw new ArgumentNullException(nameof(executor));
            }

            if (buildRequest is null)
            {
                throw new ArgumentNullException(nameof(buildRequest));
            }

            return(executor.ExecuteAsync(
                       buildRequest,
                       CancellationToken.None));
        }
Ejemplo n.º 23
0
    public async Task ErrorMiddleware_Should_MapException_WhenRegistered()
    {
        // Arrange
        IRequestExecutor executor =
            await BuildSchemaAsync(
                () => throw new InvalidOperationException(),
                field => field.Error <CustomError>());

        // Act
        IExecutionResult res = await executor.ExecuteAsync(_query);

        // Assert
        res.ToJson().MatchSnapshot();
        SnapshotFullName fullName     = Snapshot.FullName();
        SnapshotFullName snapshotName = new(fullName.Filename + "_schema", fullName.FolderPath);

        executor.Schema.Print().MatchSnapshot(snapshotName);
    }
        public async Task Nullables_Are_Set_And_NonNullables_Not_Are_Set()
        {
            Snapshot.FullName();

            IRequestExecutor executor = await CreateSchemaAsync();

            var user = new ObjectValueNode(
                new ObjectFieldNode("surname", "Smith"));

            IReadOnlyQueryRequest request =
                QueryRequestBuilder
                .New()
                .SetQuery("mutation($user: UserInput!) { addUser(user: $user) }")
                .SetVariableValue("user", user)
                .Create();

            await executor.ExecuteAsync(request).MatchSnapshotAsync();
        }
Ejemplo n.º 25
0
        public async Task SchemaBuilder_BindType()
        {
            // arrange
            string sourceText = "type Query { hello: String }";

            // act
            ISchema schema = SchemaBuilder.New()
                             .AddDocumentFromString(sourceText)
                             .BindComplexType <Query>()
                             .Create();

            // assert
            IRequestExecutor executor = schema.MakeExecutable();
            IExecutionResult result   =
                await executor.ExecuteAsync("{ hello }");

            result.ToJson().MatchSnapshot();
        }
Ejemplo n.º 26
0
        public async Task ApolloTracing_OnDemand_NoHeader()
        {
            // arrange
            IRequestExecutor executor = await CreateExecutorAsync(c => c
                                                                  .AddDocumentFromString(
                                                                      @"
                    type Query {
                        a: String
                    }")
                                                                  .AddResolver("Query", "a", () => "hello world a")
                                                                  .AddApolloTracing(TracingPreference.OnDemand, new TestTimestampProvider()));

            // act
            IExecutionResult result = await executor.ExecuteAsync("{ a }");

            // assert
            result.ToJson().MatchSnapshot();
        }
Ejemplo n.º 27
0
        public async Task Handle_Stop_Subscription()
        {
            // arrange
            var connection   = new SocketConnectionMock();
            var subscription = new Mock <ISubscription>();

            IRequestExecutor executor = await new ServiceCollection()
                                        .AddGraphQL()
                                        .AddStarWarsTypes()
                                        .AddStarWarsRepositories()
                                        .AddInMemorySubscriptions()
                                        .Services
                                        .BuildServiceProvider()
                                        .GetRequiredService <IRequestExecutorResolver>()
                                        .GetRequestExecutorAsync();

            var stream =
                (IResponseStream)await executor.ExecuteAsync(
                    "subscription { onReview(episode: NEW_HOPE) { stars } }");

            var interceptor         = new SocketSessionInterceptorMock();
            var subscriptionSession = new SubscriptionSession(
                new CancellationTokenSource(),
                interceptor,
                connection,
                stream,
                subscription.Object,
                new NoopExecutionDiagnosticEvents(),
                "123");

            connection.Subscriptions.Register(subscriptionSession);

            var handler = new DataStopMessageHandler();
            var message = new DataStopMessage("123");

            // act
            await handler.HandleAsync(
                connection,
                message,
                CancellationToken.None);

            // assert
            Assert.Empty(connection.Subscriptions);
        }
Ejemplo n.º 28
0
        public async Task Execute_CoordinateZ_NotRaiseException()
        {
            // arrange
            LineString lineString = NtsGeometryServices.Instance
                                    .CreateGeometryFactory(4326)
                                    .CreateLineString(new[]
            {
                new Coordinate(30, 10),
                new Coordinate(10, 30),
                new CoordinateZ(10, 30, 12),
                new Coordinate(40, 40)
            });

            ISchema schema = SchemaBuilder.New()
                             .AddDocumentFromString(
                @"
                        type Query {
                            test: GeoJSONLineStringType
                        }
                    ")
                             .AddSpatialTypes(x => x
                                              .DefaultSrid(4326)
                                              .AddCoordinateSystemFromString(4326, WKT4326)
                                              .AddCoordinateSystemFromString(26918, WKT26918))
                             .AddResolver("Query", "test", _ => lineString)
                             .TryAddTypeInterceptor <RoundTypeIntercetor>()
                             .Create();

            IRequestExecutor executor = schema.MakeExecutable();

            // act
            IExecutionResult result = await executor.ExecuteAsync(
                @"
                {
                    test(crs: 26918) {
                        type
                        crs
                        coordinates
                    }
                }");

            // assert
            result.ToJson().MatchSnapshot();
        }
Ejemplo n.º 29
0
        public async Task NodeResolver_ResolveNode()
        {
            // arrange
            ISchema schema = SchemaBuilder.New()
                             .EnableRelaySupport()
                             .AddType <EntityType>()
                             .AddQueryType <Query>()
                             .Create();

            IRequestExecutor executor = schema.MakeExecutable();

            // act
            IExecutionResult result = await executor.ExecuteAsync(
                "{ node(id: \"RW50aXR5CmRmb28=\")  " +
                "{ ... on Entity { id name } } }");

            // assert
            result.ToJson().MatchSnapshot();
        }
Ejemplo n.º 30
0
        public async Task Output_Return_Object()
        {
            // arrange
            ISchema schema = SchemaBuilder.New()
                             .AddQueryType(d => d
                                           .Name("Query")
                                           .Field("foo")
                                           .Type <AnyType>()
                                           .Resolve(_ => new Foo()))
                             .Create();

            IRequestExecutor executor = schema.MakeExecutable();

            // act
            IExecutionResult result = await executor.ExecuteAsync("{ foo }");

            // assert
            result.ToJson().MatchSnapshot();
        }