public void NonNullEnumsSerializeCorrectlyFromVariables() { // arrange var query = @" query getHero($episode: Episode!) { hero(episode: $episode) { name } }"; var variables = new Dictionary <string, object> { ["episode"] = "NEWHOPE" }; IQueryExecutor executor = CreateSchema().MakeExecutable(); // act IExecutionResult result = executor.Execute(query, variables); // assert result.MatchSnapshot(); }
public async Task DescriptionsAreCorrectlyRead() { // arrange string source = FileResource.Open( "schema_with_multiline_descriptions.graphql"); string query = FileResource.Open( "IntrospectionQuery.graphql"); // act ISchema schema = Schema.Create( source, c => { c.Options.StrictValidation = false; c.Use(next => context => next(context)); }); // assert IQueryExecutor executor = schema.MakeExecutable(); IExecutionResult result = await executor.ExecuteAsync(query); result.MatchSnapshot(); }
public async Task MultiPolygon_Execution_Output() { // arrange ISchema schema = SchemaBuilder.New() .AddConvention <INamingConventions, MockNamingConvention>() .BindClrType <Coordinate, GeoJsonPositionType>() .AddType <GeoJsonMultiPolygonType>() .AddQueryType( d => d .Name("Query") .Field("test") .Resolve(_geom)) .Create(); IRequestExecutor executor = schema.MakeExecutable(); // act IExecutionResult result = await executor.ExecuteAsync( "{ test { type coordinates bbox crs }}"); // assert result.MatchSnapshot(); }
public static async Task ExpectError( string query, TestConfiguration?configuration, params Action <IError>[] elementInspectors) { // arrange IRequestExecutor executor = await CreateExecutorAsync(configuration); IReadOnlyQueryRequest request = CreateRequest(configuration, query); // act IExecutionResult result = await executor.ExecuteAsync(request, default); // assert Assert.NotNull(result.Errors); if (elementInspectors.Length > 0) { Assert.Collection(result.Errors, elementInspectors); } result.MatchSnapshot(); }
public async Task ExecuteWithNonNullVariableInvalidType_Error() { // arrange var variableValues = new Dictionary <string, object>() { { "a", new IntValueNode(123) } }; 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(); }
public async Task Schema_Integration_Test() { // arrange ISchema schema = SchemaBuilder.New() .AddQueryType(d => { d.Name("Query"); d.Field("foo").Resolver("bar"); d.Field("baz").Resolver(DateTimeOffset.UtcNow); }) .Create(); IQueryExecutor executor = schema.MakeExecutable(); // act IExecutionResult result = await executor.ExecuteAsync( QueryRequestBuilder.New() .SetQuery("{ foo baz }") .Create()); // assert result.MatchSnapshot(matchOptions => matchOptions.IgnoreField("Data.baz")); }
public async Task SchemaDescription() { // arrange string sourceText = "\"\"\"\nMy Schema Description\n\"\"\"" + "schema" + "{ query: Foo }" + "type Foo { bar: String }"; // act ISchema schema = Schema.Create( sourceText, c => { c.Use(next => context => next(context)); }); // assert IQueryExecutor executor = schema.MakeExecutable(); IExecutionResult result = await executor.ExecuteAsync("{ __schema { description } }"); result.MatchSnapshot(); }
public async Task ExecuteWithNonNullVariableInvalidType_Error() { // arrange var variableValues = new Dictionary <string, object>() { { "a", new IntValueNode(123) } }; Schema schema = CreateSchema(); var executor = QueryExecutionBuilder.BuildDefault(schema); var request = new QueryRequest( "query x($a: String!) { b(a: $a) }") { VariableValues = variableValues }; // act IExecutionResult result = await executor.ExecuteAsync(request); // assert Assert.NotNull(result.Errors); result.MatchSnapshot(); }
public async Task ContextDataIsPassedAllongCorrectly() { // arrange bool allDataIsPassedAlong = false; ISchema schema = Schema.Create( "type Query { foo: String }", c => c.Use(next => context => { context.ContextData["field"] = "abc"; context.Result = context.ContextData["request"]; return(Task.CompletedTask); })); IQueryExecutor executor = schema.MakeExecutable( b => b.UseDefaultPipeline() .Use(next => context => { if (context.ContextData.ContainsKey("request") && context.ContextData.ContainsKey("field")) { allDataIsPassedAlong = true; } return(Task.CompletedTask); })); // act IExecutionResult result = await executor.ExecuteAsync( QueryRequestBuilder.New() .SetQuery("{ foo }") .SetProperty("request", "123") .Create()); // assert Assert.True(allDataIsPassedAlong); result.MatchSnapshot(); }
public async Task Custom_Scalar_Delegated_Argument() { // arrange IHttpClientFactory clientFactory = CreateRemoteSchemas(); var serviceCollection = new ServiceCollection(); serviceCollection.AddSingleton(clientFactory); serviceCollection.AddStitchedSchema(builder => builder .AddSchemaFromHttp("special") .AddExtensionsFromString("extend type Query { custom_scalar_stitched(bar: MyCustomScalarValue): MyCustomScalarValue @delegate(schema: \"special\", path: \"custom_scalar(bar: $arguments:bar)\") }") .AddSchemaConfiguration(c => { c.RegisterType <MyCustomScalarType>(); })); IServiceProvider services = serviceCollection.BuildServiceProvider(); IQueryExecutor executor = services .GetRequiredService <IQueryExecutor>(); IExecutionResult result = null; // act using (IServiceScope scope = services.CreateScope()) { IReadOnlyQueryRequest request = QueryRequestBuilder.New() .SetQuery("{ custom_scalar_stitched(bar: \"2019-11-11\") }") .SetServices(scope.ServiceProvider) .Create(); result = await executor.ExecuteAsync(request); } // assert result.MatchSnapshot(); }
public async Task TestSensorsQuery() { IServiceProvider serviceProvider = new ServiceCollection() .AddSingleton <ITimeSeriesRepository, TimeSeriesRepository>() .AddSingleton <IDatabaseConfig>(sp => new DatabaseConfig() { DatabaseConnectionString = dbConnectionString } ) .BuildServiceProvider(); IQueryExecutor executor = Schema.Create(c => { c.RegisterQueryType(new ObjectType <TimeSeriesQuery>(d => d.Name("Query"))); }) .MakeExecutable(); IReadOnlyQueryRequest request = QueryRequestBuilder.New() .SetQuery(@"query sensors{ sensors { sensorTypeName, sensorIds, sensorColumns } }") .SetServices(serviceProvider) .Create(); // act IExecutionResult result = await executor.ExecuteAsync(request); //Snapshot.Match(result); result.MatchSnapshot(); }
public async Task Interfaces_Impl_Interfaces_Are_Correctly_Exposed_Through_Introspection() { // arrange string source = @" type Query { c: C } interface A { a: String } interface B implements A { a: String } type C implements A & B { a: String } "; string query = FileResource.Open("IntrospectionQuery.graphql"); // act ISchema schema = Schema.Create( source, c => { c.Options.StrictValidation = false; c.Use(next => context => next(context)); }); // assert IQueryExecutor executor = schema.MakeExecutable(); IExecutionResult result = await executor.ExecuteAsync(query); result.MatchSnapshot(); }
public async Task ExecutePersistedQuery_NotFound() { // arrange var queryId = Guid.NewGuid().ToString("N"); var cacheDirectory = IO.Path.GetTempPath(); var cachedQuery = IO.Path.Combine(cacheDirectory, queryId + ".graphql"); await File.WriteAllTextAsync(cachedQuery, "{ __typename }"); IRequestExecutor executor = await new ServiceCollection() .AddGraphQL() .AddQueryType(c => c.Name("Query").Field("a").Resolve("b")) .AddFileSystemQueryStorage(cacheDirectory) .UseRequest(n => async c => { await n(c); if (c.IsPersistedDocument && c.Result is IQueryResult r) { c.Result = QueryResultBuilder .FromResult(r) .SetExtension("persistedDocument", true) .Create(); } }) .UsePersistedQueryPipeline() .BuildRequestExecutorAsync(); // act IExecutionResult result = await executor.ExecuteAsync(new QueryRequest(queryId : "does_not_exist")); // assert File.Delete(cachedQuery); result.MatchSnapshot(); }
public async Task FetchDataLoader() { // arrange IServiceProvider serviceProvider = new ServiceCollection() .AddDataLoaderRegistry() .BuildServiceProvider(); var schema = Schema.Create( @"type Query { fetchItem: String }", c => { c.BindResolver(async ctx => { IDataLoader <string, string> dataLoader = ctx.BatchDataLoader <string, string>( "fetchItems", keys => Task.FromResult < IReadOnlyDictionary <string, string> >( keys.ToDictionary(t => t))); return(await dataLoader.LoadAsync("fooBar")); }).To("Query", "fetchItem"); }); IQueryExecutor executor = schema.MakeExecutable(); IServiceScope scope = serviceProvider.CreateScope(); // act IExecutionResult result = await executor.ExecuteAsync( new QueryRequest("{ fetchItem }") { Services = scope.ServiceProvider });; // assert result.MatchSnapshot(); }
public async Task Create_InterfaceStringEqual_Expression() { // arrange IRequestExecutor tester = _cache .CreateSchema <BarInterface, FilterInputType <BarInterface> >( _barEntities, configure: Configure); // act // assert IExecutionResult res1 = await tester.ExecuteAsync( QueryRequestBuilder.New() .SetQuery( "{ root(where: { test: { prop: { eq: \"a\"}}}) " + "{ test{ prop }}}") .Create()); res1.MatchSnapshot("a"); IExecutionResult res2 = await tester.ExecuteAsync( QueryRequestBuilder.New() .SetQuery( "{ root(where: { test: { prop: { eq: \"b\"}}}) " + "{ test{ prop }}}") .Create()); res2.MatchSnapshot("b"); IExecutionResult res3 = await tester.ExecuteAsync( QueryRequestBuilder.New() .SetQuery( "{ root(where: { test: { prop: { eq: null}}}) " + "{ test{ prop}}}") .Create()); res3.MatchSnapshot("null"); }
public async Task ExecutePersistedQuery_ApplicationDI_Default() { // arrange var queryId = Guid.NewGuid().ToString("N"); var storage = new RedisQueryStorage(_database); await storage.WriteQueryAsync(queryId, new QuerySourceText("{ __typename }")); IRequestExecutor executor = await new ServiceCollection() // we register the multiplexer on the application services .AddSingleton(_multiplexer) .AddGraphQL() .AddQueryType(c => c.Name("Query").Field("a").Resolve("b")) // and in the redis storage setup refer to that instance. .AddRedisQueryStorage() .UseRequest(n => async c => { await n(c); if (c.IsPersistedDocument && c.Result is IQueryResult r) { c.Result = QueryResultBuilder .FromResult(r) .SetExtension("persistedDocument", true) .Create(); } }) .UsePersistedQueryPipeline() .BuildRequestExecutorAsync(); // act IExecutionResult result = await executor.ExecuteAsync(new QueryRequest(queryId : queryId)); // assert result.MatchSnapshot(); }
public async Task UpdateSchema_DuplicateName() { // arrange var serializer = new IdSerializer(); var schemaA = new Schema(Guid.NewGuid(), "abc", "def"); var schemaB = new Schema(Guid.NewGuid(), "def", "ghi"); await SchemaRepository.AddSchemaAsync(schemaA); await SchemaRepository.AddSchemaAsync(schemaB); string id = serializer.Serialize("Schema", schemaA.Id); // act IExecutionResult result = await Executor.ExecuteAsync( QueryRequestBuilder.New() .SetQuery( @"mutation($id: ID!) { updateSchema(input: { id: $id name: ""def"" description: ""def2"" clientMutationId: ""ghi"" }) { schema { id name description } clientMutationId } }") .SetVariableValue("id", id) .Create()); // assert result.MatchSnapshot(); }
public async Task VariableIsPartlyNotSerializedAndMustBeConvertedToClrType() { // arrange ISchema schema = Schema.Create(c => { c.RegisterQueryType <Query>(); c.RegisterExtendedScalarTypes(); }); var variables = new Dictionary <string, object> { { "a", new Dictionary <string, object> { { "id", "934b987bc0d842bbabfd8a3b3f8b476e" }, { "time", "2018-05-29T01:00Z" }, { "number", 123 } } } }; // act IExecutionResult result = await schema.MakeExecutable().ExecuteAsync(@" query foo($a: FooInput) { foo(foo: $a) { id time number } }", variables); // assert result.MatchSnapshot(); }
public async Task SimpleHelloWorldWithArgumentWithoutTypeBinding() { // arrange var schema = Schema.Create( @" type Query { hello(a: String!): String } ", c => { c.BindResolver(ctx => ctx.Argument <string>("a")) .To("Query", "hello"); }); // act IExecutionResult result = await schema.MakeExecutable().ExecuteAsync( "{ hello(a: \"foo\") }"); // assert Assert.Empty(result.Errors); result.MatchSnapshot(); }
public async Task MiddlewareConfig_MapWithClassFactory() { // arrange ISchema schema = Schema.Create( "type Query { a: String b: String }", c => c.Map <TestFieldMiddleware>( new FieldReference("Query", "a"), (services, next) => new TestFieldMiddleware(next)) .Map( new FieldReference("Query", "b"), next => context => { context.Result = "456"; return(Task.CompletedTask); })); IQueryExecutor executor = schema.MakeExecutable(); // act IExecutionResult result = await executor.ExecuteAsync("{ a b }"); // assert result.MatchSnapshot(); }
public async Task GetSchemaVersionsById_Invalid_Id_Type() { // arrange var serializer = new IdSerializer(); var schema = new Schema(Guid.NewGuid(), "abc", "def"); await SchemaRepository.AddSchemaAsync(schema); var schemaVersion = new SchemaVersion( Guid.NewGuid(), schema.Id, "abc", DocumentHash.FromSourceText("def"), Array.Empty <Tag>(), DateTime.UnixEpoch); await SchemaRepository.AddSchemaVersionAsync(schemaVersion); string id = serializer.Serialize("Foo", schemaVersion.Id); IFileContainer container = await Storage.CreateContainerAsync( schemaVersion.Id.ToString("N", CultureInfo.InvariantCulture)); byte[] buffer = Encoding.UTF8.GetBytes("SourceTextAbc"); await container.CreateFileAsync("schema.graphql", buffer, 0, buffer.Length); // act IExecutionResult result = await Executor.ExecuteAsync( QueryRequestBuilder.New() .SetQuery( @"query($ids: [ID!]!) { schemaVersionsById(ids: $ids) { id sourceText } }") .SetVariableValue("ids", new[] { id }) .Create()); // assert result.MatchSnapshot(); }
public async Task Resolver_Pipeline_With_Request_DbContext_Is_Created() { Snapshot.FullName(); using AuthorFixture authorFixture = new(); using IServiceScope scope = new ServiceCollection() .AddScoped(_ => authorFixture.Context) .AddGraphQL() .AddQueryType <Query>() .RegisterDbContext <BookContext>(DbContextKind.Synchronized) .ModifyRequestOptions(o => o.IncludeExceptionDetails = true) .Services .BuildServiceProvider() .CreateScope(); IExecutionResult result = await scope.ServiceProvider.ExecuteRequestAsync( QueryRequestBuilder.New() .SetQuery("{ books { title } }") .SetServices(scope.ServiceProvider) .Create()); result.MatchSnapshot(); }
public void Ensure_Type_Introspection_Returns_Null_If_Type_Not_Found() { // arrange var query = @" query { a: __type(name: ""Foo"") { name } b: __type(name: ""Query"") { name } }"; IQueryExecutor executor = CreateSchema().MakeExecutable( new QueryExecutionOptions { MaxExecutionDepth = 3 }); // act IExecutionResult result = executor.Execute(query); // assert result.MatchSnapshot(); }
public void Sort_ComparableAsc_PrefilterInResolver() { // arrange IQueryable <Foo> data = new[] { new Foo { Bar = "baz", Baz = "a" }, new Foo { Bar = "aa", Baz = "b" }, new Foo { Bar = "zz", Baz = "b" } }.AsQueryable().OrderBy(x => x.Baz); ISchema schema = SchemaBuilder.New() .AddQueryType(ctx => { ctx.Field("foo") .Resolver(data) .Type <NonNullType <ListType <NonNullType <ObjectType <Foo> > > > >() .UseSorting(); }) .Create(); IReadOnlyQueryRequest request = QueryRequestBuilder.New() .SetQuery("{ foo(order_by: { bar: DESC }) { bar } }") .Create(); // act IExecutionResult result = schema.MakeExecutable().Execute(request); // assert result.MatchSnapshot(); }
public void Skip_With_Variable(bool ifValue) { // arrange var query = $@" query ($if: Boolean!) {{ human(id: ""1000"") {{ name @skip(if: $if) height }} }}"; IQueryExecutor executor = CreateSchema().MakeExecutable(); // act IExecutionResult result = executor.Execute( query, new Dictionary <string, object> { { "if", ifValue } }); // assert result.MatchSnapshot(new SnapshotNameExtension(ifValue)); }
public void NonNullListVariableValues() { // arrange var query = @" query op($ep: [Episode!]!) { heroes(episodes: $ep) { name } }"; var variables = new Dictionary <string, object> { { "ep", new ListValueNode(new[] { new EnumValueNode("EMPIRE") }) } }; IQueryExecutor executor = CreateSchema().MakeExecutable(); // act IExecutionResult result = executor.Execute(query, variables); // assert result.MatchSnapshot(); }
public async Task GetCinema_With_Results() { //arrange Mock <ICinemaLogic> cinemaLogicMock = new Mock <ICinemaLogic>(); cinemaLogicMock.Setup(p => p.GetCinemas()).Returns(_GetCinemaList()); Mock <IServiceProvider> serviceProvider = new Mock <IServiceProvider>(); serviceProvider.Setup(p => p.GetService(typeof(ICinemaLogic))).Returns(cinemaLogicMock.Object); IQueryExecutor queryExecutor = QueryExecutorFactory.Create <CinemaQuery>(); IReadOnlyQueryRequest queryRequest = QueryRequestBuilder.New() .SetQuery(@"query GetAllCinemas{ cinemas{ edges{ cursor } nodes{ title description iD duration } } }") .AddProperty("Key", "value") .SetServices(serviceProvider.Object) .Create(); //act IExecutionResult result = await queryExecutor.ExecuteAsync(queryRequest); //assert result.MatchSnapshot(); }
public async Task AutoMerge_Execute_Variables() { // 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(); var variables = new Dictionary <string, object> { { "customerId", "Q3VzdG9tZXIKZDE=" }, { "deep", "deep" }, { "deeper", "deeper" } }; // act IExecutionResult result = await executor.ExecuteAsync( @"query customer_query( $customerId: ID! $deep: String! $deeper: String! $deeperArray: String $complex: ComplexInputType $deeperInArray: String ) { customer(id: $customerId) { name consultant { name } complexArg( arg: { value: $deep deeper: { value: ""CONSTANT"" deeper: { value: $deeper deeperArray: [ { value: ""CONSTANT_ARRAY"", deeper: { value: $deeperInArray } } ] } } deeperArray: [ { value: ""CONSTANT_ARRAY"", deeper: { value: $deeperArray } } $complex ] } ) contracts { id ... on LifeInsuranceContract { premium } ... on SomeOtherContract { expiryDate } } } }", variables); // assert result.MatchSnapshot(); }
public async Task Array_Filter_On_Scalar_Types() { // arrange IServiceProvider services = new ServiceCollection() .AddSingleton <IMongoCollection <Foo> >(sp => { IMongoDatabase database = _mongoResource.CreateDatabase(); return(database.GetCollection <Foo>("col")); }) .AddGraphQL() .AddQueryType <QueryType>() .BindRuntimeType <ObjectId, IdType>() .Services .BuildServiceProvider(); IRequestExecutor executor = await services.GetRequiredService <IRequestExecutorResolver>() .GetRequestExecutorAsync(); IMongoCollection <Foo> collection = services.GetRequiredService <IMongoCollection <Foo> >(); await collection.InsertOneAsync(new Foo { BarCollection = new List <string> { "a", "b", "c" }, BazCollection = new List <Baz> { new Baz { Quux = "a" }, new Baz { Quux = "b" } }, Bars = new[] { "d", "e", "f" }, Bazs = new[] { new Baz { Quux = "c" }, new Baz { Quux = "d" } }, Quux = "abc" }); ISchema schema = SchemaBuilder.New() .AddQueryType <QueryType>() .AddServices(services) .BindClrType <ObjectId, IdType>() .Create(); IReadOnlyQueryRequest request = QueryRequestBuilder.New() .SetQuery( "{" + "foos(where: { bars_some: { element: \"e\" } }) { bars } " + "}") .Create(); // act IExecutionResult result = await executor.ExecuteAsync(request); // assert result.MatchSnapshot(); }
public async Task ConnectionLost() { // arrange var connections = new Dictionary <string, HttpClient>(); IHttpClientFactory clientFactory = CreateRemoteSchemas(connections); var serviceCollection = new ServiceCollection(); serviceCollection.AddSingleton(clientFactory); serviceCollection.AddStitchedSchema(builder => builder.AddSchemaFromHttp("contract") .AddSchemaFromHttp("customer") .RenameType("CreateCustomerInput", "CreateCustomerInput2") .AddExtensionsFromString( FileResource.Open("StitchingExtensions.graphql")) .AddSchemaConfiguration(c => c.RegisterType <PaginationAmountType>()) .AddExecutionConfiguration(b => { b.AddErrorFilter(error => { if (error.Exception is Exception ex) { return(ErrorBuilder.FromError(error) .ClearExtensions() .SetMessage(ex.GetType().FullName) .SetException(null) .Build()); } ; return(error); }); })); IServiceProvider services = serviceCollection.BuildServiceProvider(); IQueryExecutor executor = services .GetRequiredService <IQueryExecutor>(); IExecutionResult result = null; using (IServiceScope scope = services.CreateScope()) { IReadOnlyQueryRequest request = QueryRequestBuilder.New() .SetQuery(@" mutation { createCustomer(input: { name: ""a"" }) { customer { name contracts { id } } } }") .SetServices(scope.ServiceProvider) .Create(); result = await executor.ExecuteAsync(request); } var client = new HttpClient { BaseAddress = new Uri("http://127.0.0.1") };; connections["contract"] = client; connections["customer"] = client; // act using (IServiceScope scope = services.CreateScope()) { IReadOnlyQueryRequest request = QueryRequestBuilder.New() .SetQuery(@" mutation { createCustomer(input: { name: ""a"" }) { customer { name contracts { id } } } }") .SetServices(scope.ServiceProvider) .Create(); result = await executor.ExecuteAsync(request); } // assert result.MatchSnapshot(); }