/// <summary> /// Handle a sql string and check it with the engine /// </summary> /// <param name="actual">SQL string</param> /// <returns>true, if the query defined in parameter is executed in less that expected else false</returns> public bool doMatch(IExecution actual) { Result = actual.Run(); return ( Result.TimeElapsed.TotalMilliseconds < maxTimeMilliSeconds ); }
public async Task Create_ArrayObjectNestedArraySomeStringEqual_Expression() { // arrange IRequestExecutor tester = CreateSchema <Bar, BarFilterType>(_barEntities); // act // assert IExecutionResult res1 = await tester.ExecuteAsync( QueryRequestBuilder.New() .SetQuery( "{ root(where: { foo:{ objectArray: { " + "some: { foo: { barString: { eq: \"a\"}}}}}}) " + "{ foo { objectArray { foo { barString}}}}}") .Create()); res1.MatchDocumentSnapshot("a"); IExecutionResult res2 = await tester.ExecuteAsync( QueryRequestBuilder.New() .SetQuery( "{ root(where: { foo:{ objectArray: { " + "some: { foo: { barString: { eq: \"d\"}}}}}}) " + "{ foo { objectArray { foo { barString}}}}}") .Create()); res2.MatchDocumentSnapshot("d"); IExecutionResult res3 = await tester.ExecuteAsync( QueryRequestBuilder.New() .SetQuery( "{ root(where: { foo:{ objectArray: { " + "some: { foo: { barString: { eq: null}}}}}}) " + "{ foo { objectArray { foo {barString}}}}}") .Create()); res3.MatchDocumentSnapshot("null"); }
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 Serialize_Response_Stream() { // arrange IExecutionResult result = await new ServiceCollection() .AddStarWarsRepositories() .AddGraphQL() .AddStarWarsTypes() .ExecuteRequestAsync( @"{ hero(episode: NEW_HOPE) { id ... @defer(label: ""friends"") { friends { nodes { id ... @defer { name } } } } } }"); IResponseStream stream = Assert.IsType <DeferredQueryResult>(result); var memoryStream = new MemoryStream(); var serializer = new MultiPartResponseStreamSerializer(); // act await serializer.SerializeAsync(stream, memoryStream, CancellationToken.None); // assert memoryStream.Seek(0, SeekOrigin.Begin); new StreamReader(memoryStream).ReadToEnd().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 Create_ArrayAllObjectStringEqual_Expression() { // arrange IRequestExecutor tester = await _fixture.GetOrCreateSchema <Foo, FooFilterType>(_fooEntitiesCypher); // act // assert const string query1 = @"{ root(where: { barString: { eq: ""a"" } fooNested: { all: { bar: { eq: ""a"" } } } }){ barString fooNested { bar barNested { foo } } } }"; IExecutionResult res1 = await tester.ExecuteAsync( QueryRequestBuilder.New() .SetQuery(query1) .Create()); res1.MatchDocumentSnapshot("all"); }
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 Subscribe_Attribute_With_Argument_Topic() { // arrange using var cts = new CancellationTokenSource(30000); IRequestExecutor executor = await CreateExecutorAsync(r => r .AddInMemorySubscriptions() .AddQueryType(c => c.Name("Query").Field("a").Resolver("b")) .AddMutationType <MyMutation>() .AddSubscriptionType <MySubscription>()); // act var stream = (IResponseStream)await executor.ExecuteAsync( "subscription { onMessage(userId: \"abc\") }", cts.Token); // assert IExecutionResult mutationResult = await executor.ExecuteAsync( "mutation { writeMessage(userId: \"abc\" message: \"def\") }", cts.Token); Assert.Null(mutationResult.Errors); var results = new StringBuilder(); await foreach (IQueryResult queryResult in stream.ReadResultsAsync().WithCancellation(cts.Token)) { var result = (IQueryResult)queryResult; results.AppendLine(result.ToJson()); break; } await stream.DisposeAsync(); results.ToString().MatchSnapshot(); }
protected override async Task HandleAsync( ISocketConnection connection, DataStartMessage message, CancellationToken cancellationToken) { IQueryRequestBuilder requestBuilder = QueryRequestBuilder.New() .SetQuery(message.Payload.Query) .SetQueryId(message.Payload.QueryId) .SetOperation(message.Payload.OperationName) .SetVariableValues(message.Payload.Variables) .SetProperties(message.Payload.Extensions) .SetServices(connection.RequestServices); await _socketSessionInterceptor.OnRequestAsync( connection, requestBuilder, cancellationToken); IExecutionResult result = await _requestExecutor.ExecuteAsync( requestBuilder.Create(), cancellationToken); switch (result) { case IResponseStream responseStream: var subscription = new Subscription(connection, responseStream, message.Id); connection.Subscriptions.Register(subscription); break; case IQueryResult queryResult: using (queryResult) await HandleQueryResultAsync( connection, message, queryResult, cancellationToken); break; default: throw new NotSupportedException("The response type is not supported."); } }
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(); }
private async Task <dynamic> RemoveBasketItem(Guid ownerId, Guid itemId) { var basketItemDeleteInput = new BasketItemDeleteInput(ownerId, itemId); IExecutionResult result = await ServiceProvider.ExecuteRequestAsync( QueryRequestBuilder .New() .SetQuery(@" mutation RemoveBasketItem($input: BasketItemDeleteInput!) { removeBasketItem(input: $input) { basket { id ownerId items { id quantity } } } } ") .SetVariableValue(name : "input", value : basketItemDeleteInput) .Create() ); // Check against the snapshot, the existing basket was returned var json = await result.ToJsonAsync(); Assert.NotNull(json); ExpandoObject response = JsonConvert.DeserializeObject <ExpandoObject>(json, new ExpandoObjectConverter()); Assert.NotNull(response); return(response); }
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 <IActionResult> ExecuteRuleYaml([FromBody] ExecuteRuleYamlFromUriRequest request) { var controller = new YamlScriptController(); var response = new ExecuteRuleYamlFromUriResponse(); var parameters = request.ClientParameters.Adapt <IParametersCollection>(); IExecutionResult executionResult = null; controller.QuestionCallback = (FormulaExpressionContext sender, QuestionArgs args) => { executionResult.Questions = args; }; var downloadResult = request.Endpoint.DownloadYaml(); var result = controller.Parse(downloadResult.Content); if (result.IsError) { return(StatusCode(400, response)); } ; executionResult = new ExecutionResult(ref parameters); try { executionResult = controller.ExecuteWorkflow(ref parameters, ref executionResult); } catch (UnresolvedException) { } if (executionResult.IsError) { response.ExecutionStatus = ExecuteRuleYamlResultTypes.SyntaxError; return(StatusCode(400, response)); } response.ServerParameters = executionResult.Parameters.Adapt <IEnumerable <ServerParameter> >(); return(StatusCode(200, new ExecuteRuleYamlFromUriResponse())); }
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 Interfaces_Impl_Interfaces_Are_Correctly_Exposed_Through_Introspection() { // arrange var source = @" type Query { c: C } interface A { a: String } interface B implements A { a: String } type C implements A & B { a: String } "; var query = FileResource.Open("IntrospectionQuery.graphql"); // act ISchema schema = Schema.Create( source, c => { c.Options.StrictValidation = false; c.Use(next => context => next(context)); }); // assert IRequestExecutor executor = schema.MakeExecutable(); IExecutionResult result = await executor.ExecuteAsync(query); result.ToJson().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 Create_ShortNotLowerThanOrEquals_Expression() { // arrange IRequestExecutor tester = await _fixture.GetOrCreateSchema <Foo, FooFilterType>(_fooEntitiesCypher); // act const string query1 = "{ root(where: { barShort: { nlte: 12}}){ barShort}}"; IExecutionResult res1 = await tester.ExecuteAsync( QueryRequestBuilder.New() .SetQuery(query1) .Create()); const string query2 = "{ root(where: { barShort: { nlte: 13}}){ barShort}}"; IExecutionResult res2 = await tester.ExecuteAsync( QueryRequestBuilder.New() .SetQuery(query2) .Create()); const string query3 = "{ root(where: { barShort: { nlte: 14}}){ barShort}}"; IExecutionResult res3 = await tester.ExecuteAsync( QueryRequestBuilder.New() .SetQuery(query3) .Create()); const string query4 = "{ root(where: { barShort: { nlte: null}}){ barShort}}"; IExecutionResult res4 = await tester.ExecuteAsync( QueryRequestBuilder.New() .SetQuery(query4) .Create()); // assert res1.MatchDocumentSnapshot("12"); res2.MatchDocumentSnapshot("13"); res3.MatchDocumentSnapshot("14"); res4.MatchDocumentSnapshot("null"); }
public async Task SubscribeToReview() { // arrange IRequestExecutor executor = await CreateExecutorAsync(); // act var subscriptionResult = (ISubscriptionResult)await executor.ExecuteAsync( "subscription { onReview(episode: NEW_HOPE) " + "{ stars } }"); // assert IExecutionResult result = await executor.ExecuteAsync(@" mutation { createReview(episode: NEW_HOPE, review: { stars: 5 commentary: ""foo"" }) { stars commentary } }"); IReadOnlyQueryResult eventResult = null; using (var cts = new CancellationTokenSource(2000)) { await foreach (IQueryResult queryResult in subscriptionResult.ReadResultsAsync().WithCancellation(cts.Token)) { var item = (IReadOnlyQueryResult)queryResult; eventResult = item; break; } } eventResult.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 ExecuteWithNonNullVariableNull_Error() { // arrange var variableValues = new Dictionary <string, object>() { { "a", NullValueNode.Default } }; Schema schema = CreateSchema(); var executer = QueryExecutionBuilder.BuildDefault(schema); var request = new QueryRequest( "query x($a: String!) { b(a: $a) }") { VariableValues = variableValues }; // act IExecutionResult result = await executer.ExecuteAsync(request); // assert Assert.NotNull(result.Errors); result.Snapshot(); }
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 async Task Input_Value_Null_As_Variable() { // arrange ISchema schema = SchemaBuilder.New() .AddQueryType(d => d .Name("Query") .Field("foo") .Type <AnyType>() .Argument("input", a => a.Type <AnyType>()) .Resolver(ctx => ctx.Argument <object>("input"))) .Create(); IQueryExecutor executor = schema.MakeExecutable(); // act IExecutionResult result = await executor.ExecuteAsync( QueryRequestBuilder.New() .SetQuery("query ($foo: Any) { foo(input: $foo) }") .SetVariableValue("foo", null) .Create()); // assert result.ToJson().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 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 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 async Task Create_ProjectsOneProperty_WithResolver() { // arrange IRequestExecutor tester = _cache.CreateSchema( _fooEntities, objectType: new ObjectType <Foo>( x => x .Field("foo") .Resolver( new[] { "foo" }) .Type <ListType <StringType> >())); // act // assert IExecutionResult res1 = await tester.ExecuteAsync( QueryRequestBuilder.New() .SetQuery("{ root{ baz foo }}") .Create()); res1.MatchDocumentSnapshot(); }
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 ExecuteWithNonNullVariableValidValue_NoErrors() { // arrange var variableValues = new Dictionary <string, object>() { { "a", new StringValueNode("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.Empty(result.Errors); result.MatchSnapshot(); }
public async Task ExecuteMutationSerially() { // arrange int state = 0; Schema 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"); }); var session = new Mock <ISession>(MockBehavior.Strict); session.Setup(t => t.DataLoaders).Returns((IDataLoaderProvider)null); session.Setup(t => t.CustomContexts).Returns((ICustomContextProvider)null); DocumentNode query = Parser.Default.Parse( FileResource.Open("MutationExecutionQuery.graphql")); OperationDefinitionNode operation = query.Definitions .OfType <OperationDefinitionNode>().FirstOrDefault(); // act OperationExecuter operationExecuter = new OperationExecuter(schema, query, operation); IExecutionResult result = await operationExecuter.ExecuteAsync( new OperationRequest(schema.Services, session.Object), CancellationToken.None); // assert Assert.Null(result.Errors); Assert.Equal(Snapshot.Current(), Snapshot.New(result)); }
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 Create_ObjectBool_OrderBy() { // arrange IRequestExecutor tester = _cache.CreateSchema <Bar, BarSortType>(_barEntities); // act IExecutionResult res1 = await tester.ExecuteAsync( QueryRequestBuilder.New() .SetQuery( "{ root(order: { foo: { barBool: ASC}}) " + "{ foo{ barBool}}}") .Create()); IExecutionResult res2 = await tester.ExecuteAsync( QueryRequestBuilder.New() .SetQuery( "{ root(order: { foo: { barBool: DESC}}) " + "{ foo{ barBool}}}") .Create()); // assert res1.MatchSqlSnapshot("ASC"); res2.MatchSqlSnapshot("DESC"); }
public void When_invoking_command() { _executionResult = SUT.Execute(Command); }
protected bool doMatch(IExecution actual) { Result = actual.Run(); return Result.IsSuccess; }